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 'Two-factor authentication' => sub {
117 my $patron = $builder->build_object(
118 { class => 'Koha::Patrons', value => { flags => 1 } } );
119 my $password = 'password';
120 $patron->set_password( { password => $password } );
121 $cgi = Test::MockObject->new();
124 our ( $logout, $sessionID, $verified );
128 my ( $self, $param ) = @_;
129 if ( $param eq 'userid' ) { return $patron->userid; }
130 elsif ( $param eq 'password' ) { return $password; }
131 elsif ( $param eq 'otp_token' ) { return $otp_token; }
132 elsif ( $param eq 'logout.x' ) { return $logout; }
136 $cgi->mock( 'request_method', sub { return 'POST' } );
137 $cgi->mock( 'cookie', sub { return $sessionID } );
139 my $two_factor_auth = Test::MockModule->new( 'Koha::Auth::TwoFactorAuth' );
140 $two_factor_auth->mock( 'verify', sub {$verified} );
142 my ( $userid, $cookie, $flags );
143 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired', undef, 'intranet' );
149 C4::Auth::checkauth( $cgi, 'authrequired', undef, 'intranet' );
153 t::lib::Mocks::mock_preference( 'TwoFactorAuthentication', 0 );
154 $patron->auth_method('password')->store;
155 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired', undef, 'intranet' );
156 is( $userid, $patron->userid, 'Succesful login' );
157 is( C4::Auth::get_session($sessionID)->param('waiting-for-2FA'), undef, 'Second auth not required' );
160 $patron->auth_method('two-factor')->store;
161 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired', undef, 'intranet' );
162 is( $userid, $patron->userid, 'Succesful login' );
163 is( C4::Auth::get_session($sessionID)->param('waiting-for-2FA'), undef, 'Second auth not required' );
166 t::lib::Mocks::mock_preference( 'TwoFactorAuthentication', 1 );
167 t::lib::Mocks::mock_config('encryption_key', '1234tH1s=t&st');
168 $patron->auth_method('password')->store;
169 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired', undef, 'intranet' );
170 is( $userid, $patron->userid, 'Succesful login' );
171 is( C4::Auth::get_session($sessionID)->param('waiting-for-2FA'), undef, 'Second auth not required' );
174 $patron->encode_secret('one_secret');
175 $patron->auth_method('two-factor');
177 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired', undef, 'intranet' );
178 is( $userid, $patron->userid, 'Succesful login' );
179 my $session = C4::Auth::get_session($sessionID);
180 is( C4::Auth::get_session($sessionID)->param('waiting-for-2FA'), 1, 'Second auth required' );
183 $otp_token = "wrong";
185 $patron->auth_method('two-factor')->store;
186 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired', undef, 'intranet' );
187 is( $userid, $patron->userid, 'Succesful login' );
188 is( C4::Auth::get_session($sessionID)->param('waiting-for-2FA'), 1, 'Second auth still required after wrong OTP token' );
192 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired', undef, 'intranet' );
193 is( $userid, $patron->userid, 'Succesful login' );
194 is( C4::Auth::get_session($sessionID)->param('waiting-for-2FA'), 0, 'Second auth no longer required if OTP token has been verified' );
196 t::lib::Mocks::mock_preference( 'TwoFactorAuthentication', 0 );
199 C4::Context->_new_userenv; # For next tests
203 subtest 'track_login_daily tests' => sub {
207 my $patron = $builder->build_object({ class => 'Koha::Patrons' });
208 my $userid = $patron->userid;
210 $patron->lastseen( undef );
213 my $cache = Koha::Caches->get_instance();
214 my $cache_key = "track_login_" . $patron->userid;
215 $cache->clear_from_cache($cache_key);
217 t::lib::Mocks::mock_preference( 'TrackLastPatronActivity', '1' );
219 is( $patron->lastseen, undef, 'Patron should have not last seen when newly created' );
221 C4::Auth::track_login_daily( $userid );
222 $patron->_result()->discard_changes();
223 isnt( $patron->lastseen, undef, 'Patron should have last seen set when TrackLastPatronActivity = 1' );
225 sleep(1); # We need to wait a tiny bit to make sure the timestamp will be different
226 my $last_seen = $patron->lastseen;
227 C4::Auth::track_login_daily( $userid );
228 $patron->_result()->discard_changes();
229 is( $patron->lastseen, $last_seen, 'Patron last seen should still be unchanged' );
231 $cache->clear_from_cache($cache_key);
232 C4::Auth::track_login_daily( $userid );
233 $patron->_result()->discard_changes();
234 isnt( $patron->lastseen, $last_seen, 'Patron last seen should be changed if we cleared the cache' );
236 t::lib::Mocks::mock_preference( 'TrackLastPatronActivity', '0' );
237 $patron->lastseen( undef )->store;
238 $cache->clear_from_cache($cache_key);
239 C4::Auth::track_login_daily( $userid );
240 $patron->_result()->discard_changes();
241 is( $patron->lastseen, undef, 'Patron should still have last seen unchanged when TrackLastPatronActivity = 0' );
245 subtest 'no_set_userenv parameter tests' => sub {
249 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
250 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
251 my $password = 'password';
253 t::lib::Mocks::mock_preference( 'RequireStrongPassword', 0 );
254 $patron->set_password({ password => $password });
256 ok( checkpw( $dbh, $patron->userid, $password, undef, undef, 1 ), 'checkpw returns true' );
257 is( C4::Context->userenv, undef, 'Userenv should be undef as required' );
258 C4::Context->_new_userenv('DUMMY SESSION');
259 C4::Context->set_userenv(0,0,0,'firstname','surname', $library->branchcode, 'Library 1', 0, '', '');
260 is( C4::Context->userenv->{branch}, $library->branchcode, 'Userenv gives correct branch' );
261 ok( checkpw( $dbh, $patron->userid, $password, undef, undef, 1 ), 'checkpw returns true' );
262 is( C4::Context->userenv->{branch}, $library->branchcode, 'Userenv branch is preserved if no_set_userenv is true' );
263 ok( checkpw( $dbh, $patron->userid, $password, undef, undef, 0 ), 'checkpw still returns true' );
264 isnt( C4::Context->userenv->{branch}, $library->branchcode, 'Userenv branch is overwritten if no_set_userenv is false' );
267 subtest 'checkpw lockout tests' => sub {
271 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
272 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
273 my $password = 'password';
274 t::lib::Mocks::mock_preference( 'RequireStrongPassword', 0 );
275 t::lib::Mocks::mock_preference( 'FailedLoginAttempts', 1 );
276 $patron->set_password({ password => $password });
278 my ( $checkpw, undef, undef ) = checkpw( $dbh, $patron->cardnumber, $password, undef, undef, 1 );
279 ok( $checkpw, 'checkpw returns true with right password when logging in via cardnumber' );
280 ( $checkpw, undef, undef ) = checkpw( $dbh, $patron->userid, "wrong_password", undef, undef, 1 );
281 is( $checkpw, 0, 'checkpw returns false when given wrong password' );
282 $patron = $patron->get_from_storage;
283 is( $patron->account_locked, 1, "Account is locked from failed login");
284 ( $checkpw, undef, undef ) = checkpw( $dbh, $patron->userid, $password, undef, undef, 1 );
285 is( $checkpw, undef, 'checkpw returns undef with right password when account locked' );
286 ( $checkpw, undef, undef ) = checkpw( $dbh, $patron->cardnumber, $password, undef, undef, 1 );
287 is( $checkpw, undef, 'checkpw returns undefwith right password when logging in via cardnumber if account locked' );
291 # get_template_and_user tests
293 subtest 'get_template_and_user' => sub { # Tests for the language URL parameter
295 sub MockedCheckauth {
296 my ($query,$authnotrequired,$flagsrequired,$type) = @_;
298 my $userid = 'cobain';
300 # we don't need to bother about permissions for this test
302 superlibrarian => 1, acquisition => 0,
304 catalogue => 1, circulate => 0,
305 coursereserves => 0, editauthorities => 0,
307 parameters => 0, permissions => 0,
308 plugins => 0, reports => 0,
309 reserveforothers => 0, serials => 0,
310 staffaccess => 0, tools => 0,
314 my $session_cookie = $query->cookie(
315 -name => 'CGISESSID',
320 return ( $userid, [ $session_cookie ], $sessionID, $flags );
323 # Mock checkauth, build the scenario
324 my $auth = Test::MockModule->new( 'C4::Auth' );
325 $auth->mock( 'checkauth', \&MockedCheckauth );
327 # Make sure 'EnableOpacSearchHistory' is set
328 t::lib::Mocks::mock_preference('EnableOpacSearchHistory',1);
329 # Enable es-ES for the OPAC and staff interfaces
330 t::lib::Mocks::mock_preference('OPACLanguages','en,es-ES');
331 t::lib::Mocks::mock_preference('language','en,es-ES');
333 # we need a session cookie
334 $ENV{"SERVER_PORT"} = 80;
335 $ENV{"HTTP_COOKIE"} = 'CGISESSID=nirvana';
337 my $query = CGI->new;
338 $query->param('language','es-ES');
340 my ( $template, $loggedinuser, $cookies ) = get_template_and_user(
342 template_name => "about.tt",
345 authnotrequired => 1,
346 flagsrequired => { catalogue => 1 },
351 ok ( ( all { ref($_) eq 'CGI::Cookie' } @$cookies ),
352 'BZ9735: the cookies array is flat' );
354 # new query, with non-existent language (we only have en and es-ES)
355 $query->param('language','tomas');
357 ( $template, $loggedinuser, $cookies ) = get_template_and_user(
359 template_name => "about.tt",
362 authnotrequired => 1,
363 flagsrequired => { catalogue => 1 },
368 ok( ( none { $_->name eq 'KohaOpacLanguage' and $_->value eq 'tomas' } @$cookies ),
369 'BZ9735: invalid language, it is not set');
371 ok( ( any { $_->name eq 'KohaOpacLanguage' and $_->value eq 'en' } @$cookies ),
372 'BZ9735: invalid language, then default to en');
374 for my $template_name (
376 ../../../../../../../../../../../../../../../etc/passwd
377 test/../../../../../../../../../../../../../../etc/passwd
379 test/does_not_finished_by_tt_t
383 ( $template, $loggedinuser, $cookies ) = get_template_and_user(
385 template_name => $template_name,
388 authnotrequired => 1,
389 flagsrequired => { catalogue => 1 },
393 like ( $@, qr(bad template path), "The file $template_name should not be accessible" );
395 ( $template, $loggedinuser, $cookies ) = get_template_and_user(
397 template_name => 'errors/errorpage.tt',
400 authnotrequired => 1,
401 flagsrequired => { catalogue => 1 },
404 my $file_exists = ( -f $template->{filename} ) ? 1 : 0;
405 is ( $file_exists, 1, 'The file errors/errorpage.tt should be accessible (contains integers)' );
407 # Regression test for env opac search limit override
408 $ENV{"OPAC_SEARCH_LIMIT"} = "branch:CPL";
409 $ENV{"OPAC_LIMIT_OVERRIDE"} = 1;
411 ( $template, $loggedinuser, $cookies) = get_template_and_user(
413 template_name => 'opac-main.tt',
416 authnotrequired => 1,
419 is($template->{VARS}->{'opac_name'}, "CPL", "Opac name was set correctly");
420 is($template->{VARS}->{'opac_search_limit'}, "branch:CPL", "Search limit was set correctly");
422 $ENV{"OPAC_SEARCH_LIMIT"} = "branch:multibranch-19";
424 ( $template, $loggedinuser, $cookies) = get_template_and_user(
426 template_name => 'opac-main.tt',
429 authnotrequired => 1,
432 is($template->{VARS}->{'opac_name'}, "multibranch-19", "Opac name was set correctly");
433 is($template->{VARS}->{'opac_search_limit'}, "branch:multibranch-19", "Search limit was set correctly");
435 delete $ENV{"HTTP_COOKIE"};
438 # Check that there is always an OPACBaseURL set.
439 my $input = CGI->new();
440 my ( $template1, $borrowernumber, $cookie );
441 ( $template1, $borrowernumber, $cookie ) = get_template_and_user(
443 template_name => "opac-detail.tt",
446 authnotrequired => 1,
450 ok( ( any { 'OPACBaseURL' eq $_ } keys %{$template1->{VARS}} ),
451 'OPACBaseURL is in OPAC template' );
454 ( $template2, $borrowernumber, $cookie ) = get_template_and_user(
456 template_name => "catalogue/detail.tt",
459 authnotrequired => 1,
463 ok( ( any { 'OPACBaseURL' eq $_ } keys %{$template2->{VARS}} ),
464 'OPACBaseURL is in Staff template' );
466 my $hash1 = hash_password('password');
467 my $hash2 = hash_password('password');
469 ok(C4::Auth::checkpw_hash('password', $hash1), 'password validates with first hash');
470 ok(C4::Auth::checkpw_hash('password', $hash2), 'password validates with second hash');
472 subtest 'Check value of login_attempts in checkpw' => sub {
475 t::lib::Mocks::mock_preference('FailedLoginAttempts', 3);
477 # Only interested here in regular login
481 my $patron = $builder->build_object({ class => 'Koha::Patrons' });
482 $patron->login_attempts(2);
483 $patron->password('123')->store; # yes, deliberately not hashed
485 is( $patron->account_locked, 0, 'Patron not locked' );
486 my @test = checkpw( $dbh, $patron->userid, '123', undef, 'opac', 1 );
487 # Note: 123 will not be hashed to 123 !
488 is( $test[0], 0, 'checkpw should have failed' );
489 $patron->discard_changes; # refresh
490 is( $patron->login_attempts, 3, 'Login attempts increased' );
491 is( $patron->account_locked, 1, 'Check locked status' );
493 # And another try to go over the limit: different return value!
494 @test = checkpw( $dbh, $patron->userid, '123', undef, 'opac', 1 );
495 is( @test, 0, 'checkpw failed again and returns nothing now' );
496 $patron->discard_changes; # refresh
497 is( $patron->login_attempts, 3, 'Login attempts not increased anymore' );
499 # Administrative lockout cannot be undone?
500 # Pass the right password now (or: add a nice mock).
501 my $auth = Test::MockModule->new( 'C4::Auth' );
502 $auth->mock( 'checkpw_hash', sub { return 1; } ); # not for production :)
503 $patron->login_attempts(0)->store;
504 @test = checkpw( $dbh, $patron->userid, '123', undef, 'opac', 1 );
505 is( $test[0], 1, 'Build confidence in the mock' );
506 $patron->login_attempts(-1)->store;
507 is( $patron->account_locked, 1, 'Check administrative lockout' );
508 @test = checkpw( $dbh, $patron->userid, '123', undef, 'opac', 1 );
509 is( @test, 0, 'checkpw gave red' );
510 $patron->discard_changes; # refresh
511 is( $patron->login_attempts, -1, 'Still locked out' );
512 t::lib::Mocks::mock_preference('FailedLoginAttempts', ''); # disable
513 is( $patron->account_locked, 1, 'Check administrative lockout without pref' );
516 subtest 'Check value of login_attempts in checkpw' => sub {
519 t::lib::Mocks::mock_preference('FailedLoginAttempts', 3);
520 my $patron = $builder->build_object({ class => 'Koha::Patrons' });
521 $patron->set_password({ password => '123', skip_validation => 1 });
523 my @test = checkpw( $dbh, $patron->userid, '123', undef, 'opac', 1 );
524 is( $test[0], 1, 'Patron authenticated correctly' );
526 $patron->password_expiration_date('2020-01-01')->store;
527 @test = checkpw( $dbh, $patron->userid, '123', undef, 'opac', 1 );
528 is( $test[0], -2, 'Patron returned as expired correctly' );
532 subtest '_timeout_syspref' => sub {
536 t::lib::Mocks::mock_preference('timeout', "100");
537 is( C4::Auth::_timeout_syspref, 100, );
539 t::lib::Mocks::mock_preference('timeout', "2d");
540 is( C4::Auth::_timeout_syspref, 2*86400, );
542 t::lib::Mocks::mock_preference('timeout', "2D");
543 is( C4::Auth::_timeout_syspref, 2*86400, );
545 t::lib::Mocks::mock_preference('timeout', "10h");
546 is( C4::Auth::_timeout_syspref, 10*3600, );
548 t::lib::Mocks::mock_preference('timeout', "10x");
550 { is( C4::Auth::_timeout_syspref, 600, ); }
551 "The value of the system preference 'timeout' is not correct, defaulting to 600",
552 'Bad values throw a warning and fallback to 600';
555 subtest 'check_cookie_auth' => sub {
558 t::lib::Mocks::mock_preference('timeout', "1d"); # back to default
560 my $patron = $builder->build_object({ class => 'Koha::Patrons', value => { flags => 1 } });
562 # Mock a CGI object with real userid param
563 my $cgi = Test::MockObject->new();
568 if ( $var eq 'userid' ) { return $patron->userid; }
571 $cgi->mock('multi_param', sub {return q{}} );
572 $cgi->mock( 'cookie', sub { return; } );
573 $cgi->mock( 'request_method', sub { return 'POST' } );
575 $ENV{REMOTE_ADDR} = '127.0.0.1';
577 # Setting authnotrequired=1 or we wont' hit the return but the end of the sub that prints headers
578 my ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 1 );
580 my ($auth_status, $session) = C4::Auth::check_cookie_auth($sessionID);
581 isnt( $auth_status, 'ok', 'check_cookie_auth should not return ok if the user has not been authenticated before if no permissions needed' );
582 is( $auth_status, 'anon', 'check_cookie_auth should return anon if the user has not been authenticated before and no permissions needed' );
584 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 1 );
586 ($auth_status, $session) = C4::Auth::check_cookie_auth($sessionID, {catalogue => 1});
587 isnt( $auth_status, 'ok', 'check_cookie_auth should not return ok if the user has not been authenticated before and permissions needed' );
588 is( $auth_status, 'anon', 'check_cookie_auth should return anon if the user has not been authenticated before and permissions needed' );
590 #FIXME We should have a test to cover 'failed' status when a user has logged in, but doesn't have permission
593 subtest 'checkauth & check_cookie_auth' => sub {
596 # flags = 4 => { catalogue => 1 }
597 my $patron = $builder->build_object({ class => 'Koha::Patrons', value => { flags => 4 } });
598 my $password = 'password';
599 t::lib::Mocks::mock_preference( 'RequireStrongPassword', 0 );
600 $patron->set_password( { password => $password } );
602 my $cgi_mock = Test::MockModule->new('CGI');
603 $cgi_mock->mock( 'request_method', sub { return 'POST' } );
607 my $auth = Test::MockModule->new( 'C4::Auth' );
608 # Tests will fail if we hit safe_exit
609 $auth->mock( 'safe_exit', sub { return } );
611 my ( $userid, $cookie, $sessionID, $flags );
613 # checkauth will redirect and safe_exit if not authenticated and not authorized
616 open STDOUT, '>', \$stdout;
617 C4::Auth::checkauth($cgi, 0, {catalogue => 1});
618 like( $stdout, qr{<title>\s*Log in to your account} );
619 $sessionID = ( $stdout =~ m{Set-Cookie: CGISESSID=((\d|\w)+);} ) ? $1 : undef;
624 my $first_sessionID = $sessionID;
626 $ENV{"HTTP_COOKIE"} = "CGISESSID=$sessionID";
627 # Not authenticated yet, checkauth didn't return the session
631 open STDOUT, '>', \$stdout;
632 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 0, {catalogue => 1} );
635 is( $sessionID, undef);
638 # Sending undefined fails obviously
639 my ( $auth_status, $session ) = C4::Auth::check_cookie_auth($sessionID, {catalogue => 1} );
640 is( $auth_status, 'failed' );
641 is( $session, undef );
643 # Simulating the login form submission
644 $cgi->param('userid', $patron->userid);
645 $cgi->param('password', $password);
648 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 0, {catalogue => 1});
649 is( $sessionID, $first_sessionID );
650 is( $userid, $patron->userid );
652 ( $auth_status, $session ) = C4::Auth::check_cookie_auth($sessionID, {catalogue => 1});
653 is( $auth_status, 'ok' );
654 is( $session->id, $first_sessionID );
657 $cgi->param('logout.x', 1);
658 $cgi->delete( 'userid', 'password' );
662 open STDOUT, '>', \$stdout;
663 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 0, {catalogue => 1});
666 is( $sessionID, undef );
667 is( $ENV{"HTTP_COOKIE"}, "CGISESSID=$first_sessionID", 'HTTP_COOKIE not unset' );
668 ( $auth_status, $session) = C4::Auth::check_cookie_auth( $first_sessionID, {catalogue => 1} );
669 is( $auth_status, "expired");
670 is( $session, undef );
673 # Trying to access without sessionID
675 ( $auth_status, $session) = C4::Auth::check_cookie_auth(undef, {catalogue => 1});
676 is( $auth_status, 'failed' );
677 is( $session, undef );
679 # This will fail on permissions
680 undef $ENV{"HTTP_COOKIE"};
684 open STDOUT, '>', \$stdout;
685 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 0, {catalogue => 1} );
688 is( $userid, undef );
689 is( $sessionID, undef );
695 $cgi->param('userid', $patron->userid);
696 $cgi->param('password', $password);
697 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 0, {catalogue => 1});
698 is( $userid, $patron->userid );
699 $first_sessionID = $sessionID;
701 # Patron does not have the borrowers permission
702 # $ENV{"HTTP_COOKIE"} = "CGISESSID=$sessionID"; # not needed, we use $cgi here
706 open STDOUT, '>', \$stdout;
707 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 0, {borrowers => 1} );
710 is( $userid, undef );
711 is( $sessionID, undef );
713 # When calling check_cookie_auth, the session will be deleted
714 ( $auth_status, $session) = C4::Auth::check_cookie_auth( $first_sessionID, { borrowers => 1 } );
715 is( $auth_status, "failed" );
716 is( $session, undef );
717 ( $auth_status, $session) = C4::Auth::check_cookie_auth( $first_sessionID, { borrowers => 1 } );
718 is( $auth_status, 'expired', 'Session no longer exists' );
720 # NOTE: It is not what the UI is doing.
721 # From the UI we are allowed to hit an unauthorized page then reuse the session to hit back authorized area.
722 # It is because check_cookie_auth is ALWAYS called from checkauth WITHOUT $flagsrequired
723 # It then return "ok", when the previous called got "failed"
725 # Try reusing the deleted session: since it does not exist, we should get a new one now when passing correct permissions
726 $cgi->cookie( -name => 'CGISESSID', value => $first_sessionID );
727 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 0, {catalogue => 1});
728 is( $userid, $patron->userid );
729 isnt( $sessionID, undef, 'Check if we have a sessionID' );
730 isnt( $sessionID, $first_sessionID, 'New value expected' );
731 ( $auth_status, $session) = C4::Auth::check_cookie_auth( $sessionID, {catalogue => 1} );
732 is( $auth_status, "ok" );
733 is( $session->id, $sessionID, 'Same session' );
734 # Two additional tests on userenv
735 is( $C4::Context::context->{activeuser}, $session->id, 'Check if environment has been setup for session' );
736 is( C4::Context->userenv->{id}, $userid, 'Check userid in userenv' );
740 subtest 'Userenv clearing in check_cookie_auth' => sub {
741 # Note: We did already test userenv for a logged-in user in previous subtest
744 t::lib::Mocks::mock_preference( 'timeout', 600 );
747 # Create a new anonymous session by passing a fake session ID
748 $cgi->cookie( -name => 'CGISESSID', -value => 'fake_sessionID' );
749 my ($userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 1);
750 my ( $auth_status, $session) = C4::Auth::check_cookie_auth( $sessionID );
751 is( $auth_status, 'anon', 'Should be anonymous' );
752 is( $C4::Context::context->{activeuser}, $session->id, 'Check activeuser' );
753 is( defined C4::Context->userenv, 1, 'There should be a userenv' );
754 is( C4::Context->userenv->{id}, q{}, 'userid should be empty string' );
756 # Make the session expire now, check_cookie_auth will delete it
757 $session->param('lasttime', time() - 1200 );
759 ( $auth_status, $session) = C4::Auth::check_cookie_auth( $sessionID );
760 is( $auth_status, 'expired', 'Should be expired' );
761 is( C4::Context->userenv, undef, 'Environment should be cleared too' );
763 # Show that we clear the userenv again: set up env and check deleted session
764 C4::Context->_new_userenv( $sessionID );
765 C4::Context->set_userenv; # empty
766 is( defined C4::Context->userenv, 1, 'There should be an empty userenv again' );
767 ( $auth_status, $session) = C4::Auth::check_cookie_auth( $sessionID );
768 is( $auth_status, 'expired', 'Should be expired already' );
769 is( C4::Context->userenv, undef, 'Environment should be cleared again' );
772 $schema->storage->txn_rollback;