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');
175 $mock1->mock( 'safe_exit', sub {} );
176 my $mock2 = Test::MockModule->new('CGI');
177 $mock2->mock( 'request_method', 'POST' );
178 $mock2->mock( 'cookie', sub { return $sessionID; } ); # oversimplified..
180 my $password = 'Incr3d1blyZtr@ng93$';
181 $patron2->set_password({ password => $password });
182 $cgi->param( -name => 'userid', -value => $patron2->userid );
183 $cgi->param( -name => 'password', -value => $password );
184 $cgi->param( -name => 'koha_login_context', -value => 1 );
185 my ( @return, $stdout );
189 $ENV{REMOTE_ADDR} = '1.2.3.4';
190 open STDOUT, '>', \$stdout;
191 @return = C4::Auth::checkauth( $cgi, 0, {} );
194 # Note: We can test return values from checkauth here since we mocked the safe_exit after the Redirect 303
195 is( $return[0], $patron2->userid, 'Login of patron2 approved' );
196 isnt( $return[2], $sessionID, 'Did not return previous session ID' );
197 ok( $return[2], 'New session ID not empty' );
199 # Similar situation: Relogin with former session of $patron, new user $patron2 has no permissions
200 $patron2->flags(undef)->store;
201 $session->param( 'number', $patron->id );
202 $session->param( 'id', $patron->userid );
203 $session->param( 'interface', 'intranet' );
205 $sessionID = $session->id;
206 C4::Context->_new_userenv($sessionID);
207 $cgi->param( -name => 'userid', -value => $patron2->userid );
208 $cgi->param( -name => 'password', -value => $password );
209 $cgi->param( -name => 'koha_login_context', -value => 1 );
213 $ENV{REMOTE_ADDR} = '1.2.3.4';
215 open STDOUT, '>', \$stdout;
216 @return = C4::Auth::checkauth( $cgi, 0, { catalogue => 1 }, 'intranet' ); # patron2 has no catalogue perm
219 like( $stdout, qr/You do not have permission to access this page/, 'No permission response' );
220 is( @return, 0, 'checkauth returned failure' );
223 subtest 'Two-factor authentication' => sub {
226 my $patron = $builder->build_object(
227 { class => 'Koha::Patrons', value => { flags => 1 } } );
228 my $password = 'password';
229 $patron->set_password( { password => $password } );
230 $cgi = Test::MockObject->new();
233 our ( $logout, $sessionID, $verified );
237 my ( $self, $param ) = @_;
238 if ( $param eq 'userid' ) { return $patron->userid; }
239 elsif ( $param eq 'password' ) { return $password; }
240 elsif ( $param eq 'otp_token' ) { return $otp_token; }
241 elsif ( $param eq 'logout.x' ) { return $logout; }
245 $cgi->mock( 'request_method', sub { return 'POST' } );
246 $cgi->mock( 'cookie', sub { return $sessionID } );
248 my $two_factor_auth = Test::MockModule->new( 'Koha::Auth::TwoFactorAuth' );
249 $two_factor_auth->mock( 'verify', sub {$verified} );
251 my ( $userid, $cookie, $flags );
252 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired', undef, 'intranet' );
258 C4::Auth::checkauth( $cgi, 'authrequired', undef, 'intranet' );
262 t::lib::Mocks::mock_preference( 'TwoFactorAuthentication', 'disabled' );
263 $patron->auth_method('password')->store;
264 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired', undef, 'intranet' );
265 is( $userid, $patron->userid, 'Succesful login' );
266 is( C4::Auth::get_session($sessionID)->param('waiting-for-2FA'), undef, 'Second auth not required' );
269 $patron->auth_method('two-factor')->store;
270 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired', undef, 'intranet' );
271 is( $userid, $patron->userid, 'Succesful login' );
272 is( C4::Auth::get_session($sessionID)->param('waiting-for-2FA'), undef, 'Second auth not required' );
275 t::lib::Mocks::mock_preference( 'TwoFactorAuthentication', 'enabled' );
276 t::lib::Mocks::mock_config('encryption_key', '1234tH1s=t&st');
277 $patron->auth_method('password')->store;
278 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired', undef, 'intranet' );
279 is( $userid, $patron->userid, 'Succesful login' );
280 is( C4::Auth::get_session($sessionID)->param('waiting-for-2FA'), undef, 'Second auth not required' );
283 $patron->encode_secret('one_secret');
284 $patron->auth_method('two-factor');
286 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired', undef, 'intranet' );
287 is( $userid, $patron->userid, 'Succesful login' );
288 my $session = C4::Auth::get_session($sessionID);
289 is( C4::Auth::get_session($sessionID)->param('waiting-for-2FA'), 1, 'Second auth required' );
292 $otp_token = "wrong";
294 $patron->auth_method('two-factor')->store;
295 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired', undef, 'intranet' );
296 is( $userid, $patron->userid, 'Succesful login' );
297 is( C4::Auth::get_session($sessionID)->param('waiting-for-2FA'), 1, 'Second auth still required after wrong OTP token' );
301 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired', undef, 'intranet' );
302 is( $userid, $patron->userid, 'Succesful login' );
303 is( C4::Auth::get_session($sessionID)->param('waiting-for-2FA'), 0, 'Second auth no longer required if OTP token has been verified' );
306 t::lib::Mocks::mock_preference( 'TwoFactorAuthentication', 'enforced' );
307 $patron->auth_method('password')->store;
308 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired', undef, 'intranet' );
309 is( $userid, $patron->userid, 'Succesful login' );
310 is( C4::Auth::get_session($sessionID)->param('waiting-for-2FA-setup'), 1, 'Setup 2FA required' );
313 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired', undef, 'opac' );
314 is( $userid, $patron->userid, 'Succesful login at the OPAC' );
315 is( C4::Auth::get_session($sessionID)->param('waiting-for-2FA'), undef, 'No second auth required at the OPAC' );
318 t::lib::Mocks::mock_preference( 'TwoFactorAuthentication', 'disabled' );
319 $session = C4::Auth::get_session($sessionID);
320 $session->param('waiting-for-2FA', 1);
322 my ($auth_status, undef ) = C4::Auth::check_cookie_auth($sessionID, undef );
323 is( $auth_status, 'ok', 'User authenticated, pref was disabled, access OK' );
324 $session->param('waiting-for-2FA', 0);
325 $session->param('waiting-for-2FA-setup', 1);
327 ($auth_status, undef ) = C4::Auth::check_cookie_auth($sessionID, undef );
328 is( $auth_status, 'ok', 'User waiting for 2FA setup, pref was disabled, access OK' );
331 C4::Context->_new_userenv; # For next tests
335 subtest 'track_login_daily tests' => sub {
339 my $patron = $builder->build_object({ class => 'Koha::Patrons' });
340 my $userid = $patron->userid;
342 $patron->lastseen( undef );
345 my $cache = Koha::Caches->get_instance();
346 my $cache_key = "track_login_" . $patron->userid;
347 $cache->clear_from_cache($cache_key);
349 t::lib::Mocks::mock_preference( 'TrackLastPatronActivity', '1' );
351 is( $patron->lastseen, undef, 'Patron should have not last seen when newly created' );
353 C4::Auth::track_login_daily( $userid );
354 $patron->_result()->discard_changes();
355 isnt( $patron->lastseen, undef, 'Patron should have last seen set when TrackLastPatronActivity = 1' );
357 sleep(1); # We need to wait a tiny bit to make sure the timestamp will be different
358 my $last_seen = $patron->lastseen;
359 C4::Auth::track_login_daily( $userid );
360 $patron->_result()->discard_changes();
361 is( $patron->lastseen, $last_seen, 'Patron last seen should still be unchanged' );
363 $cache->clear_from_cache($cache_key);
364 C4::Auth::track_login_daily( $userid );
365 $patron->_result()->discard_changes();
366 isnt( $patron->lastseen, $last_seen, 'Patron last seen should be changed if we cleared the cache' );
368 t::lib::Mocks::mock_preference( 'TrackLastPatronActivity', '0' );
369 $patron->lastseen( undef )->store;
370 $cache->clear_from_cache($cache_key);
371 C4::Auth::track_login_daily( $userid );
372 $patron->_result()->discard_changes();
373 is( $patron->lastseen, undef, 'Patron should still have last seen unchanged when TrackLastPatronActivity = 0' );
377 subtest 'no_set_userenv parameter tests' => sub {
381 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
382 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
383 my $password = 'password';
385 t::lib::Mocks::mock_preference( 'RequireStrongPassword', 0 );
386 $patron->set_password({ password => $password });
388 ok( checkpw( $patron->userid, $password, undef, undef, 1 ), 'checkpw returns true' );
389 is( C4::Context->userenv, undef, 'Userenv should be undef as required' );
390 C4::Context->_new_userenv('DUMMY SESSION');
391 C4::Context->set_userenv(0,0,0,'firstname','surname', $library->branchcode, 'Library 1', 0, '', '');
392 is( C4::Context->userenv->{branch}, $library->branchcode, 'Userenv gives correct branch' );
393 ok( checkpw( $patron->userid, $password, undef, undef, 1 ), 'checkpw returns true' );
394 is( C4::Context->userenv->{branch}, $library->branchcode, 'Userenv branch is preserved if no_set_userenv is true' );
395 ok( checkpw( $patron->userid, $password, undef, undef, 0 ), 'checkpw still returns true' );
396 isnt( C4::Context->userenv->{branch}, $library->branchcode, 'Userenv branch is overwritten if no_set_userenv is false' );
399 subtest 'checkpw lockout tests' => sub {
403 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
404 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
405 my $password = 'password';
406 t::lib::Mocks::mock_preference( 'RequireStrongPassword', 0 );
407 t::lib::Mocks::mock_preference( 'FailedLoginAttempts', 1 );
408 $patron->set_password({ password => $password });
410 my ( $checkpw, undef, undef ) = checkpw( $patron->cardnumber, $password, undef, undef, 1 );
411 ok( $checkpw, 'checkpw returns true with right password when logging in via cardnumber' );
412 ( $checkpw, undef, undef ) = checkpw( $patron->userid, "wrong_password", undef, undef, 1 );
413 is( $checkpw, 0, 'checkpw returns false when given wrong password' );
414 $patron = $patron->get_from_storage;
415 is( $patron->account_locked, 1, "Account is locked from failed login");
416 ( $checkpw, undef, undef ) = checkpw( $patron->userid, $password, undef, undef, 1 );
417 is( $checkpw, undef, 'checkpw returns undef with right password when account locked' );
418 ( $checkpw, undef, undef ) = checkpw( $patron->cardnumber, $password, undef, undef, 1 );
419 is( $checkpw, undef, 'checkpw returns undefwith right password when logging in via cardnumber if account locked' );
423 # get_template_and_user tests
425 subtest 'get_template_and_user' => sub { # Tests for the language URL parameter
427 sub MockedCheckauth {
428 my ($query,$authnotrequired,$flagsrequired,$type) = @_;
430 my $userid = 'cobain';
432 # we don't need to bother about permissions for this test
434 superlibrarian => 1, acquisition => 0,
436 catalogue => 1, circulate => 0,
437 coursereserves => 0, editauthorities => 0,
439 parameters => 0, permissions => 0,
440 plugins => 0, reports => 0,
441 reserveforothers => 0, serials => 0,
442 staffaccess => 0, tools => 0,
446 my $session_cookie = $query->cookie(
447 -name => 'CGISESSID',
452 return ( $userid, [ $session_cookie ], $sessionID, $flags );
455 # Mock checkauth, build the scenario
456 my $auth = Test::MockModule->new( 'C4::Auth' );
457 $auth->mock( 'checkauth', \&MockedCheckauth );
459 # Make sure 'EnableOpacSearchHistory' is set
460 t::lib::Mocks::mock_preference('EnableOpacSearchHistory',1);
461 # Enable es-ES for the OPAC and staff interfaces
462 t::lib::Mocks::mock_preference('OPACLanguages','en,es-ES');
463 t::lib::Mocks::mock_preference('language','en,es-ES');
465 # we need a session cookie
466 $ENV{"SERVER_PORT"} = 80;
467 $ENV{"HTTP_COOKIE"} = 'CGISESSID=nirvana';
469 my $query = CGI->new;
470 $query->param('language','es-ES');
472 my ( $template, $loggedinuser, $cookies ) = get_template_and_user(
474 template_name => "about.tt",
477 authnotrequired => 1,
478 flagsrequired => { catalogue => 1 },
483 ok ( ( all { ref($_) eq 'CGI::Cookie' } @$cookies ),
484 'BZ9735: the cookies array is flat' );
486 # new query, with non-existent language (we only have en and es-ES)
487 $query->param('language','tomas');
489 ( $template, $loggedinuser, $cookies ) = get_template_and_user(
491 template_name => "about.tt",
494 authnotrequired => 1,
495 flagsrequired => { catalogue => 1 },
500 ok( ( none { $_->name eq 'KohaOpacLanguage' and $_->value eq 'tomas' } @$cookies ),
501 'BZ9735: invalid language, it is not set');
503 ok( ( any { $_->name eq 'KohaOpacLanguage' and $_->value eq 'en' } @$cookies ),
504 'BZ9735: invalid language, then default to en');
506 for my $template_name (
508 ../../../../../../../../../../../../../../../etc/passwd
509 test/../../../../../../../../../../../../../../etc/passwd
511 test/does_not_finished_by_tt_t
515 ( $template, $loggedinuser, $cookies ) = get_template_and_user(
517 template_name => $template_name,
520 authnotrequired => 1,
521 flagsrequired => { catalogue => 1 },
525 like ( $@, qr(bad template path), "The file $template_name should not be accessible" );
527 ( $template, $loggedinuser, $cookies ) = get_template_and_user(
529 template_name => 'errors/errorpage.tt',
532 authnotrequired => 1,
533 flagsrequired => { catalogue => 1 },
536 my $file_exists = ( -f $template->{filename} ) ? 1 : 0;
537 is ( $file_exists, 1, 'The file errors/errorpage.tt should be accessible (contains integers)' );
539 # Regression test for env opac search limit override
540 $ENV{"OPAC_SEARCH_LIMIT"} = "branch:CPL";
541 $ENV{"OPAC_LIMIT_OVERRIDE"} = 1;
543 ( $template, $loggedinuser, $cookies) = get_template_and_user(
545 template_name => 'opac-main.tt',
548 authnotrequired => 1,
551 is($template->{VARS}->{'opac_name'}, "CPL", "Opac name was set correctly");
552 is($template->{VARS}->{'opac_search_limit'}, "branch:CPL", "Search limit was set correctly");
554 $ENV{"OPAC_SEARCH_LIMIT"} = "branch:multibranch-19";
556 ( $template, $loggedinuser, $cookies) = get_template_and_user(
558 template_name => 'opac-main.tt',
561 authnotrequired => 1,
564 is($template->{VARS}->{'opac_name'}, "multibranch-19", "Opac name was set correctly");
565 is($template->{VARS}->{'opac_search_limit'}, "branch:multibranch-19", "Search limit was set correctly");
567 delete $ENV{"HTTP_COOKIE"};
570 # Check that there is always an OPACBaseURL set.
571 my $input = CGI->new();
572 my ( $template1, $borrowernumber, $cookie );
573 ( $template1, $borrowernumber, $cookie ) = get_template_and_user(
575 template_name => "opac-detail.tt",
578 authnotrequired => 1,
582 ok( ( any { 'OPACBaseURL' eq $_ } keys %{$template1->{VARS}} ),
583 'OPACBaseURL is in OPAC template' );
586 ( $template2, $borrowernumber, $cookie ) = get_template_and_user(
588 template_name => "catalogue/detail.tt",
591 authnotrequired => 1,
595 ok( ( any { 'OPACBaseURL' eq $_ } keys %{$template2->{VARS}} ),
596 'OPACBaseURL is in Staff template' );
598 my $hash1 = hash_password('password');
599 my $hash2 = hash_password('password');
601 ok(C4::Auth::checkpw_hash('password', $hash1), 'password validates with first hash');
602 ok(C4::Auth::checkpw_hash('password', $hash2), 'password validates with second hash');
604 subtest 'Check value of login_attempts in checkpw' => sub {
607 t::lib::Mocks::mock_preference('FailedLoginAttempts', 3);
609 # Only interested here in regular login
613 my $patron = $builder->build_object({ class => 'Koha::Patrons' });
614 $patron->login_attempts(2);
615 $patron->password('123')->store; # yes, deliberately not hashed
617 is( $patron->account_locked, 0, 'Patron not locked' );
618 my @test = checkpw( $patron->userid, '123', undef, 'opac', 1 );
619 # Note: 123 will not be hashed to 123 !
620 is( $test[0], 0, 'checkpw should have failed' );
621 $patron->discard_changes; # refresh
622 is( $patron->login_attempts, 3, 'Login attempts increased' );
623 is( $patron->account_locked, 1, 'Check locked status' );
625 # And another try to go over the limit: different return value!
626 @test = checkpw( $patron->userid, '123', undef, 'opac', 1 );
627 is( @test, 0, 'checkpw failed again and returns nothing now' );
628 $patron->discard_changes; # refresh
629 is( $patron->login_attempts, 3, 'Login attempts not increased anymore' );
631 # Administrative lockout cannot be undone?
632 # Pass the right password now (or: add a nice mock).
633 my $auth = Test::MockModule->new( 'C4::Auth' );
634 $auth->mock( 'checkpw_hash', sub { return 1; } ); # not for production :)
635 $patron->login_attempts(0)->store;
636 @test = checkpw( $patron->userid, '123', undef, 'opac', 1 );
637 is( $test[0], 1, 'Build confidence in the mock' );
638 $patron->login_attempts(-1)->store;
639 is( $patron->account_locked, 1, 'Check administrative lockout' );
640 @test = checkpw( $patron->userid, '123', undef, 'opac', 1 );
641 is( @test, 0, 'checkpw gave red' );
642 $patron->discard_changes; # refresh
643 is( $patron->login_attempts, -1, 'Still locked out' );
644 t::lib::Mocks::mock_preference('FailedLoginAttempts', ''); # disable
645 is( $patron->account_locked, 1, 'Check administrative lockout without pref' );
648 subtest 'Check value of login_attempts in checkpw' => sub {
651 t::lib::Mocks::mock_preference('FailedLoginAttempts', 3);
652 my $patron = $builder->build_object({ class => 'Koha::Patrons' });
653 $patron->set_password({ password => '123', skip_validation => 1 });
655 my @test = checkpw( $patron->userid, '123', undef, 'opac', 1 );
656 is( $test[0], 1, 'Patron authenticated correctly' );
658 $patron->password_expiration_date('2020-01-01')->store;
659 @test = checkpw( $patron->userid, '123', undef, 'opac', 1 );
660 is( $test[0], -2, 'Patron returned as expired correctly' );
664 subtest '_timeout_syspref' => sub {
668 t::lib::Mocks::mock_preference('timeout', "100");
669 is( C4::Auth::_timeout_syspref, 100, );
671 t::lib::Mocks::mock_preference('timeout', "2d");
672 is( C4::Auth::_timeout_syspref, 2*86400, );
674 t::lib::Mocks::mock_preference('timeout', "2D");
675 is( C4::Auth::_timeout_syspref, 2*86400, );
677 t::lib::Mocks::mock_preference('timeout', "10h");
678 is( C4::Auth::_timeout_syspref, 10*3600, );
680 t::lib::Mocks::mock_preference('timeout', "10x");
682 { is( C4::Auth::_timeout_syspref, 600, ); }
683 "The value of the system preference 'timeout' is not correct, defaulting to 600",
684 'Bad values throw a warning and fallback to 600';
687 subtest 'check_cookie_auth' => sub {
690 t::lib::Mocks::mock_preference('timeout', "1d"); # back to default
692 my $patron = $builder->build_object({ class => 'Koha::Patrons', value => { flags => 1 } });
694 # Mock a CGI object with real userid param
695 my $cgi = Test::MockObject->new();
700 if ( $var eq 'userid' ) { return $patron->userid; }
703 $cgi->mock('multi_param', sub {return q{}} );
704 $cgi->mock( 'cookie', sub { return; } );
705 $cgi->mock( 'request_method', sub { return 'POST' } );
707 $ENV{REMOTE_ADDR} = '127.0.0.1';
709 # Setting authnotrequired=1 or we wont' hit the return but the end of the sub that prints headers
710 my ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 1 );
712 my ($auth_status, $session) = C4::Auth::check_cookie_auth($sessionID);
713 isnt( $auth_status, 'ok', 'check_cookie_auth should not return ok if the user has not been authenticated before if no permissions needed' );
714 is( $auth_status, 'anon', 'check_cookie_auth should return anon if the user has not been authenticated before and no permissions needed' );
716 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 1 );
718 ($auth_status, $session) = C4::Auth::check_cookie_auth($sessionID, {catalogue => 1});
719 isnt( $auth_status, 'ok', 'check_cookie_auth should not return ok if the user has not been authenticated before and permissions needed' );
720 is( $auth_status, 'anon', 'check_cookie_auth should return anon if the user has not been authenticated before and permissions needed' );
722 #FIXME We should have a test to cover 'failed' status when a user has logged in, but doesn't have permission
725 subtest 'checkauth & check_cookie_auth' => sub {
728 # flags = 4 => { catalogue => 1 }
729 my $patron = $builder->build_object({ class => 'Koha::Patrons', value => { flags => 4 } });
730 my $password = 'password';
731 t::lib::Mocks::mock_preference( 'RequireStrongPassword', 0 );
732 $patron->set_password( { password => $password } );
734 my $cgi_mock = Test::MockModule->new('CGI');
735 $cgi_mock->mock( 'request_method', sub { return 'POST' } );
739 my $auth = Test::MockModule->new( 'C4::Auth' );
740 # Tests will fail if we hit safe_exit
741 $auth->mock( 'safe_exit', sub { return } );
743 my ( $userid, $cookie, $sessionID, $flags );
745 # checkauth will redirect and safe_exit if not authenticated and not authorized
748 open STDOUT, '>', \$stdout;
749 C4::Auth::checkauth($cgi, 0, {catalogue => 1});
750 like( $stdout, qr{<title>\s*Log in to your account} );
751 $sessionID = ( $stdout =~ m{Set-Cookie: CGISESSID=((\d|\w)+);} ) ? $1 : undef;
756 my $first_sessionID = $sessionID;
758 $ENV{"HTTP_COOKIE"} = "CGISESSID=$sessionID";
759 # Not authenticated yet, checkauth didn't return the session
763 open STDOUT, '>', \$stdout;
764 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 0, {catalogue => 1} );
767 is( $sessionID, undef);
770 # Sending undefined fails obviously
771 my ( $auth_status, $session ) = C4::Auth::check_cookie_auth($sessionID, {catalogue => 1} );
772 is( $auth_status, 'failed' );
773 is( $session, undef );
775 # Simulating the login form submission
776 $cgi->param('userid', $patron->userid);
777 $cgi->param('password', $password);
780 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 0, {catalogue => 1});
781 is( $sessionID, $first_sessionID );
782 is( $userid, $patron->userid );
784 ( $auth_status, $session ) = C4::Auth::check_cookie_auth($sessionID, {catalogue => 1});
785 is( $auth_status, 'ok' );
786 is( $session->id, $first_sessionID );
789 $cgi->param('logout.x', 1);
790 $cgi->delete( 'userid', 'password' );
794 open STDOUT, '>', \$stdout;
795 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 0, {catalogue => 1});
798 is( $sessionID, undef );
799 is( $ENV{"HTTP_COOKIE"}, "CGISESSID=$first_sessionID", 'HTTP_COOKIE not unset' );
800 ( $auth_status, $session) = C4::Auth::check_cookie_auth( $first_sessionID, {catalogue => 1} );
801 is( $auth_status, "expired");
802 is( $session, undef );
805 # Trying to access without sessionID
807 ( $auth_status, $session) = C4::Auth::check_cookie_auth(undef, {catalogue => 1});
808 is( $auth_status, 'failed' );
809 is( $session, undef );
811 # This will fail on permissions
812 undef $ENV{"HTTP_COOKIE"};
816 open STDOUT, '>', \$stdout;
817 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 0, {catalogue => 1} );
820 is( $userid, undef );
821 is( $sessionID, undef );
827 $cgi->param('userid', $patron->userid);
828 $cgi->param('password', $password);
829 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 0, {catalogue => 1});
830 is( $userid, $patron->userid );
831 $first_sessionID = $sessionID;
833 # Patron does not have the borrowers permission
834 # $ENV{"HTTP_COOKIE"} = "CGISESSID=$sessionID"; # not needed, we use $cgi here
838 open STDOUT, '>', \$stdout;
839 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 0, {borrowers => 1} );
842 is( $userid, undef );
843 is( $sessionID, undef );
845 # When calling check_cookie_auth, the session will be deleted
846 ( $auth_status, $session) = C4::Auth::check_cookie_auth( $first_sessionID, { borrowers => 1 } );
847 is( $auth_status, "failed" );
848 is( $session, undef );
849 ( $auth_status, $session) = C4::Auth::check_cookie_auth( $first_sessionID, { borrowers => 1 } );
850 is( $auth_status, 'expired', 'Session no longer exists' );
852 # NOTE: It is not what the UI is doing.
853 # From the UI we are allowed to hit an unauthorized page then reuse the session to hit back authorized area.
854 # It is because check_cookie_auth is ALWAYS called from checkauth WITHOUT $flagsrequired
855 # It then return "ok", when the previous called got "failed"
857 # Try reusing the deleted session: since it does not exist, we should get a new one now when passing correct permissions
858 $cgi->cookie( -name => 'CGISESSID', value => $first_sessionID );
859 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 0, {catalogue => 1});
860 is( $userid, $patron->userid );
861 isnt( $sessionID, undef, 'Check if we have a sessionID' );
862 isnt( $sessionID, $first_sessionID, 'New value expected' );
863 ( $auth_status, $session) = C4::Auth::check_cookie_auth( $sessionID, {catalogue => 1} );
864 is( $auth_status, "ok" );
865 is( $session->id, $sessionID, 'Same session' );
866 # Two additional tests on userenv
867 is( $C4::Context::context->{activeuser}, $session->id, 'Check if environment has been setup for session' );
868 is( C4::Context->userenv->{id}, $userid, 'Check userid in userenv' );
872 subtest 'Userenv clearing in check_cookie_auth' => sub {
873 # Note: We did already test userenv for a logged-in user in previous subtest
876 t::lib::Mocks::mock_preference( 'timeout', 600 );
879 # Create a new anonymous session by passing a fake session ID
880 $cgi->cookie( -name => 'CGISESSID', -value => 'fake_sessionID' );
881 my ($userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 1);
882 my ( $auth_status, $session) = C4::Auth::check_cookie_auth( $sessionID );
883 is( $auth_status, 'anon', 'Should be anonymous' );
884 is( $C4::Context::context->{activeuser}, $session->id, 'Check activeuser' );
885 is( defined C4::Context->userenv, 1, 'There should be a userenv' );
886 is( C4::Context->userenv->{id}, q{}, 'userid should be empty string' );
888 # Make the session expire now, check_cookie_auth will delete it
889 $session->param('lasttime', time() - 1200 );
891 ( $auth_status, $session) = C4::Auth::check_cookie_auth( $sessionID );
892 is( $auth_status, 'expired', 'Should be expired' );
893 is( C4::Context->userenv, undef, 'Environment should be cleared too' );
895 # Show that we clear the userenv again: set up env and check deleted session
896 C4::Context->_new_userenv( $sessionID );
897 C4::Context->set_userenv; # empty
898 is( defined C4::Context->userenv, 1, 'There should be an empty userenv again' );
899 ( $auth_status, $session) = C4::Auth::check_cookie_auth( $sessionID );
900 is( $auth_status, 'expired', 'Should be expired already' );
901 is( C4::Context->userenv, undef, 'Environment should be cleared again' );
904 subtest 'create_basic_session tests' => sub {
907 my $patron = $builder->build_object({ class => 'Koha::Patrons' });
909 my $session = C4::Auth::create_basic_session({ patron => $patron, interface => 'opac' });
911 isnt($session->id, undef, 'A new sessionID was created');
912 is( $session->param('number'), $patron->borrowernumber, 'Session parameter number matches' );
913 is( $session->param('id'), $patron->userid, 'Session parameter id matches' );
914 is( $session->param('cardnumber'), $patron->cardnumber, 'Session parameter cardnumber matches' );
915 is( $session->param('firstname'), $patron->firstname, 'Session parameter firstname matches' );
916 is( $session->param('surname'), $patron->surname, 'Session parameter surname matches' );
917 is( $session->param('branch'), $patron->branchcode, 'Session parameter branch matches' );
918 is( $session->param('branchname'), $patron->library->branchname, 'Session parameter branchname matches' );
919 is( $session->param('flags'), $patron->flags, 'Session parameter flags matches' );
920 is( $session->param('emailaddress'), $patron->email, 'Session parameter emailaddress matches' );
921 is( $session->param('ip'), $session->remote_addr(), 'Session parameter ip matches' );
922 is( $session->param('interface'), 'opac', 'Session parameter interface matches' );
924 $session = C4::Auth::create_basic_session({ patron => $patron, interface => 'staff' });
925 is( $session->param('interface'), 'intranet', 'Staff interface gets converted to intranet' );
928 $schema->storage->txn_rollback;