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 subtest 'loggedinlibrary permission tests' => sub {
334 my $staff_user = $builder->build_object(
335 { class => 'Koha::Patrons', value => { flags => 536870916 } } );
337 my $branch = $builder->build_object({ class => 'Koha::Libraries' });
339 my $password = 'password';
340 t::lib::Mocks::mock_preference( 'RequireStrongPassword', 0 );
341 $staff_user->set_password( { password => $password } );
342 my $cgi = Test::MockObject->new();
343 $cgi->mock( 'cookie', sub { return; } );
347 my ( $self, $param ) = @_;
348 if ( $param eq 'userid' ) { return $staff_user->userid; }
349 elsif ( $param eq 'password' ) { return $password; }
350 elsif ( $param eq 'branch' ) { return $branch->branchcode; }
355 $cgi->mock( 'request_method', sub { return 'POST' } );
356 my ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired' );
357 my $sesh = C4::Auth::get_session($sessionID);
358 is( $sesh->param('branch'), $branch->branchcode, "If user has permission, they should be able to choose a branch" );
360 $staff_user->flags(4)->store->discard_changes;
361 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired' );
362 $sesh = C4::Auth::get_session($sessionID);
363 is( $sesh->param('branch'), $staff_user->branchcode, "If user has not permission, they should not be able to choose a branch" );
365 $staff_user->flags(1)->store->discard_changes;
366 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired' );
367 $sesh = C4::Auth::get_session($sessionID);
368 is( $sesh->param('branch'), $branch->branchcode, "If user is superlibrarian, they should be able to choose a branch" );
371 C4::Context->_new_userenv; # For next tests
374 subtest 'track_login_daily tests' => sub {
378 my $patron = $builder->build_object({ class => 'Koha::Patrons' });
379 my $userid = $patron->userid;
381 $patron->lastseen( undef );
384 my $cache = Koha::Caches->get_instance();
385 my $cache_key = "track_login_" . $patron->userid;
386 $cache->clear_from_cache($cache_key);
388 t::lib::Mocks::mock_preference( 'TrackLastPatronActivity', '1' );
390 is( $patron->lastseen, undef, 'Patron should have not last seen when newly created' );
392 C4::Auth::track_login_daily( $userid );
393 $patron->_result()->discard_changes();
394 isnt( $patron->lastseen, undef, 'Patron should have last seen set when TrackLastPatronActivity = 1' );
396 sleep(1); # We need to wait a tiny bit to make sure the timestamp will be different
397 my $last_seen = $patron->lastseen;
398 C4::Auth::track_login_daily( $userid );
399 $patron->_result()->discard_changes();
400 is( $patron->lastseen, $last_seen, 'Patron last seen should still be unchanged' );
402 $cache->clear_from_cache($cache_key);
403 C4::Auth::track_login_daily( $userid );
404 $patron->_result()->discard_changes();
405 isnt( $patron->lastseen, $last_seen, 'Patron last seen should be changed if we cleared the cache' );
407 t::lib::Mocks::mock_preference( 'TrackLastPatronActivity', '0' );
408 $patron->lastseen( undef )->store;
409 $cache->clear_from_cache($cache_key);
410 C4::Auth::track_login_daily( $userid );
411 $patron->_result()->discard_changes();
412 is( $patron->lastseen, undef, 'Patron should still have last seen unchanged when TrackLastPatronActivity = 0' );
416 subtest 'no_set_userenv parameter tests' => sub {
420 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
421 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
422 my $password = 'password';
424 t::lib::Mocks::mock_preference( 'RequireStrongPassword', 0 );
425 $patron->set_password({ password => $password });
427 ok( checkpw( $patron->userid, $password, undef, undef, 1 ), 'checkpw returns true' );
428 is( C4::Context->userenv, undef, 'Userenv should be undef as required' );
429 C4::Context->_new_userenv('DUMMY SESSION');
430 C4::Context->set_userenv(0,0,0,'firstname','surname', $library->branchcode, 'Library 1', 0, '', '');
431 is( C4::Context->userenv->{branch}, $library->branchcode, 'Userenv gives correct branch' );
432 ok( checkpw( $patron->userid, $password, undef, undef, 1 ), 'checkpw returns true' );
433 is( C4::Context->userenv->{branch}, $library->branchcode, 'Userenv branch is preserved if no_set_userenv is true' );
434 ok( checkpw( $patron->userid, $password, undef, undef, 0 ), 'checkpw still returns true' );
435 isnt( C4::Context->userenv->{branch}, $library->branchcode, 'Userenv branch is overwritten if no_set_userenv is false' );
438 subtest 'checkpw lockout tests' => sub {
442 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
443 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
444 my $password = 'password';
445 t::lib::Mocks::mock_preference( 'RequireStrongPassword', 0 );
446 t::lib::Mocks::mock_preference( 'FailedLoginAttempts', 1 );
447 $patron->set_password({ password => $password });
449 my ( $checkpw, undef, undef ) = checkpw( $patron->cardnumber, $password, undef, undef, 1 );
450 ok( $checkpw, 'checkpw returns true with right password when logging in via cardnumber' );
451 ( $checkpw, undef, undef ) = checkpw( $patron->userid, "wrong_password", undef, undef, 1 );
452 is( $checkpw, 0, 'checkpw returns false when given wrong password' );
453 $patron = $patron->get_from_storage;
454 is( $patron->account_locked, 1, "Account is locked from failed login");
455 ( $checkpw, undef, undef ) = checkpw( $patron->userid, $password, undef, undef, 1 );
456 is( $checkpw, undef, 'checkpw returns undef with right password when account locked' );
457 ( $checkpw, undef, undef ) = checkpw( $patron->cardnumber, $password, undef, undef, 1 );
458 is( $checkpw, undef, 'checkpw returns undefwith right password when logging in via cardnumber if account locked' );
462 # get_template_and_user tests
464 subtest 'get_template_and_user' => sub { # Tests for the language URL parameter
466 sub MockedCheckauth {
467 my ($query,$authnotrequired,$flagsrequired,$type) = @_;
469 my $userid = 'cobain';
471 # we don't need to bother about permissions for this test
473 superlibrarian => 1, acquisition => 0,
475 catalogue => 1, circulate => 0,
476 coursereserves => 0, editauthorities => 0,
478 parameters => 0, permissions => 0,
479 plugins => 0, reports => 0,
480 reserveforothers => 0, serials => 0,
481 staffaccess => 0, tools => 0,
485 my $session_cookie = $query->cookie(
486 -name => 'CGISESSID',
491 return ( $userid, [ $session_cookie ], $sessionID, $flags );
494 # Mock checkauth, build the scenario
495 my $auth = Test::MockModule->new( 'C4::Auth' );
496 $auth->mock( 'checkauth', \&MockedCheckauth );
498 # Make sure 'EnableOpacSearchHistory' is set
499 t::lib::Mocks::mock_preference('EnableOpacSearchHistory',1);
500 # Enable es-ES for the OPAC and staff interfaces
501 t::lib::Mocks::mock_preference('OPACLanguages','en,es-ES');
502 t::lib::Mocks::mock_preference('language','en,es-ES');
504 # we need a session cookie
505 $ENV{"SERVER_PORT"} = 80;
506 $ENV{"HTTP_COOKIE"} = 'CGISESSID=nirvana';
508 my $query = CGI->new;
509 $query->param('language','es-ES');
511 my ( $template, $loggedinuser, $cookies ) = get_template_and_user(
513 template_name => "about.tt",
516 authnotrequired => 1,
517 flagsrequired => { catalogue => 1 },
522 ok ( ( all { ref($_) eq 'CGI::Cookie' } @$cookies ),
523 'BZ9735: the cookies array is flat' );
525 # new query, with non-existent language (we only have en and es-ES)
526 $query->param('language','tomas');
528 ( $template, $loggedinuser, $cookies ) = get_template_and_user(
530 template_name => "about.tt",
533 authnotrequired => 1,
534 flagsrequired => { catalogue => 1 },
539 ok( ( none { $_->name eq 'KohaOpacLanguage' and $_->value eq 'tomas' } @$cookies ),
540 'BZ9735: invalid language, it is not set');
542 ok( ( any { $_->name eq 'KohaOpacLanguage' and $_->value eq 'en' } @$cookies ),
543 'BZ9735: invalid language, then default to en');
545 for my $template_name (
547 ../../../../../../../../../../../../../../../etc/passwd
548 test/../../../../../../../../../../../../../../etc/passwd
550 test/does_not_finished_by_tt_t
554 ( $template, $loggedinuser, $cookies ) = get_template_and_user(
556 template_name => $template_name,
559 authnotrequired => 1,
560 flagsrequired => { catalogue => 1 },
564 like ( $@, qr(bad template path), "The file $template_name should not be accessible" );
566 ( $template, $loggedinuser, $cookies ) = get_template_and_user(
568 template_name => 'errors/errorpage.tt',
571 authnotrequired => 1,
572 flagsrequired => { catalogue => 1 },
575 my $file_exists = ( -f $template->{filename} ) ? 1 : 0;
576 is ( $file_exists, 1, 'The file errors/errorpage.tt should be accessible (contains integers)' );
578 # Regression test for env opac search limit override
579 $ENV{"OPAC_SEARCH_LIMIT"} = "branch:CPL";
580 $ENV{"OPAC_LIMIT_OVERRIDE"} = 1;
582 ( $template, $loggedinuser, $cookies) = get_template_and_user(
584 template_name => 'opac-main.tt',
587 authnotrequired => 1,
590 is($template->{VARS}->{'opac_name'}, "CPL", "Opac name was set correctly");
591 is($template->{VARS}->{'opac_search_limit'}, "branch:CPL", "Search limit was set correctly");
593 $ENV{"OPAC_SEARCH_LIMIT"} = "branch:multibranch-19";
595 ( $template, $loggedinuser, $cookies) = get_template_and_user(
597 template_name => 'opac-main.tt',
600 authnotrequired => 1,
603 is($template->{VARS}->{'opac_name'}, "multibranch-19", "Opac name was set correctly");
604 is($template->{VARS}->{'opac_search_limit'}, "branch:multibranch-19", "Search limit was set correctly");
606 delete $ENV{"HTTP_COOKIE"};
609 # Check that there is always an OPACBaseURL set.
610 my $input = CGI->new();
611 my ( $template1, $borrowernumber, $cookie );
612 ( $template1, $borrowernumber, $cookie ) = get_template_and_user(
614 template_name => "opac-detail.tt",
617 authnotrequired => 1,
621 ok( ( any { 'OPACBaseURL' eq $_ } keys %{$template1->{VARS}} ),
622 'OPACBaseURL is in OPAC template' );
625 ( $template2, $borrowernumber, $cookie ) = get_template_and_user(
627 template_name => "catalogue/detail.tt",
630 authnotrequired => 1,
634 ok( ( any { 'OPACBaseURL' eq $_ } keys %{$template2->{VARS}} ),
635 'OPACBaseURL is in Staff template' );
637 my $hash1 = hash_password('password');
638 my $hash2 = hash_password('password');
640 ok(C4::Auth::checkpw_hash('password', $hash1), 'password validates with first hash');
641 ok(C4::Auth::checkpw_hash('password', $hash2), 'password validates with second hash');
643 subtest 'Check value of login_attempts in checkpw' => sub {
646 t::lib::Mocks::mock_preference('FailedLoginAttempts', 3);
648 # Only interested here in regular login
652 my $patron = $builder->build_object({ class => 'Koha::Patrons' });
653 $patron->login_attempts(2);
654 $patron->password('123')->store; # yes, deliberately not hashed
656 is( $patron->account_locked, 0, 'Patron not locked' );
657 my @test = checkpw( $patron->userid, '123', undef, 'opac', 1 );
658 # Note: 123 will not be hashed to 123 !
659 is( $test[0], 0, 'checkpw should have failed' );
660 $patron->discard_changes; # refresh
661 is( $patron->login_attempts, 3, 'Login attempts increased' );
662 is( $patron->account_locked, 1, 'Check locked status' );
664 # And another try to go over the limit: different return value!
665 @test = checkpw( $patron->userid, '123', undef, 'opac', 1 );
666 is( @test, 0, 'checkpw failed again and returns nothing now' );
667 $patron->discard_changes; # refresh
668 is( $patron->login_attempts, 3, 'Login attempts not increased anymore' );
670 # Administrative lockout cannot be undone?
671 # Pass the right password now (or: add a nice mock).
672 my $auth = Test::MockModule->new( 'C4::Auth' );
673 $auth->mock( 'checkpw_hash', sub { return 1; } ); # not for production :)
674 $patron->login_attempts(0)->store;
675 @test = checkpw( $patron->userid, '123', undef, 'opac', 1 );
676 is( $test[0], 1, 'Build confidence in the mock' );
677 $patron->login_attempts(-1)->store;
678 is( $patron->account_locked, 1, 'Check administrative lockout' );
679 @test = checkpw( $patron->userid, '123', undef, 'opac', 1 );
680 is( @test, 0, 'checkpw gave red' );
681 $patron->discard_changes; # refresh
682 is( $patron->login_attempts, -1, 'Still locked out' );
683 t::lib::Mocks::mock_preference('FailedLoginAttempts', ''); # disable
684 is( $patron->account_locked, 1, 'Check administrative lockout without pref' );
687 subtest 'Check value of login_attempts in checkpw' => sub {
690 t::lib::Mocks::mock_preference('FailedLoginAttempts', 3);
691 my $patron = $builder->build_object({ class => 'Koha::Patrons' });
692 $patron->set_password({ password => '123', skip_validation => 1 });
694 my @test = checkpw( $patron->userid, '123', undef, 'opac', 1 );
695 is( $test[0], 1, 'Patron authenticated correctly' );
697 $patron->password_expiration_date('2020-01-01')->store;
698 @test = checkpw( $patron->userid, '123', undef, 'opac', 1 );
699 is( $test[0], -2, 'Patron returned as expired correctly' );
703 subtest '_timeout_syspref' => sub {
707 t::lib::Mocks::mock_preference('timeout', "100");
708 is( C4::Auth::_timeout_syspref, 100, );
710 t::lib::Mocks::mock_preference('timeout', "2d");
711 is( C4::Auth::_timeout_syspref, 2*86400, );
713 t::lib::Mocks::mock_preference('timeout', "2D");
714 is( C4::Auth::_timeout_syspref, 2*86400, );
716 t::lib::Mocks::mock_preference('timeout', "10h");
717 is( C4::Auth::_timeout_syspref, 10*3600, );
719 t::lib::Mocks::mock_preference('timeout', "10x");
721 { is( C4::Auth::_timeout_syspref, 600, ); }
722 "The value of the system preference 'timeout' is not correct, defaulting to 600",
723 'Bad values throw a warning and fallback to 600';
726 subtest 'check_cookie_auth' => sub {
729 t::lib::Mocks::mock_preference('timeout', "1d"); # back to default
731 my $patron = $builder->build_object({ class => 'Koha::Patrons', value => { flags => 1 } });
733 # Mock a CGI object with real userid param
734 my $cgi = Test::MockObject->new();
739 if ( $var eq 'userid' ) { return $patron->userid; }
742 $cgi->mock('multi_param', sub {return q{}} );
743 $cgi->mock( 'cookie', sub { return; } );
744 $cgi->mock( 'request_method', sub { return 'POST' } );
746 $ENV{REMOTE_ADDR} = '127.0.0.1';
748 # Setting authnotrequired=1 or we wont' hit the return but the end of the sub that prints headers
749 my ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 1 );
751 my ($auth_status, $session) = C4::Auth::check_cookie_auth($sessionID);
752 isnt( $auth_status, 'ok', 'check_cookie_auth should not return ok if the user has not been authenticated before if no permissions needed' );
753 is( $auth_status, 'anon', 'check_cookie_auth should return anon if the user has not been authenticated before and no permissions needed' );
755 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 1 );
757 ($auth_status, $session) = C4::Auth::check_cookie_auth($sessionID, {catalogue => 1});
758 isnt( $auth_status, 'ok', 'check_cookie_auth should not return ok if the user has not been authenticated before and permissions needed' );
759 is( $auth_status, 'anon', 'check_cookie_auth should return anon if the user has not been authenticated before and permissions needed' );
761 #FIXME We should have a test to cover 'failed' status when a user has logged in, but doesn't have permission
764 subtest 'checkauth & check_cookie_auth' => sub {
767 # flags = 4 => { catalogue => 1 }
768 my $patron = $builder->build_object({ class => 'Koha::Patrons', value => { flags => 4 } });
769 my $password = 'password';
770 t::lib::Mocks::mock_preference( 'RequireStrongPassword', 0 );
771 $patron->set_password( { password => $password } );
773 my $cgi_mock = Test::MockModule->new('CGI');
774 $cgi_mock->mock( 'request_method', sub { return 'POST' } );
778 my $auth = Test::MockModule->new( 'C4::Auth' );
779 # Tests will fail if we hit safe_exit
780 $auth->mock( 'safe_exit', sub { return } );
782 my ( $userid, $cookie, $sessionID, $flags );
784 # checkauth will redirect and safe_exit if not authenticated and not authorized
787 open STDOUT, '>', \$stdout;
788 C4::Auth::checkauth($cgi, 0, {catalogue => 1});
789 like( $stdout, qr{<title>\s*Log in to your account} );
790 $sessionID = ( $stdout =~ m{Set-Cookie: CGISESSID=((\d|\w)+);} ) ? $1 : undef;
795 my $first_sessionID = $sessionID;
797 $ENV{"HTTP_COOKIE"} = "CGISESSID=$sessionID";
798 # Not authenticated yet, checkauth didn't return the session
802 open STDOUT, '>', \$stdout;
803 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 0, {catalogue => 1} );
806 is( $sessionID, undef);
809 # Sending undefined fails obviously
810 my ( $auth_status, $session ) = C4::Auth::check_cookie_auth($sessionID, {catalogue => 1} );
811 is( $auth_status, 'failed' );
812 is( $session, undef );
814 # Simulating the login form submission
815 $cgi->param('userid', $patron->userid);
816 $cgi->param('password', $password);
819 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 0, {catalogue => 1});
820 is( $sessionID, $first_sessionID );
821 is( $userid, $patron->userid );
823 ( $auth_status, $session ) = C4::Auth::check_cookie_auth($sessionID, {catalogue => 1});
824 is( $auth_status, 'ok' );
825 is( $session->id, $first_sessionID );
828 $cgi->param('logout.x', 1);
829 $cgi->delete( 'userid', 'password' );
833 open STDOUT, '>', \$stdout;
834 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 0, {catalogue => 1});
837 is( $sessionID, undef );
838 is( $ENV{"HTTP_COOKIE"}, "CGISESSID=$first_sessionID", 'HTTP_COOKIE not unset' );
839 ( $auth_status, $session) = C4::Auth::check_cookie_auth( $first_sessionID, {catalogue => 1} );
840 is( $auth_status, "expired");
841 is( $session, undef );
844 # Trying to access without sessionID
846 ( $auth_status, $session) = C4::Auth::check_cookie_auth(undef, {catalogue => 1});
847 is( $auth_status, 'failed' );
848 is( $session, undef );
850 # This will fail on permissions
851 undef $ENV{"HTTP_COOKIE"};
855 open STDOUT, '>', \$stdout;
856 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 0, {catalogue => 1} );
859 is( $userid, undef );
860 is( $sessionID, undef );
866 $cgi->param('userid', $patron->userid);
867 $cgi->param('password', $password);
868 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 0, {catalogue => 1});
869 is( $userid, $patron->userid );
870 $first_sessionID = $sessionID;
872 # Patron does not have the borrowers permission
873 # $ENV{"HTTP_COOKIE"} = "CGISESSID=$sessionID"; # not needed, we use $cgi here
877 open STDOUT, '>', \$stdout;
878 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 0, {borrowers => 1} );
881 is( $userid, undef );
882 is( $sessionID, undef );
884 # When calling check_cookie_auth, the session will be deleted
885 ( $auth_status, $session) = C4::Auth::check_cookie_auth( $first_sessionID, { borrowers => 1 } );
886 is( $auth_status, "failed" );
887 is( $session, undef );
888 ( $auth_status, $session) = C4::Auth::check_cookie_auth( $first_sessionID, { borrowers => 1 } );
889 is( $auth_status, 'expired', 'Session no longer exists' );
891 # NOTE: It is not what the UI is doing.
892 # From the UI we are allowed to hit an unauthorized page then reuse the session to hit back authorized area.
893 # It is because check_cookie_auth is ALWAYS called from checkauth WITHOUT $flagsrequired
894 # It then return "ok", when the previous called got "failed"
896 # Try reusing the deleted session: since it does not exist, we should get a new one now when passing correct permissions
897 $cgi->cookie( -name => 'CGISESSID', value => $first_sessionID );
898 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 0, {catalogue => 1});
899 is( $userid, $patron->userid );
900 isnt( $sessionID, undef, 'Check if we have a sessionID' );
901 isnt( $sessionID, $first_sessionID, 'New value expected' );
902 ( $auth_status, $session) = C4::Auth::check_cookie_auth( $sessionID, {catalogue => 1} );
903 is( $auth_status, "ok" );
904 is( $session->id, $sessionID, 'Same session' );
905 # Two additional tests on userenv
906 is( $C4::Context::context->{activeuser}, $session->id, 'Check if environment has been setup for session' );
907 is( C4::Context->userenv->{id}, $userid, 'Check userid in userenv' );
911 subtest 'Userenv clearing in check_cookie_auth' => sub {
912 # Note: We did already test userenv for a logged-in user in previous subtest
915 t::lib::Mocks::mock_preference( 'timeout', 600 );
918 # Create a new anonymous session by passing a fake session ID
919 $cgi->cookie( -name => 'CGISESSID', -value => 'fake_sessionID' );
920 my ($userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 1);
921 my ( $auth_status, $session) = C4::Auth::check_cookie_auth( $sessionID );
922 is( $auth_status, 'anon', 'Should be anonymous' );
923 is( $C4::Context::context->{activeuser}, $session->id, 'Check activeuser' );
924 is( defined C4::Context->userenv, 1, 'There should be a userenv' );
925 is( C4::Context->userenv->{id}, q{}, 'userid should be empty string' );
927 # Make the session expire now, check_cookie_auth will delete it
928 $session->param('lasttime', time() - 1200 );
930 ( $auth_status, $session) = C4::Auth::check_cookie_auth( $sessionID );
931 is( $auth_status, 'expired', 'Should be expired' );
932 is( C4::Context->userenv, undef, 'Environment should be cleared too' );
934 # Show that we clear the userenv again: set up env and check deleted session
935 C4::Context->_new_userenv( $sessionID );
936 C4::Context->set_userenv; # empty
937 is( defined C4::Context->userenv, 1, 'There should be an empty userenv again' );
938 ( $auth_status, $session) = C4::Auth::check_cookie_auth( $sessionID );
939 is( $auth_status, 'expired', 'Should be expired already' );
940 is( C4::Context->userenv, undef, 'Environment should be cleared again' );
943 subtest 'create_basic_session tests' => sub {
946 my $patron = $builder->build_object({ class => 'Koha::Patrons' });
948 my $session = C4::Auth::create_basic_session({ patron => $patron, interface => 'opac' });
950 isnt($session->id, undef, 'A new sessionID was created');
951 is( $session->param('number'), $patron->borrowernumber, 'Session parameter number matches' );
952 is( $session->param('id'), $patron->userid, 'Session parameter id matches' );
953 is( $session->param('cardnumber'), $patron->cardnumber, 'Session parameter cardnumber matches' );
954 is( $session->param('firstname'), $patron->firstname, 'Session parameter firstname matches' );
955 is( $session->param('surname'), $patron->surname, 'Session parameter surname matches' );
956 is( $session->param('branch'), $patron->branchcode, 'Session parameter branch matches' );
957 is( $session->param('branchname'), $patron->library->branchname, 'Session parameter branchname matches' );
958 is( $session->param('flags'), $patron->flags, 'Session parameter flags matches' );
959 is( $session->param('emailaddress'), $patron->email, 'Session parameter emailaddress matches' );
960 is( $session->param('ip'), $session->remote_addr(), 'Session parameter ip matches' );
961 is( $session->param('interface'), 'opac', 'Session parameter interface matches' );
963 $session = C4::Auth::create_basic_session({ patron => $patron, interface => 'staff' });
964 is( $session->param('interface'), 'intranet', 'Staff interface gets converted to intranet' );
967 $schema->storage->txn_rollback;