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;
31 my $dbh = C4::Context->dbh;
33 # FIXME: SessionStorage defaults to mysql, but it seems to break transaction
35 t::lib::Mocks::mock_preference( 'SessionStorage', 'tmp' );
36 t::lib::Mocks::mock_preference( 'GDPR_Policy', '' ); # Disabled
38 # To silence useless warnings
39 $ENV{REMOTE_ADDR} = '127.0.0.1';
41 $schema->storage->txn_begin;
43 subtest 'checkauth() tests' => sub {
47 my $patron = $builder->build_object({ class => 'Koha::Patrons', value => { flags => undef } });
49 # Mock a CGI object with real userid param
50 my $cgi = Test::MockObject->new();
55 if ( $var eq 'userid' ) { return $patron->userid; }
58 $cgi->mock( 'cookie', sub { return; } );
59 $cgi->mock( 'request_method', sub { return 'POST' } );
61 my $authnotrequired = 1;
62 my ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, $authnotrequired );
64 is( $userid, undef, 'checkauth() returns undef for userid if no logged in user (Bug 18275)' );
66 my $db_user_id = C4::Context->config('user');
67 my $db_user_pass = C4::Context->config('pass');
68 $cgi = Test::MockObject->new();
69 $cgi->mock( 'cookie', sub { return; } );
70 $cgi->mock( 'param', sub {
71 my ( $self, $param ) = @_;
72 if ( $param eq 'userid' ) { return $db_user_id; }
73 elsif ( $param eq 'password' ) { return $db_user_pass; }
76 $cgi->mock( 'request_method', sub { return 'POST' } );
77 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, $authnotrequired );
78 is ( $userid, undef, 'If DB user is used, it should not be logged in' );
80 my $is_allowed = C4::Auth::haspermission( $db_user_id, { can_do => 'everything' } );
82 # FIXME This belongs to t/db_dependent/Auth/haspermission.t but we do not want to c/p the pervious mock statements
83 ok( !$is_allowed, 'DB user should not have any permissions');
85 subtest 'Prevent authentication when sending credential via GET' => sub {
89 my $patron = $builder->build_object(
90 { class => 'Koha::Patrons', value => { flags => 1 } } );
91 my $password = 'password';
92 t::lib::Mocks::mock_preference( 'RequireStrongPassword', 0 );
93 $patron->set_password( { password => $password } );
94 $cgi = Test::MockObject->new();
95 $cgi->mock( 'cookie', sub { return; } );
99 my ( $self, $param ) = @_;
100 if ( $param eq 'userid' ) { return $patron->userid; }
101 elsif ( $param eq 'password' ) { return $password; }
106 $cgi->mock( 'request_method', sub { return 'POST' } );
107 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired' );
108 is( $userid, $patron->userid, 'If librarian user is used and password with POST, they should be logged in' );
110 $cgi->mock( 'request_method', sub { return 'GET' } );
111 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired' );
112 is( $userid, undef, 'If librarian user is used and password with GET, they should not be logged in' );
115 subtest 'Template params tests (password_expired)' => sub {
119 my $password_expired;
121 my $patron_class = Test::MockModule->new('Koha::Patron');
122 $patron_class->mock( 'password_expired', sub { return $password_expired; } );
124 my $patron = $builder->build_object({ class => 'Koha::Patrons', value => { flags => 1 } });
125 my $password = 'password';
126 t::lib::Mocks::mock_preference( 'RequireStrongPassword', 0 );
127 $patron->set_password( { password => $password } );
129 my $cgi_mock = Test::MockModule->new('CGI')->mock( 'request_method', 'POST' );
131 $cgi->param( -name => 'userid', -value => $patron->userid );
132 $cgi->param( -name => 'password', -value => $password );
134 my $auth = Test::MockModule->new( 'C4::Auth' );
135 # Tests will fail if we hit safe_exit
136 $auth->mock( 'safe_exit', sub { return } );
138 my ( $userid, $cookie, $sessionID, $flags );
141 t::lib::Mocks::mock_preference( 'DumpTemplateVarsOpac', 1 );
142 # checkauth will redirect and safe_exit if not authenticated and not authorized
145 open STDOUT, '>', \$stdout;
147 # Password has expired
148 $password_expired = 1;
149 C4::Auth::checkauth( $cgi, 0, { catalogue => 1 } );
150 like( $stdout, qr{'password_has_expired' => 1}, 'password_has_expired is set to 1' );
156 subtest 'Reset auth state when changing users' => sub {
158 #NOTE: It's easiest to detect this when changing to a non-existent user, since
159 #that should trigger a redirect to login (instead of returning a session cookie)
161 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { flags => undef } } );
163 my $session = C4::Auth::get_session();
164 $session->param( 'number', $patron->id );
165 $session->param( 'id', $patron->userid );
166 $session->param( 'ip', '1.2.3.4' );
167 $session->param( 'lasttime', time() );
168 $session->param( 'interface', 'intranet' );
170 my $sessionID = $session->id;
171 C4::Context->_new_userenv($sessionID);
174 C4::Auth::check_cookie_auth( $sessionID, undef, { skip_version_check => 1, remote_addr => '1.2.3.4' } );
175 is( $return, 'ok', 'Patron authenticated' );
177 my $mock1 = Test::MockModule->new('C4::Auth');
178 $mock1->mock( 'safe_exit', sub { return 'safe_exit_redirect' } );
179 my $mock2 = Test::MockModule->new('CGI');
180 $mock2->mock( 'request_method', 'POST' );
181 $mock2->mock( 'cookie', sub { return $sessionID; } ); # oversimplified..
184 $cgi->param( -name => 'userid', -value => 'Bond' );
185 $cgi->param( -name => 'password', -value => 'James Bond' );
186 $cgi->param( -name => 'koha_login_context', -value => 1 );
187 my ( @return, $stdout );
191 $ENV{REMOTE_ADDR} = '1.2.3.4';
192 open STDOUT, '>', \$stdout;
193 @return = C4::Auth::checkauth( $cgi, 0, {} );
196 is( $return[0], 'safe_exit_redirect', 'Changing to non-existent user causes a redirect to login' );
200 subtest 'While still logged in, relogin with another user' => sub {
203 my $patron = $builder->build_object({ class => 'Koha::Patrons', value => {} });
204 my $patron2 = $builder->build_object({ class => 'Koha::Patrons', value => {} });
205 # Create 'former' session
206 my $session = C4::Auth::get_session();
207 $session->param( 'number', $patron->id );
208 $session->param( 'id', $patron->userid );
209 $session->param( 'ip', '1.2.3.4' );
210 $session->param( 'lasttime', time() );
211 $session->param( 'interface', 'opac' );
213 my $sessionID = $session->id;
214 C4::Context->_new_userenv($sessionID);
216 my ( $return ) = C4::Auth::check_cookie_auth( $sessionID, undef, { skip_version_check => 1, remote_addr => '1.2.3.4' } );
217 is( $return, 'ok', 'Former session in shape now' );
219 my $mock1 = Test::MockModule->new('C4::Auth');
220 $mock1->mock( 'safe_exit', sub {} );
221 my $mock2 = Test::MockModule->new('CGI');
222 $mock2->mock( 'request_method', 'POST' );
223 $mock2->mock( 'cookie', sub { return $sessionID; } ); # oversimplified..
225 my $password = 'Incr3d1blyZtr@ng93$';
226 $patron2->set_password({ password => $password });
227 $cgi->param( -name => 'userid', -value => $patron2->userid );
228 $cgi->param( -name => 'password', -value => $password );
229 $cgi->param( -name => 'koha_login_context', -value => 1 );
230 my ( @return, $stdout );
234 $ENV{REMOTE_ADDR} = '1.2.3.4';
235 open STDOUT, '>', \$stdout;
236 @return = C4::Auth::checkauth( $cgi, 0, {} );
239 # Note: We can test return values from checkauth here since we mocked the safe_exit after the Redirect 303
240 is( $return[0], $patron2->userid, 'Login of patron2 approved' );
241 isnt( $return[2], $sessionID, 'Did not return previous session ID' );
242 ok( $return[2], 'New session ID not empty' );
244 # Similar situation: Relogin with former session of $patron, new user $patron2 has no permissions
245 $patron2->flags(undef)->store;
246 $session->param( 'number', $patron->id );
247 $session->param( 'id', $patron->userid );
248 $session->param( 'interface', 'intranet' );
250 $sessionID = $session->id;
251 C4::Context->_new_userenv($sessionID);
252 $cgi->param( -name => 'userid', -value => $patron2->userid );
253 $cgi->param( -name => 'password', -value => $password );
254 $cgi->param( -name => 'koha_login_context', -value => 1 );
258 $ENV{REMOTE_ADDR} = '1.2.3.4';
260 open STDOUT, '>', \$stdout;
261 @return = C4::Auth::checkauth( $cgi, 0, { catalogue => 1 }, 'intranet' ); # patron2 has no catalogue perm
264 like( $stdout, qr/You do not have permission to access this page/, 'No permission response' );
265 is( @return, 0, 'checkauth returned failure' );
268 subtest 'Two-factor authentication' => sub {
270 my $patron = $builder->build_object(
271 { class => 'Koha::Patrons', value => { flags => 1 } } );
272 my $password = 'password';
273 $patron->set_password( { password => $password } );
274 $cgi = Test::MockObject->new();
277 our ( $logout, $sessionID, $verified );
281 my ( $self, $param ) = @_;
282 if ( $param eq 'userid' ) { return $patron->userid; }
283 elsif ( $param eq 'password' ) { return $password; }
284 elsif ( $param eq 'otp_token' ) { return $otp_token; }
285 elsif ( $param eq 'logout.x' ) { return $logout; }
289 $cgi->mock( 'request_method', sub { return 'POST' } );
290 $cgi->mock( 'cookie', sub { return $sessionID } );
292 my $two_factor_auth = Test::MockModule->new( 'Koha::Auth::TwoFactorAuth' );
293 $two_factor_auth->mock( 'verify', sub {$verified} );
295 my ( $userid, $cookie, $flags );
296 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired', undef, 'intranet' );
302 C4::Auth::checkauth( $cgi, 'authrequired', undef, 'intranet' );
306 t::lib::Mocks::mock_preference( 'TwoFactorAuthentication', 0 );
307 $patron->auth_method('password')->store;
308 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired', undef, 'intranet' );
309 is( $userid, $patron->userid, 'Succesful login' );
310 is( C4::Auth::get_session($sessionID)->param('waiting-for-2FA'), undef, 'Second auth not required' );
313 $patron->auth_method('two-factor')->store;
314 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired', undef, 'intranet' );
315 is( $userid, $patron->userid, 'Succesful login' );
316 is( C4::Auth::get_session($sessionID)->param('waiting-for-2FA'), undef, 'Second auth not required' );
319 t::lib::Mocks::mock_preference( 'TwoFactorAuthentication', 1 );
320 t::lib::Mocks::mock_config('encryption_key', '1234tH1s=t&st');
321 $patron->auth_method('password')->store;
322 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired', undef, 'intranet' );
323 is( $userid, $patron->userid, 'Succesful login' );
324 is( C4::Auth::get_session($sessionID)->param('waiting-for-2FA'), undef, 'Second auth not required' );
327 $patron->encode_secret('one_secret');
328 $patron->auth_method('two-factor');
330 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired', undef, 'intranet' );
331 is( $userid, $patron->userid, 'Succesful login' );
332 my $session = C4::Auth::get_session($sessionID);
333 is( C4::Auth::get_session($sessionID)->param('waiting-for-2FA'), 1, 'Second auth required' );
336 $otp_token = "wrong";
338 $patron->auth_method('two-factor')->store;
339 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired', undef, 'intranet' );
340 is( $userid, $patron->userid, 'Succesful login' );
341 is( C4::Auth::get_session($sessionID)->param('waiting-for-2FA'), 1, 'Second auth still required after wrong OTP token' );
345 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired', undef, 'intranet' );
346 is( $userid, $patron->userid, 'Succesful login' );
347 is( C4::Auth::get_session($sessionID)->param('waiting-for-2FA'), 0, 'Second auth no longer required if OTP token has been verified' );
350 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired', undef, 'opac' );
351 is( $userid, $patron->userid, 'Succesful login at the OPAC' );
352 is( C4::Auth::get_session($sessionID)->param('waiting-for-2FA'), undef, 'No second auth required at the OPAC' );
354 t::lib::Mocks::mock_preference( 'TwoFactorAuthentication', 0 );
357 C4::Context->_new_userenv; # For next tests
361 subtest 'track_login_daily tests' => sub {
365 my $patron = $builder->build_object({ class => 'Koha::Patrons' });
366 my $userid = $patron->userid;
368 $patron->lastseen( undef );
371 my $cache = Koha::Caches->get_instance();
372 my $cache_key = "track_login_" . $patron->userid;
373 $cache->clear_from_cache($cache_key);
375 t::lib::Mocks::mock_preference( 'TrackLastPatronActivity', '1' );
377 is( $patron->lastseen, undef, 'Patron should have not last seen when newly created' );
379 C4::Auth::track_login_daily( $userid );
380 $patron->_result()->discard_changes();
381 isnt( $patron->lastseen, undef, 'Patron should have last seen set when TrackLastPatronActivity = 1' );
383 sleep(1); # We need to wait a tiny bit to make sure the timestamp will be different
384 my $last_seen = $patron->lastseen;
385 C4::Auth::track_login_daily( $userid );
386 $patron->_result()->discard_changes();
387 is( $patron->lastseen, $last_seen, 'Patron last seen should still be unchanged' );
389 $cache->clear_from_cache($cache_key);
390 C4::Auth::track_login_daily( $userid );
391 $patron->_result()->discard_changes();
392 isnt( $patron->lastseen, $last_seen, 'Patron last seen should be changed if we cleared the cache' );
394 t::lib::Mocks::mock_preference( 'TrackLastPatronActivity', '0' );
395 $patron->lastseen( undef )->store;
396 $cache->clear_from_cache($cache_key);
397 C4::Auth::track_login_daily( $userid );
398 $patron->_result()->discard_changes();
399 is( $patron->lastseen, undef, 'Patron should still have last seen unchanged when TrackLastPatronActivity = 0' );
403 subtest 'no_set_userenv parameter tests' => sub {
407 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
408 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
409 my $password = 'password';
411 t::lib::Mocks::mock_preference( 'RequireStrongPassword', 0 );
412 $patron->set_password({ password => $password });
414 ok( checkpw( $dbh, $patron->userid, $password, undef, undef, 1 ), 'checkpw returns true' );
415 is( C4::Context->userenv, undef, 'Userenv should be undef as required' );
416 C4::Context->_new_userenv('DUMMY SESSION');
417 C4::Context->set_userenv(0,0,0,'firstname','surname', $library->branchcode, 'Library 1', 0, '', '');
418 is( C4::Context->userenv->{branch}, $library->branchcode, 'Userenv gives correct branch' );
419 ok( checkpw( $dbh, $patron->userid, $password, undef, undef, 1 ), 'checkpw returns true' );
420 is( C4::Context->userenv->{branch}, $library->branchcode, 'Userenv branch is preserved if no_set_userenv is true' );
421 ok( checkpw( $dbh, $patron->userid, $password, undef, undef, 0 ), 'checkpw still returns true' );
422 isnt( C4::Context->userenv->{branch}, $library->branchcode, 'Userenv branch is overwritten if no_set_userenv is false' );
425 subtest 'checkpw lockout tests' => sub {
429 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
430 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
431 my $password = 'password';
432 t::lib::Mocks::mock_preference( 'RequireStrongPassword', 0 );
433 t::lib::Mocks::mock_preference( 'FailedLoginAttempts', 1 );
434 $patron->set_password({ password => $password });
436 my ( $checkpw, undef, undef ) = checkpw( $dbh, $patron->cardnumber, $password, undef, undef, 1 );
437 ok( $checkpw, 'checkpw returns true with right password when logging in via cardnumber' );
438 ( $checkpw, undef, undef ) = checkpw( $dbh, $patron->userid, "wrong_password", undef, undef, 1 );
439 is( $checkpw, 0, 'checkpw returns false when given wrong password' );
440 $patron = $patron->get_from_storage;
441 is( $patron->account_locked, 1, "Account is locked from failed login");
442 ( $checkpw, undef, undef ) = checkpw( $dbh, $patron->userid, $password, undef, undef, 1 );
443 is( $checkpw, undef, 'checkpw returns undef with right password when account locked' );
444 ( $checkpw, undef, undef ) = checkpw( $dbh, $patron->cardnumber, $password, undef, undef, 1 );
445 is( $checkpw, undef, 'checkpw returns undefwith right password when logging in via cardnumber if account locked' );
449 # get_template_and_user tests
451 subtest 'get_template_and_user' => sub { # Tests for the language URL parameter
453 sub MockedCheckauth {
454 my ($query,$authnotrequired,$flagsrequired,$type) = @_;
456 my $userid = 'cobain';
458 # we don't need to bother about permissions for this test
460 superlibrarian => 1, acquisition => 0,
462 catalogue => 1, circulate => 0,
463 coursereserves => 0, editauthorities => 0,
465 parameters => 0, permissions => 0,
466 plugins => 0, reports => 0,
467 reserveforothers => 0, serials => 0,
468 staffaccess => 0, tools => 0,
472 my $session_cookie = $query->cookie(
473 -name => 'CGISESSID',
478 return ( $userid, [ $session_cookie ], $sessionID, $flags );
481 # Mock checkauth, build the scenario
482 my $auth = Test::MockModule->new( 'C4::Auth' );
483 $auth->mock( 'checkauth', \&MockedCheckauth );
485 # Make sure 'EnableOpacSearchHistory' is set
486 t::lib::Mocks::mock_preference('EnableOpacSearchHistory',1);
487 # Enable es-ES for the OPAC and staff interfaces
488 t::lib::Mocks::mock_preference('OPACLanguages','en,es-ES');
489 t::lib::Mocks::mock_preference('language','en,es-ES');
491 # we need a session cookie
492 $ENV{"SERVER_PORT"} = 80;
493 $ENV{"HTTP_COOKIE"} = 'CGISESSID=nirvana';
495 my $query = CGI->new;
496 $query->param('language','es-ES');
498 my ( $template, $loggedinuser, $cookies ) = get_template_and_user(
500 template_name => "about.tt",
503 authnotrequired => 1,
504 flagsrequired => { catalogue => 1 },
509 ok ( ( all { ref($_) eq 'CGI::Cookie' } @$cookies ),
510 'BZ9735: the cookies array is flat' );
512 # new query, with non-existent language (we only have en and es-ES)
513 $query->param('language','tomas');
515 ( $template, $loggedinuser, $cookies ) = get_template_and_user(
517 template_name => "about.tt",
520 authnotrequired => 1,
521 flagsrequired => { catalogue => 1 },
526 ok( ( none { $_->name eq 'KohaOpacLanguage' and $_->value eq 'tomas' } @$cookies ),
527 'BZ9735: invalid language, it is not set');
529 ok( ( any { $_->name eq 'KohaOpacLanguage' and $_->value eq 'en' } @$cookies ),
530 'BZ9735: invalid language, then default to en');
532 for my $template_name (
534 ../../../../../../../../../../../../../../../etc/passwd
535 test/../../../../../../../../../../../../../../etc/passwd
537 test/does_not_finished_by_tt_t
541 ( $template, $loggedinuser, $cookies ) = get_template_and_user(
543 template_name => $template_name,
546 authnotrequired => 1,
547 flagsrequired => { catalogue => 1 },
551 like ( $@, qr(bad template path), "The file $template_name should not be accessible" );
553 ( $template, $loggedinuser, $cookies ) = get_template_and_user(
555 template_name => 'errors/errorpage.tt',
558 authnotrequired => 1,
559 flagsrequired => { catalogue => 1 },
562 my $file_exists = ( -f $template->{filename} ) ? 1 : 0;
563 is ( $file_exists, 1, 'The file errors/errorpage.tt should be accessible (contains integers)' );
565 # Regression test for env opac search limit override
566 $ENV{"OPAC_SEARCH_LIMIT"} = "branch:CPL";
567 $ENV{"OPAC_LIMIT_OVERRIDE"} = 1;
569 ( $template, $loggedinuser, $cookies) = get_template_and_user(
571 template_name => 'opac-main.tt',
574 authnotrequired => 1,
577 is($template->{VARS}->{'opac_name'}, "CPL", "Opac name was set correctly");
578 is($template->{VARS}->{'opac_search_limit'}, "branch:CPL", "Search limit was set correctly");
580 $ENV{"OPAC_SEARCH_LIMIT"} = "branch:multibranch-19";
582 ( $template, $loggedinuser, $cookies) = get_template_and_user(
584 template_name => 'opac-main.tt',
587 authnotrequired => 1,
590 is($template->{VARS}->{'opac_name'}, "multibranch-19", "Opac name was set correctly");
591 is($template->{VARS}->{'opac_search_limit'}, "branch:multibranch-19", "Search limit was set correctly");
592 ok(defined($template->{VARS}->{'csrf_token'}), "CSRF token returned");
594 delete $ENV{"HTTP_COOKIE"};
597 # Check that there is always an OPACBaseURL set.
598 my $input = CGI->new();
599 my ( $template1, $borrowernumber, $cookie );
600 ( $template1, $borrowernumber, $cookie ) = get_template_and_user(
602 template_name => "opac-detail.tt",
605 authnotrequired => 1,
609 ok( ( any { 'OPACBaseURL' eq $_ } keys %{$template1->{VARS}} ),
610 'OPACBaseURL is in OPAC template' );
613 ( $template2, $borrowernumber, $cookie ) = get_template_and_user(
615 template_name => "catalogue/detail.tt",
618 authnotrequired => 1,
622 ok( ( any { 'OPACBaseURL' eq $_ } keys %{$template2->{VARS}} ),
623 'OPACBaseURL is in Staff template' );
625 my $hash1 = hash_password('password');
626 my $hash2 = hash_password('password');
628 ok(C4::Auth::checkpw_hash('password', $hash1), 'password validates with first hash');
629 ok(C4::Auth::checkpw_hash('password', $hash2), 'password validates with second hash');
631 subtest 'Check value of login_attempts in checkpw' => sub {
634 t::lib::Mocks::mock_preference('FailedLoginAttempts', 3);
636 # Only interested here in regular login
640 my $patron = $builder->build_object({ class => 'Koha::Patrons' });
641 $patron->login_attempts(2);
642 $patron->password('123')->store; # yes, deliberately not hashed
644 is( $patron->account_locked, 0, 'Patron not locked' );
645 my @test = checkpw( $dbh, $patron->userid, '123', undef, 'opac', 1 );
646 # Note: 123 will not be hashed to 123 !
647 is( $test[0], 0, 'checkpw should have failed' );
648 $patron->discard_changes; # refresh
649 is( $patron->login_attempts, 3, 'Login attempts increased' );
650 is( $patron->account_locked, 1, 'Check locked status' );
652 # And another try to go over the limit: different return value!
653 @test = checkpw( $dbh, $patron->userid, '123', undef, 'opac', 1 );
654 is( @test, 0, 'checkpw failed again and returns nothing now' );
655 $patron->discard_changes; # refresh
656 is( $patron->login_attempts, 3, 'Login attempts not increased anymore' );
658 # Administrative lockout cannot be undone?
659 # Pass the right password now (or: add a nice mock).
660 my $auth = Test::MockModule->new( 'C4::Auth' );
661 $auth->mock( 'checkpw_hash', sub { return 1; } ); # not for production :)
662 $patron->login_attempts(0)->store;
663 @test = checkpw( $dbh, $patron->userid, '123', undef, 'opac', 1 );
664 is( $test[0], 1, 'Build confidence in the mock' );
665 $patron->login_attempts(-1)->store;
666 is( $patron->account_locked, 1, 'Check administrative lockout' );
667 @test = checkpw( $dbh, $patron->userid, '123', undef, 'opac', 1 );
668 is( @test, 0, 'checkpw gave red' );
669 $patron->discard_changes; # refresh
670 is( $patron->login_attempts, -1, 'Still locked out' );
671 t::lib::Mocks::mock_preference('FailedLoginAttempts', ''); # disable
672 is( $patron->account_locked, 1, 'Check administrative lockout without pref' );
675 subtest 'Check value of login_attempts in checkpw' => sub {
678 t::lib::Mocks::mock_preference('FailedLoginAttempts', 3);
679 my $patron = $builder->build_object({ class => 'Koha::Patrons' });
680 $patron->set_password({ password => '123', skip_validation => 1 });
682 my @test = checkpw( $dbh, $patron->userid, '123', undef, 'opac', 1 );
683 is( $test[0], 1, 'Patron authenticated correctly' );
685 $patron->password_expiration_date('2020-01-01')->store;
686 @test = checkpw( $dbh, $patron->userid, '123', undef, 'opac', 1 );
687 is( $test[0], -2, 'Patron returned as expired correctly' );
691 subtest '_timeout_syspref' => sub {
695 t::lib::Mocks::mock_preference('timeout', "100");
696 is( C4::Auth::_timeout_syspref, 100, );
698 t::lib::Mocks::mock_preference('timeout', "2d");
699 is( C4::Auth::_timeout_syspref, 2*86400, );
701 t::lib::Mocks::mock_preference('timeout', "2D");
702 is( C4::Auth::_timeout_syspref, 2*86400, );
704 t::lib::Mocks::mock_preference('timeout', "10h");
705 is( C4::Auth::_timeout_syspref, 10*3600, );
707 t::lib::Mocks::mock_preference('timeout', "10x");
709 { is( C4::Auth::_timeout_syspref, 600, ); }
710 "The value of the system preference 'timeout' is not correct, defaulting to 600",
711 'Bad values throw a warning and fallback to 600';
714 subtest 'check_cookie_auth' => sub {
717 t::lib::Mocks::mock_preference('timeout', "1d"); # back to default
719 my $patron = $builder->build_object({ class => 'Koha::Patrons', value => { flags => 1 } });
721 # Mock a CGI object with real userid param
722 my $cgi = Test::MockObject->new();
727 if ( $var eq 'userid' ) { return $patron->userid; }
730 $cgi->mock('multi_param', sub {return q{}} );
731 $cgi->mock( 'cookie', sub { return; } );
732 $cgi->mock( 'request_method', sub { return 'POST' } );
734 $ENV{REMOTE_ADDR} = '127.0.0.1';
736 # Setting authnotrequired=1 or we wont' hit the return but the end of the sub that prints headers
737 my ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 1 );
739 my ($auth_status, $session) = C4::Auth::check_cookie_auth($sessionID);
740 isnt( $auth_status, 'ok', 'check_cookie_auth should not return ok if the user has not been authenticated before if no permissions needed' );
741 is( $auth_status, 'anon', 'check_cookie_auth should return anon if the user has not been authenticated before and no permissions needed' );
743 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 1 );
745 ($auth_status, $session) = C4::Auth::check_cookie_auth($sessionID, {catalogue => 1});
746 isnt( $auth_status, 'ok', 'check_cookie_auth should not return ok if the user has not been authenticated before and permissions needed' );
747 is( $auth_status, 'anon', 'check_cookie_auth should return anon if the user has not been authenticated before and permissions needed' );
749 #FIXME We should have a test to cover 'failed' status when a user has logged in, but doesn't have permission
752 subtest 'checkauth & check_cookie_auth' => sub {
755 # flags = 4 => { catalogue => 1 }
756 my $patron = $builder->build_object({ class => 'Koha::Patrons', value => { flags => 4 } });
757 my $password = 'password';
758 t::lib::Mocks::mock_preference( 'RequireStrongPassword', 0 );
759 $patron->set_password( { password => $password } );
761 my $cgi_mock = Test::MockModule->new('CGI');
762 $cgi_mock->mock( 'request_method', sub { return 'POST' } );
766 my $auth = Test::MockModule->new( 'C4::Auth' );
767 # Tests will fail if we hit safe_exit
768 $auth->mock( 'safe_exit', sub { return } );
770 my ( $userid, $cookie, $sessionID, $flags );
772 # checkauth will redirect and safe_exit if not authenticated and not authorized
775 open STDOUT, '>', \$stdout;
776 C4::Auth::checkauth($cgi, 0, {catalogue => 1});
777 like( $stdout, qr{<title>\s*Log in to your account} );
778 $sessionID = ( $stdout =~ m{Set-Cookie: CGISESSID=((\d|\w)+);} ) ? $1 : undef;
783 my $first_sessionID = $sessionID;
785 $ENV{"HTTP_COOKIE"} = "CGISESSID=$sessionID";
786 # Not authenticated yet, checkauth didn't return the session
790 open STDOUT, '>', \$stdout;
791 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 0, {catalogue => 1} );
794 is( $sessionID, undef);
797 # Sending undefined fails obviously
798 my ( $auth_status, $session ) = C4::Auth::check_cookie_auth($sessionID, {catalogue => 1} );
799 is( $auth_status, 'failed' );
800 is( $session, undef );
802 # Simulating the login form submission
803 $cgi->param('userid', $patron->userid);
804 $cgi->param('password', $password);
807 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 0, {catalogue => 1});
808 is( $sessionID, $first_sessionID );
809 is( $userid, $patron->userid );
811 ( $auth_status, $session ) = C4::Auth::check_cookie_auth($sessionID, {catalogue => 1});
812 is( $auth_status, 'ok' );
813 is( $session->id, $first_sessionID );
816 $cgi->param('logout.x', 1);
817 $cgi->delete( 'userid', 'password' );
821 open STDOUT, '>', \$stdout;
822 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 0, {catalogue => 1});
825 is( $sessionID, undef );
826 is( $ENV{"HTTP_COOKIE"}, "CGISESSID=$first_sessionID", 'HTTP_COOKIE not unset' );
827 ( $auth_status, $session) = C4::Auth::check_cookie_auth( $first_sessionID, {catalogue => 1} );
828 is( $auth_status, "expired");
829 is( $session, undef );
832 # Trying to access without sessionID
834 ( $auth_status, $session) = C4::Auth::check_cookie_auth(undef, {catalogue => 1});
835 is( $auth_status, 'failed' );
836 is( $session, undef );
838 # This will fail on permissions
839 undef $ENV{"HTTP_COOKIE"};
843 open STDOUT, '>', \$stdout;
844 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 0, {catalogue => 1} );
847 is( $userid, undef );
848 is( $sessionID, undef );
854 $cgi->param('userid', $patron->userid);
855 $cgi->param('password', $password);
856 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 0, {catalogue => 1});
857 is( $userid, $patron->userid );
858 $first_sessionID = $sessionID;
860 # Patron does not have the borrowers permission
861 # $ENV{"HTTP_COOKIE"} = "CGISESSID=$sessionID"; # not needed, we use $cgi here
865 open STDOUT, '>', \$stdout;
866 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 0, {borrowers => 1} );
869 is( $userid, undef );
870 is( $sessionID, undef );
872 # When calling check_cookie_auth, the session will be deleted
873 ( $auth_status, $session) = C4::Auth::check_cookie_auth( $first_sessionID, { borrowers => 1 } );
874 is( $auth_status, "failed" );
875 is( $session, undef );
876 ( $auth_status, $session) = C4::Auth::check_cookie_auth( $first_sessionID, { borrowers => 1 } );
877 is( $auth_status, 'expired', 'Session no longer exists' );
879 # NOTE: It is not what the UI is doing.
880 # From the UI we are allowed to hit an unauthorized page then reuse the session to hit back authorized area.
881 # It is because check_cookie_auth is ALWAYS called from checkauth WITHOUT $flagsrequired
882 # It then return "ok", when the previous called got "failed"
884 # Try reusing the deleted session: since it does not exist, we should get a new one now when passing correct permissions
885 $cgi->cookie( -name => 'CGISESSID', value => $first_sessionID );
886 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 0, {catalogue => 1});
887 is( $userid, $patron->userid );
888 isnt( $sessionID, undef, 'Check if we have a sessionID' );
889 isnt( $sessionID, $first_sessionID, 'New value expected' );
890 ( $auth_status, $session) = C4::Auth::check_cookie_auth( $sessionID, {catalogue => 1} );
891 is( $auth_status, "ok" );
892 is( $session->id, $sessionID, 'Same session' );
893 # Two additional tests on userenv
894 is( $C4::Context::context->{activeuser}, $session->id, 'Check if environment has been setup for session' );
895 is( C4::Context->userenv->{id}, $userid, 'Check userid in userenv' );
899 subtest 'Userenv clearing in check_cookie_auth' => sub {
900 # Note: We did already test userenv for a logged-in user in previous subtest
903 t::lib::Mocks::mock_preference( 'timeout', 600 );
906 # Create a new anonymous session by passing a fake session ID
907 $cgi->cookie( -name => 'CGISESSID', -value => 'fake_sessionID' );
908 my ($userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 1);
909 my ( $auth_status, $session) = C4::Auth::check_cookie_auth( $sessionID );
910 is( $auth_status, 'anon', 'Should be anonymous' );
911 is( $C4::Context::context->{activeuser}, $session->id, 'Check activeuser' );
912 is( defined C4::Context->userenv, 1, 'There should be a userenv' );
913 is( C4::Context->userenv->{id}, q{}, 'userid should be empty string' );
915 # Make the session expire now, check_cookie_auth will delete it
916 $session->param('lasttime', time() - 1200 );
918 ( $auth_status, $session) = C4::Auth::check_cookie_auth( $sessionID );
919 is( $auth_status, 'expired', 'Should be expired' );
920 is( C4::Context->userenv, undef, 'Environment should be cleared too' );
922 # Show that we clear the userenv again: set up env and check deleted session
923 C4::Context->_new_userenv( $sessionID );
924 C4::Context->set_userenv; # empty
925 is( defined C4::Context->userenv, 1, 'There should be an empty userenv again' );
926 ( $auth_status, $session) = C4::Auth::check_cookie_auth( $sessionID );
927 is( $auth_status, 'expired', 'Should be expired already' );
928 is( C4::Context->userenv, undef, 'Environment should be cleared again' );
931 $schema->storage->txn_rollback;
933 subtest 'checkpw() return values tests' => sub {
937 subtest 'Internal check tests' => sub {
941 $schema->storage->txn_begin;
944 my $password_expired;
946 my $mock_patron = Test::MockModule->new('Koha::Patron');
947 $mock_patron->mock( 'account_locked', sub { return $account_locked; } );
948 $mock_patron->mock( 'password_expired', sub { return $password_expired; } );
950 # Only interested here in regular login
951 t::lib::Mocks::mock_config( 'useshibboleth', undef );
955 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
956 my $password = 'thePassword123';
957 $patron->set_password( { password => $password, skip_validation => 1 } );
959 my $patron_to_delete = $builder->build_object( { class => 'Koha::Patrons' } );
960 my $unused_userid = $patron_to_delete->userid;
961 my $unused_cardnumber = $patron_to_delete->cardnumber;
962 $patron_to_delete->delete;
965 my @return = checkpw( $patron->userid, $password, undef, );
966 is_deeply( \@return, [], 'If the account is locked, empty list is returned' );
970 my @matchpoints = qw(userid cardnumber);
971 foreach my $matchpoint (@matchpoints) {
973 @return = checkpw( $patron->$matchpoint, $password, undef, );
975 is( $return[0], 1, "Password validation successful returns 1 ($matchpoint)" );
976 is( $return[1], $patron->cardnumber, '`cardnumber` returned' );
977 is( $return[2], $patron->userid, '`userid` returned' );
978 is( ref( $return[3] ), 'Koha::Patron', 'Koha::Patron object reference returned' );
979 is( $return[3]->id, $patron->id, 'Correct patron returned' );
982 @return = checkpw( $patron->userid, $password . 'hey', undef, );
984 is( scalar @return, 2, "Two results on invalid password scenario" );
985 is( $return[0], 0, '0 returned on invalid password' );
986 is( ref( $return[1] ), 'Koha::Patron' );
987 is( $return[1]->id, $patron->id, 'Patron matched correctly' );
989 $password_expired = 1;
990 @return = checkpw( $patron->userid, $password, undef, );
992 is( scalar @return, 2, "Two results on expired password scenario" );
993 is( $return[0], -2, '-2 returned' );
994 is( ref( $return[1] ), 'Koha::Patron' );
995 is( $return[1]->id, $patron->id, 'Patron matched correctly' );
997 @return = checkpw( $unused_userid, $password, undef, );
999 is( scalar @return, 2, "Two results on non-existing userid scenario" );
1000 is( $return[0], 0, '0 returned' );
1001 is( $return[1], undef, 'Undef returned, representing no match' );
1003 @return = checkpw( $unused_cardnumber, $password, undef, );
1005 is( scalar @return, 2, "Only one result on non-existing cardnumber scenario" );
1006 is( $return[0], 0, '0 returned' );
1007 is( $return[1], undef, 'Undef returned, representing no match' );
1009 $schema->storage->txn_rollback;
1012 subtest 'CAS check (mocked) tests' => sub {
1016 $schema->storage->txn_begin;
1019 my $password_expired;
1021 my $mock_patron = Test::MockModule->new('Koha::Patron');
1022 $mock_patron->mock( 'account_locked', sub { return $account_locked; } );
1023 $mock_patron->mock( 'password_expired', sub { return $password_expired; } );
1025 # Only interested here in regular login
1026 t::lib::Mocks::mock_config( 'useshibboleth', undef );
1028 $C4::Auth::ldap = 0;
1030 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
1031 my $password = 'thePassword123';
1032 $patron->set_password( { password => $password, skip_validation => 1 } );
1034 my $patron_to_delete = $builder->build_object( { class => 'Koha::Patrons' } );
1035 my $unused_userid = $patron_to_delete->userid;
1036 my $unused_cardnumber = $patron_to_delete->cardnumber;
1037 $patron_to_delete->delete;
1039 my $ticket = '123456';
1040 my $query = CGI->new;
1041 $query->param( -name => 'ticket', -value => $ticket );
1043 my @cas_return = ( 1, $patron->cardnumber, $patron->userid, $ticket, Koha::Patrons->find( $patron->id ) );
1045 my $cas_mock = Test::MockModule->new('C4::Auth');
1046 $cas_mock->mock( 'checkpw_cas', sub { return @cas_return; } );
1048 $account_locked = 1;
1049 my @return = checkpw( $patron->userid, $password, $query, );
1050 is_deeply( \@return, [], 'If the account is locked, empty list is returned' );
1052 $account_locked = 0;
1054 my @matchpoints = qw(userid cardnumber);
1055 foreach my $matchpoint (@matchpoints) {
1057 @return = checkpw( $patron->$matchpoint, $password, $query, );
1059 is( $return[0], 1, "Password validation successful returns 1 ($matchpoint)" );
1060 is( $return[1], $patron->cardnumber, '`cardnumber` returned' );
1061 is( $return[2], $patron->userid, '`userid` returned' );
1062 is( ref( $return[3] ), 'Koha::Patron', 'Koha::Patron object reference returned' );
1063 is( $return[3]->id, $patron->id, 'Correct patron returned' );
1066 @return = checkpw( $patron->userid, $password . 'hey', $query, );
1068 is( scalar @return, 2, "Two results on invalid password scenario" );
1069 is( $return[0], 0, '0 returned on invalid password' );
1070 is( ref( $return[1] ), 'Koha::Patron' );
1071 is( $return[1]->id, $patron->id, 'Patron matched correctly' );
1073 $password_expired = 1;
1074 @return = checkpw( $patron->userid, $password, $query, );
1076 is( scalar @return, 2, "Two results on expired password scenario" );
1077 is( $return[0], -2, '-2 returned' );
1078 is( ref( $return[1] ), 'Koha::Patron' );
1079 is( $return[1]->id, $patron->id, 'Patron matched correctly' );
1081 @return = checkpw( $unused_userid, $password, $query, );
1083 is( scalar @return, 2, "Two results on non-existing userid scenario" );
1084 is( $return[0], 0, '0 returned' );
1085 is( $return[1], undef, 'Undef returned, representing no match' );
1087 @return = checkpw( $unused_cardnumber, $password, $query, );
1089 is( scalar @return, 2, "Only one result on non-existing cardnumber scenario" );
1090 is( $return[0], 0, '0 returned' );
1091 is( $return[1], undef, 'Undef returned, representing no match' );
1093 $schema->storage->txn_rollback;
1096 subtest 'Shibboleth check (mocked) tests' => sub {
1100 $schema->storage->txn_begin;
1103 my $password_expired;
1105 my $mock_patron = Test::MockModule->new('Koha::Patron');
1106 $mock_patron->mock( 'account_locked', sub { return $account_locked; } );
1107 $mock_patron->mock( 'password_expired', sub { return $password_expired; } );
1109 # Only interested here in regular login
1110 t::lib::Mocks::mock_config( 'useshibboleth', 1 );
1112 $C4::Auth::ldap = 0;
1114 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
1115 my $password = 'thePassword123';
1116 $patron->set_password( { password => $password, skip_validation => 1 } );
1118 my $patron_to_delete = $builder->build_object( { class => 'Koha::Patrons' } );
1119 my $unused_userid = $patron_to_delete->userid;
1120 my $unused_cardnumber = $patron_to_delete->cardnumber;
1121 $patron_to_delete->delete;
1123 my @shib_return = ( 1, $patron->cardnumber, $patron->userid, Koha::Patrons->find( $patron->id ) );
1125 my $auth_mock = Test::MockModule->new('C4::Auth');
1126 $auth_mock->mock( 'shib_ok', 1 );
1127 $auth_mock->mock( 'get_login_shib', 1 );
1129 my $shib_mock = Test::MockModule->new('C4::Auth_with_shibboleth');
1130 $shib_mock->mock( 'checkpw_shib', sub { return @shib_return; } );
1132 $account_locked = 1;
1133 my @return = checkpw( $patron->userid );
1134 is_deeply( \@return, [], 'If the account is locked, empty list is returned' );
1136 $account_locked = 0;
1138 @return = checkpw();
1140 is( $return[0], 1, "Password validation successful returns 1" );
1141 is( $return[1], $patron->cardnumber, '`cardnumber` returned' );
1142 is( $return[2], $patron->userid, '`userid` returned' );
1143 is( ref( $return[3] ), 'Koha::Patron', 'Koha::Patron object reference returned' );
1144 is( $return[3]->id, $patron->id, 'Correct patron returned' );
1146 $schema->storage->txn_rollback;