Auth: fehlerhafte JSON-Requests mit JSON und richtigem HTTP-Response-Code beantworten
[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   $::dispatcher->handle_login_error(error => 'password');
50
51   return 0;
52 }
53
54 sub _parse_http_basic_auth {
55   my ($self) = @_;
56
57   # See RFC 7617.
58
59   # Requires that the server passes the 'Authorization' header as the
60   # environment variable 'HTTP_AUTHORIZATION'. Example code for
61   # Apache:
62
63   # SetEnvIf Authorization "(.*)" HTTP_AUTHORIZATION=$1
64
65   my $data = $ENV{HTTP_AUTHORIZATION};
66
67   return unless ($data // '') =~ m{^basic +(.+)}i;
68
69   $data = Encode::decode('utf-8', MIME::Base64::decode($1));
70
71   return unless $data =~ m{(.+?):(.+)};
72
73   return ($1, $2);
74 }
75
76 1;