From 28646e1c5fb9d71fab027e25324f969750ce7e69 Mon Sep 17 00:00:00 2001 From: ajs124 Date: Sun, 13 Oct 2019 02:06:36 +0200 Subject: [PATCH] Initial attempt at adding LDAP login support --- src/lib/Hydra.pm | 6 ++++- src/lib/Hydra/Controller/User.pm | 39 ++++++++++++++++++++++++++++++-- 2 files changed, 42 insertions(+), 3 deletions(-) diff --git a/src/lib/Hydra.pm b/src/lib/Hydra.pm index f4583eed..3c8184d9 100644 --- a/src/lib/Hydra.pm +++ b/src/lib/Hydra.pm @@ -20,7 +20,8 @@ use Catalyst qw/ConfigLoader Captcha/, '-Log=warn,fatal,error'; use CatalystX::RoleApplicator; - +use YAML qw(LoadFile); +use Path::Class 'file'; our $VERSION = '0.01'; @@ -44,6 +45,9 @@ __PACKAGE__->config( role_field => "role", }, }, + ldap => LoadFile( + file($ENV{'HYDRA_LDAP_CONFIG'}) + ) }, }, 'Plugin::Static::Simple' => { diff --git a/src/lib/Hydra/Controller/User.pm b/src/lib/Hydra/Controller/User.pm index 18cc7b05..e1351be4 100644 --- a/src/lib/Hydra/Controller/User.pm +++ b/src/lib/Hydra/Controller/User.pm @@ -12,6 +12,7 @@ use Hydra::Helper::Email; use LWP::UserAgent; use JSON; use HTML::Entities; +use Encode qw(decode); __PACKAGE__->config->{namespace} = ''; @@ -28,8 +29,12 @@ sub login_POST { error($c, "You must specify a user name.") if $username eq ""; error($c, "You must specify a password.") if $password eq ""; - accessDenied($c, "Bad username or password.") - if !$c->authenticate({username => $username, password => $password}); + if ($c->authenticate({username => $username, password => $password}, 'ldap')) { + doLDAPLogin($self, $c, $username); + } elsif ($c->authenticate({username => $username, password => $password})) {} + else { + accessDenied($c, "Bad username or password.") + } currentUser_GET($self, $c); } @@ -44,6 +49,36 @@ sub logout_POST { $self->status_no_content($c); } +sub doLDAPLogin { + my ($self, $c, $username) = @_; + + my $user = $c->find_user({ username => $username }); + my $LDAPUser = $c->find_user({ username => $username }, 'ldap'); + my @LDAPRoles = grep { (substr $_, 0, 5) eq "hydra" } $LDAPUser->roles; + + if (!$user) { + $c->model('DB::Users')->create( + { username => $username + , fullname => decode('UTF-8', $LDAPUser->cn) + , password => "!" + , emailaddress => $LDAPUser->mail + , type => "LDAP" + }); + $user = $c->find_user({ username => $username }) or die; + } else { + $user->update( + { fullname => decode('UTF-8', $LDAPUser->cn) + , password => "!" + , emailaddress => $LDAPUser->mail + , type => "LDAP" + }); + } + $user->userroles->delete; + if (@LDAPRoles) { + $user->userroles->create({ role => (substr $_, 6) }) for @LDAPRoles; + } + $c->set_authenticated($user); +} sub doEmailLogin { my ($self, $c, $type, $email, $fullName) = @_;