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 => 15;
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 $schema->storage->txn_begin;
40 subtest 'checkauth() tests' => sub {
44 my $patron = $builder->build_object({ class => 'Koha::Patrons', value => { flags => undef } });
46 # Mock a CGI object with real userid param
47 my $cgi = Test::MockObject->new();
52 if ( $var eq 'userid' ) { return $patron->userid; }
55 $cgi->mock( 'cookie', sub { return; } );
56 $cgi->mock( 'request_method', sub { return 'POST' } );
58 my $authnotrequired = 1;
59 my ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, $authnotrequired );
61 is( $userid, undef, 'checkauth() returns undef for userid if no logged in user (Bug 18275)' );
63 my $db_user_id = C4::Context->config('user');
64 my $db_user_pass = C4::Context->config('pass');
65 $cgi = Test::MockObject->new();
66 $cgi->mock( 'cookie', sub { return; } );
67 $cgi->mock( 'param', sub {
68 my ( $self, $param ) = @_;
69 if ( $param eq 'userid' ) { return $db_user_id; }
70 elsif ( $param eq 'password' ) { return $db_user_pass; }
73 $cgi->mock( 'request_method', sub { return 'POST' } );
74 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, $authnotrequired );
75 is ( $userid, undef, 'If DB user is used, it should not be logged in' );
77 my $is_allowed = C4::Auth::haspermission( $db_user_id, { can_do => 'everything' } );
79 # FIXME This belongs to t/db_dependent/Auth/haspermission.t but we do not want to c/p the pervious mock statements
80 ok( !$is_allowed, 'DB user should not have any permissions');
82 subtest 'Prevent authentication when sending credential via GET' => sub {
86 my $patron = $builder->build_object(
87 { class => 'Koha::Patrons', value => { flags => 1 } } );
88 my $password = 'password';
89 t::lib::Mocks::mock_preference( 'RequireStrongPassword', 0 );
90 $patron->set_password( { password => $password } );
91 $cgi = Test::MockObject->new();
92 $cgi->mock( 'cookie', sub { return; } );
96 my ( $self, $param ) = @_;
97 if ( $param eq 'userid' ) { return $patron->userid; }
98 elsif ( $param eq 'password' ) { return $password; }
103 $cgi->mock( 'request_method', sub { return 'POST' } );
104 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired' );
105 is( $userid, $patron->userid, 'If librarian user is used and password with POST, they should be logged in' );
107 $cgi->mock( 'request_method', sub { return 'GET' } );
108 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired' );
109 is( $userid, undef, 'If librarian user is used and password with GET, they should not be logged in' );
112 subtest 'Two-factor authentication' => sub {
114 my $patron = $builder->build_object(
115 { class => 'Koha::Patrons', value => { flags => 1 } } );
116 my $password = 'password';
117 $patron->set_password( { password => $password } );
118 $cgi = Test::MockObject->new();
121 our ( $logout, $sessionID, $verified );
125 my ( $self, $param ) = @_;
126 if ( $param eq 'userid' ) { return $patron->userid; }
127 elsif ( $param eq 'password' ) { return $password; }
128 elsif ( $param eq 'otp_token' ) { return $otp_token; }
129 elsif ( $param eq 'logout.x' ) { return $logout; }
133 $cgi->mock( 'request_method', sub { return 'POST' } );
134 $cgi->mock( 'cookie', sub { return $sessionID } );
136 my $two_factor_auth = Test::MockModule->new( 'Koha::Auth::TwoFactorAuth' );
137 $two_factor_auth->mock( 'verify', sub {$verified} );
139 my ( $userid, $cookie, $flags );
140 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired', undef, 'intranet' );
146 C4::Auth::checkauth( $cgi, 'authrequired', undef, 'intranet' );
150 t::lib::Mocks::mock_preference( 'TwoFactorAuthentication', 0 );
151 $patron->secret('one_secret');
152 $patron->auth_method('password');
154 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired', undef, 'intranet' );
155 is( $userid, $patron->userid, 'Succesful login' );
156 is( C4::Auth::get_session($sessionID)->param('waiting-for-2FA'), undef, 'Second auth not required' );
159 $patron->auth_method('two-factor')->store;
160 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired', undef, 'intranet' );
161 is( $userid, $patron->userid, 'Succesful login' );
162 is( C4::Auth::get_session($sessionID)->param('waiting-for-2FA'), undef, 'Second auth not required' );
165 t::lib::Mocks::mock_preference( 'TwoFactorAuthentication', 1 );
166 $patron->auth_method('password')->store;
167 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired', undef, 'intranet' );
168 is( $userid, $patron->userid, 'Succesful login' );
169 is( C4::Auth::get_session($sessionID)->param('waiting-for-2FA'), undef, 'Second auth not required' );
172 $patron->auth_method('two-factor')->store;
173 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired', undef, 'intranet' );
174 is( $userid, $patron->userid, 'Succesful login' );
175 my $session = C4::Auth::get_session($sessionID);
176 is( C4::Auth::get_session($sessionID)->param('waiting-for-2FA'), 1, 'Second auth required' );
179 $otp_token = "wrong";
181 $patron->auth_method('two-factor')->store;
182 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired', undef, 'intranet' );
183 is( $userid, $patron->userid, 'Succesful login' );
184 is( C4::Auth::get_session($sessionID)->param('waiting-for-2FA'), 1, 'Second auth still required after wrong OTP token' );
188 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired', undef, 'intranet' );
189 is( $userid, $patron->userid, 'Succesful login' );
190 is( C4::Auth::get_session($sessionID)->param('waiting-for-2FA'), 0, 'Second auth no longer required if OTP token has been verified' );
194 C4::Context->_new_userenv; # For next tests
198 subtest 'track_login_daily tests' => sub {
202 my $patron = $builder->build_object({ class => 'Koha::Patrons' });
203 my $userid = $patron->userid;
205 $patron->lastseen( undef );
208 my $cache = Koha::Caches->get_instance();
209 my $cache_key = "track_login_" . $patron->userid;
210 $cache->clear_from_cache($cache_key);
212 t::lib::Mocks::mock_preference( 'TrackLastPatronActivity', '1' );
214 is( $patron->lastseen, undef, 'Patron should have not last seen when newly created' );
216 C4::Auth::track_login_daily( $userid );
217 $patron->_result()->discard_changes();
218 isnt( $patron->lastseen, undef, 'Patron should have last seen set when TrackLastPatronActivity = 1' );
220 sleep(1); # We need to wait a tiny bit to make sure the timestamp will be different
221 my $last_seen = $patron->lastseen;
222 C4::Auth::track_login_daily( $userid );
223 $patron->_result()->discard_changes();
224 is( $patron->lastseen, $last_seen, 'Patron last seen should still be unchanged' );
226 $cache->clear_from_cache($cache_key);
227 C4::Auth::track_login_daily( $userid );
228 $patron->_result()->discard_changes();
229 isnt( $patron->lastseen, $last_seen, 'Patron last seen should be changed if we cleared the cache' );
231 t::lib::Mocks::mock_preference( 'TrackLastPatronActivity', '0' );
232 $patron->lastseen( undef )->store;
233 $cache->clear_from_cache($cache_key);
234 C4::Auth::track_login_daily( $userid );
235 $patron->_result()->discard_changes();
236 is( $patron->lastseen, undef, 'Patron should still have last seen unchanged when TrackLastPatronActivity = 0' );
240 subtest 'no_set_userenv parameter tests' => sub {
244 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
245 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
246 my $password = 'password';
248 t::lib::Mocks::mock_preference( 'RequireStrongPassword', 0 );
249 $patron->set_password({ password => $password });
251 ok( checkpw( $dbh, $patron->userid, $password, undef, undef, 1 ), 'checkpw returns true' );
252 is( C4::Context->userenv, undef, 'Userenv should be undef as required' );
253 C4::Context->_new_userenv('DUMMY SESSION');
254 C4::Context->set_userenv(0,0,0,'firstname','surname', $library->branchcode, 'Library 1', 0, '', '');
255 is( C4::Context->userenv->{branch}, $library->branchcode, 'Userenv gives correct branch' );
256 ok( checkpw( $dbh, $patron->userid, $password, undef, undef, 1 ), 'checkpw returns true' );
257 is( C4::Context->userenv->{branch}, $library->branchcode, 'Userenv branch is preserved if no_set_userenv is true' );
258 ok( checkpw( $dbh, $patron->userid, $password, undef, undef, 0 ), 'checkpw still returns true' );
259 isnt( C4::Context->userenv->{branch}, $library->branchcode, 'Userenv branch is overwritten if no_set_userenv is false' );
262 subtest 'checkpw lockout tests' => sub {
266 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
267 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
268 my $password = 'password';
269 t::lib::Mocks::mock_preference( 'RequireStrongPassword', 0 );
270 t::lib::Mocks::mock_preference( 'FailedLoginAttempts', 1 );
271 $patron->set_password({ password => $password });
273 my ( $checkpw, undef, undef ) = checkpw( $dbh, $patron->cardnumber, $password, undef, undef, 1 );
274 ok( $checkpw, 'checkpw returns true with right password when logging in via cardnumber' );
275 ( $checkpw, undef, undef ) = checkpw( $dbh, $patron->userid, "wrong_password", undef, undef, 1 );
276 is( $checkpw, 0, 'checkpw returns false when given wrong password' );
277 $patron = $patron->get_from_storage;
278 is( $patron->account_locked, 1, "Account is locked from failed login");
279 ( $checkpw, undef, undef ) = checkpw( $dbh, $patron->userid, $password, undef, undef, 1 );
280 is( $checkpw, undef, 'checkpw returns undef with right password when account locked' );
281 ( $checkpw, undef, undef ) = checkpw( $dbh, $patron->cardnumber, $password, undef, undef, 1 );
282 is( $checkpw, undef, 'checkpw returns undefwith right password when logging in via cardnumber if account locked' );
286 # get_template_and_user tests
288 subtest 'get_template_and_user' => sub { # Tests for the language URL parameter
290 sub MockedCheckauth {
291 my ($query,$authnotrequired,$flagsrequired,$type) = @_;
293 my $userid = 'cobain';
295 # we don't need to bother about permissions for this test
297 superlibrarian => 1, acquisition => 0,
299 catalogue => 1, circulate => 0,
300 coursereserves => 0, editauthorities => 0,
302 parameters => 0, permissions => 0,
303 plugins => 0, reports => 0,
304 reserveforothers => 0, serials => 0,
305 staffaccess => 0, tools => 0,
309 my $session_cookie = $query->cookie(
310 -name => 'CGISESSID',
315 return ( $userid, [ $session_cookie ], $sessionID, $flags );
318 # Mock checkauth, build the scenario
319 my $auth = Test::MockModule->new( 'C4::Auth' );
320 $auth->mock( 'checkauth', \&MockedCheckauth );
322 # Make sure 'EnableOpacSearchHistory' is set
323 t::lib::Mocks::mock_preference('EnableOpacSearchHistory',1);
324 # Enable es-ES for the OPAC and staff interfaces
325 t::lib::Mocks::mock_preference('OPACLanguages','en,es-ES');
326 t::lib::Mocks::mock_preference('language','en,es-ES');
328 # we need a session cookie
329 $ENV{"SERVER_PORT"} = 80;
330 $ENV{"HTTP_COOKIE"} = 'CGISESSID=nirvana';
332 my $query = CGI->new;
333 $query->param('language','es-ES');
335 my ( $template, $loggedinuser, $cookies ) = get_template_and_user(
337 template_name => "about.tt",
340 authnotrequired => 1,
341 flagsrequired => { catalogue => 1 },
346 ok ( ( all { ref($_) eq 'CGI::Cookie' } @$cookies ),
347 'BZ9735: the cookies array is flat' );
349 # new query, with non-existent language (we only have en and es-ES)
350 $query->param('language','tomas');
352 ( $template, $loggedinuser, $cookies ) = get_template_and_user(
354 template_name => "about.tt",
357 authnotrequired => 1,
358 flagsrequired => { catalogue => 1 },
363 ok( ( none { $_->name eq 'KohaOpacLanguage' and $_->value eq 'tomas' } @$cookies ),
364 'BZ9735: invalid language, it is not set');
366 ok( ( any { $_->name eq 'KohaOpacLanguage' and $_->value eq 'en' } @$cookies ),
367 'BZ9735: invalid language, then default to en');
369 for my $template_name (
371 ../../../../../../../../../../../../../../../etc/passwd
372 test/../../../../../../../../../../../../../../etc/passwd
374 test/does_not_finished_by_tt_t
378 ( $template, $loggedinuser, $cookies ) = get_template_and_user(
380 template_name => $template_name,
383 authnotrequired => 1,
384 flagsrequired => { catalogue => 1 },
388 like ( $@, qr(bad template path), "The file $template_name should not be accessible" );
390 ( $template, $loggedinuser, $cookies ) = get_template_and_user(
392 template_name => 'errors/errorpage.tt',
395 authnotrequired => 1,
396 flagsrequired => { catalogue => 1 },
399 my $file_exists = ( -f $template->{filename} ) ? 1 : 0;
400 is ( $file_exists, 1, 'The file errors/errorpage.tt should be accessible (contains integers)' );
402 # Regression test for env opac search limit override
403 $ENV{"OPAC_SEARCH_LIMIT"} = "branch:CPL";
404 $ENV{"OPAC_LIMIT_OVERRIDE"} = 1;
406 ( $template, $loggedinuser, $cookies) = get_template_and_user(
408 template_name => 'opac-main.tt',
411 authnotrequired => 1,
414 is($template->{VARS}->{'opac_name'}, "CPL", "Opac name was set correctly");
415 is($template->{VARS}->{'opac_search_limit'}, "branch:CPL", "Search limit was set correctly");
417 $ENV{"OPAC_SEARCH_LIMIT"} = "branch:multibranch-19";
419 ( $template, $loggedinuser, $cookies) = get_template_and_user(
421 template_name => 'opac-main.tt',
424 authnotrequired => 1,
427 is($template->{VARS}->{'opac_name'}, "multibranch-19", "Opac name was set correctly");
428 is($template->{VARS}->{'opac_search_limit'}, "branch:multibranch-19", "Search limit was set correctly");
430 delete $ENV{"HTTP_COOKIE"};
433 # Check that there is always an OPACBaseURL set.
434 my $input = CGI->new();
435 my ( $template1, $borrowernumber, $cookie );
436 ( $template1, $borrowernumber, $cookie ) = get_template_and_user(
438 template_name => "opac-detail.tt",
441 authnotrequired => 1,
445 ok( ( any { 'OPACBaseURL' eq $_ } keys %{$template1->{VARS}} ),
446 'OPACBaseURL is in OPAC template' );
449 ( $template2, $borrowernumber, $cookie ) = get_template_and_user(
451 template_name => "catalogue/detail.tt",
454 authnotrequired => 1,
458 ok( ( any { 'OPACBaseURL' eq $_ } keys %{$template2->{VARS}} ),
459 'OPACBaseURL is in Staff template' );
461 my $hash1 = hash_password('password');
462 my $hash2 = hash_password('password');
464 ok(C4::Auth::checkpw_hash('password', $hash1), 'password validates with first hash');
465 ok(C4::Auth::checkpw_hash('password', $hash2), 'password validates with second hash');
467 subtest 'Check value of login_attempts in checkpw' => sub {
470 t::lib::Mocks::mock_preference('FailedLoginAttempts', 3);
472 # Only interested here in regular login
476 my $patron = $builder->build_object({ class => 'Koha::Patrons' });
477 $patron->login_attempts(2);
478 $patron->password('123')->store; # yes, deliberately not hashed
480 is( $patron->account_locked, 0, 'Patron not locked' );
481 my @test = checkpw( $dbh, $patron->userid, '123', undef, 'opac', 1 );
482 # Note: 123 will not be hashed to 123 !
483 is( $test[0], 0, 'checkpw should have failed' );
484 $patron->discard_changes; # refresh
485 is( $patron->login_attempts, 3, 'Login attempts increased' );
486 is( $patron->account_locked, 1, 'Check locked status' );
488 # And another try to go over the limit: different return value!
489 @test = checkpw( $dbh, $patron->userid, '123', undef, 'opac', 1 );
490 is( @test, 0, 'checkpw failed again and returns nothing now' );
491 $patron->discard_changes; # refresh
492 is( $patron->login_attempts, 3, 'Login attempts not increased anymore' );
494 # Administrative lockout cannot be undone?
495 # Pass the right password now (or: add a nice mock).
496 my $auth = Test::MockModule->new( 'C4::Auth' );
497 $auth->mock( 'checkpw_hash', sub { return 1; } ); # not for production :)
498 $patron->login_attempts(0)->store;
499 @test = checkpw( $dbh, $patron->userid, '123', undef, 'opac', 1 );
500 is( $test[0], 1, 'Build confidence in the mock' );
501 $patron->login_attempts(-1)->store;
502 is( $patron->account_locked, 1, 'Check administrative lockout' );
503 @test = checkpw( $dbh, $patron->userid, '123', undef, 'opac', 1 );
504 is( @test, 0, 'checkpw gave red' );
505 $patron->discard_changes; # refresh
506 is( $patron->login_attempts, -1, 'Still locked out' );
507 t::lib::Mocks::mock_preference('FailedLoginAttempts', ''); # disable
508 is( $patron->account_locked, 1, 'Check administrative lockout without pref' );
511 subtest '_timeout_syspref' => sub {
514 t::lib::Mocks::mock_preference('timeout', "100");
515 is( C4::Auth::_timeout_syspref, 100, );
517 t::lib::Mocks::mock_preference('timeout', "2d");
518 is( C4::Auth::_timeout_syspref, 2*86400, );
520 t::lib::Mocks::mock_preference('timeout', "2D");
521 is( C4::Auth::_timeout_syspref, 2*86400, );
523 t::lib::Mocks::mock_preference('timeout', "10h");
524 is( C4::Auth::_timeout_syspref, 10*3600, );
526 t::lib::Mocks::mock_preference('timeout', "10x");
527 is( C4::Auth::_timeout_syspref, 600, );
530 subtest 'check_cookie_auth' => sub {
533 t::lib::Mocks::mock_preference('timeout', "1d"); # back to default
535 my $patron = $builder->build_object({ class => 'Koha::Patrons', value => { flags => 1 } });
537 # Mock a CGI object with real userid param
538 my $cgi = Test::MockObject->new();
543 if ( $var eq 'userid' ) { return $patron->userid; }
546 $cgi->mock('multi_param', sub {return q{}} );
547 $cgi->mock( 'cookie', sub { return; } );
548 $cgi->mock( 'request_method', sub { return 'POST' } );
550 $ENV{REMOTE_ADDR} = '127.0.0.1';
552 # Setting authnotrequired=1 or we wont' hit the return but the end of the sub that prints headers
553 my ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 1 );
555 my ($auth_status, $session) = C4::Auth::check_cookie_auth($sessionID);
556 isnt( $auth_status, 'ok', 'check_cookie_auth should not return ok if the user has not been authenticated before if no permissions needed' );
557 is( $auth_status, 'anon', 'check_cookie_auth should return anon if the user has not been authenticated before and no permissions needed' );
559 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 1 );
561 ($auth_status, $session) = C4::Auth::check_cookie_auth($sessionID, {catalogue => 1});
562 isnt( $auth_status, 'ok', 'check_cookie_auth should not return ok if the user has not been authenticated before and permissions needed' );
563 is( $auth_status, 'anon', 'check_cookie_auth should return anon if the user has not been authenticated before and permissions needed' );
565 #FIXME We should have a test to cover 'failed' status when a user has logged in, but doesn't have permission
568 subtest 'checkauth & check_cookie_auth' => sub {
571 # flags = 4 => { catalogue => 1 }
572 my $patron = $builder->build_object({ class => 'Koha::Patrons', value => { flags => 4 } });
573 my $password = 'password';
574 t::lib::Mocks::mock_preference( 'RequireStrongPassword', 0 );
575 $patron->set_password( { password => $password } );
577 my $cgi_mock = Test::MockModule->new('CGI');
578 $cgi_mock->mock( 'request_method', sub { return 'POST' } );
582 my $auth = Test::MockModule->new( 'C4::Auth' );
583 # Tests will fail if we hit safe_exit
584 $auth->mock( 'safe_exit', sub { return } );
586 my ( $userid, $cookie, $sessionID, $flags );
588 # checkauth will redirect and safe_exit if not authenticated and not authorized
591 open STDOUT, '>', \$stdout;
592 C4::Auth::checkauth($cgi, 0, {catalogue => 1});
593 like( $stdout, qr{<title>\s*Log in to your account} );
594 $sessionID = ( $stdout =~ m{Set-Cookie: CGISESSID=((\d|\w)+);} ) ? $1 : undef;
599 my $first_sessionID = $sessionID;
601 $ENV{"HTTP_COOKIE"} = "CGISESSID=$sessionID";
602 # Not authenticated yet, checkauth didn't return the session
606 open STDOUT, '>', \$stdout;
607 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 0, {catalogue => 1} );
610 is( $sessionID, undef);
613 # Sending undefined fails obviously
614 my ( $auth_status, $session ) = C4::Auth::check_cookie_auth($sessionID, {catalogue => 1} );
615 is( $auth_status, 'failed' );
616 is( $session, undef );
618 # Simulating the login form submission
619 $cgi->param('userid', $patron->userid);
620 $cgi->param('password', $password);
623 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 0, {catalogue => 1});
624 is( $sessionID, $first_sessionID );
625 is( $userid, $patron->userid );
627 ( $auth_status, $session ) = C4::Auth::check_cookie_auth($sessionID, {catalogue => 1});
628 is( $auth_status, 'ok' );
629 is( $session->id, $first_sessionID );
632 $cgi->param('logout.x', 1);
633 $cgi->delete( 'userid', 'password' );
637 open STDOUT, '>', \$stdout;
638 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 0, {catalogue => 1});
641 is( $sessionID, undef );
642 is( $ENV{"HTTP_COOKIE"}, "CGISESSID=$first_sessionID", 'HTTP_COOKIE not unset' );
643 ( $auth_status, $session) = C4::Auth::check_cookie_auth( $first_sessionID, {catalogue => 1} );
644 is( $auth_status, "expired");
645 is( $session, undef );
648 # Trying to access without sessionID
650 ( $auth_status, $session) = C4::Auth::check_cookie_auth(undef, {catalogue => 1});
651 is( $auth_status, 'failed' );
652 is( $session, undef );
654 # This will fail on permissions
655 undef $ENV{"HTTP_COOKIE"};
659 open STDOUT, '>', \$stdout;
660 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 0, {catalogue => 1} );
663 is( $userid, undef );
664 is( $sessionID, undef );
670 $cgi->param('userid', $patron->userid);
671 $cgi->param('password', $password);
672 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 0, {catalogue => 1});
673 is( $userid, $patron->userid );
674 $first_sessionID = $sessionID;
676 # Patron does not have the borrowers permission
677 # $ENV{"HTTP_COOKIE"} = "CGISESSID=$sessionID"; # not needed, we use $cgi here
681 open STDOUT, '>', \$stdout;
682 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 0, {borrowers => 1} );
685 is( $userid, undef );
686 is( $sessionID, undef );
688 # When calling check_cookie_auth, the session will be deleted
689 ( $auth_status, $session) = C4::Auth::check_cookie_auth( $first_sessionID, { borrowers => 1 } );
690 is( $auth_status, "failed" );
691 is( $session, undef );
692 ( $auth_status, $session) = C4::Auth::check_cookie_auth( $first_sessionID, { borrowers => 1 } );
693 is( $auth_status, 'expired', 'Session no longer exists' );
695 # NOTE: It is not what the UI is doing.
696 # From the UI we are allowed to hit an unauthorized page then reuse the session to hit back authorized area.
697 # It is because check_cookie_auth is ALWAYS called from checkauth WITHOUT $flagsrequired
698 # It then return "ok", when the previous called got "failed"
700 # Try reusing the deleted session: since it does not exist, we should get a new one now when passing correct permissions
701 $cgi->cookie( -name => 'CGISESSID', value => $first_sessionID );
702 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 0, {catalogue => 1});
703 is( $userid, $patron->userid );
704 isnt( $sessionID, undef, 'Check if we have a sessionID' );
705 isnt( $sessionID, $first_sessionID, 'New value expected' );
706 ( $auth_status, $session) = C4::Auth::check_cookie_auth( $sessionID, {catalogue => 1} );
707 is( $auth_status, "ok" );
708 is( $session->id, $sessionID, 'Same session' );
709 # Two additional tests on userenv
710 is( $C4::Context::context->{activeuser}, $session->id, 'Check if environment has been setup for session' );
711 is( C4::Context->userenv->{id}, $userid, 'Check userid in userenv' );
715 subtest 'Userenv clearing in check_cookie_auth' => sub {
716 # Note: We did already test userenv for a logged-in user in previous subtest
719 t::lib::Mocks::mock_preference( 'timeout', 600 );
722 # Create a new anonymous session by passing a fake session ID
723 $cgi->cookie( -name => 'CGISESSID', -value => 'fake_sessionID' );
724 my ($userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 1);
725 my ( $auth_status, $session) = C4::Auth::check_cookie_auth( $sessionID );
726 is( $auth_status, 'anon', 'Should be anonymous' );
727 is( $C4::Context::context->{activeuser}, $session->id, 'Check activeuser' );
728 is( defined C4::Context->userenv, 1, 'There should be a userenv' );
729 is( C4::Context->userenv->{id}, q{}, 'userid should be empty string' );
731 # Make the session expire now, check_cookie_auth will delete it
732 $session->param('lasttime', time() - 1200 );
734 ( $auth_status, $session) = C4::Auth::check_cookie_auth( $sessionID );
735 is( $auth_status, 'expired', 'Should be expired' );
736 is( C4::Context->userenv, undef, 'Environment should be cleared too' );
738 # Show that we clear the userenv again: set up env and check deleted session
739 C4::Context->_new_userenv( $sessionID );
740 C4::Context->set_userenv; # empty
741 is( defined C4::Context->userenv, 1, 'There should be an empty userenv again' );
742 ( $auth_status, $session) = C4::Auth::check_cookie_auth( $sessionID );
743 is( $auth_status, 'expired', 'Should be expired already' );
744 is( C4::Context->userenv, undef, 'Environment should be cleared again' );
747 $schema->storage->txn_rollback;