acdf29c5ca427c44bb89b2943f339e6a0d7181d3
[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} = $::request->is_mobile
30     ? SL::Layout::Dispatcher->new(style => 'mobile')
31     : SL::Layout::Dispatcher->new(style => $::myconfig{menustyle});
32
33   my $ok   =  $::auth->is_api_token_cookie_valid;
34   $ok    ||=  $::form->{'{AUTH}login'}                      && (SL::Auth::OK() == $::auth->authenticate($::myconfig{login}, $::form->{'{AUTH}password'}));
35   $ok    ||= !$::form->{'{AUTH}login'} &&  $http_auth_login && (SL::Auth::OK() == $::auth->authenticate($::myconfig{login}, $http_auth_password));
36   $ok    ||= !$::form->{'{AUTH}login'} && !$http_auth_login && (SL::Auth::OK() == $::auth->authenticate($::myconfig{login}, undef));
37
38   return $self->_error(%param) if !$ok;
39
40   $::auth->create_or_refresh_session;
41   $::auth->delete_session_value('FLASH');
42   $::instance_conf->reload->data;
43
44   return 1;
45 }
46
47 sub _error {
48   my ($self, %param) = @_;
49
50   $::auth->punish_wrong_login;
51   $::dispatcher->handle_login_error(%param, error => 'password');
52
53   return 0;
54 }
55
56 sub _parse_http_basic_auth {
57   my ($self) = @_;
58
59   # See RFC 7617.
60
61   # Requires that the server passes the 'Authorization' header as the
62   # environment variable 'HTTP_AUTHORIZATION'. Example code for
63   # Apache:
64
65   # SetEnvIf Authorization "(.*)" HTTP_AUTHORIZATION=$1
66
67   my $data = $ENV{HTTP_AUTHORIZATION};
68
69   return unless ($data // '') =~ m{^basic +(.+)}i;
70
71   $data = Encode::decode('utf-8', MIME::Base64::decode($1));
72
73   return unless $data =~ m{(.+?):(.+)};
74
75   return ($1, $2);
76 }
77
78 1;