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 => 17;
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 'While still logged in, relogin with another user' => sub {
158 my $patron = $builder->build_object({ class => 'Koha::Patrons', value => {} });
159 my $patron2 = $builder->build_object({ class => 'Koha::Patrons', value => {} });
160 # Create 'former' session
161 my $session = C4::Auth::get_session();
162 $session->param( 'number', $patron->id );
163 $session->param( 'id', $patron->userid );
164 $session->param( 'ip', '1.2.3.4' );
165 $session->param( 'lasttime', time() );
166 $session->param( 'interface', 'opac' );
168 my $sessionID = $session->id;
169 C4::Context->_new_userenv($sessionID);
171 my ( $return ) = C4::Auth::check_cookie_auth( $sessionID, undef, { skip_version_check => 1, remote_addr => '1.2.3.4' } );
172 is( $return, 'ok', 'Former session in shape now' );
174 my $mock1 = Test::MockModule->new('C4::Auth')->mock( 'safe_exit', sub {} );
175 my $mock2 = Test::MockModule->new('CGI') ->mock( 'request_method', 'POST' )
176 ->mock( 'cookie', sub { return $sessionID; } ); # oversimplified..
178 my $password = 'Incr3d1blyZtr@ng93$';
179 $patron2->set_password({ password => $password });
180 $cgi->param( -name => 'userid', -value => $patron2->userid );
181 $cgi->param( -name => 'password', -value => $password );
182 $cgi->param( -name => 'koha_login_context', -value => 1 );
183 my ( @return, $stdout );
187 $ENV{REMOTE_ADDR} = '1.2.3.4';
188 open STDOUT, '>', \$stdout;
189 @return = C4::Auth::checkauth( $cgi, 0, {} );
192 # Note: We can test return values from checkauth here since we mocked the safe_exit after the Redirect 303
193 is( $return[0], $patron2->userid, 'Login of patron2 approved' );
194 isnt( $return[2], $sessionID, 'Did not return previous session ID' );
195 ok( $return[2], 'New session ID not empty' );
197 # Similar situation: Relogin with former session of $patron, new user $patron2 has no permissions
198 $patron2->flags(undef)->store;
199 $session->param( 'number', $patron->id );
200 $session->param( 'id', $patron->userid );
201 $session->param( 'interface', 'intranet' );
203 $sessionID = $session->id;
204 C4::Context->_new_userenv($sessionID);
205 $cgi->param( -name => 'userid', -value => $patron2->userid );
206 $cgi->param( -name => 'password', -value => $password );
207 $cgi->param( -name => 'koha_login_context', -value => 1 );
211 $ENV{REMOTE_ADDR} = '1.2.3.4';
213 open STDOUT, '>', \$stdout;
214 @return = C4::Auth::checkauth( $cgi, 0, { catalogue => 1 }, 'intranet' ); # patron2 has no catalogue perm
217 like( $stdout, qr/You do not have permission to access this page/, 'No permission response' );
218 is( @return, 0, 'checkauth returned failure' );
221 subtest 'Two-factor authentication' => sub {
224 my $patron = $builder->build_object(
225 { class => 'Koha::Patrons', value => { flags => 1 } } );
226 my $password = 'password';
227 $patron->set_password( { password => $password } );
228 $cgi = Test::MockObject->new();
231 our ( $logout, $sessionID, $verified );
235 my ( $self, $param ) = @_;
236 if ( $param eq 'userid' ) { return $patron->userid; }
237 elsif ( $param eq 'password' ) { return $password; }
238 elsif ( $param eq 'otp_token' ) { return $otp_token; }
239 elsif ( $param eq 'logout.x' ) { return $logout; }
243 $cgi->mock( 'request_method', sub { return 'POST' } );
244 $cgi->mock( 'cookie', sub { return $sessionID } );
246 my $two_factor_auth = Test::MockModule->new( 'Koha::Auth::TwoFactorAuth' );
247 $two_factor_auth->mock( 'verify', sub {$verified} );
249 my ( $userid, $cookie, $flags );
250 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired', undef, 'intranet' );
256 C4::Auth::checkauth( $cgi, 'authrequired', undef, 'intranet' );
260 t::lib::Mocks::mock_preference( 'TwoFactorAuthentication', 'disabled' );
261 $patron->auth_method('password')->store;
262 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired', undef, 'intranet' );
263 is( $userid, $patron->userid, 'Succesful login' );
264 is( C4::Auth::get_session($sessionID)->param('waiting-for-2FA'), undef, 'Second auth not required' );
267 $patron->auth_method('two-factor')->store;
268 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired', undef, 'intranet' );
269 is( $userid, $patron->userid, 'Succesful login' );
270 is( C4::Auth::get_session($sessionID)->param('waiting-for-2FA'), undef, 'Second auth not required' );
273 t::lib::Mocks::mock_preference( 'TwoFactorAuthentication', 'enabled' );
274 t::lib::Mocks::mock_config('encryption_key', '1234tH1s=t&st');
275 $patron->auth_method('password')->store;
276 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired', undef, 'intranet' );
277 is( $userid, $patron->userid, 'Succesful login' );
278 is( C4::Auth::get_session($sessionID)->param('waiting-for-2FA'), undef, 'Second auth not required' );
281 $patron->encode_secret('one_secret');
282 $patron->auth_method('two-factor');
284 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired', undef, 'intranet' );
285 is( $userid, $patron->userid, 'Succesful login' );
286 my $session = C4::Auth::get_session($sessionID);
287 is( C4::Auth::get_session($sessionID)->param('waiting-for-2FA'), 1, 'Second auth required' );
290 $otp_token = "wrong";
292 $patron->auth_method('two-factor')->store;
293 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired', undef, 'intranet' );
294 is( $userid, $patron->userid, 'Succesful login' );
295 is( C4::Auth::get_session($sessionID)->param('waiting-for-2FA'), 1, 'Second auth still required after wrong OTP token' );
299 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired', undef, 'intranet' );
300 is( $userid, $patron->userid, 'Succesful login' );
301 is( C4::Auth::get_session($sessionID)->param('waiting-for-2FA'), 0, 'Second auth no longer required if OTP token has been verified' );
304 t::lib::Mocks::mock_preference( 'TwoFactorAuthentication', 'enforced' );
305 $patron->auth_method('password')->store;
306 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired', undef, 'intranet' );
307 is( $userid, $patron->userid, 'Succesful login' );
308 is( C4::Auth::get_session($sessionID)->param('waiting-for-2FA-setup'), 1, 'Setup 2FA required' );
311 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired', undef, 'opac' );
312 is( $userid, $patron->userid, 'Succesful login at the OPAC' );
313 is( C4::Auth::get_session($sessionID)->param('waiting-for-2FA'), undef, 'No second auth required at the OPAC' );
316 t::lib::Mocks::mock_preference( 'TwoFactorAuthentication', 'disabled' );
317 $session = C4::Auth::get_session($sessionID);
318 $session->param('waiting-for-2FA', 1);
320 my ($auth_status, undef ) = C4::Auth::check_cookie_auth($sessionID, undef );
321 is( $auth_status, 'ok', 'User authenticated, pref was disabled, access OK' );
322 $session->param('waiting-for-2FA', 0);
323 $session->param('waiting-for-2FA-setup', 1);
325 ($auth_status, undef ) = C4::Auth::check_cookie_auth($sessionID, undef );
326 is( $auth_status, 'ok', 'User waiting for 2FA setup, pref was disabled, access OK' );
329 C4::Context->_new_userenv; # For next tests
333 subtest 'track_login_daily tests' => sub {
337 my $patron = $builder->build_object({ class => 'Koha::Patrons' });
338 my $userid = $patron->userid;
340 $patron->lastseen( undef );
343 my $cache = Koha::Caches->get_instance();
344 my $cache_key = "track_login_" . $patron->userid;
345 $cache->clear_from_cache($cache_key);
347 t::lib::Mocks::mock_preference( 'TrackLastPatronActivity', '1' );
349 is( $patron->lastseen, undef, 'Patron should have not last seen when newly created' );
351 C4::Auth::track_login_daily( $userid );
352 $patron->_result()->discard_changes();
353 isnt( $patron->lastseen, undef, 'Patron should have last seen set when TrackLastPatronActivity = 1' );
355 sleep(1); # We need to wait a tiny bit to make sure the timestamp will be different
356 my $last_seen = $patron->lastseen;
357 C4::Auth::track_login_daily( $userid );
358 $patron->_result()->discard_changes();
359 is( $patron->lastseen, $last_seen, 'Patron last seen should still be unchanged' );
361 $cache->clear_from_cache($cache_key);
362 C4::Auth::track_login_daily( $userid );
363 $patron->_result()->discard_changes();
364 isnt( $patron->lastseen, $last_seen, 'Patron last seen should be changed if we cleared the cache' );
366 t::lib::Mocks::mock_preference( 'TrackLastPatronActivity', '0' );
367 $patron->lastseen( undef )->store;
368 $cache->clear_from_cache($cache_key);
369 C4::Auth::track_login_daily( $userid );
370 $patron->_result()->discard_changes();
371 is( $patron->lastseen, undef, 'Patron should still have last seen unchanged when TrackLastPatronActivity = 0' );
375 subtest 'no_set_userenv parameter tests' => sub {
379 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
380 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
381 my $password = 'password';
383 t::lib::Mocks::mock_preference( 'RequireStrongPassword', 0 );
384 $patron->set_password({ password => $password });
386 ok( checkpw( $patron->userid, $password, undef, undef, 1 ), 'checkpw returns true' );
387 is( C4::Context->userenv, undef, 'Userenv should be undef as required' );
388 C4::Context->_new_userenv('DUMMY SESSION');
389 C4::Context->set_userenv(0,0,0,'firstname','surname', $library->branchcode, 'Library 1', 0, '', '');
390 is( C4::Context->userenv->{branch}, $library->branchcode, 'Userenv gives correct branch' );
391 ok( checkpw( $patron->userid, $password, undef, undef, 1 ), 'checkpw returns true' );
392 is( C4::Context->userenv->{branch}, $library->branchcode, 'Userenv branch is preserved if no_set_userenv is true' );
393 ok( checkpw( $patron->userid, $password, undef, undef, 0 ), 'checkpw still returns true' );
394 isnt( C4::Context->userenv->{branch}, $library->branchcode, 'Userenv branch is overwritten if no_set_userenv is false' );
397 subtest 'checkpw lockout tests' => sub {
401 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
402 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
403 my $password = 'password';
404 t::lib::Mocks::mock_preference( 'RequireStrongPassword', 0 );
405 t::lib::Mocks::mock_preference( 'FailedLoginAttempts', 1 );
406 $patron->set_password({ password => $password });
408 my ( $checkpw, undef, undef ) = checkpw( $patron->cardnumber, $password, undef, undef, 1 );
409 ok( $checkpw, 'checkpw returns true with right password when logging in via cardnumber' );
410 ( $checkpw, undef, undef ) = checkpw( $patron->userid, "wrong_password", undef, undef, 1 );
411 is( $checkpw, 0, 'checkpw returns false when given wrong password' );
412 $patron = $patron->get_from_storage;
413 is( $patron->account_locked, 1, "Account is locked from failed login");
414 ( $checkpw, undef, undef ) = checkpw( $patron->userid, $password, undef, undef, 1 );
415 is( $checkpw, undef, 'checkpw returns undef with right password when account locked' );
416 ( $checkpw, undef, undef ) = checkpw( $patron->cardnumber, $password, undef, undef, 1 );
417 is( $checkpw, undef, 'checkpw returns undefwith right password when logging in via cardnumber if account locked' );
421 # get_template_and_user tests
423 subtest 'get_template_and_user' => sub { # Tests for the language URL parameter
425 sub MockedCheckauth {
426 my ($query,$authnotrequired,$flagsrequired,$type) = @_;
428 my $userid = 'cobain';
430 # we don't need to bother about permissions for this test
432 superlibrarian => 1, acquisition => 0,
434 catalogue => 1, circulate => 0,
435 coursereserves => 0, editauthorities => 0,
437 parameters => 0, permissions => 0,
438 plugins => 0, reports => 0,
439 reserveforothers => 0, serials => 0,
440 staffaccess => 0, tools => 0,
444 my $session_cookie = $query->cookie(
445 -name => 'CGISESSID',
450 return ( $userid, [ $session_cookie ], $sessionID, $flags );
453 # Mock checkauth, build the scenario
454 my $auth = Test::MockModule->new( 'C4::Auth' );
455 $auth->mock( 'checkauth', \&MockedCheckauth );
457 # Make sure 'EnableOpacSearchHistory' is set
458 t::lib::Mocks::mock_preference('EnableOpacSearchHistory',1);
459 # Enable es-ES for the OPAC and staff interfaces
460 t::lib::Mocks::mock_preference('OPACLanguages','en,es-ES');
461 t::lib::Mocks::mock_preference('language','en,es-ES');
463 # we need a session cookie
464 $ENV{"SERVER_PORT"} = 80;
465 $ENV{"HTTP_COOKIE"} = 'CGISESSID=nirvana';
467 my $query = CGI->new;
468 $query->param('language','es-ES');
470 my ( $template, $loggedinuser, $cookies ) = get_template_and_user(
472 template_name => "about.tt",
475 authnotrequired => 1,
476 flagsrequired => { catalogue => 1 },
481 ok ( ( all { ref($_) eq 'CGI::Cookie' } @$cookies ),
482 'BZ9735: the cookies array is flat' );
484 # new query, with non-existent language (we only have en and es-ES)
485 $query->param('language','tomas');
487 ( $template, $loggedinuser, $cookies ) = get_template_and_user(
489 template_name => "about.tt",
492 authnotrequired => 1,
493 flagsrequired => { catalogue => 1 },
498 ok( ( none { $_->name eq 'KohaOpacLanguage' and $_->value eq 'tomas' } @$cookies ),
499 'BZ9735: invalid language, it is not set');
501 ok( ( any { $_->name eq 'KohaOpacLanguage' and $_->value eq 'en' } @$cookies ),
502 'BZ9735: invalid language, then default to en');
504 for my $template_name (
506 ../../../../../../../../../../../../../../../etc/passwd
507 test/../../../../../../../../../../../../../../etc/passwd
509 test/does_not_finished_by_tt_t
513 ( $template, $loggedinuser, $cookies ) = get_template_and_user(
515 template_name => $template_name,
518 authnotrequired => 1,
519 flagsrequired => { catalogue => 1 },
523 like ( $@, qr(bad template path), "The file $template_name should not be accessible" );
525 ( $template, $loggedinuser, $cookies ) = get_template_and_user(
527 template_name => 'errors/errorpage.tt',
530 authnotrequired => 1,
531 flagsrequired => { catalogue => 1 },
534 my $file_exists = ( -f $template->{filename} ) ? 1 : 0;
535 is ( $file_exists, 1, 'The file errors/errorpage.tt should be accessible (contains integers)' );
537 # Regression test for env opac search limit override
538 $ENV{"OPAC_SEARCH_LIMIT"} = "branch:CPL";
539 $ENV{"OPAC_LIMIT_OVERRIDE"} = 1;
541 ( $template, $loggedinuser, $cookies) = get_template_and_user(
543 template_name => 'opac-main.tt',
546 authnotrequired => 1,
549 is($template->{VARS}->{'opac_name'}, "CPL", "Opac name was set correctly");
550 is($template->{VARS}->{'opac_search_limit'}, "branch:CPL", "Search limit was set correctly");
552 $ENV{"OPAC_SEARCH_LIMIT"} = "branch:multibranch-19";
554 ( $template, $loggedinuser, $cookies) = get_template_and_user(
556 template_name => 'opac-main.tt',
559 authnotrequired => 1,
562 is($template->{VARS}->{'opac_name'}, "multibranch-19", "Opac name was set correctly");
563 is($template->{VARS}->{'opac_search_limit'}, "branch:multibranch-19", "Search limit was set correctly");
565 delete $ENV{"HTTP_COOKIE"};
568 # Check that there is always an OPACBaseURL set.
569 my $input = CGI->new();
570 my ( $template1, $borrowernumber, $cookie );
571 ( $template1, $borrowernumber, $cookie ) = get_template_and_user(
573 template_name => "opac-detail.tt",
576 authnotrequired => 1,
580 ok( ( any { 'OPACBaseURL' eq $_ } keys %{$template1->{VARS}} ),
581 'OPACBaseURL is in OPAC template' );
584 ( $template2, $borrowernumber, $cookie ) = get_template_and_user(
586 template_name => "catalogue/detail.tt",
589 authnotrequired => 1,
593 ok( ( any { 'OPACBaseURL' eq $_ } keys %{$template2->{VARS}} ),
594 'OPACBaseURL is in Staff template' );
596 my $hash1 = hash_password('password');
597 my $hash2 = hash_password('password');
599 ok(C4::Auth::checkpw_hash('password', $hash1), 'password validates with first hash');
600 ok(C4::Auth::checkpw_hash('password', $hash2), 'password validates with second hash');
602 subtest 'Check value of login_attempts in checkpw' => sub {
605 t::lib::Mocks::mock_preference('FailedLoginAttempts', 3);
607 # Only interested here in regular login
611 my $patron = $builder->build_object({ class => 'Koha::Patrons' });
612 $patron->login_attempts(2);
613 $patron->password('123')->store; # yes, deliberately not hashed
615 is( $patron->account_locked, 0, 'Patron not locked' );
616 my @test = checkpw( $patron->userid, '123', undef, 'opac', 1 );
617 # Note: 123 will not be hashed to 123 !
618 is( $test[0], 0, 'checkpw should have failed' );
619 $patron->discard_changes; # refresh
620 is( $patron->login_attempts, 3, 'Login attempts increased' );
621 is( $patron->account_locked, 1, 'Check locked status' );
623 # And another try to go over the limit: different return value!
624 @test = checkpw( $patron->userid, '123', undef, 'opac', 1 );
625 is( @test, 0, 'checkpw failed again and returns nothing now' );
626 $patron->discard_changes; # refresh
627 is( $patron->login_attempts, 3, 'Login attempts not increased anymore' );
629 # Administrative lockout cannot be undone?
630 # Pass the right password now (or: add a nice mock).
631 my $auth = Test::MockModule->new( 'C4::Auth' );
632 $auth->mock( 'checkpw_hash', sub { return 1; } ); # not for production :)
633 $patron->login_attempts(0)->store;
634 @test = checkpw( $patron->userid, '123', undef, 'opac', 1 );
635 is( $test[0], 1, 'Build confidence in the mock' );
636 $patron->login_attempts(-1)->store;
637 is( $patron->account_locked, 1, 'Check administrative lockout' );
638 @test = checkpw( $patron->userid, '123', undef, 'opac', 1 );
639 is( @test, 0, 'checkpw gave red' );
640 $patron->discard_changes; # refresh
641 is( $patron->login_attempts, -1, 'Still locked out' );
642 t::lib::Mocks::mock_preference('FailedLoginAttempts', ''); # disable
643 is( $patron->account_locked, 1, 'Check administrative lockout without pref' );
646 subtest 'Check value of login_attempts in checkpw' => sub {
649 t::lib::Mocks::mock_preference('FailedLoginAttempts', 3);
650 my $patron = $builder->build_object({ class => 'Koha::Patrons' });
651 $patron->set_password({ password => '123', skip_validation => 1 });
653 my @test = checkpw( $patron->userid, '123', undef, 'opac', 1 );
654 is( $test[0], 1, 'Patron authenticated correctly' );
656 $patron->password_expiration_date('2020-01-01')->store;
657 @test = checkpw( $patron->userid, '123', undef, 'opac', 1 );
658 is( $test[0], -2, 'Patron returned as expired correctly' );
662 subtest '_timeout_syspref' => sub {
666 t::lib::Mocks::mock_preference('timeout', "100");
667 is( C4::Auth::_timeout_syspref, 100, );
669 t::lib::Mocks::mock_preference('timeout', "2d");
670 is( C4::Auth::_timeout_syspref, 2*86400, );
672 t::lib::Mocks::mock_preference('timeout', "2D");
673 is( C4::Auth::_timeout_syspref, 2*86400, );
675 t::lib::Mocks::mock_preference('timeout', "10h");
676 is( C4::Auth::_timeout_syspref, 10*3600, );
678 t::lib::Mocks::mock_preference('timeout', "10x");
680 { is( C4::Auth::_timeout_syspref, 600, ); }
681 "The value of the system preference 'timeout' is not correct, defaulting to 600",
682 'Bad values throw a warning and fallback to 600';
685 subtest 'check_cookie_auth' => sub {
688 t::lib::Mocks::mock_preference('timeout', "1d"); # back to default
690 my $patron = $builder->build_object({ class => 'Koha::Patrons', value => { flags => 1 } });
692 # Mock a CGI object with real userid param
693 my $cgi = Test::MockObject->new();
698 if ( $var eq 'userid' ) { return $patron->userid; }
701 $cgi->mock('multi_param', sub {return q{}} );
702 $cgi->mock( 'cookie', sub { return; } );
703 $cgi->mock( 'request_method', sub { return 'POST' } );
705 $ENV{REMOTE_ADDR} = '127.0.0.1';
707 # Setting authnotrequired=1 or we wont' hit the return but the end of the sub that prints headers
708 my ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 1 );
710 my ($auth_status, $session) = C4::Auth::check_cookie_auth($sessionID);
711 isnt( $auth_status, 'ok', 'check_cookie_auth should not return ok if the user has not been authenticated before if no permissions needed' );
712 is( $auth_status, 'anon', 'check_cookie_auth should return anon if the user has not been authenticated before and no permissions needed' );
714 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 1 );
716 ($auth_status, $session) = C4::Auth::check_cookie_auth($sessionID, {catalogue => 1});
717 isnt( $auth_status, 'ok', 'check_cookie_auth should not return ok if the user has not been authenticated before and permissions needed' );
718 is( $auth_status, 'anon', 'check_cookie_auth should return anon if the user has not been authenticated before and permissions needed' );
720 #FIXME We should have a test to cover 'failed' status when a user has logged in, but doesn't have permission
723 subtest 'checkauth & check_cookie_auth' => sub {
726 # flags = 4 => { catalogue => 1 }
727 my $patron = $builder->build_object({ class => 'Koha::Patrons', value => { flags => 4 } });
728 my $password = 'password';
729 t::lib::Mocks::mock_preference( 'RequireStrongPassword', 0 );
730 $patron->set_password( { password => $password } );
732 my $cgi_mock = Test::MockModule->new('CGI');
733 $cgi_mock->mock( 'request_method', sub { return 'POST' } );
737 my $auth = Test::MockModule->new( 'C4::Auth' );
738 # Tests will fail if we hit safe_exit
739 $auth->mock( 'safe_exit', sub { return } );
741 my ( $userid, $cookie, $sessionID, $flags );
743 # checkauth will redirect and safe_exit if not authenticated and not authorized
746 open STDOUT, '>', \$stdout;
747 C4::Auth::checkauth($cgi, 0, {catalogue => 1});
748 like( $stdout, qr{<title>\s*Log in to your account} );
749 $sessionID = ( $stdout =~ m{Set-Cookie: CGISESSID=((\d|\w)+);} ) ? $1 : undef;
754 my $first_sessionID = $sessionID;
756 $ENV{"HTTP_COOKIE"} = "CGISESSID=$sessionID";
757 # Not authenticated yet, checkauth didn't return the session
761 open STDOUT, '>', \$stdout;
762 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 0, {catalogue => 1} );
765 is( $sessionID, undef);
768 # Sending undefined fails obviously
769 my ( $auth_status, $session ) = C4::Auth::check_cookie_auth($sessionID, {catalogue => 1} );
770 is( $auth_status, 'failed' );
771 is( $session, undef );
773 # Simulating the login form submission
774 $cgi->param('userid', $patron->userid);
775 $cgi->param('password', $password);
778 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 0, {catalogue => 1});
779 is( $sessionID, $first_sessionID );
780 is( $userid, $patron->userid );
782 ( $auth_status, $session ) = C4::Auth::check_cookie_auth($sessionID, {catalogue => 1});
783 is( $auth_status, 'ok' );
784 is( $session->id, $first_sessionID );
787 $cgi->param('logout.x', 1);
788 $cgi->delete( 'userid', 'password' );
792 open STDOUT, '>', \$stdout;
793 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 0, {catalogue => 1});
796 is( $sessionID, undef );
797 is( $ENV{"HTTP_COOKIE"}, "CGISESSID=$first_sessionID", 'HTTP_COOKIE not unset' );
798 ( $auth_status, $session) = C4::Auth::check_cookie_auth( $first_sessionID, {catalogue => 1} );
799 is( $auth_status, "expired");
800 is( $session, undef );
803 # Trying to access without sessionID
805 ( $auth_status, $session) = C4::Auth::check_cookie_auth(undef, {catalogue => 1});
806 is( $auth_status, 'failed' );
807 is( $session, undef );
809 # This will fail on permissions
810 undef $ENV{"HTTP_COOKIE"};
814 open STDOUT, '>', \$stdout;
815 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 0, {catalogue => 1} );
818 is( $userid, undef );
819 is( $sessionID, undef );
825 $cgi->param('userid', $patron->userid);
826 $cgi->param('password', $password);
827 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 0, {catalogue => 1});
828 is( $userid, $patron->userid );
829 $first_sessionID = $sessionID;
831 # Patron does not have the borrowers permission
832 # $ENV{"HTTP_COOKIE"} = "CGISESSID=$sessionID"; # not needed, we use $cgi here
836 open STDOUT, '>', \$stdout;
837 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 0, {borrowers => 1} );
840 is( $userid, undef );
841 is( $sessionID, undef );
843 # When calling check_cookie_auth, the session will be deleted
844 ( $auth_status, $session) = C4::Auth::check_cookie_auth( $first_sessionID, { borrowers => 1 } );
845 is( $auth_status, "failed" );
846 is( $session, undef );
847 ( $auth_status, $session) = C4::Auth::check_cookie_auth( $first_sessionID, { borrowers => 1 } );
848 is( $auth_status, 'expired', 'Session no longer exists' );
850 # NOTE: It is not what the UI is doing.
851 # From the UI we are allowed to hit an unauthorized page then reuse the session to hit back authorized area.
852 # It is because check_cookie_auth is ALWAYS called from checkauth WITHOUT $flagsrequired
853 # It then return "ok", when the previous called got "failed"
855 # Try reusing the deleted session: since it does not exist, we should get a new one now when passing correct permissions
856 $cgi->cookie( -name => 'CGISESSID', value => $first_sessionID );
857 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 0, {catalogue => 1});
858 is( $userid, $patron->userid );
859 isnt( $sessionID, undef, 'Check if we have a sessionID' );
860 isnt( $sessionID, $first_sessionID, 'New value expected' );
861 ( $auth_status, $session) = C4::Auth::check_cookie_auth( $sessionID, {catalogue => 1} );
862 is( $auth_status, "ok" );
863 is( $session->id, $sessionID, 'Same session' );
864 # Two additional tests on userenv
865 is( $C4::Context::context->{activeuser}, $session->id, 'Check if environment has been setup for session' );
866 is( C4::Context->userenv->{id}, $userid, 'Check userid in userenv' );
870 subtest 'Userenv clearing in check_cookie_auth' => sub {
871 # Note: We did already test userenv for a logged-in user in previous subtest
874 t::lib::Mocks::mock_preference( 'timeout', 600 );
877 # Create a new anonymous session by passing a fake session ID
878 $cgi->cookie( -name => 'CGISESSID', -value => 'fake_sessionID' );
879 my ($userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 1);
880 my ( $auth_status, $session) = C4::Auth::check_cookie_auth( $sessionID );
881 is( $auth_status, 'anon', 'Should be anonymous' );
882 is( $C4::Context::context->{activeuser}, $session->id, 'Check activeuser' );
883 is( defined C4::Context->userenv, 1, 'There should be a userenv' );
884 is( C4::Context->userenv->{id}, q{}, 'userid should be empty string' );
886 # Make the session expire now, check_cookie_auth will delete it
887 $session->param('lasttime', time() - 1200 );
889 ( $auth_status, $session) = C4::Auth::check_cookie_auth( $sessionID );
890 is( $auth_status, 'expired', 'Should be expired' );
891 is( C4::Context->userenv, undef, 'Environment should be cleared too' );
893 # Show that we clear the userenv again: set up env and check deleted session
894 C4::Context->_new_userenv( $sessionID );
895 C4::Context->set_userenv; # empty
896 is( defined C4::Context->userenv, 1, 'There should be an empty userenv again' );
897 ( $auth_status, $session) = C4::Auth::check_cookie_auth( $sessionID );
898 is( $auth_status, 'expired', 'Should be expired already' );
899 is( C4::Context->userenv, undef, 'Environment should be cleared again' );
902 subtest 'create_basic_session tests' => sub {
905 my $patron = $builder->build_object({ class => 'Koha::Patrons' });
907 my $session = C4::Auth::create_basic_session({ patron => $patron, interface => 'opac' });
909 isnt($session->id, undef, 'A new sessionID was created');
910 is( $session->param('number'), $patron->borrowernumber, 'Session parameter number matches' );
911 is( $session->param('id'), $patron->userid, 'Session parameter id matches' );
912 is( $session->param('cardnumber'), $patron->cardnumber, 'Session parameter cardnumber matches' );
913 is( $session->param('firstname'), $patron->firstname, 'Session parameter firstname matches' );
914 is( $session->param('surname'), $patron->surname, 'Session parameter surname matches' );
915 is( $session->param('branch'), $patron->branchcode, 'Session parameter branch matches' );
916 is( $session->param('branchname'), $patron->library->branchname, 'Session parameter branchname matches' );
917 is( $session->param('flags'), $patron->flags, 'Session parameter flags matches' );
918 is( $session->param('emailaddress'), $patron->email, 'Session parameter emailaddress matches' );
919 is( $session->param('ip'), $session->remote_addr(), 'Session parameter ip matches' );
920 is( $session->param('interface'), 'opac', 'Session parameter interface matches' );
922 $session = C4::Auth::create_basic_session({ patron => $patron, interface => 'staff' });
923 is( $session->param('interface'), 'intranet', 'Staff interface gets converted to intranet' );
926 $schema->storage->txn_rollback;