9 use List::MoreUtils qw/all any none/;
10 use Test::More tests => 20;
13 use t::lib::TestBuilder;
17 use Koha::AuthUtils qw( hash_password );
18 use Koha::DateUtils qw( dt_from_string );
21 use Koha::Auth::TwoFactorAuth;
26 qw( checkauth haspermission checkpw get_template_and_user checkpw_hash get_cataloguing_page_permissions )
30 my $schema = Koha::Database->schema;
31 my $builder = t::lib::TestBuilder->new;
33 # FIXME: SessionStorage defaults to mysql, but it seems to break transaction
35 t::lib::Mocks::mock_preference( 'SessionStorage', 'tmp' );
36 t::lib::Mocks::mock_preference( 'PrivacyPolicyConsent', '' ); # Disabled
38 # To silence useless warnings
39 $ENV{REMOTE_ADDR} = '127.0.0.1';
41 $schema->storage->txn_begin;
43 subtest 'checkauth() tests' => sub {
47 my $patron = $builder->build_object({ class => 'Koha::Patrons', value => { flags => undef } });
49 # Mock a CGI object with real userid param
50 my $cgi = Test::MockObject->new();
55 if ( $var eq 'userid' ) { return $patron->userid; }
58 $cgi->mock( 'cookie', sub { return; } );
59 $cgi->mock( 'request_method', sub { return 'POST' } );
61 my $authnotrequired = 1;
62 my ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, $authnotrequired );
64 is( $userid, undef, 'checkauth() returns undef for userid if no logged in user (Bug 18275)' );
66 my $db_user_id = C4::Context->config('user');
67 my $db_user_pass = C4::Context->config('pass');
68 $cgi = Test::MockObject->new();
69 $cgi->mock( 'cookie', sub { return; } );
70 $cgi->mock( 'param', sub {
71 my ( $self, $param ) = @_;
72 if ( $param eq 'userid' ) { return $db_user_id; }
73 elsif ( $param eq 'password' ) { return $db_user_pass; }
76 $cgi->mock( 'request_method', sub { return 'POST' } );
77 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, $authnotrequired );
78 is ( $userid, undef, 'If DB user is used, it should not be logged in' );
80 my $is_allowed = C4::Auth::haspermission( $db_user_id, { can_do => 'everything' } );
82 # FIXME This belongs to t/db_dependent/Auth/haspermission.t but we do not want to c/p the pervious mock statements
83 ok( !$is_allowed, 'DB user should not have any permissions');
85 subtest 'Prevent authentication when sending credential via GET' => sub {
89 my $patron = $builder->build_object(
90 { class => 'Koha::Patrons', value => { flags => 1 } } );
91 my $password = set_weak_password($patron);
92 $cgi = Test::MockObject->new();
93 $cgi->mock( 'cookie', sub { return; } );
97 my ( $self, $param ) = @_;
98 if ( $param eq 'userid' ) { return $patron->userid; }
99 elsif ( $param eq 'password' ) { return $password; }
104 $cgi->mock( 'request_method', sub { return 'POST' } );
105 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired' );
106 is( $userid, $patron->userid, 'If librarian user is used and password with POST, they should be logged in' );
108 $cgi->mock( 'request_method', sub { return 'GET' } );
109 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired' );
110 is( $userid, undef, 'If librarian user is used and password with GET, they should not be logged in' );
113 subtest 'cas_ticket must be empty in session' => sub {
117 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { flags => 1 } } );
118 my $password = 'password';
119 t::lib::Mocks::mock_preference( 'RequireStrongPassword', 0 );
120 $patron->set_password( { password => $password } );
121 $cgi = Test::MockObject->new();
122 $cgi->mock( 'cookie', sub { return; } );
126 my ( $self, $param ) = @_;
127 if ( $param eq 'userid' ) { return $patron->userid; }
128 elsif ( $param eq 'password' ) { return $password; }
133 $cgi->mock( 'request_method', sub { return 'POST' } );
134 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired' );
135 is( $userid, $patron->userid, 'If librarian user is used and password with POST, they should be logged in' );
136 my $session = C4::Auth::get_session($sessionID);
137 is( $session->param('cas_ticket'), undef );
141 subtest 'sessionID should be passed to the template for auth' => sub {
145 subtest 'hit auth.tt' => sub {
149 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { flags => 0 } } );
151 my $password = set_weak_password($patron);
153 my $cgi_mock = Test::MockModule->new('CGI');
154 $cgi_mock->mock( 'request_method', sub { return 'POST' } );
157 # Simulating the login form submission
158 $cgi->param( 'userid', $patron->userid );
159 $cgi->param( 'password', $password );
161 my ( $userid, $cookie, $sessionID, $flags, $template ) =
162 C4::Auth::checkauth( $cgi, 0, { catalogue => 1 }, 'intranet', undef, undef, { do_not_print => 1 } );
163 ok( $template->{VARS}->{sessionID} );
167 subtest 'Template params tests (password_expired)' => sub {
171 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
173 my $password = set_weak_password($patron);
174 $patron->password_expiration_date( dt_from_string->subtract(days => 1) )->store;
176 my $cgi_mock = Test::MockModule->new('CGI');
177 $cgi_mock->mock( 'request_method', sub { return 'POST' } );
179 # Simulating the login form submission
180 $cgi->param( 'userid', $patron->userid );
181 $cgi->param( 'password', $password );
183 my ( $userid, $cookie, $sessionID, $flags, $template ) = C4::Auth::checkauth( $cgi, 0, { catalogue => 1 }, 'intranet', undef, undef, { do_not_print => 1 } );
184 is( $template->{VARS}->{password_has_expired}, 1 );
187 subtest 'Reset auth state when changing users' => sub {
189 #NOTE: It's easiest to detect this when changing to a non-existent user, since
190 #that should trigger a redirect to login (instead of returning a session cookie)
192 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { flags => undef } } );
194 my $session = C4::Auth::get_session();
195 $session->param( 'number', $patron->id );
196 $session->param( 'id', $patron->userid );
197 $session->param( 'ip', '1.2.3.4' );
198 $session->param( 'lasttime', time() );
199 $session->param( 'interface', 'intranet' );
201 my $sessionID = $session->id;
202 C4::Context->_new_userenv($sessionID);
205 C4::Auth::check_cookie_auth( $sessionID, undef, { skip_version_check => 1, remote_addr => '1.2.3.4' } );
206 is( $return, 'ok', 'Patron authenticated' );
208 my $mock2 = Test::MockModule->new('CGI');
209 $mock2->mock( 'request_method', 'POST' );
210 $mock2->mock( 'cookie', sub { return $sessionID; } ); # oversimplified..
213 $cgi->param( -name => 'userid', -value => 'Bond' );
214 $cgi->param( -name => 'password', -value => 'James Bond' );
215 $cgi->param( -name => 'koha_login_context', -value => 1 );
216 my ( $userid, $cookie, $flags, $template );
217 ( $userid, $cookie, $sessionID, $flags, $template ) =
218 C4::Auth::checkauth( $cgi, 0, { catalogue => 1 }, 'intranet', undef, undef, { do_not_print => 1 } );
219 is( $template->{VARS}->{loginprompt}, 1, 'Changing to non-existent user causes a redirect to login' );
222 subtest 'While still logged in, relogin with another user' => sub {
225 my $patron = $builder->build_object({ class => 'Koha::Patrons', value => {} });
226 my $patron2 = $builder->build_object({ class => 'Koha::Patrons', value => {} });
227 # Create 'former' session
228 my $session = C4::Auth::get_session();
229 $session->param( 'number', $patron->id );
230 $session->param( 'id', $patron->userid );
231 $session->param( 'ip', '1.2.3.4' );
232 $session->param( 'lasttime', time() );
233 $session->param( 'interface', 'opac' );
235 my $previous_sessionID = $session->id;
236 C4::Context->_new_userenv($previous_sessionID);
238 my ( $return ) = C4::Auth::check_cookie_auth( $previous_sessionID, undef, { skip_version_check => 1, remote_addr => '1.2.3.4' } );
239 is( $return, 'ok', 'Former session in shape now' );
241 my $mock1 = Test::MockModule->new('C4::Auth');
242 $mock1->mock( 'safe_exit', sub {} );
243 my $mock2 = Test::MockModule->new('CGI');
244 $mock2->mock( 'request_method', 'POST' );
245 $mock2->mock( 'cookie', sub { return $previous_sessionID; } ); # oversimplified..
247 my $password = 'Incr3d1blyZtr@ng93$';
248 $patron2->set_password({ password => $password });
249 $cgi->param( -name => 'userid', -value => $patron2->userid );
250 $cgi->param( -name => 'password', -value => $password );
251 $cgi->param( -name => 'koha_login_context', -value => 1 );
252 my ( $userid, $cookie, $sessionID, $flags, $template ) =
253 C4::Auth::checkauth( $cgi, 0, {}, 'opac', undef, undef, { do_not_print => 1 } );
254 is( $userid, $patron2->userid, 'Login of patron2 approved' );
255 isnt( $sessionID, $previous_sessionID, 'Did not return previous session ID' );
256 ok( $sessionID, 'New session ID not empty' );
258 # Similar situation: Relogin with former session of $patron, new user $patron2 has no permissions
259 $patron2->flags(undef)->store;
260 $session->param( 'number', $patron->id );
261 $session->param( 'id', $patron->userid );
262 $session->param( 'interface', 'intranet' );
264 $previous_sessionID = $session->id;
265 C4::Context->_new_userenv($previous_sessionID);
266 $cgi->param( -name => 'userid', -value => $patron2->userid );
267 $cgi->param( -name => 'password', -value => $password );
268 $cgi->param( -name => 'koha_login_context', -value => 1 );
269 ( $userid, $cookie, $sessionID, $flags, $template ) =
270 C4::Auth::checkauth( $cgi, 0, { catalogue => 1 }, 'intranet', undef, undef, { do_not_print => 1 } );
271 is( $template->{VARS}->{nopermission}, 1, 'No permission response' );
274 subtest 'Two-factor authentication' => sub {
277 my $patron = $builder->build_object(
278 { class => 'Koha::Patrons', value => { flags => 1 } } );
279 my $password = 'password';
280 $patron->set_password( { password => $password } );
281 $cgi = Test::MockObject->new();
284 our ( $logout, $sessionID, $verified );
288 my ( $self, $param ) = @_;
289 if ( $param eq 'userid' ) { return $patron->userid; }
290 elsif ( $param eq 'password' ) { return $password; }
291 elsif ( $param eq 'otp_token' ) { return $otp_token; }
292 elsif ( $param eq 'logout.x' ) { return $logout; }
296 $cgi->mock( 'request_method', sub { return 'POST' } );
297 $cgi->mock( 'cookie', sub { return $sessionID } );
299 my $two_factor_auth = Test::MockModule->new( 'Koha::Auth::TwoFactorAuth' );
300 $two_factor_auth->mock( 'verify', sub {$verified} );
302 my ( $userid, $cookie, $flags );
303 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired', undef, 'intranet' );
309 C4::Auth::checkauth( $cgi, 'authrequired', undef, 'intranet' );
313 t::lib::Mocks::mock_preference( 'TwoFactorAuthentication', 'disabled' );
314 $patron->auth_method('password')->store;
315 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired', undef, 'intranet' );
316 is( $userid, $patron->userid, 'Succesful login' );
317 is( C4::Auth::get_session($sessionID)->param('waiting-for-2FA'), undef, 'Second auth not required' );
320 $patron->auth_method('two-factor')->store;
321 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired', undef, 'intranet' );
322 is( $userid, $patron->userid, 'Succesful login' );
323 is( C4::Auth::get_session($sessionID)->param('waiting-for-2FA'), undef, 'Second auth not required' );
326 t::lib::Mocks::mock_preference( 'TwoFactorAuthentication', 'enabled' );
327 t::lib::Mocks::mock_config('encryption_key', '1234tH1s=t&st');
328 $patron->auth_method('password')->store;
329 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired', undef, 'intranet' );
330 is( $userid, $patron->userid, 'Succesful login' );
331 is( C4::Auth::get_session($sessionID)->param('waiting-for-2FA'), undef, 'Second auth not required' );
334 $patron->encode_secret('one_secret');
335 $patron->auth_method('two-factor');
337 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired', undef, 'intranet' );
338 is( $userid, $patron->userid, 'Succesful login' );
339 my $session = C4::Auth::get_session($sessionID);
340 is( C4::Auth::get_session($sessionID)->param('waiting-for-2FA'), 1, 'Second auth required' );
343 $otp_token = "wrong";
345 $patron->auth_method('two-factor')->store;
346 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired', undef, 'intranet' );
347 is( $userid, $patron->userid, 'Succesful login' );
348 is( C4::Auth::get_session($sessionID)->param('waiting-for-2FA'), 1, 'Second auth still required after wrong OTP token' );
352 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired', undef, 'intranet' );
353 is( $userid, $patron->userid, 'Succesful login' );
354 is( C4::Auth::get_session($sessionID)->param('waiting-for-2FA'), 0, 'Second auth no longer required if OTP token has been verified' );
357 t::lib::Mocks::mock_preference( 'TwoFactorAuthentication', 'enforced' );
358 $patron->auth_method('password')->store;
359 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired', undef, 'intranet' );
360 is( $userid, $patron->userid, 'Succesful login' );
361 is( C4::Auth::get_session($sessionID)->param('waiting-for-2FA-setup'), 1, 'Setup 2FA required' );
364 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired', undef, 'opac' );
365 is( $userid, $patron->userid, 'Succesful login at the OPAC' );
366 is( C4::Auth::get_session($sessionID)->param('waiting-for-2FA'), undef, 'No second auth required at the OPAC' );
369 t::lib::Mocks::mock_preference( 'TwoFactorAuthentication', 'disabled' );
370 $session = C4::Auth::get_session($sessionID);
371 $session->param('waiting-for-2FA', 1);
373 my ($auth_status, undef ) = C4::Auth::check_cookie_auth($sessionID, undef );
374 is( $auth_status, 'ok', 'User authenticated, pref was disabled, access OK' );
375 $session->param('waiting-for-2FA', 0);
376 $session->param('waiting-for-2FA-setup', 1);
378 ($auth_status, undef ) = C4::Auth::check_cookie_auth($sessionID, undef );
379 is( $auth_status, 'ok', 'User waiting for 2FA setup, pref was disabled, access OK' );
382 subtest 'loggedinlibrary permission tests' => sub {
385 my $staff_user = $builder->build_object(
386 { class => 'Koha::Patrons', value => { flags => 536870916 } } );
388 my $branch = $builder->build_object({ class => 'Koha::Libraries' });
390 my $password = set_weak_password($staff_user);
391 my $cgi = Test::MockObject->new();
392 $cgi->mock( 'cookie', sub { return; } );
396 my ( $self, $param ) = @_;
397 if ( $param eq 'userid' ) { return $staff_user->userid; }
398 elsif ( $param eq 'password' ) { return $password; }
399 elsif ( $param eq 'branch' ) { return $branch->branchcode; }
404 $cgi->mock( 'request_method', sub { return 'POST' } );
405 my ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired' );
406 my $sesh = C4::Auth::get_session($sessionID);
407 is( $sesh->param('branch'), $branch->branchcode, "If user has permission, they should be able to choose a branch" );
409 $staff_user->flags(4)->store->discard_changes;
410 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired' );
411 $sesh = C4::Auth::get_session($sessionID);
412 is( $sesh->param('branch'), $staff_user->branchcode, "If user has not permission, they should not be able to choose a branch" );
414 $staff_user->flags(1)->store->discard_changes;
415 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired' );
416 $sesh = C4::Auth::get_session($sessionID);
417 is( $sesh->param('branch'), $branch->branchcode, "If user is superlibrarian, they should be able to choose a branch" );
420 C4::Context->_new_userenv; # For next tests
423 subtest 'no_set_userenv parameter tests' => sub {
427 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
428 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
430 my $password = set_weak_password($patron);
432 ok( checkpw( $patron->userid, $password, undef, undef, 1 ), 'checkpw returns true' );
433 is( C4::Context->userenv, undef, 'Userenv should be undef as required' );
434 C4::Context->_new_userenv('DUMMY SESSION');
435 C4::Context->set_userenv(0,0,0,'firstname','surname', $library->branchcode, 'Library 1', 0, '', '');
436 is( C4::Context->userenv->{branch}, $library->branchcode, 'Userenv gives correct branch' );
437 ok( checkpw( $patron->userid, $password, undef, undef, 1 ), 'checkpw returns true' );
438 is( C4::Context->userenv->{branch}, $library->branchcode, 'Userenv branch is preserved if no_set_userenv is true' );
439 ok( checkpw( $patron->userid, $password, undef, undef, 0 ), 'checkpw still returns true' );
440 isnt( C4::Context->userenv->{branch}, $library->branchcode, 'Userenv branch is overwritten if no_set_userenv is false' );
443 subtest 'checkpw lockout tests' => sub {
447 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
448 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
449 my $password = set_weak_password($patron);
450 t::lib::Mocks::mock_preference( 'FailedLoginAttempts', 1 );
452 my ( $checkpw, undef, undef ) = checkpw( $patron->cardnumber, $password, undef, undef, 1 );
453 ok( $checkpw, 'checkpw returns true with right password when logging in via cardnumber' );
454 ( $checkpw, undef, undef ) = checkpw( $patron->userid, "wrong_password", undef, undef, 1 );
455 is( $checkpw, 0, 'checkpw returns false when given wrong password' );
456 $patron = $patron->get_from_storage;
457 is( $patron->account_locked, 1, "Account is locked from failed login");
458 ( $checkpw, undef, undef ) = checkpw( $patron->userid, $password, undef, undef, 1 );
459 is( $checkpw, undef, 'checkpw returns undef with right password when account locked' );
460 ( $checkpw, undef, undef ) = checkpw( $patron->cardnumber, $password, undef, undef, 1 );
461 is( $checkpw, undef, 'checkpw returns undefwith right password when logging in via cardnumber if account locked' );
465 # get_template_and_user tests
467 subtest 'get_template_and_user' => sub { # Tests for the language URL parameter
469 sub MockedCheckauth {
470 my ($query,$authnotrequired,$flagsrequired,$type) = @_;
472 my $userid = 'cobain';
474 # we don't need to bother about permissions for this test
476 superlibrarian => 1, acquisition => 0,
478 catalogue => 1, circulate => 0,
479 coursereserves => 0, editauthorities => 0,
481 parameters => 0, permissions => 0,
482 plugins => 0, reports => 0,
483 reserveforothers => 0, serials => 0,
484 staffaccess => 0, tools => 0,
488 my $session_cookie = $query->cookie(
489 -name => 'CGISESSID',
494 return ( $userid, [ $session_cookie ], $sessionID, $flags );
497 # Mock checkauth, build the scenario
498 my $auth = Test::MockModule->new( 'C4::Auth' );
499 $auth->mock( 'checkauth', \&MockedCheckauth );
501 # Make sure 'EnableOpacSearchHistory' is set
502 t::lib::Mocks::mock_preference('EnableOpacSearchHistory',1);
503 # Enable es-ES for the OPAC and staff interfaces
504 t::lib::Mocks::mock_preference('OPACLanguages','en,es-ES');
505 t::lib::Mocks::mock_preference('language','en,es-ES');
507 # we need a session cookie
508 $ENV{"SERVER_PORT"} = 80;
509 $ENV{"HTTP_COOKIE"} = 'CGISESSID=nirvana';
511 my $query = CGI->new;
512 $query->param('language','es-ES');
514 my ( $template, $loggedinuser, $cookies ) = get_template_and_user(
516 template_name => "about.tt",
519 authnotrequired => 1,
520 flagsrequired => { catalogue => 1 },
525 ok ( ( all { ref($_) eq 'CGI::Cookie' } @$cookies ),
526 'BZ9735: the cookies array is flat' );
528 # new query, with non-existent language (we only have en and es-ES)
529 $query->param('language','tomas');
531 ( $template, $loggedinuser, $cookies ) = get_template_and_user(
533 template_name => "about.tt",
536 authnotrequired => 1,
537 flagsrequired => { catalogue => 1 },
542 ok( ( none { $_->name eq 'KohaOpacLanguage' and $_->value eq 'tomas' } @$cookies ),
543 'BZ9735: invalid language, it is not set');
545 ok( ( any { $_->name eq 'KohaOpacLanguage' and $_->value eq 'en' } @$cookies ),
546 'BZ9735: invalid language, then default to en');
548 for my $template_name (
550 ../../../../../../../../../../../../../../../etc/passwd
551 test/../../../../../../../../../../../../../../etc/passwd
553 test/does_not_finished_by_tt_t
557 ( $template, $loggedinuser, $cookies ) = get_template_and_user(
559 template_name => $template_name,
562 authnotrequired => 1,
563 flagsrequired => { catalogue => 1 },
567 like ( $@, qr(bad template path), "The file $template_name should not be accessible" );
569 ( $template, $loggedinuser, $cookies ) = get_template_and_user(
571 template_name => 'errors/errorpage.tt',
574 authnotrequired => 1,
575 flagsrequired => { catalogue => 1 },
578 my $file_exists = ( -f $template->{filename} ) ? 1 : 0;
579 is ( $file_exists, 1, 'The file errors/errorpage.tt should be accessible (contains integers)' );
581 # Regression test for env opac search limit override
582 $ENV{"OPAC_SEARCH_LIMIT"} = "branch:CPL";
583 $ENV{"OPAC_LIMIT_OVERRIDE"} = 1;
585 ( $template, $loggedinuser, $cookies) = get_template_and_user(
587 template_name => 'opac-main.tt',
590 authnotrequired => 1,
593 is($template->{VARS}->{'opac_name'}, "CPL", "Opac name was set correctly");
594 is($template->{VARS}->{'opac_search_limit'}, "branch:CPL", "Search limit was set correctly");
596 $ENV{"OPAC_SEARCH_LIMIT"} = "branch:multibranch-19";
598 ( $template, $loggedinuser, $cookies) = get_template_and_user(
600 template_name => 'opac-main.tt',
603 authnotrequired => 1,
606 is($template->{VARS}->{'opac_name'}, "multibranch-19", "Opac name was set correctly");
607 is($template->{VARS}->{'opac_search_limit'}, "branch:multibranch-19", "Search limit was set correctly");
609 delete $ENV{"HTTP_COOKIE"};
612 # Check that there is always an OPACBaseURL set.
613 my $input = CGI->new();
614 my ( $template1, $borrowernumber, $cookie );
615 ( $template1, $borrowernumber, $cookie ) = get_template_and_user(
617 template_name => "opac-detail.tt",
620 authnotrequired => 1,
624 ok( ( any { 'OPACBaseURL' eq $_ } keys %{$template1->{VARS}} ),
625 'OPACBaseURL is in OPAC template' );
628 ( $template2, $borrowernumber, $cookie ) = get_template_and_user(
630 template_name => "catalogue/detail.tt",
633 authnotrequired => 1,
637 ok( ( any { 'OPACBaseURL' eq $_ } keys %{$template2->{VARS}} ),
638 'OPACBaseURL is in Staff template' );
640 my $hash1 = hash_password('password');
641 my $hash2 = hash_password('password');
643 ok(C4::Auth::checkpw_hash('password', $hash1), 'password validates with first hash');
644 ok(C4::Auth::checkpw_hash('password', $hash2), 'password validates with second hash');
646 subtest 'Check value of login_attempts in checkpw' => sub {
649 t::lib::Mocks::mock_preference('FailedLoginAttempts', 3);
651 # Only interested here in regular login
655 my $patron = $builder->build_object({ class => 'Koha::Patrons' });
656 $patron->login_attempts(2);
657 $patron->password('123')->store; # yes, deliberately not hashed
659 is( $patron->account_locked, 0, 'Patron not locked' );
660 my @test = checkpw( $patron->userid, '123', undef, 'opac', 1 );
661 # Note: 123 will not be hashed to 123 !
662 is( $test[0], 0, 'checkpw should have failed' );
663 $patron->discard_changes; # refresh
664 is( $patron->login_attempts, 3, 'Login attempts increased' );
665 is( $patron->account_locked, 1, 'Check locked status' );
667 # And another try to go over the limit: different return value!
668 @test = checkpw( $patron->userid, '123', undef, 'opac', 1 );
669 is( @test, 0, 'checkpw failed again and returns nothing now' );
670 $patron->discard_changes; # refresh
671 is( $patron->login_attempts, 3, 'Login attempts not increased anymore' );
673 # Administrative lockout cannot be undone?
674 # Pass the right password now (or: add a nice mock).
675 my $auth = Test::MockModule->new( 'C4::Auth' );
676 $auth->mock( 'checkpw_hash', sub { return 1; } ); # not for production :)
677 $patron->login_attempts(0)->store;
678 @test = checkpw( $patron->userid, '123', undef, 'opac', 1 );
679 is( $test[0], 1, 'Build confidence in the mock' );
680 $patron->login_attempts(-1)->store;
681 is( $patron->account_locked, 1, 'Check administrative lockout' );
682 @test = checkpw( $patron->userid, '123', undef, 'opac', 1 );
683 is( @test, 0, 'checkpw gave red' );
684 $patron->discard_changes; # refresh
685 is( $patron->login_attempts, -1, 'Still locked out' );
686 t::lib::Mocks::mock_preference('FailedLoginAttempts', ''); # disable
687 is( $patron->account_locked, 1, 'Check administrative lockout without pref' );
690 subtest 'Check value of login_attempts in checkpw' => sub {
693 t::lib::Mocks::mock_preference('FailedLoginAttempts', 3);
694 my $patron = $builder->build_object({ class => 'Koha::Patrons' });
695 $patron->set_password({ password => '123', skip_validation => 1 });
697 my @test = checkpw( $patron->userid, '123', undef, 'opac', 1 );
698 is( $test[0], 1, 'Patron authenticated correctly' );
700 $patron->password_expiration_date('2020-01-01')->store;
701 @test = checkpw( $patron->userid, '123', undef, 'opac', 1 );
702 is( $test[0], -2, 'Patron returned as expired correctly' );
706 subtest '_timeout_syspref' => sub {
710 t::lib::Mocks::mock_preference('timeout', "100");
711 is( C4::Auth::_timeout_syspref, 100, );
713 t::lib::Mocks::mock_preference('timeout', "2d");
714 is( C4::Auth::_timeout_syspref, 2*86400, );
716 t::lib::Mocks::mock_preference('timeout', "2D");
717 is( C4::Auth::_timeout_syspref, 2*86400, );
719 t::lib::Mocks::mock_preference('timeout', "10h");
720 is( C4::Auth::_timeout_syspref, 10*3600, );
722 t::lib::Mocks::mock_preference('timeout', "10x");
724 { is( C4::Auth::_timeout_syspref, 600, ); }
725 "The value of the system preference 'timeout' is not correct, defaulting to 600",
726 'Bad values throw a warning and fallback to 600';
729 subtest 'check_cookie_auth' => sub {
732 t::lib::Mocks::mock_preference('timeout', "1d"); # back to default
734 my $patron = $builder->build_object({ class => 'Koha::Patrons', value => { flags => 1 } });
736 # Mock a CGI object with real userid param
737 my $cgi = Test::MockObject->new();
742 if ( $var eq 'userid' ) { return $patron->userid; }
745 $cgi->mock('multi_param', sub {return q{}} );
746 $cgi->mock( 'cookie', sub { return; } );
747 $cgi->mock( 'request_method', sub { return 'POST' } );
749 $ENV{REMOTE_ADDR} = '127.0.0.1';
751 # Setting authnotrequired=1 or we wont' hit the return but the end of the sub that prints headers
752 my ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 1 );
754 my ($auth_status, $session) = C4::Auth::check_cookie_auth($sessionID);
755 isnt( $auth_status, 'ok', 'check_cookie_auth should not return ok if the user has not been authenticated before if no permissions needed' );
756 is( $auth_status, 'anon', 'check_cookie_auth should return anon if the user has not been authenticated before and no permissions needed' );
758 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 1 );
760 ($auth_status, $session) = C4::Auth::check_cookie_auth($sessionID, {catalogue => 1});
761 isnt( $auth_status, 'ok', 'check_cookie_auth should not return ok if the user has not been authenticated before and permissions needed' );
762 is( $auth_status, 'anon', 'check_cookie_auth should return anon if the user has not been authenticated before and permissions needed' );
764 #FIXME We should have a test to cover 'failed' status when a user has logged in, but doesn't have permission
767 subtest 'checkauth & check_cookie_auth' => sub {
770 # flags = 4 => { catalogue => 1 }
771 my $patron = $builder->build_object({ class => 'Koha::Patrons', value => { flags => 4 } });
772 my $password = set_weak_password($patron);
774 my $cgi_mock = Test::MockModule->new('CGI');
775 $cgi_mock->mock( 'request_method', sub { return 'POST' } );
779 my $auth = Test::MockModule->new( 'C4::Auth' );
780 # Tests will fail if we hit safe_exit
781 $auth->mock( 'safe_exit', sub { return } );
783 my ( $userid, $cookie, $sessionID, $flags );
785 # checkauth will redirect and safe_exit if not authenticated and not authorized
788 open STDOUT, '>', \$stdout;
789 C4::Auth::checkauth($cgi, 0, {catalogue => 1});
790 like( $stdout, qr{<title>\s*Log in to your account} );
791 $sessionID = ( $stdout =~ m{Set-Cookie: CGISESSID=((\d|\w)+);} ) ? $1 : undef;
796 my $first_sessionID = $sessionID;
798 $ENV{"HTTP_COOKIE"} = "CGISESSID=$sessionID";
799 # Not authenticated yet, the login form is displayed
801 ( $userid, $cookie, $sessionID, $flags, $template ) = C4::Auth::checkauth($cgi, 0, {catalogue => 1}, 'intranet', undef, undef, { do_not_print => 1 } );
802 is( $template->{VARS}->{loginprompt}, 1, );
804 # Sending undefined fails obviously
805 my ( $auth_status, $session ) = C4::Auth::check_cookie_auth($sessionID, {catalogue => 1} );
806 is( $auth_status, 'failed' );
807 is( $session, undef );
809 # Simulating the login form submission
810 $cgi->param('userid', $patron->userid);
811 $cgi->param('password', $password);
814 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 0, {catalogue => 1});
815 is( $sessionID, $first_sessionID );
816 is( $userid, $patron->userid );
818 ( $auth_status, $session ) = C4::Auth::check_cookie_auth($sessionID, {catalogue => 1});
819 is( $auth_status, 'ok' );
820 is( $session->id, $first_sessionID );
822 my $patron_to_delete = $builder->build_object({ class => 'Koha::Patrons' });
823 my $fresh_userid = $patron_to_delete->userid;
824 $patron_to_delete->delete;
825 my $old_userid = $patron->userid;
827 # change the current session user's userid
828 $patron->userid( $fresh_userid )->store;
829 ( $auth_status, $session ) = C4::Auth::check_cookie_auth($sessionID, {catalogue => 1});
830 is( $auth_status, 'expired' );
831 is( $session, undef );
833 # restore userid and generate a new session
834 $patron->userid($old_userid)->store;
835 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 0, {catalogue => 1});
836 is( $sessionID, $first_sessionID );
837 is( $userid, $patron->userid );
840 $cgi->param('logout.x', 1);
841 $cgi->delete( 'userid', 'password' );
842 ( $userid, $cookie, $sessionID, $flags, $template ) =
843 C4::Auth::checkauth( $cgi, 0, { catalogue => 1 }, 'intranet', undef, undef, { do_not_print => 1 } );
845 is( $sessionID, undef );
846 is( $ENV{"HTTP_COOKIE"}, "CGISESSID=$first_sessionID", 'HTTP_COOKIE not unset' );
847 ( $auth_status, $session) = C4::Auth::check_cookie_auth( $first_sessionID, {catalogue => 1} );
848 is( $auth_status, "expired");
849 is( $session, undef );
852 # Trying to access without sessionID
854 ( $auth_status, $session) = C4::Auth::check_cookie_auth(undef, {catalogue => 1});
855 is( $auth_status, 'failed' );
856 is( $session, undef );
858 # This will fail on permissions
859 undef $ENV{"HTTP_COOKIE"};
863 open STDOUT, '>', \$stdout;
864 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 0, {catalogue => 1} );
867 is( $userid, undef );
868 is( $sessionID, undef );
874 $cgi->param('userid', $patron->userid);
875 $cgi->param('password', $password);
876 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 0, {catalogue => 1});
877 is( $userid, $patron->userid );
878 $first_sessionID = $sessionID;
880 # Patron does not have the borrowers permission
881 # $ENV{"HTTP_COOKIE"} = "CGISESSID=$sessionID"; # not needed, we use $cgi here
885 open STDOUT, '>', \$stdout;
886 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 0, {borrowers => 1} );
889 is( $userid, undef );
890 is( $sessionID, undef );
892 # When calling check_cookie_auth, the session will be deleted
893 ( $auth_status, $session) = C4::Auth::check_cookie_auth( $first_sessionID, { borrowers => 1 } );
894 is( $auth_status, "failed" );
895 is( $session, undef );
896 ( $auth_status, $session) = C4::Auth::check_cookie_auth( $first_sessionID, { borrowers => 1 } );
897 is( $auth_status, 'expired', 'Session no longer exists' );
899 # NOTE: It is not what the UI is doing.
900 # From the UI we are allowed to hit an unauthorized page then reuse the session to hit back authorized area.
901 # It is because check_cookie_auth is ALWAYS called from checkauth WITHOUT $flagsrequired
902 # It then return "ok", when the previous called got "failed"
904 # Try reusing the deleted session: since it does not exist, we should get a new one now when passing correct permissions
905 $cgi->cookie( -name => 'CGISESSID', value => $first_sessionID );
906 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 0, {catalogue => 1});
907 is( $userid, $patron->userid );
908 isnt( $sessionID, undef, 'Check if we have a sessionID' );
909 isnt( $sessionID, $first_sessionID, 'New value expected' );
910 ( $auth_status, $session) = C4::Auth::check_cookie_auth( $sessionID, {catalogue => 1} );
911 is( $auth_status, "ok" );
912 is( $session->id, $sessionID, 'Same session' );
913 # Two additional tests on userenv
914 is( $C4::Context::context->{activeuser}, $session->id, 'Check if environment has been setup for session' );
915 is( C4::Context->userenv->{id}, $userid, 'Check userid in userenv' );
919 subtest 'Userenv clearing in check_cookie_auth' => sub {
920 # Note: We did already test userenv for a logged-in user in previous subtest
923 t::lib::Mocks::mock_preference( 'timeout', 600 );
926 # Create a new anonymous session by passing a fake session ID
927 $cgi->cookie( -name => 'CGISESSID', -value => 'fake_sessionID' );
928 my ($userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 1);
929 my ( $auth_status, $session) = C4::Auth::check_cookie_auth( $sessionID );
930 is( $auth_status, 'anon', 'Should be anonymous' );
931 is( $C4::Context::context->{activeuser}, $session->id, 'Check activeuser' );
932 is( defined C4::Context->userenv, 1, 'There should be a userenv' );
933 is( C4::Context->userenv->{id}, q{}, 'userid should be empty string' );
935 # Make the session expire now, check_cookie_auth will delete it
936 $session->param('lasttime', time() - 1200 );
938 ( $auth_status, $session) = C4::Auth::check_cookie_auth( $sessionID );
939 is( $auth_status, 'expired', 'Should be expired' );
940 is( C4::Context->userenv, undef, 'Environment should be cleared too' );
942 # Show that we clear the userenv again: set up env and check deleted session
943 C4::Context->_new_userenv( $sessionID );
944 C4::Context->set_userenv; # empty
945 is( defined C4::Context->userenv, 1, 'There should be an empty userenv again' );
946 ( $auth_status, $session) = C4::Auth::check_cookie_auth( $sessionID );
947 is( $auth_status, 'expired', 'Should be expired already' );
948 is( C4::Context->userenv, undef, 'Environment should be cleared again' );
951 subtest 'create_basic_session tests' => sub {
954 my $patron = $builder->build_object({ class => 'Koha::Patrons' });
956 my $session = C4::Auth::create_basic_session({ patron => $patron, interface => 'opac' });
958 isnt($session->id, undef, 'A new sessionID was created');
959 is( $session->param('number'), $patron->borrowernumber, 'Session parameter number matches' );
960 is( $session->param('id'), $patron->userid, 'Session parameter id matches' );
961 is( $session->param('cardnumber'), $patron->cardnumber, 'Session parameter cardnumber matches' );
962 is( $session->param('firstname'), $patron->firstname, 'Session parameter firstname matches' );
963 is( $session->param('surname'), $patron->surname, 'Session parameter surname matches' );
964 is( $session->param('branch'), $patron->branchcode, 'Session parameter branch matches' );
965 is( $session->param('branchname'), $patron->library->branchname, 'Session parameter branchname matches' );
966 is( $session->param('flags'), $patron->flags, 'Session parameter flags matches' );
967 is( $session->param('emailaddress'), $patron->email, 'Session parameter emailaddress matches' );
968 is( $session->param('ip'), $session->remote_addr(), 'Session parameter ip matches' );
969 is( $session->param('interface'), 'opac', 'Session parameter interface matches' );
971 $session = C4::Auth::create_basic_session({ patron => $patron, interface => 'staff' });
972 is( $session->param('interface'), 'intranet', 'Staff interface gets converted to intranet' );
975 subtest 'check_cookie_auth overwriting interface already set' => sub {
978 t::lib::Mocks::mock_preference( 'SessionRestrictionByIP', 0 );
980 my $patron = $builder->build_object({ class => 'Koha::Patrons' });
981 my $session = C4::Auth::get_session();
982 $session->param( 'number', $patron->id );
983 $session->param( 'id', $patron->userid );
984 $session->param( 'ip', '1.2.3.4' );
985 $session->param( 'lasttime', time() );
986 $session->param( 'interface', 'opac' );
989 C4::Context->interface('intranet');
990 C4::Auth::check_cookie_auth( $session->id );
991 is( C4::Context->interface, 'intranet', 'check_cookie_auth did not overwrite' );
992 delete $C4::Context::context->{interface}; # clear context interface
993 C4::Auth::check_cookie_auth( $session->id );
994 is( C4::Context->interface, 'opac', 'check_cookie_auth used interface from session when context interface was empty' );
996 t::lib::Mocks::mock_preference( 'SessionRestrictionByIP', 1 );
999 $schema->storage->txn_rollback;
1001 subtest 'get_cataloguing_page_permissions() tests' => sub {
1005 $schema->storage->txn_begin;
1007 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { flags => 2**2 } } ); # catalogue
1010 !C4::Auth::haspermission( $patron->userid, get_cataloguing_page_permissions() ),
1011 '"catalogue" is not enough to see the cataloguing page'
1016 source => 'UserPermission',
1018 borrowernumber => $patron->id,
1019 module_bit => 24, # stockrotation
1020 code => 'manage_rotas',
1025 t::lib::Mocks::mock_preference( 'StockRotation', 1 );
1027 C4::Auth::haspermission( $patron->userid, get_cataloguing_page_permissions() ),
1028 '"stockrotation => manage_rotas" is enough'
1031 t::lib::Mocks::mock_preference( 'StockRotation', 0 );
1033 !C4::Auth::haspermission( $patron->userid, get_cataloguing_page_permissions() ),
1034 '"stockrotation => manage_rotas" is not enough when `StockRotation` is disabled'
1039 source => 'UserPermission',
1041 borrowernumber => $patron->id,
1042 module_bit => 13, # tools
1043 code => 'manage_staged_marc',
1049 C4::Auth::haspermission( $patron->userid, get_cataloguing_page_permissions() ),
1050 'Having one of the listed `tools` subperm is enough'
1053 $schema->resultset('UserPermission')->search( { borrowernumber => $patron->id } )->delete;
1056 !C4::Auth::haspermission( $patron->userid, get_cataloguing_page_permissions() ),
1057 'Permission removed, no access'
1062 source => 'UserPermission',
1064 borrowernumber => $patron->id,
1065 module_bit => 9, # editcatalogue
1066 code => 'delete_all_items',
1072 C4::Auth::haspermission( $patron->userid, get_cataloguing_page_permissions() ),
1073 'Having any `editcatalogue` subperm is enough'
1076 $schema->storage->txn_rollback;
1079 subtest 'checkpw() return values tests' => sub {
1083 subtest 'Internal check tests' => sub {
1087 $schema->storage->txn_begin;
1090 my $password_expired;
1092 my $mock_patron = Test::MockModule->new('Koha::Patron');
1093 $mock_patron->mock( 'account_locked', sub { return $account_locked; } );
1094 $mock_patron->mock( 'password_expired', sub { return $password_expired; } );
1096 # Only interested here in regular login
1097 t::lib::Mocks::mock_config( 'useshibboleth', undef );
1099 $C4::Auth::ldap = 0;
1101 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
1102 my $password = set_weak_password($patron);
1104 my $patron_to_delete = $builder->build_object( { class => 'Koha::Patrons' } );
1105 my $unused_userid = $patron_to_delete->userid;
1106 my $unused_cardnumber = $patron_to_delete->cardnumber;
1107 $patron_to_delete->delete;
1109 $account_locked = 1;
1110 my @return = checkpw( $patron->userid, $password, undef, );
1111 is_deeply( \@return, [], 'If the account is locked, empty list is returned' );
1113 $account_locked = 0;
1115 my @matchpoints = qw(userid cardnumber);
1116 foreach my $matchpoint (@matchpoints) {
1118 @return = checkpw( $patron->$matchpoint, $password, undef, );
1120 is( $return[0], 1, "Password validation successful returns 1 ($matchpoint)" );
1121 is( $return[1], $patron->cardnumber, '`cardnumber` returned' );
1122 is( $return[2], $patron->userid, '`userid` returned' );
1123 is( ref( $return[3] ), 'Koha::Patron', 'Koha::Patron object reference returned' );
1124 is( $return[3]->id, $patron->id, 'Correct patron returned' );
1127 @return = checkpw( $patron->userid, $password . 'hey', undef, );
1129 is( scalar @return, 2, "Two results on invalid password scenario" );
1130 is( $return[0], 0, '0 returned on invalid password' );
1131 is( ref( $return[1] ), 'Koha::Patron' );
1132 is( $return[1]->id, $patron->id, 'Patron matched correctly' );
1134 $password_expired = 1;
1135 @return = checkpw( $patron->userid, $password, undef, );
1137 is( scalar @return, 2, "Two results on expired password scenario" );
1138 is( $return[0], -2, '-2 returned' );
1139 is( ref( $return[1] ), 'Koha::Patron' );
1140 is( $return[1]->id, $patron->id, 'Patron matched correctly' );
1142 @return = checkpw( $unused_userid, $password, undef, );
1144 is( scalar @return, 2, "Two results on non-existing userid scenario" );
1145 is( $return[0], 0, '0 returned' );
1146 is( $return[1], undef, 'Undef returned, representing no match' );
1148 @return = checkpw( $unused_cardnumber, $password, undef, );
1150 is( scalar @return, 2, "Only one result on non-existing cardnumber scenario" );
1151 is( $return[0], 0, '0 returned' );
1152 is( $return[1], undef, 'Undef returned, representing no match' );
1154 $schema->storage->txn_rollback;
1157 subtest 'CAS check (mocked) tests' => sub {
1161 $schema->storage->txn_begin;
1164 my $password_expired;
1166 my $mock_patron = Test::MockModule->new('Koha::Patron');
1167 $mock_patron->mock( 'account_locked', sub { return $account_locked; } );
1168 $mock_patron->mock( 'password_expired', sub { return $password_expired; } );
1170 # Only interested here in regular login
1171 t::lib::Mocks::mock_config( 'useshibboleth', undef );
1173 $C4::Auth::ldap = 0;
1175 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
1176 my $password = 'thePassword123';
1177 $patron->set_password( { password => $password, skip_validation => 1 } );
1179 my $patron_to_delete = $builder->build_object( { class => 'Koha::Patrons' } );
1180 my $unused_userid = $patron_to_delete->userid;
1181 my $unused_cardnumber = $patron_to_delete->cardnumber;
1182 $patron_to_delete->delete;
1184 my $ticket = '123456';
1185 my $query = CGI->new;
1186 $query->param( -name => 'ticket', -value => $ticket );
1188 my @cas_return = ( 1, $patron->cardnumber, $patron->userid, $ticket, Koha::Patrons->find( $patron->id ) );
1190 my $cas_mock = Test::MockModule->new('C4::Auth');
1191 $cas_mock->mock( 'checkpw_cas', sub { return @cas_return; } );
1193 $account_locked = 1;
1194 my @return = checkpw( $patron->userid, $password, $query, );
1195 is_deeply( \@return, [], 'If the account is locked, empty list is returned' );
1197 $account_locked = 0;
1199 my @matchpoints = qw(userid cardnumber);
1200 foreach my $matchpoint (@matchpoints) {
1202 @return = checkpw( $patron->$matchpoint, $password, $query, );
1204 is( $return[0], 1, "Password validation successful returns 1 ($matchpoint)" );
1205 is( $return[1], $patron->cardnumber, '`cardnumber` returned' );
1206 is( $return[2], $patron->userid, '`userid` returned' );
1207 is( ref( $return[3] ), 'Koha::Patron', 'Koha::Patron object reference returned' );
1208 is( $return[3]->id, $patron->id, 'Correct patron returned' );
1211 @return = checkpw( $patron->userid, $password . 'hey', $query, );
1213 is( scalar @return, 2, "Two results on invalid password scenario" );
1214 is( $return[0], 0, '0 returned on invalid password' );
1215 is( ref( $return[1] ), 'Koha::Patron' );
1216 is( $return[1]->id, $patron->id, 'Patron matched correctly' );
1218 $password_expired = 1;
1219 @return = checkpw( $patron->userid, $password, $query, );
1221 is( scalar @return, 2, "Two results on expired password scenario" );
1222 is( $return[0], -2, '-2 returned' );
1223 is( ref( $return[1] ), 'Koha::Patron' );
1224 is( $return[1]->id, $patron->id, 'Patron matched correctly' );
1226 @return = checkpw( $unused_userid, $password, $query, );
1228 is( scalar @return, 2, "Two results on non-existing userid scenario" );
1229 is( $return[0], 0, '0 returned' );
1230 is( $return[1], undef, 'Undef returned, representing no match' );
1232 @return = checkpw( $unused_cardnumber, $password, $query, );
1234 is( scalar @return, 2, "Only one result on non-existing cardnumber scenario" );
1235 is( $return[0], 0, '0 returned' );
1236 is( $return[1], undef, 'Undef returned, representing no match' );
1238 $schema->storage->txn_rollback;
1241 subtest 'Shibboleth check (mocked) tests' => sub {
1245 $schema->storage->txn_begin;
1248 my $password_expired;
1250 my $mock_patron = Test::MockModule->new('Koha::Patron');
1251 $mock_patron->mock( 'account_locked', sub { return $account_locked; } );
1252 $mock_patron->mock( 'password_expired', sub { return $password_expired; } );
1254 # Only interested here in regular login
1255 t::lib::Mocks::mock_config( 'useshibboleth', 1 );
1257 $C4::Auth::ldap = 0;
1259 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
1260 my $password = 'thePassword123';
1261 $patron->set_password( { password => $password, skip_validation => 1 } );
1263 my $patron_to_delete = $builder->build_object( { class => 'Koha::Patrons' } );
1264 my $unused_userid = $patron_to_delete->userid;
1265 my $unused_cardnumber = $patron_to_delete->cardnumber;
1266 $patron_to_delete->delete;
1268 my @shib_return = ( 1, $patron->cardnumber, $patron->userid, Koha::Patrons->find( $patron->id ) );
1270 my $auth_mock = Test::MockModule->new('C4::Auth');
1271 $auth_mock->mock( 'shib_ok', 1 );
1272 $auth_mock->mock( 'get_login_shib', 1 );
1274 my $shib_mock = Test::MockModule->new('C4::Auth_with_shibboleth');
1275 $shib_mock->mock( 'checkpw_shib', sub { return @shib_return; } );
1277 $account_locked = 1;
1278 my @return = checkpw( $patron->userid );
1279 is_deeply( \@return, [], 'If the account is locked, empty list is returned' );
1281 $account_locked = 0;
1283 @return = checkpw();
1285 is( $return[0], 1, "Password validation successful returns 1" );
1286 is( $return[1], $patron->cardnumber, '`cardnumber` returned' );
1287 is( $return[2], $patron->userid, '`userid` returned' );
1288 is( ref( $return[3] ), 'Koha::Patron', 'Koha::Patron object reference returned' );
1289 is( $return[3]->id, $patron->id, 'Correct patron returned' );
1291 $schema->storage->txn_rollback;
1295 subtest 'AutoLocation' => sub {
1299 $schema->storage->txn_begin;
1301 t::lib::Mocks::mock_preference( 'AutoLocation', 0 );
1303 my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { flags => 1 } } );
1304 my $password = 'password';
1305 t::lib::Mocks::mock_preference( 'RequireStrongPassword', 0 );
1306 $patron->set_password( { password => $password } );
1308 my $cgi_mock = Test::MockModule->new('CGI');
1309 $cgi_mock->mock( 'request_method', sub { return 'POST' } );
1311 my $auth = Test::MockModule->new('C4::Auth');
1313 # Simulating the login form submission
1314 $cgi->param( 'userid', $patron->userid );
1315 $cgi->param( 'password', $password );
1317 $ENV{REMOTE_ADDR} = '127.0.0.1';
1318 my ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 0, { catalogue => 1 }, 'intranet' );
1319 is( $userid, $patron->userid );
1322 t::lib::Mocks::mock_preference( 'AutoLocation', 1 );
1324 # AutoLocation: "Require staff to log in from a computer in the IP address range specified by their library (if any)"
1325 $patron->library->branchip('')->store; # There is none, allow access from anywhere
1326 ( $userid, $cookie, $sessionID, $flags, $template ) =
1327 C4::Auth::checkauth( $cgi, 0, { catalogue => 1 }, 'intranet' );
1328 is( $userid, $patron->userid );
1329 is( $template, undef );
1331 $patron->library->branchip('1.2.3.4')->store;
1332 ( $userid, $cookie, $sessionID, $flags, $template ) =
1333 C4::Auth::checkauth( $cgi, 0, { catalogue => 1 }, 'intranet', undef, undef, { do_not_print => 1 } );
1334 is( $template->{VARS}->{wrongip}, 1 );
1336 $patron->library->branchip('127.0.0.1')->store;
1337 ( $userid, $cookie, $sessionID, $flags, $template ) =
1338 C4::Auth::checkauth( $cgi, 0, { catalogue => 1 }, 'intranet' );
1339 is( $userid, $patron->userid );
1340 is( $template, undef );
1342 my $other_library = $builder->build_object( { class => 'Koha::Libraries', value => { branchip => '127.0.0.1' } } );
1343 $patron->library->branchip('127.0.0.1')->store;
1344 ( $userid, $cookie, $sessionID, $flags, $template ) =
1345 C4::Auth::checkauth( $cgi, 0, { catalogue => 1 }, 'intranet' );
1346 my $session = C4::Auth::get_session($sessionID);
1347 is( $session->param('branch'), $patron->branchcode );
1349 $schema->storage->txn_rollback;
1353 sub set_weak_password {
1355 my $password = 'password';
1356 t::lib::Mocks::mock_preference( 'RequireStrongPassword', 0 );
1357 $patron->set_password( { password => $password } );