182d654425b1db8575bf60bae339a38588979062
[kivitendo-erp.git] / SL / Dispatcher / AuthHandler / User.pm
1 package SL::Dispatcher::AuthHandler::User;
2
3 use strict;
4 use parent qw(Rose::Object);
5
6 use Encode ();
7 use MIME::Base64 ();
8
9 use SL::Layout::Dispatcher;
10
11 sub handle {
12   my ($self, %param) = @_;
13
14   my ($http_auth_login, $http_auth_password) = $self->_parse_http_basic_auth;
15
16   my $login = $::form->{'{AUTH}login'} // $http_auth_login // $::auth->get_session_value('login');
17
18   return $self->_error(%param) if !defined $login;
19
20   my $client_id = $::form->{'{AUTH}client_id'} // $::auth->get_session_value('client_id') // $::auth->get_default_client_id;
21
22   return $self->_error(%param) if !$client_id || !$::auth->set_client($client_id);
23
24   %::myconfig = User->get_default_myconfig($::auth->read_user(login => $login));
25
26   return $self->_error(%param) unless $::myconfig{login};
27
28   $::locale = Locale->new($::myconfig{countrycode});
29   $::request->{layout} = SL::Layout::Dispatcher->new(style => $::myconfig{menustyle});
30
31   my $ok   =  $::auth->is_api_token_cookie_valid;
32   $ok    ||=  $::form->{'{AUTH}login'}                      && (SL::Auth::OK() == $::auth->authenticate($::myconfig{login}, $::form->{'{AUTH}password'}));
33   $ok    ||= !$::form->{'{AUTH}login'} &&  $http_auth_login && (SL::Auth::OK() == $::auth->authenticate($::myconfig{login}, $http_auth_password));
34   $ok    ||= !$::form->{'{AUTH}login'} && !$http_auth_login && (SL::Auth::OK() == $::auth->authenticate($::myconfig{login}, undef));
35
36   return $self->_error(%param) if !$ok;
37
38   $::auth->create_or_refresh_session;
39   $::auth->delete_session_value('FLASH');
40   $::instance_conf->reload->data;
41
42   return 1;
43 }
44
45 sub _error {
46   my $self = shift;
47
48   $::auth->punish_wrong_login;
49
50   require SL::Controller::Base;
51   SL::Controller::Base->new->redirect_to('controller.pl?action=LoginScreen/user_login&error=password');
52   return 0;
53 }
54
55 sub _parse_http_basic_auth {
56   my ($self) = @_;
57
58   # See RFC 7617.
59
60   # Requires that the server passes the 'Authorization' header as the
61   # environment variable 'HTTP_AUTHORIZATION'. Example code for
62   # Apache:
63
64   # SetEnvIf Authorization "(.*)" HTTP_AUTHORIZATION=$1
65
66   my $data = $ENV{HTTP_AUTHORIZATION};
67
68   return unless ($data // '') =~ m{^basic +(.+)}i;
69
70   $data = Encode::decode('utf-8', MIME::Base64::decode($1));
71
72   return unless $data =~ m{(.+?):(.+)};
73
74   return ($1, $2);
75 }
76
77 1;