3 # This Koha test module is a stub!
4 # Add more tests here!!!
12 use List::MoreUtils qw/all any none/;
13 use Test::More tests => 17;
16 use t::lib::TestBuilder;
20 use Koha::AuthUtils qw/hash_password/;
23 use Koha::Auth::TwoFactorAuth;
26 use_ok('C4::Auth', qw( checkauth haspermission track_login_daily checkpw get_template_and_user checkpw_hash ));
29 my $schema = Koha::Database->schema;
30 my $builder = t::lib::TestBuilder->new;
32 # FIXME: SessionStorage defaults to mysql, but it seems to break transaction
34 t::lib::Mocks::mock_preference( 'SessionStorage', 'tmp' );
35 t::lib::Mocks::mock_preference( 'GDPR_Policy', '' ); # Disabled
37 # To silence useless warnings
38 $ENV{REMOTE_ADDR} = '127.0.0.1';
40 $schema->storage->txn_begin;
42 subtest 'checkauth() tests' => sub {
46 my $patron = $builder->build_object({ class => 'Koha::Patrons', value => { flags => undef } });
48 # Mock a CGI object with real userid param
49 my $cgi = Test::MockObject->new();
54 if ( $var eq 'userid' ) { return $patron->userid; }
57 $cgi->mock( 'cookie', sub { return; } );
58 $cgi->mock( 'request_method', sub { return 'POST' } );
60 my $authnotrequired = 1;
61 my ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, $authnotrequired );
63 is( $userid, undef, 'checkauth() returns undef for userid if no logged in user (Bug 18275)' );
65 my $db_user_id = C4::Context->config('user');
66 my $db_user_pass = C4::Context->config('pass');
67 $cgi = Test::MockObject->new();
68 $cgi->mock( 'cookie', sub { return; } );
69 $cgi->mock( 'param', sub {
70 my ( $self, $param ) = @_;
71 if ( $param eq 'userid' ) { return $db_user_id; }
72 elsif ( $param eq 'password' ) { return $db_user_pass; }
75 $cgi->mock( 'request_method', sub { return 'POST' } );
76 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, $authnotrequired );
77 is ( $userid, undef, 'If DB user is used, it should not be logged in' );
79 my $is_allowed = C4::Auth::haspermission( $db_user_id, { can_do => 'everything' } );
81 # FIXME This belongs to t/db_dependent/Auth/haspermission.t but we do not want to c/p the pervious mock statements
82 ok( !$is_allowed, 'DB user should not have any permissions');
84 subtest 'Prevent authentication when sending credential via GET' => sub {
88 my $patron = $builder->build_object(
89 { class => 'Koha::Patrons', value => { flags => 1 } } );
90 my $password = 'password';
91 t::lib::Mocks::mock_preference( 'RequireStrongPassword', 0 );
92 $patron->set_password( { password => $password } );
93 $cgi = Test::MockObject->new();
94 $cgi->mock( 'cookie', sub { return; } );
98 my ( $self, $param ) = @_;
99 if ( $param eq 'userid' ) { return $patron->userid; }
100 elsif ( $param eq 'password' ) { return $password; }
105 $cgi->mock( 'request_method', sub { return 'POST' } );
106 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired' );
107 is( $userid, $patron->userid, 'If librarian user is used and password with POST, they should be logged in' );
109 $cgi->mock( 'request_method', sub { return 'GET' } );
110 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired' );
111 is( $userid, undef, 'If librarian user is used and password with GET, they should not be logged in' );
114 subtest 'Template params tests (password_expired)' => sub {
118 my $password_expired;
120 my $patron_class = Test::MockModule->new('Koha::Patron');
121 $patron_class->mock( 'password_expired', sub { return $password_expired; } );
123 my $patron = $builder->build_object({ class => 'Koha::Patrons', value => { flags => 1 } });
124 my $password = 'password';
125 t::lib::Mocks::mock_preference( 'RequireStrongPassword', 0 );
126 $patron->set_password( { password => $password } );
128 my $cgi_mock = Test::MockModule->new('CGI')->mock( 'request_method', 'POST' );
130 $cgi->param( -name => 'userid', -value => $patron->userid );
131 $cgi->param( -name => 'password', -value => $password );
133 my $auth = Test::MockModule->new( 'C4::Auth' );
134 # Tests will fail if we hit safe_exit
135 $auth->mock( 'safe_exit', sub { return } );
137 my ( $userid, $cookie, $sessionID, $flags );
140 t::lib::Mocks::mock_preference( 'DumpTemplateVarsOpac', 1 );
141 # checkauth will redirect and safe_exit if not authenticated and not authorized
144 open STDOUT, '>', \$stdout;
146 # Password has expired
147 $password_expired = 1;
148 C4::Auth::checkauth( $cgi, 0, { catalogue => 1 } );
149 like( $stdout, qr{'password_has_expired' => 1}, 'password_has_expired is set to 1' );
155 subtest 'Reset auth state when changing users' => sub {
157 #NOTE: It's easiest to detect this when changing to a non-existent user, since
158 #that should trigger a redirect to login (instead of returning a session cookie)
160 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { flags => undef } } );
162 my $session = C4::Auth::get_session();
163 $session->param( 'number', $patron->id );
164 $session->param( 'id', $patron->userid );
165 $session->param( 'ip', '1.2.3.4' );
166 $session->param( 'lasttime', time() );
167 $session->param( 'interface', 'intranet' );
169 my $sessionID = $session->id;
170 C4::Context->_new_userenv($sessionID);
173 C4::Auth::check_cookie_auth( $sessionID, undef, { skip_version_check => 1, remote_addr => '1.2.3.4' } );
174 is( $return, 'ok', 'Patron authenticated' );
176 my $mock1 = Test::MockModule->new('C4::Auth');
177 $mock1->mock( 'safe_exit', sub { return 'safe_exit_redirect' } );
178 my $mock2 = Test::MockModule->new('CGI');
179 $mock2->mock( 'request_method', 'POST' );
180 $mock2->mock( 'cookie', sub { return $sessionID; } ); # oversimplified..
183 $cgi->param( -name => 'userid', -value => 'Bond' );
184 $cgi->param( -name => 'password', -value => 'James Bond' );
185 $cgi->param( -name => 'koha_login_context', -value => 1 );
186 my ( @return, $stdout );
190 $ENV{REMOTE_ADDR} = '1.2.3.4';
191 open STDOUT, '>', \$stdout;
192 @return = C4::Auth::checkauth( $cgi, 0, {} );
195 is( $return[0], 'safe_exit_redirect', 'Changing to non-existent user causes a redirect to login' );
199 subtest 'While still logged in, relogin with another user' => sub {
202 my $patron = $builder->build_object({ class => 'Koha::Patrons', value => {} });
203 my $patron2 = $builder->build_object({ class => 'Koha::Patrons', value => {} });
204 # Create 'former' session
205 my $session = C4::Auth::get_session();
206 $session->param( 'number', $patron->id );
207 $session->param( 'id', $patron->userid );
208 $session->param( 'ip', '1.2.3.4' );
209 $session->param( 'lasttime', time() );
210 $session->param( 'interface', 'opac' );
212 my $sessionID = $session->id;
213 C4::Context->_new_userenv($sessionID);
215 my ( $return ) = C4::Auth::check_cookie_auth( $sessionID, undef, { skip_version_check => 1, remote_addr => '1.2.3.4' } );
216 is( $return, 'ok', 'Former session in shape now' );
218 my $mock1 = Test::MockModule->new('C4::Auth');
219 $mock1->mock( 'safe_exit', sub {} );
220 my $mock2 = Test::MockModule->new('CGI');
221 $mock2->mock( 'request_method', 'POST' );
222 $mock2->mock( 'cookie', sub { return $sessionID; } ); # oversimplified..
224 my $password = 'Incr3d1blyZtr@ng93$';
225 $patron2->set_password({ password => $password });
226 $cgi->param( -name => 'userid', -value => $patron2->userid );
227 $cgi->param( -name => 'password', -value => $password );
228 $cgi->param( -name => 'koha_login_context', -value => 1 );
229 my ( @return, $stdout );
233 $ENV{REMOTE_ADDR} = '1.2.3.4';
234 open STDOUT, '>', \$stdout;
235 @return = C4::Auth::checkauth( $cgi, 0, {} );
238 # Note: We can test return values from checkauth here since we mocked the safe_exit after the Redirect 303
239 is( $return[0], $patron2->userid, 'Login of patron2 approved' );
240 isnt( $return[2], $sessionID, 'Did not return previous session ID' );
241 ok( $return[2], 'New session ID not empty' );
243 # Similar situation: Relogin with former session of $patron, new user $patron2 has no permissions
244 $patron2->flags(undef)->store;
245 $session->param( 'number', $patron->id );
246 $session->param( 'id', $patron->userid );
247 $session->param( 'interface', 'intranet' );
249 $sessionID = $session->id;
250 C4::Context->_new_userenv($sessionID);
251 $cgi->param( -name => 'userid', -value => $patron2->userid );
252 $cgi->param( -name => 'password', -value => $password );
253 $cgi->param( -name => 'koha_login_context', -value => 1 );
257 $ENV{REMOTE_ADDR} = '1.2.3.4';
259 open STDOUT, '>', \$stdout;
260 @return = C4::Auth::checkauth( $cgi, 0, { catalogue => 1 }, 'intranet' ); # patron2 has no catalogue perm
263 like( $stdout, qr/You do not have permission to access this page/, 'No permission response' );
264 is( @return, 0, 'checkauth returned failure' );
267 subtest 'Two-factor authentication' => sub {
269 my $patron = $builder->build_object(
270 { class => 'Koha::Patrons', value => { flags => 1 } } );
271 my $password = 'password';
272 $patron->set_password( { password => $password } );
273 $cgi = Test::MockObject->new();
276 our ( $logout, $sessionID, $verified );
280 my ( $self, $param ) = @_;
281 if ( $param eq 'userid' ) { return $patron->userid; }
282 elsif ( $param eq 'password' ) { return $password; }
283 elsif ( $param eq 'otp_token' ) { return $otp_token; }
284 elsif ( $param eq 'logout.x' ) { return $logout; }
288 $cgi->mock( 'request_method', sub { return 'POST' } );
289 $cgi->mock( 'cookie', sub { return $sessionID } );
291 my $two_factor_auth = Test::MockModule->new( 'Koha::Auth::TwoFactorAuth' );
292 $two_factor_auth->mock( 'verify', sub {$verified} );
294 my ( $userid, $cookie, $flags );
295 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired', undef, 'intranet' );
301 C4::Auth::checkauth( $cgi, 'authrequired', undef, 'intranet' );
305 t::lib::Mocks::mock_preference( 'TwoFactorAuthentication', 0 );
306 $patron->auth_method('password')->store;
307 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired', undef, 'intranet' );
308 is( $userid, $patron->userid, 'Succesful login' );
309 is( C4::Auth::get_session($sessionID)->param('waiting-for-2FA'), undef, 'Second auth not required' );
312 $patron->auth_method('two-factor')->store;
313 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired', undef, 'intranet' );
314 is( $userid, $patron->userid, 'Succesful login' );
315 is( C4::Auth::get_session($sessionID)->param('waiting-for-2FA'), undef, 'Second auth not required' );
318 t::lib::Mocks::mock_preference( 'TwoFactorAuthentication', 1 );
319 t::lib::Mocks::mock_config('encryption_key', '1234tH1s=t&st');
320 $patron->auth_method('password')->store;
321 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired', undef, 'intranet' );
322 is( $userid, $patron->userid, 'Succesful login' );
323 is( C4::Auth::get_session($sessionID)->param('waiting-for-2FA'), undef, 'Second auth not required' );
326 $patron->encode_secret('one_secret');
327 $patron->auth_method('two-factor');
329 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired', undef, 'intranet' );
330 is( $userid, $patron->userid, 'Succesful login' );
331 my $session = C4::Auth::get_session($sessionID);
332 is( C4::Auth::get_session($sessionID)->param('waiting-for-2FA'), 1, 'Second auth required' );
335 $otp_token = "wrong";
337 $patron->auth_method('two-factor')->store;
338 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired', undef, 'intranet' );
339 is( $userid, $patron->userid, 'Succesful login' );
340 is( C4::Auth::get_session($sessionID)->param('waiting-for-2FA'), 1, 'Second auth still required after wrong OTP token' );
344 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired', undef, 'intranet' );
345 is( $userid, $patron->userid, 'Succesful login' );
346 is( C4::Auth::get_session($sessionID)->param('waiting-for-2FA'), 0, 'Second auth no longer required if OTP token has been verified' );
349 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired', undef, 'opac' );
350 is( $userid, $patron->userid, 'Succesful login at the OPAC' );
351 is( C4::Auth::get_session($sessionID)->param('waiting-for-2FA'), undef, 'No second auth required at the OPAC' );
353 t::lib::Mocks::mock_preference( 'TwoFactorAuthentication', 0 );
356 C4::Context->_new_userenv; # For next tests
360 subtest 'track_login_daily tests' => sub {
364 my $patron = $builder->build_object({ class => 'Koha::Patrons' });
365 my $userid = $patron->userid;
367 $patron->lastseen( undef );
370 my $cache = Koha::Caches->get_instance();
371 my $cache_key = "track_login_" . $patron->userid;
372 $cache->clear_from_cache($cache_key);
374 t::lib::Mocks::mock_preference( 'TrackLastPatronActivity', '1' );
376 is( $patron->lastseen, undef, 'Patron should have not last seen when newly created' );
378 C4::Auth::track_login_daily( $userid );
379 $patron->_result()->discard_changes();
380 isnt( $patron->lastseen, undef, 'Patron should have last seen set when TrackLastPatronActivity = 1' );
382 sleep(1); # We need to wait a tiny bit to make sure the timestamp will be different
383 my $last_seen = $patron->lastseen;
384 C4::Auth::track_login_daily( $userid );
385 $patron->_result()->discard_changes();
386 is( $patron->lastseen, $last_seen, 'Patron last seen should still be unchanged' );
388 $cache->clear_from_cache($cache_key);
389 C4::Auth::track_login_daily( $userid );
390 $patron->_result()->discard_changes();
391 isnt( $patron->lastseen, $last_seen, 'Patron last seen should be changed if we cleared the cache' );
393 t::lib::Mocks::mock_preference( 'TrackLastPatronActivity', '0' );
394 $patron->lastseen( undef )->store;
395 $cache->clear_from_cache($cache_key);
396 C4::Auth::track_login_daily( $userid );
397 $patron->_result()->discard_changes();
398 is( $patron->lastseen, undef, 'Patron should still have last seen unchanged when TrackLastPatronActivity = 0' );
402 subtest 'no_set_userenv parameter tests' => sub {
406 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
407 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
408 my $password = 'password';
410 t::lib::Mocks::mock_preference( 'RequireStrongPassword', 0 );
411 $patron->set_password({ password => $password });
413 ok( checkpw( $patron->userid, $password, undef, undef, 1 ), 'checkpw returns true' );
414 is( C4::Context->userenv, undef, 'Userenv should be undef as required' );
415 C4::Context->_new_userenv('DUMMY SESSION');
416 C4::Context->set_userenv(0,0,0,'firstname','surname', $library->branchcode, 'Library 1', 0, '', '');
417 is( C4::Context->userenv->{branch}, $library->branchcode, 'Userenv gives correct branch' );
418 ok( checkpw( $patron->userid, $password, undef, undef, 1 ), 'checkpw returns true' );
419 is( C4::Context->userenv->{branch}, $library->branchcode, 'Userenv branch is preserved if no_set_userenv is true' );
420 ok( checkpw( $patron->userid, $password, undef, undef, 0 ), 'checkpw still returns true' );
421 isnt( C4::Context->userenv->{branch}, $library->branchcode, 'Userenv branch is overwritten if no_set_userenv is false' );
424 subtest 'checkpw lockout tests' => sub {
428 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
429 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
430 my $password = 'password';
431 t::lib::Mocks::mock_preference( 'RequireStrongPassword', 0 );
432 t::lib::Mocks::mock_preference( 'FailedLoginAttempts', 1 );
433 $patron->set_password({ password => $password });
435 my ( $checkpw, undef, undef ) = checkpw( $patron->cardnumber, $password, undef, undef, 1 );
436 ok( $checkpw, 'checkpw returns true with right password when logging in via cardnumber' );
437 ( $checkpw, undef, undef ) = checkpw( $patron->userid, "wrong_password", undef, undef, 1 );
438 is( $checkpw, 0, 'checkpw returns false when given wrong password' );
439 $patron = $patron->get_from_storage;
440 is( $patron->account_locked, 1, "Account is locked from failed login");
441 ( $checkpw, undef, undef ) = checkpw( $patron->userid, $password, undef, undef, 1 );
442 is( $checkpw, undef, 'checkpw returns undef with right password when account locked' );
443 ( $checkpw, undef, undef ) = checkpw( $patron->cardnumber, $password, undef, undef, 1 );
444 is( $checkpw, undef, 'checkpw returns undefwith right password when logging in via cardnumber if account locked' );
448 # get_template_and_user tests
450 subtest 'get_template_and_user' => sub { # Tests for the language URL parameter
452 sub MockedCheckauth {
453 my ($query,$authnotrequired,$flagsrequired,$type) = @_;
455 my $userid = 'cobain';
457 # we don't need to bother about permissions for this test
459 superlibrarian => 1, acquisition => 0,
461 catalogue => 1, circulate => 0,
462 coursereserves => 0, editauthorities => 0,
464 parameters => 0, permissions => 0,
465 plugins => 0, reports => 0,
466 reserveforothers => 0, serials => 0,
467 staffaccess => 0, tools => 0,
471 my $session_cookie = $query->cookie(
472 -name => 'CGISESSID',
477 return ( $userid, [ $session_cookie ], $sessionID, $flags );
480 # Mock checkauth, build the scenario
481 my $auth = Test::MockModule->new( 'C4::Auth' );
482 $auth->mock( 'checkauth', \&MockedCheckauth );
484 # Make sure 'EnableOpacSearchHistory' is set
485 t::lib::Mocks::mock_preference('EnableOpacSearchHistory',1);
486 # Enable es-ES for the OPAC and staff interfaces
487 t::lib::Mocks::mock_preference('OPACLanguages','en,es-ES');
488 t::lib::Mocks::mock_preference('language','en,es-ES');
490 # we need a session cookie
491 $ENV{"SERVER_PORT"} = 80;
492 $ENV{"HTTP_COOKIE"} = 'CGISESSID=nirvana';
494 my $query = CGI->new;
495 $query->param('language','es-ES');
497 my ( $template, $loggedinuser, $cookies ) = get_template_and_user(
499 template_name => "about.tt",
502 authnotrequired => 1,
503 flagsrequired => { catalogue => 1 },
508 ok ( ( all { ref($_) eq 'CGI::Cookie' } @$cookies ),
509 'BZ9735: the cookies array is flat' );
511 # new query, with non-existent language (we only have en and es-ES)
512 $query->param('language','tomas');
514 ( $template, $loggedinuser, $cookies ) = get_template_and_user(
516 template_name => "about.tt",
519 authnotrequired => 1,
520 flagsrequired => { catalogue => 1 },
525 ok( ( none { $_->name eq 'KohaOpacLanguage' and $_->value eq 'tomas' } @$cookies ),
526 'BZ9735: invalid language, it is not set');
528 ok( ( any { $_->name eq 'KohaOpacLanguage' and $_->value eq 'en' } @$cookies ),
529 'BZ9735: invalid language, then default to en');
531 for my $template_name (
533 ../../../../../../../../../../../../../../../etc/passwd
534 test/../../../../../../../../../../../../../../etc/passwd
536 test/does_not_finished_by_tt_t
540 ( $template, $loggedinuser, $cookies ) = get_template_and_user(
542 template_name => $template_name,
545 authnotrequired => 1,
546 flagsrequired => { catalogue => 1 },
550 like ( $@, qr(bad template path), "The file $template_name should not be accessible" );
552 ( $template, $loggedinuser, $cookies ) = get_template_and_user(
554 template_name => 'errors/errorpage.tt',
557 authnotrequired => 1,
558 flagsrequired => { catalogue => 1 },
561 my $file_exists = ( -f $template->{filename} ) ? 1 : 0;
562 is ( $file_exists, 1, 'The file errors/errorpage.tt should be accessible (contains integers)' );
564 # Regression test for env opac search limit override
565 $ENV{"OPAC_SEARCH_LIMIT"} = "branch:CPL";
566 $ENV{"OPAC_LIMIT_OVERRIDE"} = 1;
568 ( $template, $loggedinuser, $cookies) = get_template_and_user(
570 template_name => 'opac-main.tt',
573 authnotrequired => 1,
576 is($template->{VARS}->{'opac_name'}, "CPL", "Opac name was set correctly");
577 is($template->{VARS}->{'opac_search_limit'}, "branch:CPL", "Search limit was set correctly");
579 $ENV{"OPAC_SEARCH_LIMIT"} = "branch:multibranch-19";
581 ( $template, $loggedinuser, $cookies) = get_template_and_user(
583 template_name => 'opac-main.tt',
586 authnotrequired => 1,
589 is($template->{VARS}->{'opac_name'}, "multibranch-19", "Opac name was set correctly");
590 is($template->{VARS}->{'opac_search_limit'}, "branch:multibranch-19", "Search limit was set correctly");
591 ok(defined($template->{VARS}->{'csrf_token'}), "CSRF token returned");
593 delete $ENV{"HTTP_COOKIE"};
596 # Check that there is always an OPACBaseURL set.
597 my $input = CGI->new();
598 my ( $template1, $borrowernumber, $cookie );
599 ( $template1, $borrowernumber, $cookie ) = get_template_and_user(
601 template_name => "opac-detail.tt",
604 authnotrequired => 1,
608 ok( ( any { 'OPACBaseURL' eq $_ } keys %{$template1->{VARS}} ),
609 'OPACBaseURL is in OPAC template' );
612 ( $template2, $borrowernumber, $cookie ) = get_template_and_user(
614 template_name => "catalogue/detail.tt",
617 authnotrequired => 1,
621 ok( ( any { 'OPACBaseURL' eq $_ } keys %{$template2->{VARS}} ),
622 'OPACBaseURL is in Staff template' );
624 my $hash1 = hash_password('password');
625 my $hash2 = hash_password('password');
627 ok(C4::Auth::checkpw_hash('password', $hash1), 'password validates with first hash');
628 ok(C4::Auth::checkpw_hash('password', $hash2), 'password validates with second hash');
630 subtest 'Check value of login_attempts in checkpw' => sub {
633 t::lib::Mocks::mock_preference('FailedLoginAttempts', 3);
635 # Only interested here in regular login
639 my $patron = $builder->build_object({ class => 'Koha::Patrons' });
640 $patron->login_attempts(2);
641 $patron->password('123')->store; # yes, deliberately not hashed
643 is( $patron->account_locked, 0, 'Patron not locked' );
644 my @test = checkpw( $patron->userid, '123', undef, 'opac', 1 );
645 # Note: 123 will not be hashed to 123 !
646 is( $test[0], 0, 'checkpw should have failed' );
647 $patron->discard_changes; # refresh
648 is( $patron->login_attempts, 3, 'Login attempts increased' );
649 is( $patron->account_locked, 1, 'Check locked status' );
651 # And another try to go over the limit: different return value!
652 @test = checkpw( $patron->userid, '123', undef, 'opac', 1 );
653 is( @test, 0, 'checkpw failed again and returns nothing now' );
654 $patron->discard_changes; # refresh
655 is( $patron->login_attempts, 3, 'Login attempts not increased anymore' );
657 # Administrative lockout cannot be undone?
658 # Pass the right password now (or: add a nice mock).
659 my $auth = Test::MockModule->new( 'C4::Auth' );
660 $auth->mock( 'checkpw_hash', sub { return 1; } ); # not for production :)
661 $patron->login_attempts(0)->store;
662 @test = checkpw( $patron->userid, '123', undef, 'opac', 1 );
663 is( $test[0], 1, 'Build confidence in the mock' );
664 $patron->login_attempts(-1)->store;
665 is( $patron->account_locked, 1, 'Check administrative lockout' );
666 @test = checkpw( $patron->userid, '123', undef, 'opac', 1 );
667 is( @test, 0, 'checkpw gave red' );
668 $patron->discard_changes; # refresh
669 is( $patron->login_attempts, -1, 'Still locked out' );
670 t::lib::Mocks::mock_preference('FailedLoginAttempts', ''); # disable
671 is( $patron->account_locked, 1, 'Check administrative lockout without pref' );
674 subtest 'Check value of login_attempts in checkpw' => sub {
677 t::lib::Mocks::mock_preference('FailedLoginAttempts', 3);
678 my $patron = $builder->build_object({ class => 'Koha::Patrons' });
679 $patron->set_password({ password => '123', skip_validation => 1 });
681 my @test = checkpw( $dbh, $patron->userid, '123', undef, 'opac', 1 );
682 is( $test[0], 1, 'Patron authenticated correctly' );
684 $patron->password_expiration_date('2020-01-01')->store;
685 @test = checkpw( $dbh, $patron->userid, '123', undef, 'opac', 1 );
686 is( $test[0], -2, 'Patron returned as expired correctly' );
690 subtest '_timeout_syspref' => sub {
694 t::lib::Mocks::mock_preference('timeout', "100");
695 is( C4::Auth::_timeout_syspref, 100, );
697 t::lib::Mocks::mock_preference('timeout', "2d");
698 is( C4::Auth::_timeout_syspref, 2*86400, );
700 t::lib::Mocks::mock_preference('timeout', "2D");
701 is( C4::Auth::_timeout_syspref, 2*86400, );
703 t::lib::Mocks::mock_preference('timeout', "10h");
704 is( C4::Auth::_timeout_syspref, 10*3600, );
706 t::lib::Mocks::mock_preference('timeout', "10x");
708 { is( C4::Auth::_timeout_syspref, 600, ); }
709 "The value of the system preference 'timeout' is not correct, defaulting to 600",
710 'Bad values throw a warning and fallback to 600';
713 subtest 'check_cookie_auth' => sub {
716 t::lib::Mocks::mock_preference('timeout', "1d"); # back to default
718 my $patron = $builder->build_object({ class => 'Koha::Patrons', value => { flags => 1 } });
720 # Mock a CGI object with real userid param
721 my $cgi = Test::MockObject->new();
726 if ( $var eq 'userid' ) { return $patron->userid; }
729 $cgi->mock('multi_param', sub {return q{}} );
730 $cgi->mock( 'cookie', sub { return; } );
731 $cgi->mock( 'request_method', sub { return 'POST' } );
733 $ENV{REMOTE_ADDR} = '127.0.0.1';
735 # Setting authnotrequired=1 or we wont' hit the return but the end of the sub that prints headers
736 my ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 1 );
738 my ($auth_status, $session) = C4::Auth::check_cookie_auth($sessionID);
739 isnt( $auth_status, 'ok', 'check_cookie_auth should not return ok if the user has not been authenticated before if no permissions needed' );
740 is( $auth_status, 'anon', 'check_cookie_auth should return anon if the user has not been authenticated before and no permissions needed' );
742 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 1 );
744 ($auth_status, $session) = C4::Auth::check_cookie_auth($sessionID, {catalogue => 1});
745 isnt( $auth_status, 'ok', 'check_cookie_auth should not return ok if the user has not been authenticated before and permissions needed' );
746 is( $auth_status, 'anon', 'check_cookie_auth should return anon if the user has not been authenticated before and permissions needed' );
748 #FIXME We should have a test to cover 'failed' status when a user has logged in, but doesn't have permission
751 subtest 'checkauth & check_cookie_auth' => sub {
754 # flags = 4 => { catalogue => 1 }
755 my $patron = $builder->build_object({ class => 'Koha::Patrons', value => { flags => 4 } });
756 my $password = 'password';
757 t::lib::Mocks::mock_preference( 'RequireStrongPassword', 0 );
758 $patron->set_password( { password => $password } );
760 my $cgi_mock = Test::MockModule->new('CGI');
761 $cgi_mock->mock( 'request_method', sub { return 'POST' } );
765 my $auth = Test::MockModule->new( 'C4::Auth' );
766 # Tests will fail if we hit safe_exit
767 $auth->mock( 'safe_exit', sub { return } );
769 my ( $userid, $cookie, $sessionID, $flags );
771 # checkauth will redirect and safe_exit if not authenticated and not authorized
774 open STDOUT, '>', \$stdout;
775 C4::Auth::checkauth($cgi, 0, {catalogue => 1});
776 like( $stdout, qr{<title>\s*Log in to your account} );
777 $sessionID = ( $stdout =~ m{Set-Cookie: CGISESSID=((\d|\w)+);} ) ? $1 : undef;
782 my $first_sessionID = $sessionID;
784 $ENV{"HTTP_COOKIE"} = "CGISESSID=$sessionID";
785 # Not authenticated yet, checkauth didn't return the session
789 open STDOUT, '>', \$stdout;
790 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 0, {catalogue => 1} );
793 is( $sessionID, undef);
796 # Sending undefined fails obviously
797 my ( $auth_status, $session ) = C4::Auth::check_cookie_auth($sessionID, {catalogue => 1} );
798 is( $auth_status, 'failed' );
799 is( $session, undef );
801 # Simulating the login form submission
802 $cgi->param('userid', $patron->userid);
803 $cgi->param('password', $password);
806 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 0, {catalogue => 1});
807 is( $sessionID, $first_sessionID );
808 is( $userid, $patron->userid );
810 ( $auth_status, $session ) = C4::Auth::check_cookie_auth($sessionID, {catalogue => 1});
811 is( $auth_status, 'ok' );
812 is( $session->id, $first_sessionID );
815 $cgi->param('logout.x', 1);
816 $cgi->delete( 'userid', 'password' );
820 open STDOUT, '>', \$stdout;
821 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 0, {catalogue => 1});
824 is( $sessionID, undef );
825 is( $ENV{"HTTP_COOKIE"}, "CGISESSID=$first_sessionID", 'HTTP_COOKIE not unset' );
826 ( $auth_status, $session) = C4::Auth::check_cookie_auth( $first_sessionID, {catalogue => 1} );
827 is( $auth_status, "expired");
828 is( $session, undef );
831 # Trying to access without sessionID
833 ( $auth_status, $session) = C4::Auth::check_cookie_auth(undef, {catalogue => 1});
834 is( $auth_status, 'failed' );
835 is( $session, undef );
837 # This will fail on permissions
838 undef $ENV{"HTTP_COOKIE"};
842 open STDOUT, '>', \$stdout;
843 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 0, {catalogue => 1} );
846 is( $userid, undef );
847 is( $sessionID, undef );
853 $cgi->param('userid', $patron->userid);
854 $cgi->param('password', $password);
855 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 0, {catalogue => 1});
856 is( $userid, $patron->userid );
857 $first_sessionID = $sessionID;
859 # Patron does not have the borrowers permission
860 # $ENV{"HTTP_COOKIE"} = "CGISESSID=$sessionID"; # not needed, we use $cgi here
864 open STDOUT, '>', \$stdout;
865 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 0, {borrowers => 1} );
868 is( $userid, undef );
869 is( $sessionID, undef );
871 # When calling check_cookie_auth, the session will be deleted
872 ( $auth_status, $session) = C4::Auth::check_cookie_auth( $first_sessionID, { borrowers => 1 } );
873 is( $auth_status, "failed" );
874 is( $session, undef );
875 ( $auth_status, $session) = C4::Auth::check_cookie_auth( $first_sessionID, { borrowers => 1 } );
876 is( $auth_status, 'expired', 'Session no longer exists' );
878 # NOTE: It is not what the UI is doing.
879 # From the UI we are allowed to hit an unauthorized page then reuse the session to hit back authorized area.
880 # It is because check_cookie_auth is ALWAYS called from checkauth WITHOUT $flagsrequired
881 # It then return "ok", when the previous called got "failed"
883 # Try reusing the deleted session: since it does not exist, we should get a new one now when passing correct permissions
884 $cgi->cookie( -name => 'CGISESSID', value => $first_sessionID );
885 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 0, {catalogue => 1});
886 is( $userid, $patron->userid );
887 isnt( $sessionID, undef, 'Check if we have a sessionID' );
888 isnt( $sessionID, $first_sessionID, 'New value expected' );
889 ( $auth_status, $session) = C4::Auth::check_cookie_auth( $sessionID, {catalogue => 1} );
890 is( $auth_status, "ok" );
891 is( $session->id, $sessionID, 'Same session' );
892 # Two additional tests on userenv
893 is( $C4::Context::context->{activeuser}, $session->id, 'Check if environment has been setup for session' );
894 is( C4::Context->userenv->{id}, $userid, 'Check userid in userenv' );
898 subtest 'Userenv clearing in check_cookie_auth' => sub {
899 # Note: We did already test userenv for a logged-in user in previous subtest
902 t::lib::Mocks::mock_preference( 'timeout', 600 );
905 # Create a new anonymous session by passing a fake session ID
906 $cgi->cookie( -name => 'CGISESSID', -value => 'fake_sessionID' );
907 my ($userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 1);
908 my ( $auth_status, $session) = C4::Auth::check_cookie_auth( $sessionID );
909 is( $auth_status, 'anon', 'Should be anonymous' );
910 is( $C4::Context::context->{activeuser}, $session->id, 'Check activeuser' );
911 is( defined C4::Context->userenv, 1, 'There should be a userenv' );
912 is( C4::Context->userenv->{id}, q{}, 'userid should be empty string' );
914 # Make the session expire now, check_cookie_auth will delete it
915 $session->param('lasttime', time() - 1200 );
917 ( $auth_status, $session) = C4::Auth::check_cookie_auth( $sessionID );
918 is( $auth_status, 'expired', 'Should be expired' );
919 is( C4::Context->userenv, undef, 'Environment should be cleared too' );
921 # Show that we clear the userenv again: set up env and check deleted session
922 C4::Context->_new_userenv( $sessionID );
923 C4::Context->set_userenv; # empty
924 is( defined C4::Context->userenv, 1, 'There should be an empty userenv again' );
925 ( $auth_status, $session) = C4::Auth::check_cookie_auth( $sessionID );
926 is( $auth_status, 'expired', 'Should be expired already' );
927 is( C4::Context->userenv, undef, 'Environment should be cleared again' );
930 $schema->storage->txn_rollback;
932 subtest 'checkpw() return values tests' => sub {
936 subtest 'Internal check tests' => sub {
940 $schema->storage->txn_begin;
943 my $password_expired;
945 my $mock_patron = Test::MockModule->new('Koha::Patron');
946 $mock_patron->mock( 'account_locked', sub { return $account_locked; } );
947 $mock_patron->mock( 'password_expired', sub { return $password_expired; } );
949 # Only interested here in regular login
950 t::lib::Mocks::mock_config( 'useshibboleth', undef );
954 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
955 my $password = 'thePassword123';
956 $patron->set_password( { password => $password, skip_validation => 1 } );
958 my $patron_to_delete = $builder->build_object( { class => 'Koha::Patrons' } );
959 my $unused_userid = $patron_to_delete->userid;
960 my $unused_cardnumber = $patron_to_delete->cardnumber;
961 $patron_to_delete->delete;
964 my @return = checkpw( $patron->userid, $password, undef, );
965 is_deeply( \@return, [], 'If the account is locked, empty list is returned' );
969 my @matchpoints = qw(userid cardnumber);
970 foreach my $matchpoint (@matchpoints) {
972 @return = checkpw( $patron->$matchpoint, $password, undef, );
974 is( $return[0], 1, "Password validation successful returns 1 ($matchpoint)" );
975 is( $return[1], $patron->cardnumber, '`cardnumber` returned' );
976 is( $return[2], $patron->userid, '`userid` returned' );
977 is( ref( $return[3] ), 'Koha::Patron', 'Koha::Patron object reference returned' );
978 is( $return[3]->id, $patron->id, 'Correct patron returned' );
981 @return = checkpw( $patron->userid, $password . 'hey', undef, );
983 is( scalar @return, 2, "Two results on invalid password scenario" );
984 is( $return[0], 0, '0 returned on invalid password' );
985 is( ref( $return[1] ), 'Koha::Patron' );
986 is( $return[1]->id, $patron->id, 'Patron matched correctly' );
988 $password_expired = 1;
989 @return = checkpw( $patron->userid, $password, undef, );
991 is( scalar @return, 2, "Two results on expired password scenario" );
992 is( $return[0], -2, '-2 returned' );
993 is( ref( $return[1] ), 'Koha::Patron' );
994 is( $return[1]->id, $patron->id, 'Patron matched correctly' );
996 @return = checkpw( $unused_userid, $password, undef, );
998 is( scalar @return, 2, "Two results on non-existing userid scenario" );
999 is( $return[0], 0, '0 returned' );
1000 is( $return[1], undef, 'Undef returned, representing no match' );
1002 @return = checkpw( $unused_cardnumber, $password, undef, );
1004 is( scalar @return, 2, "Only one result on non-existing cardnumber scenario" );
1005 is( $return[0], 0, '0 returned' );
1006 is( $return[1], undef, 'Undef returned, representing no match' );
1008 $schema->storage->txn_rollback;
1011 subtest 'CAS check (mocked) tests' => sub {
1015 $schema->storage->txn_begin;
1018 my $password_expired;
1020 my $mock_patron = Test::MockModule->new('Koha::Patron');
1021 $mock_patron->mock( 'account_locked', sub { return $account_locked; } );
1022 $mock_patron->mock( 'password_expired', sub { return $password_expired; } );
1024 # Only interested here in regular login
1025 t::lib::Mocks::mock_config( 'useshibboleth', undef );
1027 $C4::Auth::ldap = 0;
1029 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
1030 my $password = 'thePassword123';
1031 $patron->set_password( { password => $password, skip_validation => 1 } );
1033 my $patron_to_delete = $builder->build_object( { class => 'Koha::Patrons' } );
1034 my $unused_userid = $patron_to_delete->userid;
1035 my $unused_cardnumber = $patron_to_delete->cardnumber;
1036 $patron_to_delete->delete;
1038 my $ticket = '123456';
1039 my $query = CGI->new;
1040 $query->param( -name => 'ticket', -value => $ticket );
1042 my @cas_return = ( 1, $patron->cardnumber, $patron->userid, $ticket, Koha::Patrons->find( $patron->id ) );
1044 my $cas_mock = Test::MockModule->new('C4::Auth');
1045 $cas_mock->mock( 'checkpw_cas', sub { return @cas_return; } );
1047 $account_locked = 1;
1048 my @return = checkpw( $patron->userid, $password, $query, );
1049 is_deeply( \@return, [], 'If the account is locked, empty list is returned' );
1051 $account_locked = 0;
1053 my @matchpoints = qw(userid cardnumber);
1054 foreach my $matchpoint (@matchpoints) {
1056 @return = checkpw( $patron->$matchpoint, $password, $query, );
1058 is( $return[0], 1, "Password validation successful returns 1 ($matchpoint)" );
1059 is( $return[1], $patron->cardnumber, '`cardnumber` returned' );
1060 is( $return[2], $patron->userid, '`userid` returned' );
1061 is( ref( $return[3] ), 'Koha::Patron', 'Koha::Patron object reference returned' );
1062 is( $return[3]->id, $patron->id, 'Correct patron returned' );
1065 @return = checkpw( $patron->userid, $password . 'hey', $query, );
1067 is( scalar @return, 2, "Two results on invalid password scenario" );
1068 is( $return[0], 0, '0 returned on invalid password' );
1069 is( ref( $return[1] ), 'Koha::Patron' );
1070 is( $return[1]->id, $patron->id, 'Patron matched correctly' );
1072 $password_expired = 1;
1073 @return = checkpw( $patron->userid, $password, $query, );
1075 is( scalar @return, 2, "Two results on expired password scenario" );
1076 is( $return[0], -2, '-2 returned' );
1077 is( ref( $return[1] ), 'Koha::Patron' );
1078 is( $return[1]->id, $patron->id, 'Patron matched correctly' );
1080 @return = checkpw( $unused_userid, $password, $query, );
1082 is( scalar @return, 2, "Two results on non-existing userid scenario" );
1083 is( $return[0], 0, '0 returned' );
1084 is( $return[1], undef, 'Undef returned, representing no match' );
1086 @return = checkpw( $unused_cardnumber, $password, $query, );
1088 is( scalar @return, 2, "Only one result on non-existing cardnumber scenario" );
1089 is( $return[0], 0, '0 returned' );
1090 is( $return[1], undef, 'Undef returned, representing no match' );
1092 $schema->storage->txn_rollback;
1095 subtest 'Shibboleth check (mocked) tests' => sub {
1099 $schema->storage->txn_begin;
1102 my $password_expired;
1104 my $mock_patron = Test::MockModule->new('Koha::Patron');
1105 $mock_patron->mock( 'account_locked', sub { return $account_locked; } );
1106 $mock_patron->mock( 'password_expired', sub { return $password_expired; } );
1108 # Only interested here in regular login
1109 t::lib::Mocks::mock_config( 'useshibboleth', 1 );
1111 $C4::Auth::ldap = 0;
1113 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
1114 my $password = 'thePassword123';
1115 $patron->set_password( { password => $password, skip_validation => 1 } );
1117 my $patron_to_delete = $builder->build_object( { class => 'Koha::Patrons' } );
1118 my $unused_userid = $patron_to_delete->userid;
1119 my $unused_cardnumber = $patron_to_delete->cardnumber;
1120 $patron_to_delete->delete;
1122 my @shib_return = ( 1, $patron->cardnumber, $patron->userid, Koha::Patrons->find( $patron->id ) );
1124 my $auth_mock = Test::MockModule->new('C4::Auth');
1125 $auth_mock->mock( 'shib_ok', 1 );
1126 $auth_mock->mock( 'get_login_shib', 1 );
1128 my $shib_mock = Test::MockModule->new('C4::Auth_with_shibboleth');
1129 $shib_mock->mock( 'checkpw_shib', sub { return @shib_return; } );
1131 $account_locked = 1;
1132 my @return = checkpw( $patron->userid );
1133 is_deeply( \@return, [], 'If the account is locked, empty list is returned' );
1135 $account_locked = 0;
1137 @return = checkpw();
1139 is( $return[0], 1, "Password validation successful returns 1" );
1140 is( $return[1], $patron->cardnumber, '`cardnumber` returned' );
1141 is( $return[2], $patron->userid, '`userid` returned' );
1142 is( ref( $return[3] ), 'Koha::Patron', 'Koha::Patron object reference returned' );
1143 is( $return[3]->id, $patron->id, 'Correct patron returned' );
1145 $schema->storage->txn_rollback;