9 use List::MoreUtils qw/all any none/;
10 use Test::More tests => 18;
13 use t::lib::TestBuilder;
17 use Koha::AuthUtils qw/hash_password/;
20 use Koha::Auth::TwoFactorAuth;
23 use_ok('C4::Auth', qw( checkauth haspermission track_login_daily checkpw get_template_and_user checkpw_hash ));
26 my $schema = Koha::Database->schema;
27 my $builder = t::lib::TestBuilder->new;
29 # FIXME: SessionStorage defaults to mysql, but it seems to break transaction
31 t::lib::Mocks::mock_preference( 'SessionStorage', 'tmp' );
32 t::lib::Mocks::mock_preference( 'PrivacyPolicyConsent', '' ); # Disabled
34 # To silence useless warnings
35 $ENV{REMOTE_ADDR} = '127.0.0.1';
37 $schema->storage->txn_begin;
39 subtest 'checkauth() tests' => sub {
43 my $patron = $builder->build_object({ class => 'Koha::Patrons', value => { flags => undef } });
45 # Mock a CGI object with real userid param
46 my $cgi = Test::MockObject->new();
51 if ( $var eq 'userid' ) { return $patron->userid; }
54 $cgi->mock( 'cookie', sub { return; } );
55 $cgi->mock( 'request_method', sub { return 'POST' } );
57 my $authnotrequired = 1;
58 my ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, $authnotrequired );
60 is( $userid, undef, 'checkauth() returns undef for userid if no logged in user (Bug 18275)' );
62 my $db_user_id = C4::Context->config('user');
63 my $db_user_pass = C4::Context->config('pass');
64 $cgi = Test::MockObject->new();
65 $cgi->mock( 'cookie', sub { return; } );
66 $cgi->mock( 'param', sub {
67 my ( $self, $param ) = @_;
68 if ( $param eq 'userid' ) { return $db_user_id; }
69 elsif ( $param eq 'password' ) { return $db_user_pass; }
72 $cgi->mock( 'request_method', sub { return 'POST' } );
73 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, $authnotrequired );
74 is ( $userid, undef, 'If DB user is used, it should not be logged in' );
76 my $is_allowed = C4::Auth::haspermission( $db_user_id, { can_do => 'everything' } );
78 # FIXME This belongs to t/db_dependent/Auth/haspermission.t but we do not want to c/p the pervious mock statements
79 ok( !$is_allowed, 'DB user should not have any permissions');
81 subtest 'Prevent authentication when sending credential via GET' => sub {
85 my $patron = $builder->build_object(
86 { class => 'Koha::Patrons', value => { flags => 1 } } );
87 my $password = 'password';
88 t::lib::Mocks::mock_preference( 'RequireStrongPassword', 0 );
89 $patron->set_password( { password => $password } );
90 $cgi = Test::MockObject->new();
91 $cgi->mock( 'cookie', sub { return; } );
95 my ( $self, $param ) = @_;
96 if ( $param eq 'userid' ) { return $patron->userid; }
97 elsif ( $param eq 'password' ) { return $password; }
102 $cgi->mock( 'request_method', sub { return 'POST' } );
103 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired' );
104 is( $userid, $patron->userid, 'If librarian user is used and password with POST, they should be logged in' );
106 $cgi->mock( 'request_method', sub { return 'GET' } );
107 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired' );
108 is( $userid, undef, 'If librarian user is used and password with GET, they should not be logged in' );
111 subtest 'Template params tests (password_expired)' => sub {
115 my $password_expired;
117 my $patron_class = Test::MockModule->new('Koha::Patron');
118 $patron_class->mock( 'password_expired', sub { return $password_expired; } );
120 my $patron = $builder->build_object({ class => 'Koha::Patrons', value => { flags => 1 } });
121 my $password = 'password';
122 t::lib::Mocks::mock_preference( 'RequireStrongPassword', 0 );
123 $patron->set_password( { password => $password } );
125 my $cgi_mock = Test::MockModule->new('CGI')->mock( 'request_method', 'POST' );
127 $cgi->param( -name => 'userid', -value => $patron->userid );
128 $cgi->param( -name => 'password', -value => $password );
130 my $auth = Test::MockModule->new( 'C4::Auth' );
131 # Tests will fail if we hit safe_exit
132 $auth->mock( 'safe_exit', sub { return } );
134 my ( $userid, $cookie, $sessionID, $flags );
137 t::lib::Mocks::mock_preference( 'DumpTemplateVarsOpac', 1 );
138 # checkauth will redirect and safe_exit if not authenticated and not authorized
141 open STDOUT, '>', \$stdout;
143 # Password has expired
144 $password_expired = 1;
145 C4::Auth::checkauth( $cgi, 0, { catalogue => 1 } );
146 like( $stdout, qr{'password_has_expired' => 1}, 'password_has_expired is set to 1' );
152 subtest 'While still logged in, relogin with another user' => sub {
155 my $patron = $builder->build_object({ class => 'Koha::Patrons', value => {} });
156 my $patron2 = $builder->build_object({ class => 'Koha::Patrons', value => {} });
157 # Create 'former' session
158 my $session = C4::Auth::get_session();
159 $session->param( 'number', $patron->id );
160 $session->param( 'id', $patron->userid );
161 $session->param( 'ip', '1.2.3.4' );
162 $session->param( 'lasttime', time() );
163 $session->param( 'interface', 'opac' );
165 my $sessionID = $session->id;
166 C4::Context->_new_userenv($sessionID);
168 my ( $return ) = C4::Auth::check_cookie_auth( $sessionID, undef, { skip_version_check => 1, remote_addr => '1.2.3.4' } );
169 is( $return, 'ok', 'Former session in shape now' );
171 my $mock1 = Test::MockModule->new('C4::Auth');
172 $mock1->mock( 'safe_exit', sub {} );
173 my $mock2 = Test::MockModule->new('CGI');
174 $mock2->mock( 'request_method', 'POST' );
175 $mock2->mock( 'cookie', sub { return $sessionID; } ); # oversimplified..
177 my $password = 'Incr3d1blyZtr@ng93$';
178 $patron2->set_password({ password => $password });
179 $cgi->param( -name => 'userid', -value => $patron2->userid );
180 $cgi->param( -name => 'password', -value => $password );
181 $cgi->param( -name => 'koha_login_context', -value => 1 );
182 my ( @return, $stdout );
186 $ENV{REMOTE_ADDR} = '1.2.3.4';
187 open STDOUT, '>', \$stdout;
188 @return = C4::Auth::checkauth( $cgi, 0, {} );
191 # Note: We can test return values from checkauth here since we mocked the safe_exit after the Redirect 303
192 is( $return[0], $patron2->userid, 'Login of patron2 approved' );
193 isnt( $return[2], $sessionID, 'Did not return previous session ID' );
194 ok( $return[2], 'New session ID not empty' );
196 # Similar situation: Relogin with former session of $patron, new user $patron2 has no permissions
197 $patron2->flags(undef)->store;
198 $session->param( 'number', $patron->id );
199 $session->param( 'id', $patron->userid );
200 $session->param( 'interface', 'intranet' );
202 $sessionID = $session->id;
203 C4::Context->_new_userenv($sessionID);
204 $cgi->param( -name => 'userid', -value => $patron2->userid );
205 $cgi->param( -name => 'password', -value => $password );
206 $cgi->param( -name => 'koha_login_context', -value => 1 );
210 $ENV{REMOTE_ADDR} = '1.2.3.4';
212 open STDOUT, '>', \$stdout;
213 @return = C4::Auth::checkauth( $cgi, 0, { catalogue => 1 }, 'intranet' ); # patron2 has no catalogue perm
216 like( $stdout, qr/You do not have permission to access this page/, 'No permission response' );
217 is( @return, 0, 'checkauth returned failure' );
220 subtest 'Two-factor authentication' => sub {
223 my $patron = $builder->build_object(
224 { class => 'Koha::Patrons', value => { flags => 1 } } );
225 my $password = 'password';
226 $patron->set_password( { password => $password } );
227 $cgi = Test::MockObject->new();
230 our ( $logout, $sessionID, $verified );
234 my ( $self, $param ) = @_;
235 if ( $param eq 'userid' ) { return $patron->userid; }
236 elsif ( $param eq 'password' ) { return $password; }
237 elsif ( $param eq 'otp_token' ) { return $otp_token; }
238 elsif ( $param eq 'logout.x' ) { return $logout; }
242 $cgi->mock( 'request_method', sub { return 'POST' } );
243 $cgi->mock( 'cookie', sub { return $sessionID } );
245 my $two_factor_auth = Test::MockModule->new( 'Koha::Auth::TwoFactorAuth' );
246 $two_factor_auth->mock( 'verify', sub {$verified} );
248 my ( $userid, $cookie, $flags );
249 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired', undef, 'intranet' );
255 C4::Auth::checkauth( $cgi, 'authrequired', undef, 'intranet' );
259 t::lib::Mocks::mock_preference( 'TwoFactorAuthentication', 'disabled' );
260 $patron->auth_method('password')->store;
261 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired', undef, 'intranet' );
262 is( $userid, $patron->userid, 'Succesful login' );
263 is( C4::Auth::get_session($sessionID)->param('waiting-for-2FA'), undef, 'Second auth not required' );
266 $patron->auth_method('two-factor')->store;
267 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired', undef, 'intranet' );
268 is( $userid, $patron->userid, 'Succesful login' );
269 is( C4::Auth::get_session($sessionID)->param('waiting-for-2FA'), undef, 'Second auth not required' );
272 t::lib::Mocks::mock_preference( 'TwoFactorAuthentication', 'enabled' );
273 t::lib::Mocks::mock_config('encryption_key', '1234tH1s=t&st');
274 $patron->auth_method('password')->store;
275 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired', undef, 'intranet' );
276 is( $userid, $patron->userid, 'Succesful login' );
277 is( C4::Auth::get_session($sessionID)->param('waiting-for-2FA'), undef, 'Second auth not required' );
280 $patron->encode_secret('one_secret');
281 $patron->auth_method('two-factor');
283 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired', undef, 'intranet' );
284 is( $userid, $patron->userid, 'Succesful login' );
285 my $session = C4::Auth::get_session($sessionID);
286 is( C4::Auth::get_session($sessionID)->param('waiting-for-2FA'), 1, 'Second auth required' );
289 $otp_token = "wrong";
291 $patron->auth_method('two-factor')->store;
292 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired', undef, 'intranet' );
293 is( $userid, $patron->userid, 'Succesful login' );
294 is( C4::Auth::get_session($sessionID)->param('waiting-for-2FA'), 1, 'Second auth still required after wrong OTP token' );
298 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired', undef, 'intranet' );
299 is( $userid, $patron->userid, 'Succesful login' );
300 is( C4::Auth::get_session($sessionID)->param('waiting-for-2FA'), 0, 'Second auth no longer required if OTP token has been verified' );
303 t::lib::Mocks::mock_preference( 'TwoFactorAuthentication', 'enforced' );
304 $patron->auth_method('password')->store;
305 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired', undef, 'intranet' );
306 is( $userid, $patron->userid, 'Succesful login' );
307 is( C4::Auth::get_session($sessionID)->param('waiting-for-2FA-setup'), 1, 'Setup 2FA required' );
310 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired', undef, 'opac' );
311 is( $userid, $patron->userid, 'Succesful login at the OPAC' );
312 is( C4::Auth::get_session($sessionID)->param('waiting-for-2FA'), undef, 'No second auth required at the OPAC' );
315 t::lib::Mocks::mock_preference( 'TwoFactorAuthentication', 'disabled' );
316 $session = C4::Auth::get_session($sessionID);
317 $session->param('waiting-for-2FA', 1);
319 my ($auth_status, undef ) = C4::Auth::check_cookie_auth($sessionID, undef );
320 is( $auth_status, 'ok', 'User authenticated, pref was disabled, access OK' );
321 $session->param('waiting-for-2FA', 0);
322 $session->param('waiting-for-2FA-setup', 1);
324 ($auth_status, undef ) = C4::Auth::check_cookie_auth($sessionID, undef );
325 is( $auth_status, 'ok', 'User waiting for 2FA setup, pref was disabled, access OK' );
328 subtest 'loggedinlibrary permission tests' => sub {
331 my $staff_user = $builder->build_object(
332 { class => 'Koha::Patrons', value => { flags => 536870916 } } );
334 my $branch = $builder->build_object({ class => 'Koha::Libraries' });
336 my $password = 'password';
337 t::lib::Mocks::mock_preference( 'RequireStrongPassword', 0 );
338 $staff_user->set_password( { password => $password } );
339 my $cgi = Test::MockObject->new();
340 $cgi->mock( 'cookie', sub { return; } );
344 my ( $self, $param ) = @_;
345 if ( $param eq 'userid' ) { return $staff_user->userid; }
346 elsif ( $param eq 'password' ) { return $password; }
347 elsif ( $param eq 'branch' ) { return $branch->branchcode; }
352 $cgi->mock( 'request_method', sub { return 'POST' } );
353 my ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired' );
354 my $sesh = C4::Auth::get_session($sessionID);
355 is( $sesh->param('branch'), $branch->branchcode, "If user has permission, they should be able to choose a branch" );
357 $staff_user->flags(4)->store->discard_changes;
358 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired' );
359 $sesh = C4::Auth::get_session($sessionID);
360 is( $sesh->param('branch'), $staff_user->branchcode, "If user has not permission, they should not be able to choose a branch" );
362 $staff_user->flags(1)->store->discard_changes;
363 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired' );
364 $sesh = C4::Auth::get_session($sessionID);
365 is( $sesh->param('branch'), $branch->branchcode, "If user is superlibrarian, they should be able to choose a branch" );
368 C4::Context->_new_userenv; # For next tests
371 subtest 'track_login_daily tests' => sub {
375 my $patron = $builder->build_object({ class => 'Koha::Patrons' });
376 my $userid = $patron->userid;
378 $patron->lastseen( undef );
381 my $cache = Koha::Caches->get_instance();
382 my $cache_key = "track_login_" . $patron->userid;
383 $cache->clear_from_cache($cache_key);
385 t::lib::Mocks::mock_preference( 'TrackLastPatronActivity', '1' );
387 is( $patron->lastseen, undef, 'Patron should have not last seen when newly created' );
389 C4::Auth::track_login_daily( $userid );
390 $patron->_result()->discard_changes();
391 isnt( $patron->lastseen, undef, 'Patron should have last seen set when TrackLastPatronActivity = 1' );
393 sleep(1); # We need to wait a tiny bit to make sure the timestamp will be different
394 my $last_seen = $patron->lastseen;
395 C4::Auth::track_login_daily( $userid );
396 $patron->_result()->discard_changes();
397 is( $patron->lastseen, $last_seen, 'Patron last seen should still be unchanged' );
399 $cache->clear_from_cache($cache_key);
400 C4::Auth::track_login_daily( $userid );
401 $patron->_result()->discard_changes();
402 isnt( $patron->lastseen, $last_seen, 'Patron last seen should be changed if we cleared the cache' );
404 t::lib::Mocks::mock_preference( 'TrackLastPatronActivity', '0' );
405 $patron->lastseen( undef )->store;
406 $cache->clear_from_cache($cache_key);
407 C4::Auth::track_login_daily( $userid );
408 $patron->_result()->discard_changes();
409 is( $patron->lastseen, undef, 'Patron should still have last seen unchanged when TrackLastPatronActivity = 0' );
413 subtest 'no_set_userenv parameter tests' => sub {
417 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
418 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
419 my $password = 'password';
421 t::lib::Mocks::mock_preference( 'RequireStrongPassword', 0 );
422 $patron->set_password({ password => $password });
424 ok( checkpw( $patron->userid, $password, undef, undef, 1 ), 'checkpw returns true' );
425 is( C4::Context->userenv, undef, 'Userenv should be undef as required' );
426 C4::Context->_new_userenv('DUMMY SESSION');
427 C4::Context->set_userenv(0,0,0,'firstname','surname', $library->branchcode, 'Library 1', 0, '', '');
428 is( C4::Context->userenv->{branch}, $library->branchcode, 'Userenv gives correct branch' );
429 ok( checkpw( $patron->userid, $password, undef, undef, 1 ), 'checkpw returns true' );
430 is( C4::Context->userenv->{branch}, $library->branchcode, 'Userenv branch is preserved if no_set_userenv is true' );
431 ok( checkpw( $patron->userid, $password, undef, undef, 0 ), 'checkpw still returns true' );
432 isnt( C4::Context->userenv->{branch}, $library->branchcode, 'Userenv branch is overwritten if no_set_userenv is false' );
435 subtest 'checkpw lockout tests' => sub {
439 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
440 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
441 my $password = 'password';
442 t::lib::Mocks::mock_preference( 'RequireStrongPassword', 0 );
443 t::lib::Mocks::mock_preference( 'FailedLoginAttempts', 1 );
444 $patron->set_password({ password => $password });
446 my ( $checkpw, undef, undef ) = checkpw( $patron->cardnumber, $password, undef, undef, 1 );
447 ok( $checkpw, 'checkpw returns true with right password when logging in via cardnumber' );
448 ( $checkpw, undef, undef ) = checkpw( $patron->userid, "wrong_password", undef, undef, 1 );
449 is( $checkpw, 0, 'checkpw returns false when given wrong password' );
450 $patron = $patron->get_from_storage;
451 is( $patron->account_locked, 1, "Account is locked from failed login");
452 ( $checkpw, undef, undef ) = checkpw( $patron->userid, $password, undef, undef, 1 );
453 is( $checkpw, undef, 'checkpw returns undef with right password when account locked' );
454 ( $checkpw, undef, undef ) = checkpw( $patron->cardnumber, $password, undef, undef, 1 );
455 is( $checkpw, undef, 'checkpw returns undefwith right password when logging in via cardnumber if account locked' );
459 # get_template_and_user tests
461 subtest 'get_template_and_user' => sub { # Tests for the language URL parameter
463 sub MockedCheckauth {
464 my ($query,$authnotrequired,$flagsrequired,$type) = @_;
466 my $userid = 'cobain';
468 # we don't need to bother about permissions for this test
470 superlibrarian => 1, acquisition => 0,
472 catalogue => 1, circulate => 0,
473 coursereserves => 0, editauthorities => 0,
475 parameters => 0, permissions => 0,
476 plugins => 0, reports => 0,
477 reserveforothers => 0, serials => 0,
478 staffaccess => 0, tools => 0,
482 my $session_cookie = $query->cookie(
483 -name => 'CGISESSID',
488 return ( $userid, [ $session_cookie ], $sessionID, $flags );
491 # Mock checkauth, build the scenario
492 my $auth = Test::MockModule->new( 'C4::Auth' );
493 $auth->mock( 'checkauth', \&MockedCheckauth );
495 # Make sure 'EnableOpacSearchHistory' is set
496 t::lib::Mocks::mock_preference('EnableOpacSearchHistory',1);
497 # Enable es-ES for the OPAC and staff interfaces
498 t::lib::Mocks::mock_preference('OPACLanguages','en,es-ES');
499 t::lib::Mocks::mock_preference('language','en,es-ES');
501 # we need a session cookie
502 $ENV{"SERVER_PORT"} = 80;
503 $ENV{"HTTP_COOKIE"} = 'CGISESSID=nirvana';
505 my $query = CGI->new;
506 $query->param('language','es-ES');
508 my ( $template, $loggedinuser, $cookies ) = get_template_and_user(
510 template_name => "about.tt",
513 authnotrequired => 1,
514 flagsrequired => { catalogue => 1 },
519 ok ( ( all { ref($_) eq 'CGI::Cookie' } @$cookies ),
520 'BZ9735: the cookies array is flat' );
522 # new query, with non-existent language (we only have en and es-ES)
523 $query->param('language','tomas');
525 ( $template, $loggedinuser, $cookies ) = get_template_and_user(
527 template_name => "about.tt",
530 authnotrequired => 1,
531 flagsrequired => { catalogue => 1 },
536 ok( ( none { $_->name eq 'KohaOpacLanguage' and $_->value eq 'tomas' } @$cookies ),
537 'BZ9735: invalid language, it is not set');
539 ok( ( any { $_->name eq 'KohaOpacLanguage' and $_->value eq 'en' } @$cookies ),
540 'BZ9735: invalid language, then default to en');
542 for my $template_name (
544 ../../../../../../../../../../../../../../../etc/passwd
545 test/../../../../../../../../../../../../../../etc/passwd
547 test/does_not_finished_by_tt_t
551 ( $template, $loggedinuser, $cookies ) = get_template_and_user(
553 template_name => $template_name,
556 authnotrequired => 1,
557 flagsrequired => { catalogue => 1 },
561 like ( $@, qr(bad template path), "The file $template_name should not be accessible" );
563 ( $template, $loggedinuser, $cookies ) = get_template_and_user(
565 template_name => 'errors/errorpage.tt',
568 authnotrequired => 1,
569 flagsrequired => { catalogue => 1 },
572 my $file_exists = ( -f $template->{filename} ) ? 1 : 0;
573 is ( $file_exists, 1, 'The file errors/errorpage.tt should be accessible (contains integers)' );
575 # Regression test for env opac search limit override
576 $ENV{"OPAC_SEARCH_LIMIT"} = "branch:CPL";
577 $ENV{"OPAC_LIMIT_OVERRIDE"} = 1;
579 ( $template, $loggedinuser, $cookies) = get_template_and_user(
581 template_name => 'opac-main.tt',
584 authnotrequired => 1,
587 is($template->{VARS}->{'opac_name'}, "CPL", "Opac name was set correctly");
588 is($template->{VARS}->{'opac_search_limit'}, "branch:CPL", "Search limit was set correctly");
590 $ENV{"OPAC_SEARCH_LIMIT"} = "branch:multibranch-19";
592 ( $template, $loggedinuser, $cookies) = get_template_and_user(
594 template_name => 'opac-main.tt',
597 authnotrequired => 1,
600 is($template->{VARS}->{'opac_name'}, "multibranch-19", "Opac name was set correctly");
601 is($template->{VARS}->{'opac_search_limit'}, "branch:multibranch-19", "Search limit was set correctly");
603 delete $ENV{"HTTP_COOKIE"};
606 # Check that there is always an OPACBaseURL set.
607 my $input = CGI->new();
608 my ( $template1, $borrowernumber, $cookie );
609 ( $template1, $borrowernumber, $cookie ) = get_template_and_user(
611 template_name => "opac-detail.tt",
614 authnotrequired => 1,
618 ok( ( any { 'OPACBaseURL' eq $_ } keys %{$template1->{VARS}} ),
619 'OPACBaseURL is in OPAC template' );
622 ( $template2, $borrowernumber, $cookie ) = get_template_and_user(
624 template_name => "catalogue/detail.tt",
627 authnotrequired => 1,
631 ok( ( any { 'OPACBaseURL' eq $_ } keys %{$template2->{VARS}} ),
632 'OPACBaseURL is in Staff template' );
634 my $hash1 = hash_password('password');
635 my $hash2 = hash_password('password');
637 ok(C4::Auth::checkpw_hash('password', $hash1), 'password validates with first hash');
638 ok(C4::Auth::checkpw_hash('password', $hash2), 'password validates with second hash');
640 subtest 'Check value of login_attempts in checkpw' => sub {
643 t::lib::Mocks::mock_preference('FailedLoginAttempts', 3);
645 # Only interested here in regular login
649 my $patron = $builder->build_object({ class => 'Koha::Patrons' });
650 $patron->login_attempts(2);
651 $patron->password('123')->store; # yes, deliberately not hashed
653 is( $patron->account_locked, 0, 'Patron not locked' );
654 my @test = checkpw( $patron->userid, '123', undef, 'opac', 1 );
655 # Note: 123 will not be hashed to 123 !
656 is( $test[0], 0, 'checkpw should have failed' );
657 $patron->discard_changes; # refresh
658 is( $patron->login_attempts, 3, 'Login attempts increased' );
659 is( $patron->account_locked, 1, 'Check locked status' );
661 # And another try to go over the limit: different return value!
662 @test = checkpw( $patron->userid, '123', undef, 'opac', 1 );
663 is( @test, 0, 'checkpw failed again and returns nothing now' );
664 $patron->discard_changes; # refresh
665 is( $patron->login_attempts, 3, 'Login attempts not increased anymore' );
667 # Administrative lockout cannot be undone?
668 # Pass the right password now (or: add a nice mock).
669 my $auth = Test::MockModule->new( 'C4::Auth' );
670 $auth->mock( 'checkpw_hash', sub { return 1; } ); # not for production :)
671 $patron->login_attempts(0)->store;
672 @test = checkpw( $patron->userid, '123', undef, 'opac', 1 );
673 is( $test[0], 1, 'Build confidence in the mock' );
674 $patron->login_attempts(-1)->store;
675 is( $patron->account_locked, 1, 'Check administrative lockout' );
676 @test = checkpw( $patron->userid, '123', undef, 'opac', 1 );
677 is( @test, 0, 'checkpw gave red' );
678 $patron->discard_changes; # refresh
679 is( $patron->login_attempts, -1, 'Still locked out' );
680 t::lib::Mocks::mock_preference('FailedLoginAttempts', ''); # disable
681 is( $patron->account_locked, 1, 'Check administrative lockout without pref' );
684 subtest 'Check value of login_attempts in checkpw' => sub {
687 t::lib::Mocks::mock_preference('FailedLoginAttempts', 3);
688 my $patron = $builder->build_object({ class => 'Koha::Patrons' });
689 $patron->set_password({ password => '123', skip_validation => 1 });
691 my @test = checkpw( $patron->userid, '123', undef, 'opac', 1 );
692 is( $test[0], 1, 'Patron authenticated correctly' );
694 $patron->password_expiration_date('2020-01-01')->store;
695 @test = checkpw( $patron->userid, '123', undef, 'opac', 1 );
696 is( $test[0], -2, 'Patron returned as expired correctly' );
700 subtest '_timeout_syspref' => sub {
704 t::lib::Mocks::mock_preference('timeout', "100");
705 is( C4::Auth::_timeout_syspref, 100, );
707 t::lib::Mocks::mock_preference('timeout', "2d");
708 is( C4::Auth::_timeout_syspref, 2*86400, );
710 t::lib::Mocks::mock_preference('timeout', "2D");
711 is( C4::Auth::_timeout_syspref, 2*86400, );
713 t::lib::Mocks::mock_preference('timeout', "10h");
714 is( C4::Auth::_timeout_syspref, 10*3600, );
716 t::lib::Mocks::mock_preference('timeout', "10x");
718 { is( C4::Auth::_timeout_syspref, 600, ); }
719 "The value of the system preference 'timeout' is not correct, defaulting to 600",
720 'Bad values throw a warning and fallback to 600';
723 subtest 'check_cookie_auth' => sub {
726 t::lib::Mocks::mock_preference('timeout', "1d"); # back to default
728 my $patron = $builder->build_object({ class => 'Koha::Patrons', value => { flags => 1 } });
730 # Mock a CGI object with real userid param
731 my $cgi = Test::MockObject->new();
736 if ( $var eq 'userid' ) { return $patron->userid; }
739 $cgi->mock('multi_param', sub {return q{}} );
740 $cgi->mock( 'cookie', sub { return; } );
741 $cgi->mock( 'request_method', sub { return 'POST' } );
743 $ENV{REMOTE_ADDR} = '127.0.0.1';
745 # Setting authnotrequired=1 or we wont' hit the return but the end of the sub that prints headers
746 my ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 1 );
748 my ($auth_status, $session) = C4::Auth::check_cookie_auth($sessionID);
749 isnt( $auth_status, 'ok', 'check_cookie_auth should not return ok if the user has not been authenticated before if no permissions needed' );
750 is( $auth_status, 'anon', 'check_cookie_auth should return anon if the user has not been authenticated before and no permissions needed' );
752 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 1 );
754 ($auth_status, $session) = C4::Auth::check_cookie_auth($sessionID, {catalogue => 1});
755 isnt( $auth_status, 'ok', 'check_cookie_auth should not return ok if the user has not been authenticated before and permissions needed' );
756 is( $auth_status, 'anon', 'check_cookie_auth should return anon if the user has not been authenticated before and permissions needed' );
758 #FIXME We should have a test to cover 'failed' status when a user has logged in, but doesn't have permission
761 subtest 'checkauth & check_cookie_auth' => sub {
764 # flags = 4 => { catalogue => 1 }
765 my $patron = $builder->build_object({ class => 'Koha::Patrons', value => { flags => 4 } });
766 my $password = 'password';
767 t::lib::Mocks::mock_preference( 'RequireStrongPassword', 0 );
768 $patron->set_password( { password => $password } );
770 my $cgi_mock = Test::MockModule->new('CGI');
771 $cgi_mock->mock( 'request_method', sub { return 'POST' } );
775 my $auth = Test::MockModule->new( 'C4::Auth' );
776 # Tests will fail if we hit safe_exit
777 $auth->mock( 'safe_exit', sub { return } );
779 my ( $userid, $cookie, $sessionID, $flags );
781 # checkauth will redirect and safe_exit if not authenticated and not authorized
784 open STDOUT, '>', \$stdout;
785 C4::Auth::checkauth($cgi, 0, {catalogue => 1});
786 like( $stdout, qr{<title>\s*Log in to your account} );
787 $sessionID = ( $stdout =~ m{Set-Cookie: CGISESSID=((\d|\w)+);} ) ? $1 : undef;
792 my $first_sessionID = $sessionID;
794 $ENV{"HTTP_COOKIE"} = "CGISESSID=$sessionID";
795 # Not authenticated yet, checkauth didn't return the session
799 open STDOUT, '>', \$stdout;
800 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 0, {catalogue => 1} );
803 is( $sessionID, undef);
806 # Sending undefined fails obviously
807 my ( $auth_status, $session ) = C4::Auth::check_cookie_auth($sessionID, {catalogue => 1} );
808 is( $auth_status, 'failed' );
809 is( $session, undef );
811 # Simulating the login form submission
812 $cgi->param('userid', $patron->userid);
813 $cgi->param('password', $password);
816 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 0, {catalogue => 1});
817 is( $sessionID, $first_sessionID );
818 is( $userid, $patron->userid );
820 ( $auth_status, $session ) = C4::Auth::check_cookie_auth($sessionID, {catalogue => 1});
821 is( $auth_status, 'ok' );
822 is( $session->id, $first_sessionID );
824 my $patron_to_delete = $builder->build_object({ class => 'Koha::Patrons' });
825 my $fresh_userid = $patron_to_delete->userid;
826 $patron_to_delete->delete;
827 my $old_userid = $patron->userid;
829 # change the current session user's userid
830 $patron->userid( $fresh_userid )->store;
831 ( $auth_status, $session ) = C4::Auth::check_cookie_auth($sessionID, {catalogue => 1});
832 is( $auth_status, 'expired' );
833 is( $session, undef );
835 # restore userid and generate a new session
836 $patron->userid($old_userid)->store;
837 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 0, {catalogue => 1});
838 is( $sessionID, $first_sessionID );
839 is( $userid, $patron->userid );
842 $cgi->param('logout.x', 1);
843 $cgi->delete( 'userid', 'password' );
847 open STDOUT, '>', \$stdout;
848 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 0, {catalogue => 1});
851 is( $sessionID, undef );
852 is( $ENV{"HTTP_COOKIE"}, "CGISESSID=$first_sessionID", 'HTTP_COOKIE not unset' );
853 ( $auth_status, $session) = C4::Auth::check_cookie_auth( $first_sessionID, {catalogue => 1} );
854 is( $auth_status, "expired");
855 is( $session, undef );
858 # Trying to access without sessionID
860 ( $auth_status, $session) = C4::Auth::check_cookie_auth(undef, {catalogue => 1});
861 is( $auth_status, 'failed' );
862 is( $session, undef );
864 # This will fail on permissions
865 undef $ENV{"HTTP_COOKIE"};
869 open STDOUT, '>', \$stdout;
870 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 0, {catalogue => 1} );
873 is( $userid, undef );
874 is( $sessionID, undef );
880 $cgi->param('userid', $patron->userid);
881 $cgi->param('password', $password);
882 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 0, {catalogue => 1});
883 is( $userid, $patron->userid );
884 $first_sessionID = $sessionID;
886 # Patron does not have the borrowers permission
887 # $ENV{"HTTP_COOKIE"} = "CGISESSID=$sessionID"; # not needed, we use $cgi here
891 open STDOUT, '>', \$stdout;
892 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 0, {borrowers => 1} );
895 is( $userid, undef );
896 is( $sessionID, undef );
898 # When calling check_cookie_auth, the session will be deleted
899 ( $auth_status, $session) = C4::Auth::check_cookie_auth( $first_sessionID, { borrowers => 1 } );
900 is( $auth_status, "failed" );
901 is( $session, undef );
902 ( $auth_status, $session) = C4::Auth::check_cookie_auth( $first_sessionID, { borrowers => 1 } );
903 is( $auth_status, 'expired', 'Session no longer exists' );
905 # NOTE: It is not what the UI is doing.
906 # From the UI we are allowed to hit an unauthorized page then reuse the session to hit back authorized area.
907 # It is because check_cookie_auth is ALWAYS called from checkauth WITHOUT $flagsrequired
908 # It then return "ok", when the previous called got "failed"
910 # Try reusing the deleted session: since it does not exist, we should get a new one now when passing correct permissions
911 $cgi->cookie( -name => 'CGISESSID', value => $first_sessionID );
912 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 0, {catalogue => 1});
913 is( $userid, $patron->userid );
914 isnt( $sessionID, undef, 'Check if we have a sessionID' );
915 isnt( $sessionID, $first_sessionID, 'New value expected' );
916 ( $auth_status, $session) = C4::Auth::check_cookie_auth( $sessionID, {catalogue => 1} );
917 is( $auth_status, "ok" );
918 is( $session->id, $sessionID, 'Same session' );
919 # Two additional tests on userenv
920 is( $C4::Context::context->{activeuser}, $session->id, 'Check if environment has been setup for session' );
921 is( C4::Context->userenv->{id}, $userid, 'Check userid in userenv' );
925 subtest 'Userenv clearing in check_cookie_auth' => sub {
926 # Note: We did already test userenv for a logged-in user in previous subtest
929 t::lib::Mocks::mock_preference( 'timeout', 600 );
932 # Create a new anonymous session by passing a fake session ID
933 $cgi->cookie( -name => 'CGISESSID', -value => 'fake_sessionID' );
934 my ($userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 1);
935 my ( $auth_status, $session) = C4::Auth::check_cookie_auth( $sessionID );
936 is( $auth_status, 'anon', 'Should be anonymous' );
937 is( $C4::Context::context->{activeuser}, $session->id, 'Check activeuser' );
938 is( defined C4::Context->userenv, 1, 'There should be a userenv' );
939 is( C4::Context->userenv->{id}, q{}, 'userid should be empty string' );
941 # Make the session expire now, check_cookie_auth will delete it
942 $session->param('lasttime', time() - 1200 );
944 ( $auth_status, $session) = C4::Auth::check_cookie_auth( $sessionID );
945 is( $auth_status, 'expired', 'Should be expired' );
946 is( C4::Context->userenv, undef, 'Environment should be cleared too' );
948 # Show that we clear the userenv again: set up env and check deleted session
949 C4::Context->_new_userenv( $sessionID );
950 C4::Context->set_userenv; # empty
951 is( defined C4::Context->userenv, 1, 'There should be an empty userenv again' );
952 ( $auth_status, $session) = C4::Auth::check_cookie_auth( $sessionID );
953 is( $auth_status, 'expired', 'Should be expired already' );
954 is( C4::Context->userenv, undef, 'Environment should be cleared again' );
957 subtest 'create_basic_session tests' => sub {
960 my $patron = $builder->build_object({ class => 'Koha::Patrons' });
962 my $session = C4::Auth::create_basic_session({ patron => $patron, interface => 'opac' });
964 isnt($session->id, undef, 'A new sessionID was created');
965 is( $session->param('number'), $patron->borrowernumber, 'Session parameter number matches' );
966 is( $session->param('id'), $patron->userid, 'Session parameter id matches' );
967 is( $session->param('cardnumber'), $patron->cardnumber, 'Session parameter cardnumber matches' );
968 is( $session->param('firstname'), $patron->firstname, 'Session parameter firstname matches' );
969 is( $session->param('surname'), $patron->surname, 'Session parameter surname matches' );
970 is( $session->param('branch'), $patron->branchcode, 'Session parameter branch matches' );
971 is( $session->param('branchname'), $patron->library->branchname, 'Session parameter branchname matches' );
972 is( $session->param('flags'), $patron->flags, 'Session parameter flags matches' );
973 is( $session->param('emailaddress'), $patron->email, 'Session parameter emailaddress matches' );
974 is( $session->param('ip'), $session->remote_addr(), 'Session parameter ip matches' );
975 is( $session->param('interface'), 'opac', 'Session parameter interface matches' );
977 $session = C4::Auth::create_basic_session({ patron => $patron, interface => 'staff' });
978 is( $session->param('interface'), 'intranet', 'Staff interface gets converted to intranet' );
981 subtest 'check_cookie_auth overwriting interface already set' => sub {
984 t::lib::Mocks::mock_preference( 'SessionRestrictionByIP', 0 );
986 my $patron = $builder->build_object({ class => 'Koha::Patrons' });
987 my $session = C4::Auth::get_session();
988 $session->param( 'number', $patron->id );
989 $session->param( 'id', $patron->userid );
990 $session->param( 'ip', '1.2.3.4' );
991 $session->param( 'lasttime', time() );
992 $session->param( 'interface', 'opac' );
995 C4::Context->interface('intranet');
996 C4::Auth::check_cookie_auth( $session->id );
997 is( C4::Context->interface, 'intranet', 'check_cookie_auth did not overwrite' );
998 delete $C4::Context::context->{interface}; # clear context interface
999 C4::Auth::check_cookie_auth( $session->id );
1000 is( C4::Context->interface, 'opac', 'check_cookie_auth used interface from session when context interface was empty' );
1002 t::lib::Mocks::mock_preference( 'SessionRestrictionByIP', 1 );
1005 $schema->storage->txn_rollback;