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' );
197 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired', undef, 'opac' );
198 is( $userid, $patron->userid, 'Succesful login at the OPAC' );
199 is( C4::Auth::get_session($sessionID)->param('waiting-for-2FA'), undef, 'No second auth required at the OPAC' );
201 t::lib::Mocks::mock_preference( 'TwoFactorAuthentication', 0 );
204 C4::Context->_new_userenv; # For next tests
208 subtest 'track_login_daily tests' => sub {
212 my $patron = $builder->build_object({ class => 'Koha::Patrons' });
213 my $userid = $patron->userid;
215 $patron->lastseen( undef );
218 my $cache = Koha::Caches->get_instance();
219 my $cache_key = "track_login_" . $patron->userid;
220 $cache->clear_from_cache($cache_key);
222 t::lib::Mocks::mock_preference( 'TrackLastPatronActivity', '1' );
224 is( $patron->lastseen, undef, 'Patron should have not last seen when newly created' );
226 C4::Auth::track_login_daily( $userid );
227 $patron->_result()->discard_changes();
228 isnt( $patron->lastseen, undef, 'Patron should have last seen set when TrackLastPatronActivity = 1' );
230 sleep(1); # We need to wait a tiny bit to make sure the timestamp will be different
231 my $last_seen = $patron->lastseen;
232 C4::Auth::track_login_daily( $userid );
233 $patron->_result()->discard_changes();
234 is( $patron->lastseen, $last_seen, 'Patron last seen should still be unchanged' );
236 $cache->clear_from_cache($cache_key);
237 C4::Auth::track_login_daily( $userid );
238 $patron->_result()->discard_changes();
239 isnt( $patron->lastseen, $last_seen, 'Patron last seen should be changed if we cleared the cache' );
241 t::lib::Mocks::mock_preference( 'TrackLastPatronActivity', '0' );
242 $patron->lastseen( undef )->store;
243 $cache->clear_from_cache($cache_key);
244 C4::Auth::track_login_daily( $userid );
245 $patron->_result()->discard_changes();
246 is( $patron->lastseen, undef, 'Patron should still have last seen unchanged when TrackLastPatronActivity = 0' );
250 subtest 'no_set_userenv parameter tests' => sub {
254 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
255 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
256 my $password = 'password';
258 t::lib::Mocks::mock_preference( 'RequireStrongPassword', 0 );
259 $patron->set_password({ password => $password });
261 ok( checkpw( $dbh, $patron->userid, $password, undef, undef, 1 ), 'checkpw returns true' );
262 is( C4::Context->userenv, undef, 'Userenv should be undef as required' );
263 C4::Context->_new_userenv('DUMMY SESSION');
264 C4::Context->set_userenv(0,0,0,'firstname','surname', $library->branchcode, 'Library 1', 0, '', '');
265 is( C4::Context->userenv->{branch}, $library->branchcode, 'Userenv gives correct branch' );
266 ok( checkpw( $dbh, $patron->userid, $password, undef, undef, 1 ), 'checkpw returns true' );
267 is( C4::Context->userenv->{branch}, $library->branchcode, 'Userenv branch is preserved if no_set_userenv is true' );
268 ok( checkpw( $dbh, $patron->userid, $password, undef, undef, 0 ), 'checkpw still returns true' );
269 isnt( C4::Context->userenv->{branch}, $library->branchcode, 'Userenv branch is overwritten if no_set_userenv is false' );
272 subtest 'checkpw lockout tests' => sub {
276 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
277 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
278 my $password = 'password';
279 t::lib::Mocks::mock_preference( 'RequireStrongPassword', 0 );
280 t::lib::Mocks::mock_preference( 'FailedLoginAttempts', 1 );
281 $patron->set_password({ password => $password });
283 my ( $checkpw, undef, undef ) = checkpw( $dbh, $patron->cardnumber, $password, undef, undef, 1 );
284 ok( $checkpw, 'checkpw returns true with right password when logging in via cardnumber' );
285 ( $checkpw, undef, undef ) = checkpw( $dbh, $patron->userid, "wrong_password", undef, undef, 1 );
286 is( $checkpw, 0, 'checkpw returns false when given wrong password' );
287 $patron = $patron->get_from_storage;
288 is( $patron->account_locked, 1, "Account is locked from failed login");
289 ( $checkpw, undef, undef ) = checkpw( $dbh, $patron->userid, $password, undef, undef, 1 );
290 is( $checkpw, undef, 'checkpw returns undef with right password when account locked' );
291 ( $checkpw, undef, undef ) = checkpw( $dbh, $patron->cardnumber, $password, undef, undef, 1 );
292 is( $checkpw, undef, 'checkpw returns undefwith right password when logging in via cardnumber if account locked' );
296 # get_template_and_user tests
298 subtest 'get_template_and_user' => sub { # Tests for the language URL parameter
300 sub MockedCheckauth {
301 my ($query,$authnotrequired,$flagsrequired,$type) = @_;
303 my $userid = 'cobain';
305 # we don't need to bother about permissions for this test
307 superlibrarian => 1, acquisition => 0,
309 catalogue => 1, circulate => 0,
310 coursereserves => 0, editauthorities => 0,
312 parameters => 0, permissions => 0,
313 plugins => 0, reports => 0,
314 reserveforothers => 0, serials => 0,
315 staffaccess => 0, tools => 0,
319 my $session_cookie = $query->cookie(
320 -name => 'CGISESSID',
325 return ( $userid, [ $session_cookie ], $sessionID, $flags );
328 # Mock checkauth, build the scenario
329 my $auth = Test::MockModule->new( 'C4::Auth' );
330 $auth->mock( 'checkauth', \&MockedCheckauth );
332 # Make sure 'EnableOpacSearchHistory' is set
333 t::lib::Mocks::mock_preference('EnableOpacSearchHistory',1);
334 # Enable es-ES for the OPAC and staff interfaces
335 t::lib::Mocks::mock_preference('OPACLanguages','en,es-ES');
336 t::lib::Mocks::mock_preference('language','en,es-ES');
338 # we need a session cookie
339 $ENV{"SERVER_PORT"} = 80;
340 $ENV{"HTTP_COOKIE"} = 'CGISESSID=nirvana';
342 my $query = CGI->new;
343 $query->param('language','es-ES');
345 my ( $template, $loggedinuser, $cookies ) = get_template_and_user(
347 template_name => "about.tt",
350 authnotrequired => 1,
351 flagsrequired => { catalogue => 1 },
356 ok ( ( all { ref($_) eq 'CGI::Cookie' } @$cookies ),
357 'BZ9735: the cookies array is flat' );
359 # new query, with non-existent language (we only have en and es-ES)
360 $query->param('language','tomas');
362 ( $template, $loggedinuser, $cookies ) = get_template_and_user(
364 template_name => "about.tt",
367 authnotrequired => 1,
368 flagsrequired => { catalogue => 1 },
373 ok( ( none { $_->name eq 'KohaOpacLanguage' and $_->value eq 'tomas' } @$cookies ),
374 'BZ9735: invalid language, it is not set');
376 ok( ( any { $_->name eq 'KohaOpacLanguage' and $_->value eq 'en' } @$cookies ),
377 'BZ9735: invalid language, then default to en');
379 for my $template_name (
381 ../../../../../../../../../../../../../../../etc/passwd
382 test/../../../../../../../../../../../../../../etc/passwd
384 test/does_not_finished_by_tt_t
388 ( $template, $loggedinuser, $cookies ) = get_template_and_user(
390 template_name => $template_name,
393 authnotrequired => 1,
394 flagsrequired => { catalogue => 1 },
398 like ( $@, qr(bad template path), "The file $template_name should not be accessible" );
400 ( $template, $loggedinuser, $cookies ) = get_template_and_user(
402 template_name => 'errors/errorpage.tt',
405 authnotrequired => 1,
406 flagsrequired => { catalogue => 1 },
409 my $file_exists = ( -f $template->{filename} ) ? 1 : 0;
410 is ( $file_exists, 1, 'The file errors/errorpage.tt should be accessible (contains integers)' );
412 # Regression test for env opac search limit override
413 $ENV{"OPAC_SEARCH_LIMIT"} = "branch:CPL";
414 $ENV{"OPAC_LIMIT_OVERRIDE"} = 1;
416 ( $template, $loggedinuser, $cookies) = get_template_and_user(
418 template_name => 'opac-main.tt',
421 authnotrequired => 1,
424 is($template->{VARS}->{'opac_name'}, "CPL", "Opac name was set correctly");
425 is($template->{VARS}->{'opac_search_limit'}, "branch:CPL", "Search limit was set correctly");
427 $ENV{"OPAC_SEARCH_LIMIT"} = "branch:multibranch-19";
429 ( $template, $loggedinuser, $cookies) = get_template_and_user(
431 template_name => 'opac-main.tt',
434 authnotrequired => 1,
437 is($template->{VARS}->{'opac_name'}, "multibranch-19", "Opac name was set correctly");
438 is($template->{VARS}->{'opac_search_limit'}, "branch:multibranch-19", "Search limit was set correctly");
440 delete $ENV{"HTTP_COOKIE"};
443 # Check that there is always an OPACBaseURL set.
444 my $input = CGI->new();
445 my ( $template1, $borrowernumber, $cookie );
446 ( $template1, $borrowernumber, $cookie ) = get_template_and_user(
448 template_name => "opac-detail.tt",
451 authnotrequired => 1,
455 ok( ( any { 'OPACBaseURL' eq $_ } keys %{$template1->{VARS}} ),
456 'OPACBaseURL is in OPAC template' );
459 ( $template2, $borrowernumber, $cookie ) = get_template_and_user(
461 template_name => "catalogue/detail.tt",
464 authnotrequired => 1,
468 ok( ( any { 'OPACBaseURL' eq $_ } keys %{$template2->{VARS}} ),
469 'OPACBaseURL is in Staff template' );
471 my $hash1 = hash_password('password');
472 my $hash2 = hash_password('password');
474 ok(C4::Auth::checkpw_hash('password', $hash1), 'password validates with first hash');
475 ok(C4::Auth::checkpw_hash('password', $hash2), 'password validates with second hash');
477 subtest 'Check value of login_attempts in checkpw' => sub {
480 t::lib::Mocks::mock_preference('FailedLoginAttempts', 3);
482 # Only interested here in regular login
486 my $patron = $builder->build_object({ class => 'Koha::Patrons' });
487 $patron->login_attempts(2);
488 $patron->password('123')->store; # yes, deliberately not hashed
490 is( $patron->account_locked, 0, 'Patron not locked' );
491 my @test = checkpw( $dbh, $patron->userid, '123', undef, 'opac', 1 );
492 # Note: 123 will not be hashed to 123 !
493 is( $test[0], 0, 'checkpw should have failed' );
494 $patron->discard_changes; # refresh
495 is( $patron->login_attempts, 3, 'Login attempts increased' );
496 is( $patron->account_locked, 1, 'Check locked status' );
498 # And another try to go over the limit: different return value!
499 @test = checkpw( $dbh, $patron->userid, '123', undef, 'opac', 1 );
500 is( @test, 0, 'checkpw failed again and returns nothing now' );
501 $patron->discard_changes; # refresh
502 is( $patron->login_attempts, 3, 'Login attempts not increased anymore' );
504 # Administrative lockout cannot be undone?
505 # Pass the right password now (or: add a nice mock).
506 my $auth = Test::MockModule->new( 'C4::Auth' );
507 $auth->mock( 'checkpw_hash', sub { return 1; } ); # not for production :)
508 $patron->login_attempts(0)->store;
509 @test = checkpw( $dbh, $patron->userid, '123', undef, 'opac', 1 );
510 is( $test[0], 1, 'Build confidence in the mock' );
511 $patron->login_attempts(-1)->store;
512 is( $patron->account_locked, 1, 'Check administrative lockout' );
513 @test = checkpw( $dbh, $patron->userid, '123', undef, 'opac', 1 );
514 is( @test, 0, 'checkpw gave red' );
515 $patron->discard_changes; # refresh
516 is( $patron->login_attempts, -1, 'Still locked out' );
517 t::lib::Mocks::mock_preference('FailedLoginAttempts', ''); # disable
518 is( $patron->account_locked, 1, 'Check administrative lockout without pref' );
521 subtest 'Check value of login_attempts in checkpw' => sub {
524 t::lib::Mocks::mock_preference('FailedLoginAttempts', 3);
525 my $patron = $builder->build_object({ class => 'Koha::Patrons' });
526 $patron->set_password({ password => '123', skip_validation => 1 });
528 my @test = checkpw( $dbh, $patron->userid, '123', undef, 'opac', 1 );
529 is( $test[0], 1, 'Patron authenticated correctly' );
531 $patron->password_expiration_date('2020-01-01')->store;
532 @test = checkpw( $dbh, $patron->userid, '123', undef, 'opac', 1 );
533 is( $test[0], -2, 'Patron returned as expired correctly' );
537 subtest '_timeout_syspref' => sub {
541 t::lib::Mocks::mock_preference('timeout', "100");
542 is( C4::Auth::_timeout_syspref, 100, );
544 t::lib::Mocks::mock_preference('timeout', "2d");
545 is( C4::Auth::_timeout_syspref, 2*86400, );
547 t::lib::Mocks::mock_preference('timeout', "2D");
548 is( C4::Auth::_timeout_syspref, 2*86400, );
550 t::lib::Mocks::mock_preference('timeout', "10h");
551 is( C4::Auth::_timeout_syspref, 10*3600, );
553 t::lib::Mocks::mock_preference('timeout', "10x");
555 { is( C4::Auth::_timeout_syspref, 600, ); }
556 "The value of the system preference 'timeout' is not correct, defaulting to 600",
557 'Bad values throw a warning and fallback to 600';
560 subtest 'check_cookie_auth' => sub {
563 t::lib::Mocks::mock_preference('timeout', "1d"); # back to default
565 my $patron = $builder->build_object({ class => 'Koha::Patrons', value => { flags => 1 } });
567 # Mock a CGI object with real userid param
568 my $cgi = Test::MockObject->new();
573 if ( $var eq 'userid' ) { return $patron->userid; }
576 $cgi->mock('multi_param', sub {return q{}} );
577 $cgi->mock( 'cookie', sub { return; } );
578 $cgi->mock( 'request_method', sub { return 'POST' } );
580 $ENV{REMOTE_ADDR} = '127.0.0.1';
582 # Setting authnotrequired=1 or we wont' hit the return but the end of the sub that prints headers
583 my ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 1 );
585 my ($auth_status, $session) = C4::Auth::check_cookie_auth($sessionID);
586 isnt( $auth_status, 'ok', 'check_cookie_auth should not return ok if the user has not been authenticated before if no permissions needed' );
587 is( $auth_status, 'anon', 'check_cookie_auth should return anon if the user has not been authenticated before and no permissions needed' );
589 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 1 );
591 ($auth_status, $session) = C4::Auth::check_cookie_auth($sessionID, {catalogue => 1});
592 isnt( $auth_status, 'ok', 'check_cookie_auth should not return ok if the user has not been authenticated before and permissions needed' );
593 is( $auth_status, 'anon', 'check_cookie_auth should return anon if the user has not been authenticated before and permissions needed' );
595 #FIXME We should have a test to cover 'failed' status when a user has logged in, but doesn't have permission
598 subtest 'checkauth & check_cookie_auth' => sub {
601 # flags = 4 => { catalogue => 1 }
602 my $patron = $builder->build_object({ class => 'Koha::Patrons', value => { flags => 4 } });
603 my $password = 'password';
604 t::lib::Mocks::mock_preference( 'RequireStrongPassword', 0 );
605 $patron->set_password( { password => $password } );
607 my $cgi_mock = Test::MockModule->new('CGI');
608 $cgi_mock->mock( 'request_method', sub { return 'POST' } );
612 my $auth = Test::MockModule->new( 'C4::Auth' );
613 # Tests will fail if we hit safe_exit
614 $auth->mock( 'safe_exit', sub { return } );
616 my ( $userid, $cookie, $sessionID, $flags );
618 # checkauth will redirect and safe_exit if not authenticated and not authorized
621 open STDOUT, '>', \$stdout;
622 C4::Auth::checkauth($cgi, 0, {catalogue => 1});
623 like( $stdout, qr{<title>\s*Log in to your account} );
624 $sessionID = ( $stdout =~ m{Set-Cookie: CGISESSID=((\d|\w)+);} ) ? $1 : undef;
629 my $first_sessionID = $sessionID;
631 $ENV{"HTTP_COOKIE"} = "CGISESSID=$sessionID";
632 # Not authenticated yet, checkauth didn't return the session
636 open STDOUT, '>', \$stdout;
637 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 0, {catalogue => 1} );
640 is( $sessionID, undef);
643 # Sending undefined fails obviously
644 my ( $auth_status, $session ) = C4::Auth::check_cookie_auth($sessionID, {catalogue => 1} );
645 is( $auth_status, 'failed' );
646 is( $session, undef );
648 # Simulating the login form submission
649 $cgi->param('userid', $patron->userid);
650 $cgi->param('password', $password);
653 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 0, {catalogue => 1});
654 is( $sessionID, $first_sessionID );
655 is( $userid, $patron->userid );
657 ( $auth_status, $session ) = C4::Auth::check_cookie_auth($sessionID, {catalogue => 1});
658 is( $auth_status, 'ok' );
659 is( $session->id, $first_sessionID );
662 $cgi->param('logout.x', 1);
663 $cgi->delete( 'userid', 'password' );
667 open STDOUT, '>', \$stdout;
668 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 0, {catalogue => 1});
671 is( $sessionID, undef );
672 is( $ENV{"HTTP_COOKIE"}, "CGISESSID=$first_sessionID", 'HTTP_COOKIE not unset' );
673 ( $auth_status, $session) = C4::Auth::check_cookie_auth( $first_sessionID, {catalogue => 1} );
674 is( $auth_status, "expired");
675 is( $session, undef );
678 # Trying to access without sessionID
680 ( $auth_status, $session) = C4::Auth::check_cookie_auth(undef, {catalogue => 1});
681 is( $auth_status, 'failed' );
682 is( $session, undef );
684 # This will fail on permissions
685 undef $ENV{"HTTP_COOKIE"};
689 open STDOUT, '>', \$stdout;
690 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 0, {catalogue => 1} );
693 is( $userid, undef );
694 is( $sessionID, undef );
700 $cgi->param('userid', $patron->userid);
701 $cgi->param('password', $password);
702 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 0, {catalogue => 1});
703 is( $userid, $patron->userid );
704 $first_sessionID = $sessionID;
706 # Patron does not have the borrowers permission
707 # $ENV{"HTTP_COOKIE"} = "CGISESSID=$sessionID"; # not needed, we use $cgi here
711 open STDOUT, '>', \$stdout;
712 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 0, {borrowers => 1} );
715 is( $userid, undef );
716 is( $sessionID, undef );
718 # When calling check_cookie_auth, the session will be deleted
719 ( $auth_status, $session) = C4::Auth::check_cookie_auth( $first_sessionID, { borrowers => 1 } );
720 is( $auth_status, "failed" );
721 is( $session, undef );
722 ( $auth_status, $session) = C4::Auth::check_cookie_auth( $first_sessionID, { borrowers => 1 } );
723 is( $auth_status, 'expired', 'Session no longer exists' );
725 # NOTE: It is not what the UI is doing.
726 # From the UI we are allowed to hit an unauthorized page then reuse the session to hit back authorized area.
727 # It is because check_cookie_auth is ALWAYS called from checkauth WITHOUT $flagsrequired
728 # It then return "ok", when the previous called got "failed"
730 # Try reusing the deleted session: since it does not exist, we should get a new one now when passing correct permissions
731 $cgi->cookie( -name => 'CGISESSID', value => $first_sessionID );
732 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 0, {catalogue => 1});
733 is( $userid, $patron->userid );
734 isnt( $sessionID, undef, 'Check if we have a sessionID' );
735 isnt( $sessionID, $first_sessionID, 'New value expected' );
736 ( $auth_status, $session) = C4::Auth::check_cookie_auth( $sessionID, {catalogue => 1} );
737 is( $auth_status, "ok" );
738 is( $session->id, $sessionID, 'Same session' );
739 # Two additional tests on userenv
740 is( $C4::Context::context->{activeuser}, $session->id, 'Check if environment has been setup for session' );
741 is( C4::Context->userenv->{id}, $userid, 'Check userid in userenv' );
745 subtest 'Userenv clearing in check_cookie_auth' => sub {
746 # Note: We did already test userenv for a logged-in user in previous subtest
749 t::lib::Mocks::mock_preference( 'timeout', 600 );
752 # Create a new anonymous session by passing a fake session ID
753 $cgi->cookie( -name => 'CGISESSID', -value => 'fake_sessionID' );
754 my ($userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 1);
755 my ( $auth_status, $session) = C4::Auth::check_cookie_auth( $sessionID );
756 is( $auth_status, 'anon', 'Should be anonymous' );
757 is( $C4::Context::context->{activeuser}, $session->id, 'Check activeuser' );
758 is( defined C4::Context->userenv, 1, 'There should be a userenv' );
759 is( C4::Context->userenv->{id}, q{}, 'userid should be empty string' );
761 # Make the session expire now, check_cookie_auth will delete it
762 $session->param('lasttime', time() - 1200 );
764 ( $auth_status, $session) = C4::Auth::check_cookie_auth( $sessionID );
765 is( $auth_status, 'expired', 'Should be expired' );
766 is( C4::Context->userenv, undef, 'Environment should be cleared too' );
768 # Show that we clear the userenv again: set up env and check deleted session
769 C4::Context->_new_userenv( $sessionID );
770 C4::Context->set_userenv; # empty
771 is( defined C4::Context->userenv, 1, 'There should be an empty userenv again' );
772 ( $auth_status, $session) = C4::Auth::check_cookie_auth( $sessionID );
773 is( $auth_status, 'expired', 'Should be expired already' );
774 is( C4::Context->userenv, undef, 'Environment should be cleared again' );
777 $schema->storage->txn_rollback;