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;
32 # FIXME: SessionStorage defaults to mysql, but it seems to break transaction
34 t::lib::Mocks::mock_preference( 'SessionStorage', 'tmp' );
35 t::lib::Mocks::mock_preference( 'GDPR_Policy', '' ); # Disabled
37 # To silence useless warnings
38 $ENV{REMOTE_ADDR} = '127.0.0.1';
40 $schema->storage->txn_begin;
42 subtest 'checkauth() tests' => sub {
46 my $patron = $builder->build_object({ class => 'Koha::Patrons', value => { flags => undef } });
48 # Mock a CGI object with real userid param
49 my $cgi = Test::MockObject->new();
54 if ( $var eq 'userid' ) { return $patron->userid; }
57 $cgi->mock( 'cookie', sub { return; } );
58 $cgi->mock( 'request_method', sub { return 'POST' } );
60 my $authnotrequired = 1;
61 my ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, $authnotrequired );
63 is( $userid, undef, 'checkauth() returns undef for userid if no logged in user (Bug 18275)' );
65 my $db_user_id = C4::Context->config('user');
66 my $db_user_pass = C4::Context->config('pass');
67 $cgi = Test::MockObject->new();
68 $cgi->mock( 'cookie', sub { return; } );
69 $cgi->mock( 'param', sub {
70 my ( $self, $param ) = @_;
71 if ( $param eq 'userid' ) { return $db_user_id; }
72 elsif ( $param eq 'password' ) { return $db_user_pass; }
75 $cgi->mock( 'request_method', sub { return 'POST' } );
76 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, $authnotrequired );
77 is ( $userid, undef, 'If DB user is used, it should not be logged in' );
79 my $is_allowed = C4::Auth::haspermission( $db_user_id, { can_do => 'everything' } );
81 # FIXME This belongs to t/db_dependent/Auth/haspermission.t but we do not want to c/p the pervious mock statements
82 ok( !$is_allowed, 'DB user should not have any permissions');
84 subtest 'Prevent authentication when sending credential via GET' => sub {
88 my $patron = $builder->build_object(
89 { class => 'Koha::Patrons', value => { flags => 1 } } );
90 my $password = 'password';
91 t::lib::Mocks::mock_preference( 'RequireStrongPassword', 0 );
92 $patron->set_password( { password => $password } );
93 $cgi = Test::MockObject->new();
94 $cgi->mock( 'cookie', sub { return; } );
98 my ( $self, $param ) = @_;
99 if ( $param eq 'userid' ) { return $patron->userid; }
100 elsif ( $param eq 'password' ) { return $password; }
105 $cgi->mock( 'request_method', sub { return 'POST' } );
106 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired' );
107 is( $userid, $patron->userid, 'If librarian user is used and password with POST, they should be logged in' );
109 $cgi->mock( 'request_method', sub { return 'GET' } );
110 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired' );
111 is( $userid, undef, 'If librarian user is used and password with GET, they should not be logged in' );
114 subtest 'Template params tests (password_expired)' => sub {
118 my $password_expired;
120 my $patron_class = Test::MockModule->new('Koha::Patron');
121 $patron_class->mock( 'password_expired', sub { return $password_expired; } );
123 my $patron = $builder->build_object({ class => 'Koha::Patrons', value => { flags => 1 } });
124 my $password = 'password';
125 t::lib::Mocks::mock_preference( 'RequireStrongPassword', 0 );
126 $patron->set_password( { password => $password } );
128 my $cgi_mock = Test::MockModule->new('CGI')->mock( 'request_method', 'POST' );
130 $cgi->param( -name => 'userid', -value => $patron->userid );
131 $cgi->param( -name => 'password', -value => $password );
133 my $auth = Test::MockModule->new( 'C4::Auth' );
134 # Tests will fail if we hit safe_exit
135 $auth->mock( 'safe_exit', sub { return } );
137 my ( $userid, $cookie, $sessionID, $flags );
140 t::lib::Mocks::mock_preference( 'DumpTemplateVarsOpac', 1 );
141 # checkauth will redirect and safe_exit if not authenticated and not authorized
144 open STDOUT, '>', \$stdout;
146 # Password has expired
147 $password_expired = 1;
148 C4::Auth::checkauth( $cgi, 0, { catalogue => 1 } );
149 like( $stdout, qr{'password_has_expired' => 1}, 'password_has_expired is set to 1' );
155 subtest 'Two-factor authentication' => sub {
157 my $patron = $builder->build_object(
158 { class => 'Koha::Patrons', value => { flags => 1 } } );
159 my $password = 'password';
160 $patron->set_password( { password => $password } );
161 $cgi = Test::MockObject->new();
164 our ( $logout, $sessionID, $verified );
168 my ( $self, $param ) = @_;
169 if ( $param eq 'userid' ) { return $patron->userid; }
170 elsif ( $param eq 'password' ) { return $password; }
171 elsif ( $param eq 'otp_token' ) { return $otp_token; }
172 elsif ( $param eq 'logout.x' ) { return $logout; }
176 $cgi->mock( 'request_method', sub { return 'POST' } );
177 $cgi->mock( 'cookie', sub { return $sessionID } );
179 my $two_factor_auth = Test::MockModule->new( 'Koha::Auth::TwoFactorAuth' );
180 $two_factor_auth->mock( 'verify', sub {$verified} );
182 my ( $userid, $cookie, $flags );
183 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired', undef, 'intranet' );
189 C4::Auth::checkauth( $cgi, 'authrequired', undef, 'intranet' );
193 t::lib::Mocks::mock_preference( 'TwoFactorAuthentication', 'disabled' );
194 $patron->auth_method('password')->store;
195 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired', undef, 'intranet' );
196 is( $userid, $patron->userid, 'Succesful login' );
197 is( C4::Auth::get_session($sessionID)->param('waiting-for-2FA'), undef, 'Second auth not required' );
200 $patron->auth_method('two-factor')->store;
201 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired', undef, 'intranet' );
202 is( $userid, $patron->userid, 'Succesful login' );
203 is( C4::Auth::get_session($sessionID)->param('waiting-for-2FA'), undef, 'Second auth not required' );
206 t::lib::Mocks::mock_preference( 'TwoFactorAuthentication', 'enabled' );
207 t::lib::Mocks::mock_config('encryption_key', '1234tH1s=t&st');
208 $patron->auth_method('password')->store;
209 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired', undef, 'intranet' );
210 is( $userid, $patron->userid, 'Succesful login' );
211 is( C4::Auth::get_session($sessionID)->param('waiting-for-2FA'), undef, 'Second auth not required' );
214 $patron->encode_secret('one_secret');
215 $patron->auth_method('two-factor');
217 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired', undef, 'intranet' );
218 is( $userid, $patron->userid, 'Succesful login' );
219 my $session = C4::Auth::get_session($sessionID);
220 is( C4::Auth::get_session($sessionID)->param('waiting-for-2FA'), 1, 'Second auth required' );
223 $otp_token = "wrong";
225 $patron->auth_method('two-factor')->store;
226 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired', undef, 'intranet' );
227 is( $userid, $patron->userid, 'Succesful login' );
228 is( C4::Auth::get_session($sessionID)->param('waiting-for-2FA'), 1, 'Second auth still required after wrong OTP token' );
232 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired', undef, 'intranet' );
233 is( $userid, $patron->userid, 'Succesful login' );
234 is( C4::Auth::get_session($sessionID)->param('waiting-for-2FA'), 0, 'Second auth no longer required if OTP token has been verified' );
237 t::lib::Mocks::mock_preference( 'TwoFactorAuthentication', 'enforced' );
238 $patron->auth_method('password')->store;
239 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired', undef, 'intranet' );
240 is( $userid, $patron->userid, 'Succesful login' );
241 is( C4::Auth::get_session($sessionID)->param('waiting-for-2FA-setup'), 1, 'Setup 2FA required' );
244 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired', undef, 'opac' );
245 is( $userid, $patron->userid, 'Succesful login at the OPAC' );
246 is( C4::Auth::get_session($sessionID)->param('waiting-for-2FA'), undef, 'No second auth required at the OPAC' );
248 t::lib::Mocks::mock_preference( 'TwoFactorAuthentication', 'disabled' );
251 C4::Context->_new_userenv; # For next tests
255 subtest 'track_login_daily tests' => sub {
259 my $patron = $builder->build_object({ class => 'Koha::Patrons' });
260 my $userid = $patron->userid;
262 $patron->lastseen( undef );
265 my $cache = Koha::Caches->get_instance();
266 my $cache_key = "track_login_" . $patron->userid;
267 $cache->clear_from_cache($cache_key);
269 t::lib::Mocks::mock_preference( 'TrackLastPatronActivity', '1' );
271 is( $patron->lastseen, undef, 'Patron should have not last seen when newly created' );
273 C4::Auth::track_login_daily( $userid );
274 $patron->_result()->discard_changes();
275 isnt( $patron->lastseen, undef, 'Patron should have last seen set when TrackLastPatronActivity = 1' );
277 sleep(1); # We need to wait a tiny bit to make sure the timestamp will be different
278 my $last_seen = $patron->lastseen;
279 C4::Auth::track_login_daily( $userid );
280 $patron->_result()->discard_changes();
281 is( $patron->lastseen, $last_seen, 'Patron last seen should still be unchanged' );
283 $cache->clear_from_cache($cache_key);
284 C4::Auth::track_login_daily( $userid );
285 $patron->_result()->discard_changes();
286 isnt( $patron->lastseen, $last_seen, 'Patron last seen should be changed if we cleared the cache' );
288 t::lib::Mocks::mock_preference( 'TrackLastPatronActivity', '0' );
289 $patron->lastseen( undef )->store;
290 $cache->clear_from_cache($cache_key);
291 C4::Auth::track_login_daily( $userid );
292 $patron->_result()->discard_changes();
293 is( $patron->lastseen, undef, 'Patron should still have last seen unchanged when TrackLastPatronActivity = 0' );
297 subtest 'no_set_userenv parameter tests' => sub {
301 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
302 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
303 my $password = 'password';
305 t::lib::Mocks::mock_preference( 'RequireStrongPassword', 0 );
306 $patron->set_password({ password => $password });
308 ok( checkpw( $patron->userid, $password, undef, undef, 1 ), 'checkpw returns true' );
309 is( C4::Context->userenv, undef, 'Userenv should be undef as required' );
310 C4::Context->_new_userenv('DUMMY SESSION');
311 C4::Context->set_userenv(0,0,0,'firstname','surname', $library->branchcode, 'Library 1', 0, '', '');
312 is( C4::Context->userenv->{branch}, $library->branchcode, 'Userenv gives correct branch' );
313 ok( checkpw( $patron->userid, $password, undef, undef, 1 ), 'checkpw returns true' );
314 is( C4::Context->userenv->{branch}, $library->branchcode, 'Userenv branch is preserved if no_set_userenv is true' );
315 ok( checkpw( $patron->userid, $password, undef, undef, 0 ), 'checkpw still returns true' );
316 isnt( C4::Context->userenv->{branch}, $library->branchcode, 'Userenv branch is overwritten if no_set_userenv is false' );
319 subtest 'checkpw lockout tests' => sub {
323 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
324 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
325 my $password = 'password';
326 t::lib::Mocks::mock_preference( 'RequireStrongPassword', 0 );
327 t::lib::Mocks::mock_preference( 'FailedLoginAttempts', 1 );
328 $patron->set_password({ password => $password });
330 my ( $checkpw, undef, undef ) = checkpw( $patron->cardnumber, $password, undef, undef, 1 );
331 ok( $checkpw, 'checkpw returns true with right password when logging in via cardnumber' );
332 ( $checkpw, undef, undef ) = checkpw( $patron->userid, "wrong_password", undef, undef, 1 );
333 is( $checkpw, 0, 'checkpw returns false when given wrong password' );
334 $patron = $patron->get_from_storage;
335 is( $patron->account_locked, 1, "Account is locked from failed login");
336 ( $checkpw, undef, undef ) = checkpw( $patron->userid, $password, undef, undef, 1 );
337 is( $checkpw, undef, 'checkpw returns undef with right password when account locked' );
338 ( $checkpw, undef, undef ) = checkpw( $patron->cardnumber, $password, undef, undef, 1 );
339 is( $checkpw, undef, 'checkpw returns undefwith right password when logging in via cardnumber if account locked' );
343 # get_template_and_user tests
345 subtest 'get_template_and_user' => sub { # Tests for the language URL parameter
347 sub MockedCheckauth {
348 my ($query,$authnotrequired,$flagsrequired,$type) = @_;
350 my $userid = 'cobain';
352 # we don't need to bother about permissions for this test
354 superlibrarian => 1, acquisition => 0,
356 catalogue => 1, circulate => 0,
357 coursereserves => 0, editauthorities => 0,
359 parameters => 0, permissions => 0,
360 plugins => 0, reports => 0,
361 reserveforothers => 0, serials => 0,
362 staffaccess => 0, tools => 0,
366 my $session_cookie = $query->cookie(
367 -name => 'CGISESSID',
372 return ( $userid, [ $session_cookie ], $sessionID, $flags );
375 # Mock checkauth, build the scenario
376 my $auth = Test::MockModule->new( 'C4::Auth' );
377 $auth->mock( 'checkauth', \&MockedCheckauth );
379 # Make sure 'EnableOpacSearchHistory' is set
380 t::lib::Mocks::mock_preference('EnableOpacSearchHistory',1);
381 # Enable es-ES for the OPAC and staff interfaces
382 t::lib::Mocks::mock_preference('OPACLanguages','en,es-ES');
383 t::lib::Mocks::mock_preference('language','en,es-ES');
385 # we need a session cookie
386 $ENV{"SERVER_PORT"} = 80;
387 $ENV{"HTTP_COOKIE"} = 'CGISESSID=nirvana';
389 my $query = CGI->new;
390 $query->param('language','es-ES');
392 my ( $template, $loggedinuser, $cookies ) = get_template_and_user(
394 template_name => "about.tt",
397 authnotrequired => 1,
398 flagsrequired => { catalogue => 1 },
403 ok ( ( all { ref($_) eq 'CGI::Cookie' } @$cookies ),
404 'BZ9735: the cookies array is flat' );
406 # new query, with non-existent language (we only have en and es-ES)
407 $query->param('language','tomas');
409 ( $template, $loggedinuser, $cookies ) = get_template_and_user(
411 template_name => "about.tt",
414 authnotrequired => 1,
415 flagsrequired => { catalogue => 1 },
420 ok( ( none { $_->name eq 'KohaOpacLanguage' and $_->value eq 'tomas' } @$cookies ),
421 'BZ9735: invalid language, it is not set');
423 ok( ( any { $_->name eq 'KohaOpacLanguage' and $_->value eq 'en' } @$cookies ),
424 'BZ9735: invalid language, then default to en');
426 for my $template_name (
428 ../../../../../../../../../../../../../../../etc/passwd
429 test/../../../../../../../../../../../../../../etc/passwd
431 test/does_not_finished_by_tt_t
435 ( $template, $loggedinuser, $cookies ) = get_template_and_user(
437 template_name => $template_name,
440 authnotrequired => 1,
441 flagsrequired => { catalogue => 1 },
445 like ( $@, qr(bad template path), "The file $template_name should not be accessible" );
447 ( $template, $loggedinuser, $cookies ) = get_template_and_user(
449 template_name => 'errors/errorpage.tt',
452 authnotrequired => 1,
453 flagsrequired => { catalogue => 1 },
456 my $file_exists = ( -f $template->{filename} ) ? 1 : 0;
457 is ( $file_exists, 1, 'The file errors/errorpage.tt should be accessible (contains integers)' );
459 # Regression test for env opac search limit override
460 $ENV{"OPAC_SEARCH_LIMIT"} = "branch:CPL";
461 $ENV{"OPAC_LIMIT_OVERRIDE"} = 1;
463 ( $template, $loggedinuser, $cookies) = get_template_and_user(
465 template_name => 'opac-main.tt',
468 authnotrequired => 1,
471 is($template->{VARS}->{'opac_name'}, "CPL", "Opac name was set correctly");
472 is($template->{VARS}->{'opac_search_limit'}, "branch:CPL", "Search limit was set correctly");
474 $ENV{"OPAC_SEARCH_LIMIT"} = "branch:multibranch-19";
476 ( $template, $loggedinuser, $cookies) = get_template_and_user(
478 template_name => 'opac-main.tt',
481 authnotrequired => 1,
484 is($template->{VARS}->{'opac_name'}, "multibranch-19", "Opac name was set correctly");
485 is($template->{VARS}->{'opac_search_limit'}, "branch:multibranch-19", "Search limit was set correctly");
487 delete $ENV{"HTTP_COOKIE"};
490 # Check that there is always an OPACBaseURL set.
491 my $input = CGI->new();
492 my ( $template1, $borrowernumber, $cookie );
493 ( $template1, $borrowernumber, $cookie ) = get_template_and_user(
495 template_name => "opac-detail.tt",
498 authnotrequired => 1,
502 ok( ( any { 'OPACBaseURL' eq $_ } keys %{$template1->{VARS}} ),
503 'OPACBaseURL is in OPAC template' );
506 ( $template2, $borrowernumber, $cookie ) = get_template_and_user(
508 template_name => "catalogue/detail.tt",
511 authnotrequired => 1,
515 ok( ( any { 'OPACBaseURL' eq $_ } keys %{$template2->{VARS}} ),
516 'OPACBaseURL is in Staff template' );
518 my $hash1 = hash_password('password');
519 my $hash2 = hash_password('password');
521 ok(C4::Auth::checkpw_hash('password', $hash1), 'password validates with first hash');
522 ok(C4::Auth::checkpw_hash('password', $hash2), 'password validates with second hash');
524 subtest 'Check value of login_attempts in checkpw' => sub {
527 t::lib::Mocks::mock_preference('FailedLoginAttempts', 3);
529 # Only interested here in regular login
533 my $patron = $builder->build_object({ class => 'Koha::Patrons' });
534 $patron->login_attempts(2);
535 $patron->password('123')->store; # yes, deliberately not hashed
537 is( $patron->account_locked, 0, 'Patron not locked' );
538 my @test = checkpw( $patron->userid, '123', undef, 'opac', 1 );
539 # Note: 123 will not be hashed to 123 !
540 is( $test[0], 0, 'checkpw should have failed' );
541 $patron->discard_changes; # refresh
542 is( $patron->login_attempts, 3, 'Login attempts increased' );
543 is( $patron->account_locked, 1, 'Check locked status' );
545 # And another try to go over the limit: different return value!
546 @test = checkpw( $patron->userid, '123', undef, 'opac', 1 );
547 is( @test, 0, 'checkpw failed again and returns nothing now' );
548 $patron->discard_changes; # refresh
549 is( $patron->login_attempts, 3, 'Login attempts not increased anymore' );
551 # Administrative lockout cannot be undone?
552 # Pass the right password now (or: add a nice mock).
553 my $auth = Test::MockModule->new( 'C4::Auth' );
554 $auth->mock( 'checkpw_hash', sub { return 1; } ); # not for production :)
555 $patron->login_attempts(0)->store;
556 @test = checkpw( $patron->userid, '123', undef, 'opac', 1 );
557 is( $test[0], 1, 'Build confidence in the mock' );
558 $patron->login_attempts(-1)->store;
559 is( $patron->account_locked, 1, 'Check administrative lockout' );
560 @test = checkpw( $patron->userid, '123', undef, 'opac', 1 );
561 is( @test, 0, 'checkpw gave red' );
562 $patron->discard_changes; # refresh
563 is( $patron->login_attempts, -1, 'Still locked out' );
564 t::lib::Mocks::mock_preference('FailedLoginAttempts', ''); # disable
565 is( $patron->account_locked, 1, 'Check administrative lockout without pref' );
568 subtest 'Check value of login_attempts in checkpw' => sub {
571 t::lib::Mocks::mock_preference('FailedLoginAttempts', 3);
572 my $patron = $builder->build_object({ class => 'Koha::Patrons' });
573 $patron->set_password({ password => '123', skip_validation => 1 });
575 my @test = checkpw( $patron->userid, '123', undef, 'opac', 1 );
576 is( $test[0], 1, 'Patron authenticated correctly' );
578 $patron->password_expiration_date('2020-01-01')->store;
579 @test = checkpw( $patron->userid, '123', undef, 'opac', 1 );
580 is( $test[0], -2, 'Patron returned as expired correctly' );
584 subtest '_timeout_syspref' => sub {
588 t::lib::Mocks::mock_preference('timeout', "100");
589 is( C4::Auth::_timeout_syspref, 100, );
591 t::lib::Mocks::mock_preference('timeout', "2d");
592 is( C4::Auth::_timeout_syspref, 2*86400, );
594 t::lib::Mocks::mock_preference('timeout', "2D");
595 is( C4::Auth::_timeout_syspref, 2*86400, );
597 t::lib::Mocks::mock_preference('timeout', "10h");
598 is( C4::Auth::_timeout_syspref, 10*3600, );
600 t::lib::Mocks::mock_preference('timeout', "10x");
602 { is( C4::Auth::_timeout_syspref, 600, ); }
603 "The value of the system preference 'timeout' is not correct, defaulting to 600",
604 'Bad values throw a warning and fallback to 600';
607 subtest 'check_cookie_auth' => sub {
610 t::lib::Mocks::mock_preference('timeout', "1d"); # back to default
612 my $patron = $builder->build_object({ class => 'Koha::Patrons', value => { flags => 1 } });
614 # Mock a CGI object with real userid param
615 my $cgi = Test::MockObject->new();
620 if ( $var eq 'userid' ) { return $patron->userid; }
623 $cgi->mock('multi_param', sub {return q{}} );
624 $cgi->mock( 'cookie', sub { return; } );
625 $cgi->mock( 'request_method', sub { return 'POST' } );
627 $ENV{REMOTE_ADDR} = '127.0.0.1';
629 # Setting authnotrequired=1 or we wont' hit the return but the end of the sub that prints headers
630 my ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 1 );
632 my ($auth_status, $session) = C4::Auth::check_cookie_auth($sessionID);
633 isnt( $auth_status, 'ok', 'check_cookie_auth should not return ok if the user has not been authenticated before if no permissions needed' );
634 is( $auth_status, 'anon', 'check_cookie_auth should return anon if the user has not been authenticated before and no permissions needed' );
636 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 1 );
638 ($auth_status, $session) = C4::Auth::check_cookie_auth($sessionID, {catalogue => 1});
639 isnt( $auth_status, 'ok', 'check_cookie_auth should not return ok if the user has not been authenticated before and permissions needed' );
640 is( $auth_status, 'anon', 'check_cookie_auth should return anon if the user has not been authenticated before and permissions needed' );
642 #FIXME We should have a test to cover 'failed' status when a user has logged in, but doesn't have permission
645 subtest 'checkauth & check_cookie_auth' => sub {
648 # flags = 4 => { catalogue => 1 }
649 my $patron = $builder->build_object({ class => 'Koha::Patrons', value => { flags => 4 } });
650 my $password = 'password';
651 t::lib::Mocks::mock_preference( 'RequireStrongPassword', 0 );
652 $patron->set_password( { password => $password } );
654 my $cgi_mock = Test::MockModule->new('CGI');
655 $cgi_mock->mock( 'request_method', sub { return 'POST' } );
659 my $auth = Test::MockModule->new( 'C4::Auth' );
660 # Tests will fail if we hit safe_exit
661 $auth->mock( 'safe_exit', sub { return } );
663 my ( $userid, $cookie, $sessionID, $flags );
665 # checkauth will redirect and safe_exit if not authenticated and not authorized
668 open STDOUT, '>', \$stdout;
669 C4::Auth::checkauth($cgi, 0, {catalogue => 1});
670 like( $stdout, qr{<title>\s*Log in to your account} );
671 $sessionID = ( $stdout =~ m{Set-Cookie: CGISESSID=((\d|\w)+);} ) ? $1 : undef;
676 my $first_sessionID = $sessionID;
678 $ENV{"HTTP_COOKIE"} = "CGISESSID=$sessionID";
679 # Not authenticated yet, checkauth didn't return the session
683 open STDOUT, '>', \$stdout;
684 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 0, {catalogue => 1} );
687 is( $sessionID, undef);
690 # Sending undefined fails obviously
691 my ( $auth_status, $session ) = C4::Auth::check_cookie_auth($sessionID, {catalogue => 1} );
692 is( $auth_status, 'failed' );
693 is( $session, undef );
695 # Simulating the login form submission
696 $cgi->param('userid', $patron->userid);
697 $cgi->param('password', $password);
700 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 0, {catalogue => 1});
701 is( $sessionID, $first_sessionID );
702 is( $userid, $patron->userid );
704 ( $auth_status, $session ) = C4::Auth::check_cookie_auth($sessionID, {catalogue => 1});
705 is( $auth_status, 'ok' );
706 is( $session->id, $first_sessionID );
709 $cgi->param('logout.x', 1);
710 $cgi->delete( 'userid', 'password' );
714 open STDOUT, '>', \$stdout;
715 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 0, {catalogue => 1});
718 is( $sessionID, undef );
719 is( $ENV{"HTTP_COOKIE"}, "CGISESSID=$first_sessionID", 'HTTP_COOKIE not unset' );
720 ( $auth_status, $session) = C4::Auth::check_cookie_auth( $first_sessionID, {catalogue => 1} );
721 is( $auth_status, "expired");
722 is( $session, undef );
725 # Trying to access without sessionID
727 ( $auth_status, $session) = C4::Auth::check_cookie_auth(undef, {catalogue => 1});
728 is( $auth_status, 'failed' );
729 is( $session, undef );
731 # This will fail on permissions
732 undef $ENV{"HTTP_COOKIE"};
736 open STDOUT, '>', \$stdout;
737 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 0, {catalogue => 1} );
740 is( $userid, undef );
741 is( $sessionID, undef );
747 $cgi->param('userid', $patron->userid);
748 $cgi->param('password', $password);
749 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 0, {catalogue => 1});
750 is( $userid, $patron->userid );
751 $first_sessionID = $sessionID;
753 # Patron does not have the borrowers permission
754 # $ENV{"HTTP_COOKIE"} = "CGISESSID=$sessionID"; # not needed, we use $cgi here
758 open STDOUT, '>', \$stdout;
759 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 0, {borrowers => 1} );
762 is( $userid, undef );
763 is( $sessionID, undef );
765 # When calling check_cookie_auth, the session will be deleted
766 ( $auth_status, $session) = C4::Auth::check_cookie_auth( $first_sessionID, { borrowers => 1 } );
767 is( $auth_status, "failed" );
768 is( $session, undef );
769 ( $auth_status, $session) = C4::Auth::check_cookie_auth( $first_sessionID, { borrowers => 1 } );
770 is( $auth_status, 'expired', 'Session no longer exists' );
772 # NOTE: It is not what the UI is doing.
773 # From the UI we are allowed to hit an unauthorized page then reuse the session to hit back authorized area.
774 # It is because check_cookie_auth is ALWAYS called from checkauth WITHOUT $flagsrequired
775 # It then return "ok", when the previous called got "failed"
777 # Try reusing the deleted session: since it does not exist, we should get a new one now when passing correct permissions
778 $cgi->cookie( -name => 'CGISESSID', value => $first_sessionID );
779 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 0, {catalogue => 1});
780 is( $userid, $patron->userid );
781 isnt( $sessionID, undef, 'Check if we have a sessionID' );
782 isnt( $sessionID, $first_sessionID, 'New value expected' );
783 ( $auth_status, $session) = C4::Auth::check_cookie_auth( $sessionID, {catalogue => 1} );
784 is( $auth_status, "ok" );
785 is( $session->id, $sessionID, 'Same session' );
786 # Two additional tests on userenv
787 is( $C4::Context::context->{activeuser}, $session->id, 'Check if environment has been setup for session' );
788 is( C4::Context->userenv->{id}, $userid, 'Check userid in userenv' );
792 subtest 'Userenv clearing in check_cookie_auth' => sub {
793 # Note: We did already test userenv for a logged-in user in previous subtest
796 t::lib::Mocks::mock_preference( 'timeout', 600 );
799 # Create a new anonymous session by passing a fake session ID
800 $cgi->cookie( -name => 'CGISESSID', -value => 'fake_sessionID' );
801 my ($userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 1);
802 my ( $auth_status, $session) = C4::Auth::check_cookie_auth( $sessionID );
803 is( $auth_status, 'anon', 'Should be anonymous' );
804 is( $C4::Context::context->{activeuser}, $session->id, 'Check activeuser' );
805 is( defined C4::Context->userenv, 1, 'There should be a userenv' );
806 is( C4::Context->userenv->{id}, q{}, 'userid should be empty string' );
808 # Make the session expire now, check_cookie_auth will delete it
809 $session->param('lasttime', time() - 1200 );
811 ( $auth_status, $session) = C4::Auth::check_cookie_auth( $sessionID );
812 is( $auth_status, 'expired', 'Should be expired' );
813 is( C4::Context->userenv, undef, 'Environment should be cleared too' );
815 # Show that we clear the userenv again: set up env and check deleted session
816 C4::Context->_new_userenv( $sessionID );
817 C4::Context->set_userenv; # empty
818 is( defined C4::Context->userenv, 1, 'There should be an empty userenv again' );
819 ( $auth_status, $session) = C4::Auth::check_cookie_auth( $sessionID );
820 is( $auth_status, 'expired', 'Should be expired already' );
821 is( C4::Context->userenv, undef, 'Environment should be cleared again' );
824 $schema->storage->txn_rollback;