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 => 23;
16 use t::lib::TestBuilder;
18 use C4::Auth qw(checkpw);
20 use Koha::AuthUtils qw/hash_password/;
28 my $schema = Koha::Database->schema;
29 my $builder = t::lib::TestBuilder->new;
30 my $dbh = C4::Context->dbh;
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 $schema->storage->txn_begin;
39 subtest 'checkauth() tests' => sub {
43 my $patron = $builder->build_object({ class => 'Koha::Patrons', value => { flags => undef } });
45 # Mock a CGI object with real userid param
46 my $cgi = Test::MockObject->new();
51 if ( $var eq 'userid' ) { return $patron->userid; }
54 $cgi->mock( 'cookie', sub { return; } );
55 $cgi->mock( 'request_method', sub { return 'POST' } );
57 my $authnotrequired = 1;
58 my ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, $authnotrequired );
60 is( $userid, undef, 'checkauth() returns undef for userid if no logged in user (Bug 18275)' );
62 my $db_user_id = C4::Context->config('user');
63 my $db_user_pass = C4::Context->config('pass');
64 $cgi = Test::MockObject->new();
65 $cgi->mock( 'cookie', sub { return; } );
66 $cgi->mock( 'param', sub {
67 my ( $self, $param ) = @_;
68 if ( $param eq 'userid' ) { return $db_user_id; }
69 elsif ( $param eq 'password' ) { return $db_user_pass; }
72 $cgi->mock( 'request_method', sub { return 'POST' } );
73 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, $authnotrequired );
74 is ( $userid, undef, 'If DB user is used, it should not be logged in' );
76 my $is_allowed = C4::Auth::haspermission( $db_user_id, { can_do => 'everything' } );
78 # FIXME This belongs to t/db_dependent/Auth/haspermission.t but we do not want to c/p the pervious mock statements
79 ok( !$is_allowed, 'DB user should not have any permissions');
81 subtest 'Prevent authentication when sending credential via GET' => sub {
85 my $patron = $builder->build_object(
86 { class => 'Koha::Patrons', value => { flags => 1 } } );
87 my $password = 'password';
88 t::lib::Mocks::mock_preference( 'RequireStrongPassword', 0 );
89 $patron->set_password( { password => $password } );
90 $cgi = Test::MockObject->new();
91 $cgi->mock( 'cookie', sub { return; } );
95 my ( $self, $param ) = @_;
96 if ( $param eq 'userid' ) { return $patron->userid; }
97 elsif ( $param eq 'password' ) { return $password; }
102 $cgi->mock( 'request_method', sub { return 'POST' } );
103 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired' );
104 is( $userid, $patron->userid, 'If librarian user is used and password with POST, they should be logged in' );
106 $cgi->mock( 'request_method', sub { return 'GET' } );
107 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired' );
108 is( $userid, undef, 'If librarian user is used and password with GET, they should not be logged in' );
111 C4::Context->_new_userenv; # For next tests
115 subtest 'track_login_daily tests' => sub {
119 my $patron = $builder->build_object({ class => 'Koha::Patrons' });
120 my $userid = $patron->userid;
122 $patron->lastseen( undef );
125 my $cache = Koha::Caches->get_instance();
126 my $cache_key = "track_login_" . $patron->userid;
127 $cache->clear_from_cache($cache_key);
129 t::lib::Mocks::mock_preference( 'TrackLastPatronActivity', '1' );
131 is( $patron->lastseen, undef, 'Patron should have not last seen when newly created' );
133 C4::Auth::track_login_daily( $userid );
134 $patron->_result()->discard_changes();
135 isnt( $patron->lastseen, undef, 'Patron should have last seen set when TrackLastPatronActivity = 1' );
137 sleep(1); # We need to wait a tiny bit to make sure the timestamp will be different
138 my $last_seen = $patron->lastseen;
139 C4::Auth::track_login_daily( $userid );
140 $patron->_result()->discard_changes();
141 is( $patron->lastseen, $last_seen, 'Patron last seen should still be unchanged' );
143 $cache->clear_from_cache($cache_key);
144 C4::Auth::track_login_daily( $userid );
145 $patron->_result()->discard_changes();
146 isnt( $patron->lastseen, $last_seen, 'Patron last seen should be changed if we cleared the cache' );
148 t::lib::Mocks::mock_preference( 'TrackLastPatronActivity', '0' );
149 $patron->lastseen( undef )->store;
150 $cache->clear_from_cache($cache_key);
151 C4::Auth::track_login_daily( $userid );
152 $patron->_result()->discard_changes();
153 is( $patron->lastseen, undef, 'Patron should still have last seen unchanged when TrackLastPatronActivity = 0' );
157 subtest 'no_set_userenv parameter tests' => sub {
161 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
162 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
163 my $password = 'password';
165 t::lib::Mocks::mock_preference( 'RequireStrongPassword', 0 );
166 $patron->set_password({ password => $password });
168 ok( checkpw( $dbh, $patron->userid, $password, undef, undef, 1 ), 'checkpw returns true' );
169 is( C4::Context->userenv, undef, 'Userenv should be undef as required' );
170 C4::Context->_new_userenv('DUMMY SESSION');
171 C4::Context->set_userenv(0,0,0,'firstname','surname', $library->branchcode, 'Library 1', 0, '', '');
172 is( C4::Context->userenv->{branch}, $library->branchcode, 'Userenv gives correct branch' );
173 ok( checkpw( $dbh, $patron->userid, $password, undef, undef, 1 ), 'checkpw returns true' );
174 is( C4::Context->userenv->{branch}, $library->branchcode, 'Userenv branch is preserved if no_set_userenv is true' );
175 ok( checkpw( $dbh, $patron->userid, $password, undef, undef, 0 ), 'checkpw still returns true' );
176 isnt( C4::Context->userenv->{branch}, $library->branchcode, 'Userenv branch is overwritten if no_set_userenv is false' );
179 subtest 'checkpw lockout tests' => sub {
183 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
184 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
185 my $password = 'password';
186 t::lib::Mocks::mock_preference( 'RequireStrongPassword', 0 );
187 t::lib::Mocks::mock_preference( 'FailedLoginAttempts', 1 );
188 $patron->set_password({ password => $password });
190 my ( $checkpw, undef, undef ) = checkpw( $dbh, $patron->cardnumber, $password, undef, undef, 1 );
191 ok( $checkpw, 'checkpw returns true with right password when logging in via cardnumber' );
192 ( $checkpw, undef, undef ) = checkpw( $dbh, $patron->userid, "wrong_password", undef, undef, 1 );
193 is( $checkpw, 0, 'checkpw returns false when given wrong password' );
194 $patron = $patron->get_from_storage;
195 is( $patron->account_locked, 1, "Account is locked from failed login");
196 ( $checkpw, undef, undef ) = checkpw( $dbh, $patron->userid, $password, undef, undef, 1 );
197 is( $checkpw, undef, 'checkpw returns undef with right password when account locked' );
198 ( $checkpw, undef, undef ) = checkpw( $dbh, $patron->cardnumber, $password, undef, undef, 1 );
199 is( $checkpw, undef, 'checkpw returns undefwith right password when logging in via cardnumber if account locked' );
203 # get_template_and_user tests
205 { # Tests for the language URL parameter
207 sub MockedCheckauth {
208 my ($query,$authnotrequired,$flagsrequired,$type) = @_;
210 my $userid = 'cobain';
212 # we don't need to bother about permissions for this test
214 superlibrarian => 1, acquisition => 0,
216 catalogue => 1, circulate => 0,
217 coursereserves => 0, editauthorities => 0,
219 parameters => 0, permissions => 0,
220 plugins => 0, reports => 0,
221 reserveforothers => 0, serials => 0,
222 staffaccess => 0, tools => 0,
226 my $session_cookie = $query->cookie(
227 -name => 'CGISESSID',
232 return ( $userid, $session_cookie, $sessionID, $flags );
235 # Mock checkauth, build the scenario
236 my $auth = Test::MockModule->new( 'C4::Auth' );
237 $auth->mock( 'checkauth', \&MockedCheckauth );
239 # Make sure 'EnableOpacSearchHistory' is set
240 t::lib::Mocks::mock_preference('EnableOpacSearchHistory',1);
241 # Enable es-ES for the OPAC and staff interfaces
242 t::lib::Mocks::mock_preference('OPACLanguages','en,es-ES');
243 t::lib::Mocks::mock_preference('language','en,es-ES');
245 # we need a session cookie
246 $ENV{"SERVER_PORT"} = 80;
247 $ENV{"HTTP_COOKIE"} = 'CGISESSID=nirvana';
249 my $query = CGI->new;
250 $query->param('language','es-ES');
252 my ( $template, $loggedinuser, $cookies ) = get_template_and_user(
254 template_name => "about.tt",
257 authnotrequired => 1,
258 flagsrequired => { catalogue => 1 },
263 ok ( ( all { ref($_) eq 'CGI::Cookie' } @$cookies ),
264 'BZ9735: the cookies array is flat' );
266 # new query, with non-existent language (we only have en and es-ES)
267 $query->param('language','tomas');
269 ( $template, $loggedinuser, $cookies ) = get_template_and_user(
271 template_name => "about.tt",
274 authnotrequired => 1,
275 flagsrequired => { catalogue => 1 },
280 ok( ( none { $_->name eq 'KohaOpacLanguage' and $_->value eq 'tomas' } @$cookies ),
281 'BZ9735: invalid language, it is not set');
283 ok( ( any { $_->name eq 'KohaOpacLanguage' and $_->value eq 'en' } @$cookies ),
284 'BZ9735: invalid language, then default to en');
286 for my $template_name (
288 ../../../../../../../../../../../../../../../etc/passwd
289 test/../../../../../../../../../../../../../../etc/passwd
291 test/does_not_finished_by_tt_t
295 ( $template, $loggedinuser, $cookies ) = get_template_and_user(
297 template_name => $template_name,
300 authnotrequired => 1,
301 flagsrequired => { catalogue => 1 },
305 like ( $@, qr(^bad template path), "The file $template_name should not be accessible" );
307 ( $template, $loggedinuser, $cookies ) = get_template_and_user(
309 template_name => 'errors/errorpage.tt',
312 authnotrequired => 1,
313 flagsrequired => { catalogue => 1 },
316 my $file_exists = ( -f $template->{filename} ) ? 1 : 0;
317 is ( $file_exists, 1, 'The file errors/errorpage.tt should be accessible (contains integers)' );
319 # Regression test for env opac search limit override
320 $ENV{"OPAC_SEARCH_LIMIT"} = "branch:CPL";
321 $ENV{"OPAC_LIMIT_OVERRIDE"} = 1;
323 ( $template, $loggedinuser, $cookies) = get_template_and_user(
325 template_name => 'opac-main.tt',
328 authnotrequired => 1,
331 is($template->{VARS}->{'opac_name'}, "CPL", "Opac name was set correctly");
332 is($template->{VARS}->{'opac_search_limit'}, "branch:CPL", "Search limit was set correctly");
334 $ENV{"OPAC_SEARCH_LIMIT"} = "branch:multibranch-19";
336 ( $template, $loggedinuser, $cookies) = get_template_and_user(
338 template_name => 'opac-main.tt',
341 authnotrequired => 1,
344 is($template->{VARS}->{'opac_name'}, "multibranch-19", "Opac name was set correctly");
345 is($template->{VARS}->{'opac_search_limit'}, "branch:multibranch-19", "Search limit was set correctly");
348 # Check that there is always an OPACBaseURL set.
349 my $input = CGI->new();
350 my ( $template1, $borrowernumber, $cookie );
351 ( $template1, $borrowernumber, $cookie ) = get_template_and_user(
353 template_name => "opac-detail.tt",
356 authnotrequired => 1,
360 ok( ( any { 'OPACBaseURL' eq $_ } keys %{$template1->{VARS}} ),
361 'OPACBaseURL is in OPAC template' );
364 ( $template2, $borrowernumber, $cookie ) = get_template_and_user(
366 template_name => "catalogue/detail.tt",
369 authnotrequired => 1,
373 ok( ( any { 'OPACBaseURL' eq $_ } keys %{$template2->{VARS}} ),
374 'OPACBaseURL is in Staff template' );
376 my $hash1 = hash_password('password');
377 my $hash2 = hash_password('password');
379 ok(C4::Auth::checkpw_hash('password', $hash1), 'password validates with first hash');
380 ok(C4::Auth::checkpw_hash('password', $hash2), 'password validates with second hash');
382 subtest 'Check value of login_attempts in checkpw' => sub {
385 t::lib::Mocks::mock_preference('FailedLoginAttempts', 3);
387 # Only interested here in regular login
391 my $patron = $builder->build_object({ class => 'Koha::Patrons' });
392 $patron->login_attempts(2);
393 $patron->password('123')->store; # yes, deliberately not hashed
395 is( $patron->account_locked, 0, 'Patron not locked' );
396 my @test = checkpw( $dbh, $patron->userid, '123', undef, 'opac', 1 );
397 # Note: 123 will not be hashed to 123 !
398 is( $test[0], 0, 'checkpw should have failed' );
399 $patron->discard_changes; # refresh
400 is( $patron->login_attempts, 3, 'Login attempts increased' );
401 is( $patron->account_locked, 1, 'Check locked status' );
403 # And another try to go over the limit: different return value!
404 @test = checkpw( $dbh, $patron->userid, '123', undef, 'opac', 1 );
405 is( @test, 0, 'checkpw failed again and returns nothing now' );
406 $patron->discard_changes; # refresh
407 is( $patron->login_attempts, 3, 'Login attempts not increased anymore' );
409 # Administrative lockout cannot be undone?
410 # Pass the right password now (or: add a nice mock).
411 my $auth = Test::MockModule->new( 'C4::Auth' );
412 $auth->mock( 'checkpw_hash', sub { return 1; } ); # not for production :)
413 $patron->login_attempts(0)->store;
414 @test = checkpw( $dbh, $patron->userid, '123', undef, 'opac', 1 );
415 is( $test[0], 1, 'Build confidence in the mock' );
416 $patron->login_attempts(-1)->store;
417 is( $patron->account_locked, 1, 'Check administrative lockout' );
418 @test = checkpw( $dbh, $patron->userid, '123', undef, 'opac', 1 );
419 is( @test, 0, 'checkpw gave red' );
420 $patron->discard_changes; # refresh
421 is( $patron->login_attempts, -1, 'Still locked out' );
422 t::lib::Mocks::mock_preference('FailedLoginAttempts', ''); # disable
423 is( $patron->account_locked, 1, 'Check administrative lockout without pref' );
426 subtest '_timeout_syspref' => sub {
429 t::lib::Mocks::mock_preference('timeout', "100");
430 is( C4::Auth::_timeout_syspref, 100, );
432 t::lib::Mocks::mock_preference('timeout', "2d");
433 is( C4::Auth::_timeout_syspref, 2*86400, );
435 t::lib::Mocks::mock_preference('timeout', "2D");
436 is( C4::Auth::_timeout_syspref, 2*86400, );
438 t::lib::Mocks::mock_preference('timeout', "10h");
439 is( C4::Auth::_timeout_syspref, 10*3600, );
441 t::lib::Mocks::mock_preference('timeout', "10x");
442 is( C4::Auth::_timeout_syspref, 600, );
445 $schema->storage->txn_rollback;