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 => 16;
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 'While still logged in, relogin with another user' => sub {
159 my $patron = $builder->build_object({ class => 'Koha::Patrons', value => {} });
160 my $patron2 = $builder->build_object({ class => 'Koha::Patrons', value => {} });
161 # Create 'former' session
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', 'opac' );
169 my $sessionID = $session->id;
170 C4::Context->_new_userenv($sessionID);
172 my ( $return ) = C4::Auth::check_cookie_auth( $sessionID, undef, { skip_version_check => 1, remote_addr => '1.2.3.4' } );
173 is( $return, 'ok', 'Former session in shape now' );
175 my $mock1 = Test::MockModule->new('C4::Auth');
176 $mock1->mock( 'safe_exit', sub {} );
177 my $mock2 = Test::MockModule->new('CGI');
178 $mock2->mock( 'request_method', 'POST' );
179 $mock2->mock( 'cookie', sub { return $sessionID; } ); # oversimplified..
181 my $password = 'Incr3d1blyZtr@ng93$';
182 $patron2->set_password({ password => $password });
183 $cgi->param( -name => 'userid', -value => $patron2->userid );
184 $cgi->param( -name => 'password', -value => $password );
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 # Note: We can test return values from checkauth here since we mocked the safe_exit after the Redirect 303
196 is( $return[0], $patron2->userid, 'Login of patron2 approved' );
197 isnt( $return[2], $sessionID, 'Did not return previous session ID' );
198 ok( $return[2], 'New session ID not empty' );
200 # Similar situation: Relogin with former session of $patron, new user $patron2 has no permissions
201 $patron2->flags(undef)->store;
202 $session->param( 'number', $patron->id );
203 $session->param( 'id', $patron->userid );
204 $session->param( 'interface', 'intranet' );
206 $sessionID = $session->id;
207 C4::Context->_new_userenv($sessionID);
208 $cgi->param( -name => 'userid', -value => $patron2->userid );
209 $cgi->param( -name => 'password', -value => $password );
210 $cgi->param( -name => 'koha_login_context', -value => 1 );
214 $ENV{REMOTE_ADDR} = '1.2.3.4';
216 open STDOUT, '>', \$stdout;
217 @return = C4::Auth::checkauth( $cgi, 0, { catalogue => 1 }, 'intranet' ); # patron2 has no catalogue perm
220 like( $stdout, qr/You do not have permission to access this page/, 'No permission response' );
221 is( @return, 0, 'checkauth returned failure' );
224 subtest 'Two-factor authentication' => sub {
226 my $patron = $builder->build_object(
227 { class => 'Koha::Patrons', value => { flags => 1 } } );
228 my $password = 'password';
229 $patron->set_password( { password => $password } );
230 $cgi = Test::MockObject->new();
233 our ( $logout, $sessionID, $verified );
237 my ( $self, $param ) = @_;
238 if ( $param eq 'userid' ) { return $patron->userid; }
239 elsif ( $param eq 'password' ) { return $password; }
240 elsif ( $param eq 'otp_token' ) { return $otp_token; }
241 elsif ( $param eq 'logout.x' ) { return $logout; }
245 $cgi->mock( 'request_method', sub { return 'POST' } );
246 $cgi->mock( 'cookie', sub { return $sessionID } );
248 my $two_factor_auth = Test::MockModule->new( 'Koha::Auth::TwoFactorAuth' );
249 $two_factor_auth->mock( 'verify', sub {$verified} );
251 my ( $userid, $cookie, $flags );
252 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired', undef, 'intranet' );
258 C4::Auth::checkauth( $cgi, 'authrequired', undef, 'intranet' );
262 t::lib::Mocks::mock_preference( 'TwoFactorAuthentication', 0 );
263 $patron->auth_method('password')->store;
264 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired', undef, 'intranet' );
265 is( $userid, $patron->userid, 'Succesful login' );
266 is( C4::Auth::get_session($sessionID)->param('waiting-for-2FA'), undef, 'Second auth not required' );
269 $patron->auth_method('two-factor')->store;
270 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired', undef, 'intranet' );
271 is( $userid, $patron->userid, 'Succesful login' );
272 is( C4::Auth::get_session($sessionID)->param('waiting-for-2FA'), undef, 'Second auth not required' );
275 t::lib::Mocks::mock_preference( 'TwoFactorAuthentication', 1 );
276 t::lib::Mocks::mock_config('encryption_key', '1234tH1s=t&st');
277 $patron->auth_method('password')->store;
278 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired', undef, 'intranet' );
279 is( $userid, $patron->userid, 'Succesful login' );
280 is( C4::Auth::get_session($sessionID)->param('waiting-for-2FA'), undef, 'Second auth not required' );
283 $patron->encode_secret('one_secret');
284 $patron->auth_method('two-factor');
286 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired', undef, 'intranet' );
287 is( $userid, $patron->userid, 'Succesful login' );
288 my $session = C4::Auth::get_session($sessionID);
289 is( C4::Auth::get_session($sessionID)->param('waiting-for-2FA'), 1, 'Second auth required' );
292 $otp_token = "wrong";
294 $patron->auth_method('two-factor')->store;
295 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired', undef, 'intranet' );
296 is( $userid, $patron->userid, 'Succesful login' );
297 is( C4::Auth::get_session($sessionID)->param('waiting-for-2FA'), 1, 'Second auth still required after wrong OTP token' );
301 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired', undef, 'intranet' );
302 is( $userid, $patron->userid, 'Succesful login' );
303 is( C4::Auth::get_session($sessionID)->param('waiting-for-2FA'), 0, 'Second auth no longer required if OTP token has been verified' );
306 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired', undef, 'opac' );
307 is( $userid, $patron->userid, 'Succesful login at the OPAC' );
308 is( C4::Auth::get_session($sessionID)->param('waiting-for-2FA'), undef, 'No second auth required at the OPAC' );
310 t::lib::Mocks::mock_preference( 'TwoFactorAuthentication', 0 );
313 C4::Context->_new_userenv; # For next tests
317 subtest 'track_login_daily tests' => sub {
321 my $patron = $builder->build_object({ class => 'Koha::Patrons' });
322 my $userid = $patron->userid;
324 $patron->lastseen( undef );
327 my $cache = Koha::Caches->get_instance();
328 my $cache_key = "track_login_" . $patron->userid;
329 $cache->clear_from_cache($cache_key);
331 t::lib::Mocks::mock_preference( 'TrackLastPatronActivity', '1' );
333 is( $patron->lastseen, undef, 'Patron should have not last seen when newly created' );
335 C4::Auth::track_login_daily( $userid );
336 $patron->_result()->discard_changes();
337 isnt( $patron->lastseen, undef, 'Patron should have last seen set when TrackLastPatronActivity = 1' );
339 sleep(1); # We need to wait a tiny bit to make sure the timestamp will be different
340 my $last_seen = $patron->lastseen;
341 C4::Auth::track_login_daily( $userid );
342 $patron->_result()->discard_changes();
343 is( $patron->lastseen, $last_seen, 'Patron last seen should still be unchanged' );
345 $cache->clear_from_cache($cache_key);
346 C4::Auth::track_login_daily( $userid );
347 $patron->_result()->discard_changes();
348 isnt( $patron->lastseen, $last_seen, 'Patron last seen should be changed if we cleared the cache' );
350 t::lib::Mocks::mock_preference( 'TrackLastPatronActivity', '0' );
351 $patron->lastseen( undef )->store;
352 $cache->clear_from_cache($cache_key);
353 C4::Auth::track_login_daily( $userid );
354 $patron->_result()->discard_changes();
355 is( $patron->lastseen, undef, 'Patron should still have last seen unchanged when TrackLastPatronActivity = 0' );
359 subtest 'no_set_userenv parameter tests' => sub {
363 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
364 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
365 my $password = 'password';
367 t::lib::Mocks::mock_preference( 'RequireStrongPassword', 0 );
368 $patron->set_password({ password => $password });
370 ok( checkpw( $dbh, $patron->userid, $password, undef, undef, 1 ), 'checkpw returns true' );
371 is( C4::Context->userenv, undef, 'Userenv should be undef as required' );
372 C4::Context->_new_userenv('DUMMY SESSION');
373 C4::Context->set_userenv(0,0,0,'firstname','surname', $library->branchcode, 'Library 1', 0, '', '');
374 is( C4::Context->userenv->{branch}, $library->branchcode, 'Userenv gives correct branch' );
375 ok( checkpw( $dbh, $patron->userid, $password, undef, undef, 1 ), 'checkpw returns true' );
376 is( C4::Context->userenv->{branch}, $library->branchcode, 'Userenv branch is preserved if no_set_userenv is true' );
377 ok( checkpw( $dbh, $patron->userid, $password, undef, undef, 0 ), 'checkpw still returns true' );
378 isnt( C4::Context->userenv->{branch}, $library->branchcode, 'Userenv branch is overwritten if no_set_userenv is false' );
381 subtest 'checkpw lockout tests' => sub {
385 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
386 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
387 my $password = 'password';
388 t::lib::Mocks::mock_preference( 'RequireStrongPassword', 0 );
389 t::lib::Mocks::mock_preference( 'FailedLoginAttempts', 1 );
390 $patron->set_password({ password => $password });
392 my ( $checkpw, undef, undef ) = checkpw( $dbh, $patron->cardnumber, $password, undef, undef, 1 );
393 ok( $checkpw, 'checkpw returns true with right password when logging in via cardnumber' );
394 ( $checkpw, undef, undef ) = checkpw( $dbh, $patron->userid, "wrong_password", undef, undef, 1 );
395 is( $checkpw, 0, 'checkpw returns false when given wrong password' );
396 $patron = $patron->get_from_storage;
397 is( $patron->account_locked, 1, "Account is locked from failed login");
398 ( $checkpw, undef, undef ) = checkpw( $dbh, $patron->userid, $password, undef, undef, 1 );
399 is( $checkpw, undef, 'checkpw returns undef with right password when account locked' );
400 ( $checkpw, undef, undef ) = checkpw( $dbh, $patron->cardnumber, $password, undef, undef, 1 );
401 is( $checkpw, undef, 'checkpw returns undefwith right password when logging in via cardnumber if account locked' );
405 # get_template_and_user tests
407 subtest 'get_template_and_user' => sub { # Tests for the language URL parameter
409 sub MockedCheckauth {
410 my ($query,$authnotrequired,$flagsrequired,$type) = @_;
412 my $userid = 'cobain';
414 # we don't need to bother about permissions for this test
416 superlibrarian => 1, acquisition => 0,
418 catalogue => 1, circulate => 0,
419 coursereserves => 0, editauthorities => 0,
421 parameters => 0, permissions => 0,
422 plugins => 0, reports => 0,
423 reserveforothers => 0, serials => 0,
424 staffaccess => 0, tools => 0,
428 my $session_cookie = $query->cookie(
429 -name => 'CGISESSID',
434 return ( $userid, [ $session_cookie ], $sessionID, $flags );
437 # Mock checkauth, build the scenario
438 my $auth = Test::MockModule->new( 'C4::Auth' );
439 $auth->mock( 'checkauth', \&MockedCheckauth );
441 # Make sure 'EnableOpacSearchHistory' is set
442 t::lib::Mocks::mock_preference('EnableOpacSearchHistory',1);
443 # Enable es-ES for the OPAC and staff interfaces
444 t::lib::Mocks::mock_preference('OPACLanguages','en,es-ES');
445 t::lib::Mocks::mock_preference('language','en,es-ES');
447 # we need a session cookie
448 $ENV{"SERVER_PORT"} = 80;
449 $ENV{"HTTP_COOKIE"} = 'CGISESSID=nirvana';
451 my $query = CGI->new;
452 $query->param('language','es-ES');
454 my ( $template, $loggedinuser, $cookies ) = get_template_and_user(
456 template_name => "about.tt",
459 authnotrequired => 1,
460 flagsrequired => { catalogue => 1 },
465 ok ( ( all { ref($_) eq 'CGI::Cookie' } @$cookies ),
466 'BZ9735: the cookies array is flat' );
468 # new query, with non-existent language (we only have en and es-ES)
469 $query->param('language','tomas');
471 ( $template, $loggedinuser, $cookies ) = get_template_and_user(
473 template_name => "about.tt",
476 authnotrequired => 1,
477 flagsrequired => { catalogue => 1 },
482 ok( ( none { $_->name eq 'KohaOpacLanguage' and $_->value eq 'tomas' } @$cookies ),
483 'BZ9735: invalid language, it is not set');
485 ok( ( any { $_->name eq 'KohaOpacLanguage' and $_->value eq 'en' } @$cookies ),
486 'BZ9735: invalid language, then default to en');
488 for my $template_name (
490 ../../../../../../../../../../../../../../../etc/passwd
491 test/../../../../../../../../../../../../../../etc/passwd
493 test/does_not_finished_by_tt_t
497 ( $template, $loggedinuser, $cookies ) = get_template_and_user(
499 template_name => $template_name,
502 authnotrequired => 1,
503 flagsrequired => { catalogue => 1 },
507 like ( $@, qr(bad template path), "The file $template_name should not be accessible" );
509 ( $template, $loggedinuser, $cookies ) = get_template_and_user(
511 template_name => 'errors/errorpage.tt',
514 authnotrequired => 1,
515 flagsrequired => { catalogue => 1 },
518 my $file_exists = ( -f $template->{filename} ) ? 1 : 0;
519 is ( $file_exists, 1, 'The file errors/errorpage.tt should be accessible (contains integers)' );
521 # Regression test for env opac search limit override
522 $ENV{"OPAC_SEARCH_LIMIT"} = "branch:CPL";
523 $ENV{"OPAC_LIMIT_OVERRIDE"} = 1;
525 ( $template, $loggedinuser, $cookies) = get_template_and_user(
527 template_name => 'opac-main.tt',
530 authnotrequired => 1,
533 is($template->{VARS}->{'opac_name'}, "CPL", "Opac name was set correctly");
534 is($template->{VARS}->{'opac_search_limit'}, "branch:CPL", "Search limit was set correctly");
536 $ENV{"OPAC_SEARCH_LIMIT"} = "branch:multibranch-19";
538 ( $template, $loggedinuser, $cookies) = get_template_and_user(
540 template_name => 'opac-main.tt',
543 authnotrequired => 1,
546 is($template->{VARS}->{'opac_name'}, "multibranch-19", "Opac name was set correctly");
547 is($template->{VARS}->{'opac_search_limit'}, "branch:multibranch-19", "Search limit was set correctly");
549 delete $ENV{"HTTP_COOKIE"};
552 # Check that there is always an OPACBaseURL set.
553 my $input = CGI->new();
554 my ( $template1, $borrowernumber, $cookie );
555 ( $template1, $borrowernumber, $cookie ) = get_template_and_user(
557 template_name => "opac-detail.tt",
560 authnotrequired => 1,
564 ok( ( any { 'OPACBaseURL' eq $_ } keys %{$template1->{VARS}} ),
565 'OPACBaseURL is in OPAC template' );
568 ( $template2, $borrowernumber, $cookie ) = get_template_and_user(
570 template_name => "catalogue/detail.tt",
573 authnotrequired => 1,
577 ok( ( any { 'OPACBaseURL' eq $_ } keys %{$template2->{VARS}} ),
578 'OPACBaseURL is in Staff template' );
580 my $hash1 = hash_password('password');
581 my $hash2 = hash_password('password');
583 ok(C4::Auth::checkpw_hash('password', $hash1), 'password validates with first hash');
584 ok(C4::Auth::checkpw_hash('password', $hash2), 'password validates with second hash');
586 subtest 'Check value of login_attempts in checkpw' => sub {
589 t::lib::Mocks::mock_preference('FailedLoginAttempts', 3);
591 # Only interested here in regular login
595 my $patron = $builder->build_object({ class => 'Koha::Patrons' });
596 $patron->login_attempts(2);
597 $patron->password('123')->store; # yes, deliberately not hashed
599 is( $patron->account_locked, 0, 'Patron not locked' );
600 my @test = checkpw( $dbh, $patron->userid, '123', undef, 'opac', 1 );
601 # Note: 123 will not be hashed to 123 !
602 is( $test[0], 0, 'checkpw should have failed' );
603 $patron->discard_changes; # refresh
604 is( $patron->login_attempts, 3, 'Login attempts increased' );
605 is( $patron->account_locked, 1, 'Check locked status' );
607 # And another try to go over the limit: different return value!
608 @test = checkpw( $dbh, $patron->userid, '123', undef, 'opac', 1 );
609 is( @test, 0, 'checkpw failed again and returns nothing now' );
610 $patron->discard_changes; # refresh
611 is( $patron->login_attempts, 3, 'Login attempts not increased anymore' );
613 # Administrative lockout cannot be undone?
614 # Pass the right password now (or: add a nice mock).
615 my $auth = Test::MockModule->new( 'C4::Auth' );
616 $auth->mock( 'checkpw_hash', sub { return 1; } ); # not for production :)
617 $patron->login_attempts(0)->store;
618 @test = checkpw( $dbh, $patron->userid, '123', undef, 'opac', 1 );
619 is( $test[0], 1, 'Build confidence in the mock' );
620 $patron->login_attempts(-1)->store;
621 is( $patron->account_locked, 1, 'Check administrative lockout' );
622 @test = checkpw( $dbh, $patron->userid, '123', undef, 'opac', 1 );
623 is( @test, 0, 'checkpw gave red' );
624 $patron->discard_changes; # refresh
625 is( $patron->login_attempts, -1, 'Still locked out' );
626 t::lib::Mocks::mock_preference('FailedLoginAttempts', ''); # disable
627 is( $patron->account_locked, 1, 'Check administrative lockout without pref' );
630 subtest 'Check value of login_attempts in checkpw' => sub {
633 t::lib::Mocks::mock_preference('FailedLoginAttempts', 3);
634 my $patron = $builder->build_object({ class => 'Koha::Patrons' });
635 $patron->set_password({ password => '123', skip_validation => 1 });
637 my @test = checkpw( $dbh, $patron->userid, '123', undef, 'opac', 1 );
638 is( $test[0], 1, 'Patron authenticated correctly' );
640 $patron->password_expiration_date('2020-01-01')->store;
641 @test = checkpw( $dbh, $patron->userid, '123', undef, 'opac', 1 );
642 is( $test[0], -2, 'Patron returned as expired correctly' );
646 subtest '_timeout_syspref' => sub {
650 t::lib::Mocks::mock_preference('timeout', "100");
651 is( C4::Auth::_timeout_syspref, 100, );
653 t::lib::Mocks::mock_preference('timeout', "2d");
654 is( C4::Auth::_timeout_syspref, 2*86400, );
656 t::lib::Mocks::mock_preference('timeout', "2D");
657 is( C4::Auth::_timeout_syspref, 2*86400, );
659 t::lib::Mocks::mock_preference('timeout', "10h");
660 is( C4::Auth::_timeout_syspref, 10*3600, );
662 t::lib::Mocks::mock_preference('timeout', "10x");
664 { is( C4::Auth::_timeout_syspref, 600, ); }
665 "The value of the system preference 'timeout' is not correct, defaulting to 600",
666 'Bad values throw a warning and fallback to 600';
669 subtest 'check_cookie_auth' => sub {
672 t::lib::Mocks::mock_preference('timeout', "1d"); # back to default
674 my $patron = $builder->build_object({ class => 'Koha::Patrons', value => { flags => 1 } });
676 # Mock a CGI object with real userid param
677 my $cgi = Test::MockObject->new();
682 if ( $var eq 'userid' ) { return $patron->userid; }
685 $cgi->mock('multi_param', sub {return q{}} );
686 $cgi->mock( 'cookie', sub { return; } );
687 $cgi->mock( 'request_method', sub { return 'POST' } );
689 $ENV{REMOTE_ADDR} = '127.0.0.1';
691 # Setting authnotrequired=1 or we wont' hit the return but the end of the sub that prints headers
692 my ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 1 );
694 my ($auth_status, $session) = C4::Auth::check_cookie_auth($sessionID);
695 isnt( $auth_status, 'ok', 'check_cookie_auth should not return ok if the user has not been authenticated before if no permissions needed' );
696 is( $auth_status, 'anon', 'check_cookie_auth should return anon if the user has not been authenticated before and no permissions needed' );
698 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 1 );
700 ($auth_status, $session) = C4::Auth::check_cookie_auth($sessionID, {catalogue => 1});
701 isnt( $auth_status, 'ok', 'check_cookie_auth should not return ok if the user has not been authenticated before and permissions needed' );
702 is( $auth_status, 'anon', 'check_cookie_auth should return anon if the user has not been authenticated before and permissions needed' );
704 #FIXME We should have a test to cover 'failed' status when a user has logged in, but doesn't have permission
707 subtest 'checkauth & check_cookie_auth' => sub {
710 # flags = 4 => { catalogue => 1 }
711 my $patron = $builder->build_object({ class => 'Koha::Patrons', value => { flags => 4 } });
712 my $password = 'password';
713 t::lib::Mocks::mock_preference( 'RequireStrongPassword', 0 );
714 $patron->set_password( { password => $password } );
716 my $cgi_mock = Test::MockModule->new('CGI');
717 $cgi_mock->mock( 'request_method', sub { return 'POST' } );
721 my $auth = Test::MockModule->new( 'C4::Auth' );
722 # Tests will fail if we hit safe_exit
723 $auth->mock( 'safe_exit', sub { return } );
725 my ( $userid, $cookie, $sessionID, $flags );
727 # checkauth will redirect and safe_exit if not authenticated and not authorized
730 open STDOUT, '>', \$stdout;
731 C4::Auth::checkauth($cgi, 0, {catalogue => 1});
732 like( $stdout, qr{<title>\s*Log in to your account} );
733 $sessionID = ( $stdout =~ m{Set-Cookie: CGISESSID=((\d|\w)+);} ) ? $1 : undef;
738 my $first_sessionID = $sessionID;
740 $ENV{"HTTP_COOKIE"} = "CGISESSID=$sessionID";
741 # Not authenticated yet, checkauth didn't return the session
745 open STDOUT, '>', \$stdout;
746 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 0, {catalogue => 1} );
749 is( $sessionID, undef);
752 # Sending undefined fails obviously
753 my ( $auth_status, $session ) = C4::Auth::check_cookie_auth($sessionID, {catalogue => 1} );
754 is( $auth_status, 'failed' );
755 is( $session, undef );
757 # Simulating the login form submission
758 $cgi->param('userid', $patron->userid);
759 $cgi->param('password', $password);
762 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 0, {catalogue => 1});
763 is( $sessionID, $first_sessionID );
764 is( $userid, $patron->userid );
766 ( $auth_status, $session ) = C4::Auth::check_cookie_auth($sessionID, {catalogue => 1});
767 is( $auth_status, 'ok' );
768 is( $session->id, $first_sessionID );
771 $cgi->param('logout.x', 1);
772 $cgi->delete( 'userid', 'password' );
776 open STDOUT, '>', \$stdout;
777 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 0, {catalogue => 1});
780 is( $sessionID, undef );
781 is( $ENV{"HTTP_COOKIE"}, "CGISESSID=$first_sessionID", 'HTTP_COOKIE not unset' );
782 ( $auth_status, $session) = C4::Auth::check_cookie_auth( $first_sessionID, {catalogue => 1} );
783 is( $auth_status, "expired");
784 is( $session, undef );
787 # Trying to access without sessionID
789 ( $auth_status, $session) = C4::Auth::check_cookie_auth(undef, {catalogue => 1});
790 is( $auth_status, 'failed' );
791 is( $session, undef );
793 # This will fail on permissions
794 undef $ENV{"HTTP_COOKIE"};
798 open STDOUT, '>', \$stdout;
799 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 0, {catalogue => 1} );
802 is( $userid, undef );
803 is( $sessionID, undef );
809 $cgi->param('userid', $patron->userid);
810 $cgi->param('password', $password);
811 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 0, {catalogue => 1});
812 is( $userid, $patron->userid );
813 $first_sessionID = $sessionID;
815 # Patron does not have the borrowers permission
816 # $ENV{"HTTP_COOKIE"} = "CGISESSID=$sessionID"; # not needed, we use $cgi here
820 open STDOUT, '>', \$stdout;
821 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 0, {borrowers => 1} );
824 is( $userid, undef );
825 is( $sessionID, undef );
827 # When calling check_cookie_auth, the session will be deleted
828 ( $auth_status, $session) = C4::Auth::check_cookie_auth( $first_sessionID, { borrowers => 1 } );
829 is( $auth_status, "failed" );
830 is( $session, undef );
831 ( $auth_status, $session) = C4::Auth::check_cookie_auth( $first_sessionID, { borrowers => 1 } );
832 is( $auth_status, 'expired', 'Session no longer exists' );
834 # NOTE: It is not what the UI is doing.
835 # From the UI we are allowed to hit an unauthorized page then reuse the session to hit back authorized area.
836 # It is because check_cookie_auth is ALWAYS called from checkauth WITHOUT $flagsrequired
837 # It then return "ok", when the previous called got "failed"
839 # Try reusing the deleted session: since it does not exist, we should get a new one now when passing correct permissions
840 $cgi->cookie( -name => 'CGISESSID', value => $first_sessionID );
841 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 0, {catalogue => 1});
842 is( $userid, $patron->userid );
843 isnt( $sessionID, undef, 'Check if we have a sessionID' );
844 isnt( $sessionID, $first_sessionID, 'New value expected' );
845 ( $auth_status, $session) = C4::Auth::check_cookie_auth( $sessionID, {catalogue => 1} );
846 is( $auth_status, "ok" );
847 is( $session->id, $sessionID, 'Same session' );
848 # Two additional tests on userenv
849 is( $C4::Context::context->{activeuser}, $session->id, 'Check if environment has been setup for session' );
850 is( C4::Context->userenv->{id}, $userid, 'Check userid in userenv' );
854 subtest 'Userenv clearing in check_cookie_auth' => sub {
855 # Note: We did already test userenv for a logged-in user in previous subtest
858 t::lib::Mocks::mock_preference( 'timeout', 600 );
861 # Create a new anonymous session by passing a fake session ID
862 $cgi->cookie( -name => 'CGISESSID', -value => 'fake_sessionID' );
863 my ($userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 1);
864 my ( $auth_status, $session) = C4::Auth::check_cookie_auth( $sessionID );
865 is( $auth_status, 'anon', 'Should be anonymous' );
866 is( $C4::Context::context->{activeuser}, $session->id, 'Check activeuser' );
867 is( defined C4::Context->userenv, 1, 'There should be a userenv' );
868 is( C4::Context->userenv->{id}, q{}, 'userid should be empty string' );
870 # Make the session expire now, check_cookie_auth will delete it
871 $session->param('lasttime', time() - 1200 );
873 ( $auth_status, $session) = C4::Auth::check_cookie_auth( $sessionID );
874 is( $auth_status, 'expired', 'Should be expired' );
875 is( C4::Context->userenv, undef, 'Environment should be cleared too' );
877 # Show that we clear the userenv again: set up env and check deleted session
878 C4::Context->_new_userenv( $sessionID );
879 C4::Context->set_userenv; # empty
880 is( defined C4::Context->userenv, 1, 'There should be an empty userenv again' );
881 ( $auth_status, $session) = C4::Auth::check_cookie_auth( $sessionID );
882 is( $auth_status, 'expired', 'Should be expired already' );
883 is( C4::Context->userenv, undef, 'Environment should be cleared again' );
886 $schema->storage->txn_rollback;