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 {
157 my $patron = $builder->build_object({ class => 'Koha::Patrons', value => {} });
158 my $patron2 = $builder->build_object({ class => 'Koha::Patrons', value => {} });
159 # Create 'former' session
160 my $session = C4::Auth::get_session();
161 $session->param( 'number', $patron->id );
162 $session->param( 'id', $patron->userid );
163 $session->param( 'ip', '1.2.3.4' );
164 $session->param( 'lasttime', time() );
165 $session->param( 'interface', 'opac' );
167 my $sessionID = $session->id;
168 C4::Context->_new_userenv($sessionID);
170 my ( $return ) = C4::Auth::check_cookie_auth( $sessionID, undef, { skip_version_check => 1, remote_addr => '1.2.3.4' } );
171 is( $return, 'ok', 'Former session in shape now' );
173 my $mock1 = Test::MockModule->new('C4::Auth')->mock( 'safe_exit', sub {} );
174 my $mock2 = Test::MockModule->new('CGI') ->mock( 'request_method', 'POST' )
175 ->mock( 'cookie', sub { return $sessionID; } ); # oversimplified..
177 my $password = 'Incr3d1blyZtr@ng93$';
178 $patron2->set_password({ password => $password });
179 $cgi->param( -name => 'userid', -value => $patron2->userid );
180 $cgi->param( -name => 'password', -value => $password );
181 $cgi->param( -name => 'koha_login_context', -value => 1 );
186 $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' );
198 subtest 'Two-factor authentication' => sub {
201 my $patron = $builder->build_object(
202 { class => 'Koha::Patrons', value => { flags => 1 } } );
203 my $password = 'password';
204 $patron->set_password( { password => $password } );
205 $cgi = Test::MockObject->new();
208 our ( $logout, $sessionID, $verified );
212 my ( $self, $param ) = @_;
213 if ( $param eq 'userid' ) { return $patron->userid; }
214 elsif ( $param eq 'password' ) { return $password; }
215 elsif ( $param eq 'otp_token' ) { return $otp_token; }
216 elsif ( $param eq 'logout.x' ) { return $logout; }
220 $cgi->mock( 'request_method', sub { return 'POST' } );
221 $cgi->mock( 'cookie', sub { return $sessionID } );
223 my $two_factor_auth = Test::MockModule->new( 'Koha::Auth::TwoFactorAuth' );
224 $two_factor_auth->mock( 'verify', sub {$verified} );
226 my ( $userid, $cookie, $flags );
227 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired', undef, 'intranet' );
233 C4::Auth::checkauth( $cgi, 'authrequired', undef, 'intranet' );
237 t::lib::Mocks::mock_preference( 'TwoFactorAuthentication', 'disabled' );
238 $patron->auth_method('password')->store;
239 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired', undef, 'intranet' );
240 is( $userid, $patron->userid, 'Succesful login' );
241 is( C4::Auth::get_session($sessionID)->param('waiting-for-2FA'), undef, 'Second auth not required' );
244 $patron->auth_method('two-factor')->store;
245 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired', undef, 'intranet' );
246 is( $userid, $patron->userid, 'Succesful login' );
247 is( C4::Auth::get_session($sessionID)->param('waiting-for-2FA'), undef, 'Second auth not required' );
250 t::lib::Mocks::mock_preference( 'TwoFactorAuthentication', 'enabled' );
251 t::lib::Mocks::mock_config('encryption_key', '1234tH1s=t&st');
252 $patron->auth_method('password')->store;
253 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired', undef, 'intranet' );
254 is( $userid, $patron->userid, 'Succesful login' );
255 is( C4::Auth::get_session($sessionID)->param('waiting-for-2FA'), undef, 'Second auth not required' );
258 $patron->encode_secret('one_secret');
259 $patron->auth_method('two-factor');
261 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired', undef, 'intranet' );
262 is( $userid, $patron->userid, 'Succesful login' );
263 my $session = C4::Auth::get_session($sessionID);
264 is( C4::Auth::get_session($sessionID)->param('waiting-for-2FA'), 1, 'Second auth required' );
267 $otp_token = "wrong";
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'), 1, 'Second auth still required after wrong OTP token' );
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'), 0, 'Second auth no longer required if OTP token has been verified' );
281 t::lib::Mocks::mock_preference( 'TwoFactorAuthentication', 'enforced' );
282 $patron->auth_method('password')->store;
283 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired', undef, 'intranet' );
284 is( $userid, $patron->userid, 'Succesful login' );
285 is( C4::Auth::get_session($sessionID)->param('waiting-for-2FA-setup'), 1, 'Setup 2FA required' );
288 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired', undef, 'opac' );
289 is( $userid, $patron->userid, 'Succesful login at the OPAC' );
290 is( C4::Auth::get_session($sessionID)->param('waiting-for-2FA'), undef, 'No second auth required at the OPAC' );
293 t::lib::Mocks::mock_preference( 'TwoFactorAuthentication', 'disabled' );
294 $session = C4::Auth::get_session($sessionID);
295 $session->param('waiting-for-2FA', 1);
297 my ($auth_status, undef ) = C4::Auth::check_cookie_auth($sessionID, undef );
298 is( $auth_status, 'ok', 'User authenticated, pref was disabled, access OK' );
299 $session->param('waiting-for-2FA', 0);
300 $session->param('waiting-for-2FA-setup', 1);
302 ($auth_status, undef ) = C4::Auth::check_cookie_auth($sessionID, undef );
303 is( $auth_status, 'ok', 'User waiting for 2FA setup, pref was disabled, access OK' );
306 C4::Context->_new_userenv; # For next tests
310 subtest 'track_login_daily tests' => sub {
314 my $patron = $builder->build_object({ class => 'Koha::Patrons' });
315 my $userid = $patron->userid;
317 $patron->lastseen( undef );
320 my $cache = Koha::Caches->get_instance();
321 my $cache_key = "track_login_" . $patron->userid;
322 $cache->clear_from_cache($cache_key);
324 t::lib::Mocks::mock_preference( 'TrackLastPatronActivity', '1' );
326 is( $patron->lastseen, undef, 'Patron should have not last seen when newly created' );
328 C4::Auth::track_login_daily( $userid );
329 $patron->_result()->discard_changes();
330 isnt( $patron->lastseen, undef, 'Patron should have last seen set when TrackLastPatronActivity = 1' );
332 sleep(1); # We need to wait a tiny bit to make sure the timestamp will be different
333 my $last_seen = $patron->lastseen;
334 C4::Auth::track_login_daily( $userid );
335 $patron->_result()->discard_changes();
336 is( $patron->lastseen, $last_seen, 'Patron last seen should still be unchanged' );
338 $cache->clear_from_cache($cache_key);
339 C4::Auth::track_login_daily( $userid );
340 $patron->_result()->discard_changes();
341 isnt( $patron->lastseen, $last_seen, 'Patron last seen should be changed if we cleared the cache' );
343 t::lib::Mocks::mock_preference( 'TrackLastPatronActivity', '0' );
344 $patron->lastseen( undef )->store;
345 $cache->clear_from_cache($cache_key);
346 C4::Auth::track_login_daily( $userid );
347 $patron->_result()->discard_changes();
348 is( $patron->lastseen, undef, 'Patron should still have last seen unchanged when TrackLastPatronActivity = 0' );
352 subtest 'no_set_userenv parameter tests' => sub {
356 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
357 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
358 my $password = 'password';
360 t::lib::Mocks::mock_preference( 'RequireStrongPassword', 0 );
361 $patron->set_password({ password => $password });
363 ok( checkpw( $patron->userid, $password, undef, undef, 1 ), 'checkpw returns true' );
364 is( C4::Context->userenv, undef, 'Userenv should be undef as required' );
365 C4::Context->_new_userenv('DUMMY SESSION');
366 C4::Context->set_userenv(0,0,0,'firstname','surname', $library->branchcode, 'Library 1', 0, '', '');
367 is( C4::Context->userenv->{branch}, $library->branchcode, 'Userenv gives correct branch' );
368 ok( checkpw( $patron->userid, $password, undef, undef, 1 ), 'checkpw returns true' );
369 is( C4::Context->userenv->{branch}, $library->branchcode, 'Userenv branch is preserved if no_set_userenv is true' );
370 ok( checkpw( $patron->userid, $password, undef, undef, 0 ), 'checkpw still returns true' );
371 isnt( C4::Context->userenv->{branch}, $library->branchcode, 'Userenv branch is overwritten if no_set_userenv is false' );
374 subtest 'checkpw lockout tests' => sub {
378 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
379 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
380 my $password = 'password';
381 t::lib::Mocks::mock_preference( 'RequireStrongPassword', 0 );
382 t::lib::Mocks::mock_preference( 'FailedLoginAttempts', 1 );
383 $patron->set_password({ password => $password });
385 my ( $checkpw, undef, undef ) = checkpw( $patron->cardnumber, $password, undef, undef, 1 );
386 ok( $checkpw, 'checkpw returns true with right password when logging in via cardnumber' );
387 ( $checkpw, undef, undef ) = checkpw( $patron->userid, "wrong_password", undef, undef, 1 );
388 is( $checkpw, 0, 'checkpw returns false when given wrong password' );
389 $patron = $patron->get_from_storage;
390 is( $patron->account_locked, 1, "Account is locked from failed login");
391 ( $checkpw, undef, undef ) = checkpw( $patron->userid, $password, undef, undef, 1 );
392 is( $checkpw, undef, 'checkpw returns undef with right password when account locked' );
393 ( $checkpw, undef, undef ) = checkpw( $patron->cardnumber, $password, undef, undef, 1 );
394 is( $checkpw, undef, 'checkpw returns undefwith right password when logging in via cardnumber if account locked' );
398 # get_template_and_user tests
400 subtest 'get_template_and_user' => sub { # Tests for the language URL parameter
402 sub MockedCheckauth {
403 my ($query,$authnotrequired,$flagsrequired,$type) = @_;
405 my $userid = 'cobain';
407 # we don't need to bother about permissions for this test
409 superlibrarian => 1, acquisition => 0,
411 catalogue => 1, circulate => 0,
412 coursereserves => 0, editauthorities => 0,
414 parameters => 0, permissions => 0,
415 plugins => 0, reports => 0,
416 reserveforothers => 0, serials => 0,
417 staffaccess => 0, tools => 0,
421 my $session_cookie = $query->cookie(
422 -name => 'CGISESSID',
427 return ( $userid, [ $session_cookie ], $sessionID, $flags );
430 # Mock checkauth, build the scenario
431 my $auth = Test::MockModule->new( 'C4::Auth' );
432 $auth->mock( 'checkauth', \&MockedCheckauth );
434 # Make sure 'EnableOpacSearchHistory' is set
435 t::lib::Mocks::mock_preference('EnableOpacSearchHistory',1);
436 # Enable es-ES for the OPAC and staff interfaces
437 t::lib::Mocks::mock_preference('OPACLanguages','en,es-ES');
438 t::lib::Mocks::mock_preference('language','en,es-ES');
440 # we need a session cookie
441 $ENV{"SERVER_PORT"} = 80;
442 $ENV{"HTTP_COOKIE"} = 'CGISESSID=nirvana';
444 my $query = CGI->new;
445 $query->param('language','es-ES');
447 my ( $template, $loggedinuser, $cookies ) = get_template_and_user(
449 template_name => "about.tt",
452 authnotrequired => 1,
453 flagsrequired => { catalogue => 1 },
458 ok ( ( all { ref($_) eq 'CGI::Cookie' } @$cookies ),
459 'BZ9735: the cookies array is flat' );
461 # new query, with non-existent language (we only have en and es-ES)
462 $query->param('language','tomas');
464 ( $template, $loggedinuser, $cookies ) = get_template_and_user(
466 template_name => "about.tt",
469 authnotrequired => 1,
470 flagsrequired => { catalogue => 1 },
475 ok( ( none { $_->name eq 'KohaOpacLanguage' and $_->value eq 'tomas' } @$cookies ),
476 'BZ9735: invalid language, it is not set');
478 ok( ( any { $_->name eq 'KohaOpacLanguage' and $_->value eq 'en' } @$cookies ),
479 'BZ9735: invalid language, then default to en');
481 for my $template_name (
483 ../../../../../../../../../../../../../../../etc/passwd
484 test/../../../../../../../../../../../../../../etc/passwd
486 test/does_not_finished_by_tt_t
490 ( $template, $loggedinuser, $cookies ) = get_template_and_user(
492 template_name => $template_name,
495 authnotrequired => 1,
496 flagsrequired => { catalogue => 1 },
500 like ( $@, qr(bad template path), "The file $template_name should not be accessible" );
502 ( $template, $loggedinuser, $cookies ) = get_template_and_user(
504 template_name => 'errors/errorpage.tt',
507 authnotrequired => 1,
508 flagsrequired => { catalogue => 1 },
511 my $file_exists = ( -f $template->{filename} ) ? 1 : 0;
512 is ( $file_exists, 1, 'The file errors/errorpage.tt should be accessible (contains integers)' );
514 # Regression test for env opac search limit override
515 $ENV{"OPAC_SEARCH_LIMIT"} = "branch:CPL";
516 $ENV{"OPAC_LIMIT_OVERRIDE"} = 1;
518 ( $template, $loggedinuser, $cookies) = get_template_and_user(
520 template_name => 'opac-main.tt',
523 authnotrequired => 1,
526 is($template->{VARS}->{'opac_name'}, "CPL", "Opac name was set correctly");
527 is($template->{VARS}->{'opac_search_limit'}, "branch:CPL", "Search limit was set correctly");
529 $ENV{"OPAC_SEARCH_LIMIT"} = "branch:multibranch-19";
531 ( $template, $loggedinuser, $cookies) = get_template_and_user(
533 template_name => 'opac-main.tt',
536 authnotrequired => 1,
539 is($template->{VARS}->{'opac_name'}, "multibranch-19", "Opac name was set correctly");
540 is($template->{VARS}->{'opac_search_limit'}, "branch:multibranch-19", "Search limit was set correctly");
542 delete $ENV{"HTTP_COOKIE"};
545 # Check that there is always an OPACBaseURL set.
546 my $input = CGI->new();
547 my ( $template1, $borrowernumber, $cookie );
548 ( $template1, $borrowernumber, $cookie ) = get_template_and_user(
550 template_name => "opac-detail.tt",
553 authnotrequired => 1,
557 ok( ( any { 'OPACBaseURL' eq $_ } keys %{$template1->{VARS}} ),
558 'OPACBaseURL is in OPAC template' );
561 ( $template2, $borrowernumber, $cookie ) = get_template_and_user(
563 template_name => "catalogue/detail.tt",
566 authnotrequired => 1,
570 ok( ( any { 'OPACBaseURL' eq $_ } keys %{$template2->{VARS}} ),
571 'OPACBaseURL is in Staff template' );
573 my $hash1 = hash_password('password');
574 my $hash2 = hash_password('password');
576 ok(C4::Auth::checkpw_hash('password', $hash1), 'password validates with first hash');
577 ok(C4::Auth::checkpw_hash('password', $hash2), 'password validates with second hash');
579 subtest 'Check value of login_attempts in checkpw' => sub {
582 t::lib::Mocks::mock_preference('FailedLoginAttempts', 3);
584 # Only interested here in regular login
588 my $patron = $builder->build_object({ class => 'Koha::Patrons' });
589 $patron->login_attempts(2);
590 $patron->password('123')->store; # yes, deliberately not hashed
592 is( $patron->account_locked, 0, 'Patron not locked' );
593 my @test = checkpw( $patron->userid, '123', undef, 'opac', 1 );
594 # Note: 123 will not be hashed to 123 !
595 is( $test[0], 0, 'checkpw should have failed' );
596 $patron->discard_changes; # refresh
597 is( $patron->login_attempts, 3, 'Login attempts increased' );
598 is( $patron->account_locked, 1, 'Check locked status' );
600 # And another try to go over the limit: different return value!
601 @test = checkpw( $patron->userid, '123', undef, 'opac', 1 );
602 is( @test, 0, 'checkpw failed again and returns nothing now' );
603 $patron->discard_changes; # refresh
604 is( $patron->login_attempts, 3, 'Login attempts not increased anymore' );
606 # Administrative lockout cannot be undone?
607 # Pass the right password now (or: add a nice mock).
608 my $auth = Test::MockModule->new( 'C4::Auth' );
609 $auth->mock( 'checkpw_hash', sub { return 1; } ); # not for production :)
610 $patron->login_attempts(0)->store;
611 @test = checkpw( $patron->userid, '123', undef, 'opac', 1 );
612 is( $test[0], 1, 'Build confidence in the mock' );
613 $patron->login_attempts(-1)->store;
614 is( $patron->account_locked, 1, 'Check administrative lockout' );
615 @test = checkpw( $patron->userid, '123', undef, 'opac', 1 );
616 is( @test, 0, 'checkpw gave red' );
617 $patron->discard_changes; # refresh
618 is( $patron->login_attempts, -1, 'Still locked out' );
619 t::lib::Mocks::mock_preference('FailedLoginAttempts', ''); # disable
620 is( $patron->account_locked, 1, 'Check administrative lockout without pref' );
623 subtest 'Check value of login_attempts in checkpw' => sub {
626 t::lib::Mocks::mock_preference('FailedLoginAttempts', 3);
627 my $patron = $builder->build_object({ class => 'Koha::Patrons' });
628 $patron->set_password({ password => '123', skip_validation => 1 });
630 my @test = checkpw( $patron->userid, '123', undef, 'opac', 1 );
631 is( $test[0], 1, 'Patron authenticated correctly' );
633 $patron->password_expiration_date('2020-01-01')->store;
634 @test = checkpw( $patron->userid, '123', undef, 'opac', 1 );
635 is( $test[0], -2, 'Patron returned as expired correctly' );
639 subtest '_timeout_syspref' => sub {
643 t::lib::Mocks::mock_preference('timeout', "100");
644 is( C4::Auth::_timeout_syspref, 100, );
646 t::lib::Mocks::mock_preference('timeout', "2d");
647 is( C4::Auth::_timeout_syspref, 2*86400, );
649 t::lib::Mocks::mock_preference('timeout', "2D");
650 is( C4::Auth::_timeout_syspref, 2*86400, );
652 t::lib::Mocks::mock_preference('timeout', "10h");
653 is( C4::Auth::_timeout_syspref, 10*3600, );
655 t::lib::Mocks::mock_preference('timeout', "10x");
657 { is( C4::Auth::_timeout_syspref, 600, ); }
658 "The value of the system preference 'timeout' is not correct, defaulting to 600",
659 'Bad values throw a warning and fallback to 600';
662 subtest 'check_cookie_auth' => sub {
665 t::lib::Mocks::mock_preference('timeout', "1d"); # back to default
667 my $patron = $builder->build_object({ class => 'Koha::Patrons', value => { flags => 1 } });
669 # Mock a CGI object with real userid param
670 my $cgi = Test::MockObject->new();
675 if ( $var eq 'userid' ) { return $patron->userid; }
678 $cgi->mock('multi_param', sub {return q{}} );
679 $cgi->mock( 'cookie', sub { return; } );
680 $cgi->mock( 'request_method', sub { return 'POST' } );
682 $ENV{REMOTE_ADDR} = '127.0.0.1';
684 # Setting authnotrequired=1 or we wont' hit the return but the end of the sub that prints headers
685 my ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 1 );
687 my ($auth_status, $session) = C4::Auth::check_cookie_auth($sessionID);
688 isnt( $auth_status, 'ok', 'check_cookie_auth should not return ok if the user has not been authenticated before if no permissions needed' );
689 is( $auth_status, 'anon', 'check_cookie_auth should return anon if the user has not been authenticated before and no permissions needed' );
691 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 1 );
693 ($auth_status, $session) = C4::Auth::check_cookie_auth($sessionID, {catalogue => 1});
694 isnt( $auth_status, 'ok', 'check_cookie_auth should not return ok if the user has not been authenticated before and permissions needed' );
695 is( $auth_status, 'anon', 'check_cookie_auth should return anon if the user has not been authenticated before and permissions needed' );
697 #FIXME We should have a test to cover 'failed' status when a user has logged in, but doesn't have permission
700 subtest 'checkauth & check_cookie_auth' => sub {
703 # flags = 4 => { catalogue => 1 }
704 my $patron = $builder->build_object({ class => 'Koha::Patrons', value => { flags => 4 } });
705 my $password = 'password';
706 t::lib::Mocks::mock_preference( 'RequireStrongPassword', 0 );
707 $patron->set_password( { password => $password } );
709 my $cgi_mock = Test::MockModule->new('CGI');
710 $cgi_mock->mock( 'request_method', sub { return 'POST' } );
714 my $auth = Test::MockModule->new( 'C4::Auth' );
715 # Tests will fail if we hit safe_exit
716 $auth->mock( 'safe_exit', sub { return } );
718 my ( $userid, $cookie, $sessionID, $flags );
720 # checkauth will redirect and safe_exit if not authenticated and not authorized
723 open STDOUT, '>', \$stdout;
724 C4::Auth::checkauth($cgi, 0, {catalogue => 1});
725 like( $stdout, qr{<title>\s*Log in to your account} );
726 $sessionID = ( $stdout =~ m{Set-Cookie: CGISESSID=((\d|\w)+);} ) ? $1 : undef;
731 my $first_sessionID = $sessionID;
733 $ENV{"HTTP_COOKIE"} = "CGISESSID=$sessionID";
734 # Not authenticated yet, checkauth didn't return the session
738 open STDOUT, '>', \$stdout;
739 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 0, {catalogue => 1} );
742 is( $sessionID, undef);
745 # Sending undefined fails obviously
746 my ( $auth_status, $session ) = C4::Auth::check_cookie_auth($sessionID, {catalogue => 1} );
747 is( $auth_status, 'failed' );
748 is( $session, undef );
750 # Simulating the login form submission
751 $cgi->param('userid', $patron->userid);
752 $cgi->param('password', $password);
755 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 0, {catalogue => 1});
756 is( $sessionID, $first_sessionID );
757 is( $userid, $patron->userid );
759 ( $auth_status, $session ) = C4::Auth::check_cookie_auth($sessionID, {catalogue => 1});
760 is( $auth_status, 'ok' );
761 is( $session->id, $first_sessionID );
764 $cgi->param('logout.x', 1);
765 $cgi->delete( 'userid', 'password' );
769 open STDOUT, '>', \$stdout;
770 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 0, {catalogue => 1});
773 is( $sessionID, undef );
774 is( $ENV{"HTTP_COOKIE"}, "CGISESSID=$first_sessionID", 'HTTP_COOKIE not unset' );
775 ( $auth_status, $session) = C4::Auth::check_cookie_auth( $first_sessionID, {catalogue => 1} );
776 is( $auth_status, "expired");
777 is( $session, undef );
780 # Trying to access without sessionID
782 ( $auth_status, $session) = C4::Auth::check_cookie_auth(undef, {catalogue => 1});
783 is( $auth_status, 'failed' );
784 is( $session, undef );
786 # This will fail on permissions
787 undef $ENV{"HTTP_COOKIE"};
791 open STDOUT, '>', \$stdout;
792 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 0, {catalogue => 1} );
795 is( $userid, undef );
796 is( $sessionID, undef );
802 $cgi->param('userid', $patron->userid);
803 $cgi->param('password', $password);
804 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 0, {catalogue => 1});
805 is( $userid, $patron->userid );
806 $first_sessionID = $sessionID;
808 # Patron does not have the borrowers permission
809 # $ENV{"HTTP_COOKIE"} = "CGISESSID=$sessionID"; # not needed, we use $cgi here
813 open STDOUT, '>', \$stdout;
814 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 0, {borrowers => 1} );
817 is( $userid, undef );
818 is( $sessionID, undef );
820 # When calling check_cookie_auth, the session will be deleted
821 ( $auth_status, $session) = C4::Auth::check_cookie_auth( $first_sessionID, { borrowers => 1 } );
822 is( $auth_status, "failed" );
823 is( $session, undef );
824 ( $auth_status, $session) = C4::Auth::check_cookie_auth( $first_sessionID, { borrowers => 1 } );
825 is( $auth_status, 'expired', 'Session no longer exists' );
827 # NOTE: It is not what the UI is doing.
828 # From the UI we are allowed to hit an unauthorized page then reuse the session to hit back authorized area.
829 # It is because check_cookie_auth is ALWAYS called from checkauth WITHOUT $flagsrequired
830 # It then return "ok", when the previous called got "failed"
832 # Try reusing the deleted session: since it does not exist, we should get a new one now when passing correct permissions
833 $cgi->cookie( -name => 'CGISESSID', value => $first_sessionID );
834 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 0, {catalogue => 1});
835 is( $userid, $patron->userid );
836 isnt( $sessionID, undef, 'Check if we have a sessionID' );
837 isnt( $sessionID, $first_sessionID, 'New value expected' );
838 ( $auth_status, $session) = C4::Auth::check_cookie_auth( $sessionID, {catalogue => 1} );
839 is( $auth_status, "ok" );
840 is( $session->id, $sessionID, 'Same session' );
841 # Two additional tests on userenv
842 is( $C4::Context::context->{activeuser}, $session->id, 'Check if environment has been setup for session' );
843 is( C4::Context->userenv->{id}, $userid, 'Check userid in userenv' );
847 subtest 'Userenv clearing in check_cookie_auth' => sub {
848 # Note: We did already test userenv for a logged-in user in previous subtest
851 t::lib::Mocks::mock_preference( 'timeout', 600 );
854 # Create a new anonymous session by passing a fake session ID
855 $cgi->cookie( -name => 'CGISESSID', -value => 'fake_sessionID' );
856 my ($userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 1);
857 my ( $auth_status, $session) = C4::Auth::check_cookie_auth( $sessionID );
858 is( $auth_status, 'anon', 'Should be anonymous' );
859 is( $C4::Context::context->{activeuser}, $session->id, 'Check activeuser' );
860 is( defined C4::Context->userenv, 1, 'There should be a userenv' );
861 is( C4::Context->userenv->{id}, q{}, 'userid should be empty string' );
863 # Make the session expire now, check_cookie_auth will delete it
864 $session->param('lasttime', time() - 1200 );
866 ( $auth_status, $session) = C4::Auth::check_cookie_auth( $sessionID );
867 is( $auth_status, 'expired', 'Should be expired' );
868 is( C4::Context->userenv, undef, 'Environment should be cleared too' );
870 # Show that we clear the userenv again: set up env and check deleted session
871 C4::Context->_new_userenv( $sessionID );
872 C4::Context->set_userenv; # empty
873 is( defined C4::Context->userenv, 1, 'There should be an empty userenv again' );
874 ( $auth_status, $session) = C4::Auth::check_cookie_auth( $sessionID );
875 is( $auth_status, 'expired', 'Should be expired already' );
876 is( C4::Context->userenv, undef, 'Environment should be cleared again' );
879 subtest 'create_basic_session tests' => sub {
882 my $patron = $builder->build_object({ class => 'Koha::Patrons' });
884 my $session = C4::Auth::create_basic_session({ patron => $patron, interface => 'opac' });
886 isnt($session->id, undef, 'A new sessionID was created');
887 is( $session->param('number'), $patron->borrowernumber, 'Session parameter number matches' );
888 is( $session->param('id'), $patron->userid, 'Session parameter id matches' );
889 is( $session->param('cardnumber'), $patron->cardnumber, 'Session parameter cardnumber matches' );
890 is( $session->param('firstname'), $patron->firstname, 'Session parameter firstname matches' );
891 is( $session->param('surname'), $patron->surname, 'Session parameter surname matches' );
892 is( $session->param('branch'), $patron->branchcode, 'Session parameter branch matches' );
893 is( $session->param('branchname'), $patron->library->branchname, 'Session parameter branchname matches' );
894 is( $session->param('flags'), $patron->flags, 'Session parameter flags matches' );
895 is( $session->param('emailaddress'), $patron->email, 'Session parameter emailaddress matches' );
896 is( $session->param('ip'), $session->remote_addr(), 'Session parameter ip matches' );
897 is( $session->param('interface'), 'opac', 'Session parameter interface matches' );
899 $session = C4::Auth::create_basic_session({ patron => $patron, interface => 'staff' });
900 is( $session->param('interface'), 'intranet', 'Staff interface gets converted to intranet' );
903 $schema->storage->txn_rollback;