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 => 24;
16 use t::lib::TestBuilder;
19 use Koha::AuthUtils qw/hash_password/;
24 use_ok('C4::Auth', qw( checkauth haspermission track_login_daily checkpw get_template_and_user checkpw_hash ));
27 my $schema = Koha::Database->schema;
28 my $builder = t::lib::TestBuilder->new;
29 my $dbh = C4::Context->dbh;
31 # FIXME: SessionStorage defaults to mysql, but it seems to break transaction
33 t::lib::Mocks::mock_preference( 'SessionStorage', 'tmp' );
34 t::lib::Mocks::mock_preference( 'GDPR_Policy', '' ); # Disabled
36 $schema->storage->txn_begin;
38 subtest 'checkauth() tests' => sub {
42 my $patron = $builder->build_object({ class => 'Koha::Patrons', value => { flags => undef } });
44 # Mock a CGI object with real userid param
45 my $cgi = Test::MockObject->new();
50 if ( $var eq 'userid' ) { return $patron->userid; }
53 $cgi->mock( 'cookie', sub { return; } );
54 $cgi->mock( 'request_method', sub { return 'POST' } );
56 my $authnotrequired = 1;
57 my ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, $authnotrequired );
59 is( $userid, undef, 'checkauth() returns undef for userid if no logged in user (Bug 18275)' );
61 my $db_user_id = C4::Context->config('user');
62 my $db_user_pass = C4::Context->config('pass');
63 $cgi = Test::MockObject->new();
64 $cgi->mock( 'cookie', sub { return; } );
65 $cgi->mock( 'param', sub {
66 my ( $self, $param ) = @_;
67 if ( $param eq 'userid' ) { return $db_user_id; }
68 elsif ( $param eq 'password' ) { return $db_user_pass; }
71 $cgi->mock( 'request_method', sub { return 'POST' } );
72 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, $authnotrequired );
73 is ( $userid, undef, 'If DB user is used, it should not be logged in' );
75 my $is_allowed = C4::Auth::haspermission( $db_user_id, { can_do => 'everything' } );
77 # FIXME This belongs to t/db_dependent/Auth/haspermission.t but we do not want to c/p the pervious mock statements
78 ok( !$is_allowed, 'DB user should not have any permissions');
80 subtest 'Prevent authentication when sending credential via GET' => sub {
84 my $patron = $builder->build_object(
85 { class => 'Koha::Patrons', value => { flags => 1 } } );
86 my $password = 'password';
87 t::lib::Mocks::mock_preference( 'RequireStrongPassword', 0 );
88 $patron->set_password( { password => $password } );
89 $cgi = Test::MockObject->new();
90 $cgi->mock( 'cookie', sub { return; } );
94 my ( $self, $param ) = @_;
95 if ( $param eq 'userid' ) { return $patron->userid; }
96 elsif ( $param eq 'password' ) { return $password; }
101 $cgi->mock( 'request_method', sub { return 'POST' } );
102 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired' );
103 is( $userid, $patron->userid, 'If librarian user is used and password with POST, they should be logged in' );
105 $cgi->mock( 'request_method', sub { return 'GET' } );
106 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired' );
107 is( $userid, undef, 'If librarian user is used and password with GET, they should not be logged in' );
110 C4::Context->_new_userenv; # For next tests
114 subtest 'track_login_daily tests' => sub {
118 my $patron = $builder->build_object({ class => 'Koha::Patrons' });
119 my $userid = $patron->userid;
121 $patron->lastseen( undef );
124 my $cache = Koha::Caches->get_instance();
125 my $cache_key = "track_login_" . $patron->userid;
126 $cache->clear_from_cache($cache_key);
128 t::lib::Mocks::mock_preference( 'TrackLastPatronActivity', '1' );
130 is( $patron->lastseen, undef, 'Patron should have not last seen when newly created' );
132 C4::Auth::track_login_daily( $userid );
133 $patron->_result()->discard_changes();
134 isnt( $patron->lastseen, undef, 'Patron should have last seen set when TrackLastPatronActivity = 1' );
136 sleep(1); # We need to wait a tiny bit to make sure the timestamp will be different
137 my $last_seen = $patron->lastseen;
138 C4::Auth::track_login_daily( $userid );
139 $patron->_result()->discard_changes();
140 is( $patron->lastseen, $last_seen, 'Patron last seen should still be unchanged' );
142 $cache->clear_from_cache($cache_key);
143 C4::Auth::track_login_daily( $userid );
144 $patron->_result()->discard_changes();
145 isnt( $patron->lastseen, $last_seen, 'Patron last seen should be changed if we cleared the cache' );
147 t::lib::Mocks::mock_preference( 'TrackLastPatronActivity', '0' );
148 $patron->lastseen( undef )->store;
149 $cache->clear_from_cache($cache_key);
150 C4::Auth::track_login_daily( $userid );
151 $patron->_result()->discard_changes();
152 is( $patron->lastseen, undef, 'Patron should still have last seen unchanged when TrackLastPatronActivity = 0' );
156 subtest 'no_set_userenv parameter tests' => sub {
160 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
161 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
162 my $password = 'password';
164 t::lib::Mocks::mock_preference( 'RequireStrongPassword', 0 );
165 $patron->set_password({ password => $password });
167 ok( checkpw( $dbh, $patron->userid, $password, undef, undef, 1 ), 'checkpw returns true' );
168 is( C4::Context->userenv, undef, 'Userenv should be undef as required' );
169 C4::Context->_new_userenv('DUMMY SESSION');
170 C4::Context->set_userenv(0,0,0,'firstname','surname', $library->branchcode, 'Library 1', 0, '', '');
171 is( C4::Context->userenv->{branch}, $library->branchcode, 'Userenv gives correct branch' );
172 ok( checkpw( $dbh, $patron->userid, $password, undef, undef, 1 ), 'checkpw returns true' );
173 is( C4::Context->userenv->{branch}, $library->branchcode, 'Userenv branch is preserved if no_set_userenv is true' );
174 ok( checkpw( $dbh, $patron->userid, $password, undef, undef, 0 ), 'checkpw still returns true' );
175 isnt( C4::Context->userenv->{branch}, $library->branchcode, 'Userenv branch is overwritten if no_set_userenv is false' );
178 subtest 'checkpw lockout tests' => sub {
182 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
183 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
184 my $password = 'password';
185 t::lib::Mocks::mock_preference( 'RequireStrongPassword', 0 );
186 t::lib::Mocks::mock_preference( 'FailedLoginAttempts', 1 );
187 $patron->set_password({ password => $password });
189 my ( $checkpw, undef, undef ) = checkpw( $dbh, $patron->cardnumber, $password, undef, undef, 1 );
190 ok( $checkpw, 'checkpw returns true with right password when logging in via cardnumber' );
191 ( $checkpw, undef, undef ) = checkpw( $dbh, $patron->userid, "wrong_password", undef, undef, 1 );
192 is( $checkpw, 0, 'checkpw returns false when given wrong password' );
193 $patron = $patron->get_from_storage;
194 is( $patron->account_locked, 1, "Account is locked from failed login");
195 ( $checkpw, undef, undef ) = checkpw( $dbh, $patron->userid, $password, undef, undef, 1 );
196 is( $checkpw, undef, 'checkpw returns undef with right password when account locked' );
197 ( $checkpw, undef, undef ) = checkpw( $dbh, $patron->cardnumber, $password, undef, undef, 1 );
198 is( $checkpw, undef, 'checkpw returns undefwith right password when logging in via cardnumber if account locked' );
202 # get_template_and_user tests
204 { # Tests for the language URL parameter
206 sub MockedCheckauth {
207 my ($query,$authnotrequired,$flagsrequired,$type) = @_;
209 my $userid = 'cobain';
211 # we don't need to bother about permissions for this test
213 superlibrarian => 1, acquisition => 0,
215 catalogue => 1, circulate => 0,
216 coursereserves => 0, editauthorities => 0,
218 parameters => 0, permissions => 0,
219 plugins => 0, reports => 0,
220 reserveforothers => 0, serials => 0,
221 staffaccess => 0, tools => 0,
225 my $session_cookie = $query->cookie(
226 -name => 'CGISESSID',
231 return ( $userid, $session_cookie, $sessionID, $flags );
234 # Mock checkauth, build the scenario
235 my $auth = Test::MockModule->new( 'C4::Auth' );
236 $auth->mock( 'checkauth', \&MockedCheckauth );
238 # Make sure 'EnableOpacSearchHistory' is set
239 t::lib::Mocks::mock_preference('EnableOpacSearchHistory',1);
240 # Enable es-ES for the OPAC and staff interfaces
241 t::lib::Mocks::mock_preference('OPACLanguages','en,es-ES');
242 t::lib::Mocks::mock_preference('language','en,es-ES');
244 # we need a session cookie
245 $ENV{"SERVER_PORT"} = 80;
246 $ENV{"HTTP_COOKIE"} = 'CGISESSID=nirvana';
248 my $query = CGI->new;
249 $query->param('language','es-ES');
251 my ( $template, $loggedinuser, $cookies ) = get_template_and_user(
253 template_name => "about.tt",
256 authnotrequired => 1,
257 flagsrequired => { catalogue => 1 },
262 ok ( ( all { ref($_) eq 'CGI::Cookie' } @$cookies ),
263 'BZ9735: the cookies array is flat' );
265 # new query, with non-existent language (we only have en and es-ES)
266 $query->param('language','tomas');
268 ( $template, $loggedinuser, $cookies ) = get_template_and_user(
270 template_name => "about.tt",
273 authnotrequired => 1,
274 flagsrequired => { catalogue => 1 },
279 ok( ( none { $_->name eq 'KohaOpacLanguage' and $_->value eq 'tomas' } @$cookies ),
280 'BZ9735: invalid language, it is not set');
282 ok( ( any { $_->name eq 'KohaOpacLanguage' and $_->value eq 'en' } @$cookies ),
283 'BZ9735: invalid language, then default to en');
285 for my $template_name (
287 ../../../../../../../../../../../../../../../etc/passwd
288 test/../../../../../../../../../../../../../../etc/passwd
290 test/does_not_finished_by_tt_t
294 ( $template, $loggedinuser, $cookies ) = get_template_and_user(
296 template_name => $template_name,
299 authnotrequired => 1,
300 flagsrequired => { catalogue => 1 },
304 like ( $@, qr(bad template path), "The file $template_name should not be accessible" );
306 ( $template, $loggedinuser, $cookies ) = get_template_and_user(
308 template_name => 'errors/errorpage.tt',
311 authnotrequired => 1,
312 flagsrequired => { catalogue => 1 },
315 my $file_exists = ( -f $template->{filename} ) ? 1 : 0;
316 is ( $file_exists, 1, 'The file errors/errorpage.tt should be accessible (contains integers)' );
318 # Regression test for env opac search limit override
319 $ENV{"OPAC_SEARCH_LIMIT"} = "branch:CPL";
320 $ENV{"OPAC_LIMIT_OVERRIDE"} = 1;
322 ( $template, $loggedinuser, $cookies) = get_template_and_user(
324 template_name => 'opac-main.tt',
327 authnotrequired => 1,
330 is($template->{VARS}->{'opac_name'}, "CPL", "Opac name was set correctly");
331 is($template->{VARS}->{'opac_search_limit'}, "branch:CPL", "Search limit was set correctly");
333 $ENV{"OPAC_SEARCH_LIMIT"} = "branch:multibranch-19";
335 ( $template, $loggedinuser, $cookies) = get_template_and_user(
337 template_name => 'opac-main.tt',
340 authnotrequired => 1,
343 is($template->{VARS}->{'opac_name'}, "multibranch-19", "Opac name was set correctly");
344 is($template->{VARS}->{'opac_search_limit'}, "branch:multibranch-19", "Search limit was set correctly");
347 # Check that there is always an OPACBaseURL set.
348 my $input = CGI->new();
349 my ( $template1, $borrowernumber, $cookie );
350 ( $template1, $borrowernumber, $cookie ) = get_template_and_user(
352 template_name => "opac-detail.tt",
355 authnotrequired => 1,
359 ok( ( any { 'OPACBaseURL' eq $_ } keys %{$template1->{VARS}} ),
360 'OPACBaseURL is in OPAC template' );
363 ( $template2, $borrowernumber, $cookie ) = get_template_and_user(
365 template_name => "catalogue/detail.tt",
368 authnotrequired => 1,
372 ok( ( any { 'OPACBaseURL' eq $_ } keys %{$template2->{VARS}} ),
373 'OPACBaseURL is in Staff template' );
375 my $hash1 = hash_password('password');
376 my $hash2 = hash_password('password');
378 ok(C4::Auth::checkpw_hash('password', $hash1), 'password validates with first hash');
379 ok(C4::Auth::checkpw_hash('password', $hash2), 'password validates with second hash');
381 subtest 'Check value of login_attempts in checkpw' => sub {
384 t::lib::Mocks::mock_preference('FailedLoginAttempts', 3);
386 # Only interested here in regular login
390 my $patron = $builder->build_object({ class => 'Koha::Patrons' });
391 $patron->login_attempts(2);
392 $patron->password('123')->store; # yes, deliberately not hashed
394 is( $patron->account_locked, 0, 'Patron not locked' );
395 my @test = checkpw( $dbh, $patron->userid, '123', undef, 'opac', 1 );
396 # Note: 123 will not be hashed to 123 !
397 is( $test[0], 0, 'checkpw should have failed' );
398 $patron->discard_changes; # refresh
399 is( $patron->login_attempts, 3, 'Login attempts increased' );
400 is( $patron->account_locked, 1, 'Check locked status' );
402 # And another try to go over the limit: different return value!
403 @test = checkpw( $dbh, $patron->userid, '123', undef, 'opac', 1 );
404 is( @test, 0, 'checkpw failed again and returns nothing now' );
405 $patron->discard_changes; # refresh
406 is( $patron->login_attempts, 3, 'Login attempts not increased anymore' );
408 # Administrative lockout cannot be undone?
409 # Pass the right password now (or: add a nice mock).
410 my $auth = Test::MockModule->new( 'C4::Auth' );
411 $auth->mock( 'checkpw_hash', sub { return 1; } ); # not for production :)
412 $patron->login_attempts(0)->store;
413 @test = checkpw( $dbh, $patron->userid, '123', undef, 'opac', 1 );
414 is( $test[0], 1, 'Build confidence in the mock' );
415 $patron->login_attempts(-1)->store;
416 is( $patron->account_locked, 1, 'Check administrative lockout' );
417 @test = checkpw( $dbh, $patron->userid, '123', undef, 'opac', 1 );
418 is( @test, 0, 'checkpw gave red' );
419 $patron->discard_changes; # refresh
420 is( $patron->login_attempts, -1, 'Still locked out' );
421 t::lib::Mocks::mock_preference('FailedLoginAttempts', ''); # disable
422 is( $patron->account_locked, 1, 'Check administrative lockout without pref' );
425 subtest '_timeout_syspref' => sub {
428 t::lib::Mocks::mock_preference('timeout', "100");
429 is( C4::Auth::_timeout_syspref, 100, );
431 t::lib::Mocks::mock_preference('timeout', "2d");
432 is( C4::Auth::_timeout_syspref, 2*86400, );
434 t::lib::Mocks::mock_preference('timeout', "2D");
435 is( C4::Auth::_timeout_syspref, 2*86400, );
437 t::lib::Mocks::mock_preference('timeout', "10h");
438 is( C4::Auth::_timeout_syspref, 10*3600, );
440 t::lib::Mocks::mock_preference('timeout', "10x");
441 is( C4::Auth::_timeout_syspref, 600, );
444 subtest 'check_cookie_auth' => sub {
447 t::lib::Mocks::mock_preference('timeout', "1d"); # back to default
449 my $patron = $builder->build_object({ class => 'Koha::Patrons', value => { flags => 1 } });
451 # Mock a CGI object with real userid param
452 my $cgi = Test::MockObject->new();
457 if ( $var eq 'userid' ) { return $patron->userid; }
460 $cgi->mock('multi_param', sub {return q{}} );
461 $cgi->mock( 'cookie', sub { return; } );
462 $cgi->mock( 'request_method', sub { return 'POST' } );
464 $ENV{REMOTE_ADDR} = '127.0.0.1';
466 # Setting authnotrequired=1 or we wont' hit the return but the end of the sub that prints headers
467 my ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 1 );
469 my ($auth_status, $session) = C4::Auth::check_cookie_auth($sessionID);
470 isnt( $auth_status, 'ok', 'check_cookie_auth should not return ok if the user has not been authenticated before if no permissions needed' );
471 is( $auth_status, 'anon', 'check_cookie_auth should return anon if the user has not been authenticated before and no permissions needed' );
473 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 1 );
475 ($auth_status, $session) = C4::Auth::check_cookie_auth($sessionID, {catalogue => 1});
476 isnt( $auth_status, 'ok', 'check_cookie_auth should not return ok if the user has not been authenticated before and permissions needed' );
477 is( $auth_status, 'anon', 'check_cookie_auth should return anon if the user has not been authenticated before and permissions needed' );
479 #FIXME We should have a test to cover 'failed' status when a user has logged in, but doesn't have permission
482 $schema->storage->txn_rollback;