Bug 24786: (QA follow-up) Remove trailing space in classes
[koha.git] / t / db_dependent / Auth.t
blobafe4ccaa81e12eb70ca89fe8dd2e2c02d5ad2fdc
1 #!/usr/bin/perl
3 # This Koha test module is a stub!
4 # Add more tests here!!!
6 use Modern::Perl;
8 use CGI qw ( -utf8 );
10 use Test::MockObject;
11 use Test::MockModule;
12 use List::MoreUtils qw/all any none/;
13 use Test::More tests => 23;
14 use Test::Warn;
15 use t::lib::Mocks;
16 use t::lib::TestBuilder;
18 use C4::Auth qw(checkpw);
19 use C4::Members;
20 use Koha::AuthUtils qw/hash_password/;
21 use Koha::Database;
22 use Koha::Patrons;
24 BEGIN {
25 use_ok('C4::Auth');
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
33 # handling
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 {
41 plan tests => 3;
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();
47 $cgi->mock(
48 'param',
49 sub {
50 my $var = shift;
51 if ( $var eq 'userid' ) { return $patron->userid; }
54 $cgi->mock( 'cookie', sub { return; } );
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; }
69 else { return; }
70 });
71 ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, $authnotrequired );
72 is ( $userid, undef, 'If DB user is used, it should not be logged in' );
74 my $is_allowed = C4::Auth::haspermission( $db_user_id, { can_do => 'everything' } );
76 # FIXME This belongs to t/db_dependent/Auth/haspermission.t but we do not want to c/p the pervious mock statements
77 ok( !$is_allowed, 'DB user should not have any permissions');
79 C4::Context->_new_userenv; # For next tests
83 subtest 'track_login_daily tests' => sub {
85 plan tests => 5;
87 my $patron = $builder->build_object({ class => 'Koha::Patrons' });
88 my $userid = $patron->userid;
90 $patron->lastseen( undef );
91 $patron->store();
93 my $cache = Koha::Caches->get_instance();
94 my $cache_key = "track_login_" . $patron->userid;
95 $cache->clear_from_cache($cache_key);
97 t::lib::Mocks::mock_preference( 'TrackLastPatronActivity', '1' );
99 is( $patron->lastseen, undef, 'Patron should have not last seen when newly created' );
101 C4::Auth::track_login_daily( $userid );
102 $patron->_result()->discard_changes();
103 isnt( $patron->lastseen, undef, 'Patron should have last seen set when TrackLastPatronActivity = 1' );
105 sleep(1); # We need to wait a tiny bit to make sure the timestamp will be different
106 my $last_seen = $patron->lastseen;
107 C4::Auth::track_login_daily( $userid );
108 $patron->_result()->discard_changes();
109 is( $patron->lastseen, $last_seen, 'Patron last seen should still be unchanged' );
111 $cache->clear_from_cache($cache_key);
112 C4::Auth::track_login_daily( $userid );
113 $patron->_result()->discard_changes();
114 isnt( $patron->lastseen, $last_seen, 'Patron last seen should be changed if we cleared the cache' );
116 t::lib::Mocks::mock_preference( 'TrackLastPatronActivity', '0' );
117 $patron->lastseen( undef )->store;
118 $cache->clear_from_cache($cache_key);
119 C4::Auth::track_login_daily( $userid );
120 $patron->_result()->discard_changes();
121 is( $patron->lastseen, undef, 'Patron should still have last seen unchanged when TrackLastPatronActivity = 0' );
125 subtest 'no_set_userenv parameter tests' => sub {
127 plan tests => 7;
129 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
130 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
131 my $password = 'password';
133 t::lib::Mocks::mock_preference( 'RequireStrongPassword', 0 );
134 $patron->set_password({ password => $password });
136 ok( checkpw( $dbh, $patron->userid, $password, undef, undef, 1 ), 'checkpw returns true' );
137 is( C4::Context->userenv, undef, 'Userenv should be undef as required' );
138 C4::Context->_new_userenv('DUMMY SESSION');
139 C4::Context->set_userenv(0,0,0,'firstname','surname', $library->branchcode, 'Library 1', 0, '', '');
140 is( C4::Context->userenv->{branch}, $library->branchcode, 'Userenv gives correct branch' );
141 ok( checkpw( $dbh, $patron->userid, $password, undef, undef, 1 ), 'checkpw returns true' );
142 is( C4::Context->userenv->{branch}, $library->branchcode, 'Userenv branch is preserved if no_set_userenv is true' );
143 ok( checkpw( $dbh, $patron->userid, $password, undef, undef, 0 ), 'checkpw still returns true' );
144 isnt( C4::Context->userenv->{branch}, $library->branchcode, 'Userenv branch is overwritten if no_set_userenv is false' );
147 subtest 'checkpw lockout tests' => sub {
149 plan tests => 5;
151 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
152 my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
153 my $password = 'password';
154 t::lib::Mocks::mock_preference( 'RequireStrongPassword', 0 );
155 t::lib::Mocks::mock_preference( 'FailedLoginAttempts', 1 );
156 $patron->set_password({ password => $password });
158 my ( $checkpw, undef, undef ) = checkpw( $dbh, $patron->cardnumber, $password, undef, undef, 1 );
159 ok( $checkpw, 'checkpw returns true with right password when logging in via cardnumber' );
160 ( $checkpw, undef, undef ) = checkpw( $dbh, $patron->userid, "wrong_password", undef, undef, 1 );
161 is( $checkpw, 0, 'checkpw returns false when given wrong password' );
162 $patron = $patron->get_from_storage;
163 is( $patron->account_locked, 1, "Account is locked from failed login");
164 ( $checkpw, undef, undef ) = checkpw( $dbh, $patron->userid, $password, undef, undef, 1 );
165 is( $checkpw, undef, 'checkpw returns undef with right password when account locked' );
166 ( $checkpw, undef, undef ) = checkpw( $dbh, $patron->cardnumber, $password, undef, undef, 1 );
167 is( $checkpw, undef, 'checkpw returns undefwith right password when logging in via cardnumber if account locked' );
171 # get_template_and_user tests
173 { # Tests for the language URL parameter
175 sub MockedCheckauth {
176 my ($query,$authnotrequired,$flagsrequired,$type) = @_;
177 # return vars
178 my $userid = 'cobain';
179 my $sessionID = 234;
180 # we don't need to bother about permissions for this test
181 my $flags = {
182 superlibrarian => 1, acquisition => 0,
183 borrowers => 0,
184 catalogue => 1, circulate => 0,
185 coursereserves => 0, editauthorities => 0,
186 editcatalogue => 0,
187 parameters => 0, permissions => 0,
188 plugins => 0, reports => 0,
189 reserveforothers => 0, serials => 0,
190 staffaccess => 0, tools => 0,
191 updatecharges => 0
194 my $session_cookie = $query->cookie(
195 -name => 'CGISESSID',
196 -value => 'nirvana',
197 -HttpOnly => 1
200 return ( $userid, $session_cookie, $sessionID, $flags );
203 # Mock checkauth, build the scenario
204 my $auth = Test::MockModule->new( 'C4::Auth' );
205 $auth->mock( 'checkauth', \&MockedCheckauth );
207 # Make sure 'EnableOpacSearchHistory' is set
208 t::lib::Mocks::mock_preference('EnableOpacSearchHistory',1);
209 # Enable es-ES for the OPAC and staff interfaces
210 t::lib::Mocks::mock_preference('opaclanguages','en,es-ES');
211 t::lib::Mocks::mock_preference('language','en,es-ES');
213 # we need a session cookie
214 $ENV{"SERVER_PORT"} = 80;
215 $ENV{"HTTP_COOKIE"} = 'CGISESSID=nirvana';
217 my $query = CGI->new;
218 $query->param('language','es-ES');
220 my ( $template, $loggedinuser, $cookies ) = get_template_and_user(
222 template_name => "about.tt",
223 query => $query,
224 type => "opac",
225 authnotrequired => 1,
226 flagsrequired => { catalogue => 1 },
227 debug => 1
231 ok ( ( all { ref($_) eq 'CGI::Cookie' } @$cookies ),
232 'BZ9735: the cookies array is flat' );
234 # new query, with non-existent language (we only have en and es-ES)
235 $query->param('language','tomas');
237 ( $template, $loggedinuser, $cookies ) = get_template_and_user(
239 template_name => "about.tt",
240 query => $query,
241 type => "opac",
242 authnotrequired => 1,
243 flagsrequired => { catalogue => 1 },
244 debug => 1
248 ok( ( none { $_->name eq 'KohaOpacLanguage' and $_->value eq 'tomas' } @$cookies ),
249 'BZ9735: invalid language, it is not set');
251 ok( ( any { $_->name eq 'KohaOpacLanguage' and $_->value eq 'en' } @$cookies ),
252 'BZ9735: invalid language, then default to en');
254 for my $template_name (
256 ../../../../../../../../../../../../../../../etc/passwd
257 test/../../../../../../../../../../../../../../etc/passwd
258 /etc/passwd
259 test/does_not_finished_by_tt_t
262 eval {
263 ( $template, $loggedinuser, $cookies ) = get_template_and_user(
265 template_name => $template_name,
266 query => $query,
267 type => "intranet",
268 authnotrequired => 1,
269 flagsrequired => { catalogue => 1 },
273 like ( $@, qr(^bad template path), "The file $template_name should not be accessible" );
275 ( $template, $loggedinuser, $cookies ) = get_template_and_user(
277 template_name => 'errors/errorpage.tt',
278 query => $query,
279 type => "intranet",
280 authnotrequired => 1,
281 flagsrequired => { catalogue => 1 },
284 my $file_exists = ( -f $template->{filename} ) ? 1 : 0;
285 is ( $file_exists, 1, 'The file errors/errorpage.tt should be accessible (contains integers)' );
287 # Regression test for env opac search limit override
288 $ENV{"OPAC_SEARCH_LIMIT"} = "branch:CPL";
289 $ENV{"OPAC_LIMIT_OVERRIDE"} = 1;
291 ( $template, $loggedinuser, $cookies) = get_template_and_user(
293 template_name => 'opac-main.tt',
294 query => $query,
295 type => 'opac',
296 authnotrequired => 1,
299 is($template->{VARS}->{'opac_name'}, "CPL", "Opac name was set correctly");
300 is($template->{VARS}->{'opac_search_limit'}, "branch:CPL", "Search limit was set correctly");
302 $ENV{"OPAC_SEARCH_LIMIT"} = "branch:multibranch-19";
304 ( $template, $loggedinuser, $cookies) = get_template_and_user(
306 template_name => 'opac-main.tt',
307 query => $query,
308 type => 'opac',
309 authnotrequired => 1,
312 is($template->{VARS}->{'opac_name'}, "multibranch-19", "Opac name was set correctly");
313 is($template->{VARS}->{'opac_search_limit'}, "branch:multibranch-19", "Search limit was set correctly");
316 # Check that there is always an OPACBaseURL set.
317 my $input = CGI->new();
318 my ( $template1, $borrowernumber, $cookie );
319 ( $template1, $borrowernumber, $cookie ) = get_template_and_user(
321 template_name => "opac-detail.tt",
322 type => "opac",
323 query => $input,
324 authnotrequired => 1,
328 ok( ( any { 'OPACBaseURL' eq $_ } keys %{$template1->{VARS}} ),
329 'OPACBaseURL is in OPAC template' );
331 my ( $template2 );
332 ( $template2, $borrowernumber, $cookie ) = get_template_and_user(
334 template_name => "catalogue/detail.tt",
335 type => "intranet",
336 query => $input,
337 authnotrequired => 1,
341 ok( ( any { 'OPACBaseURL' eq $_ } keys %{$template2->{VARS}} ),
342 'OPACBaseURL is in Staff template' );
344 my $hash1 = hash_password('password');
345 my $hash2 = hash_password('password');
347 ok(C4::Auth::checkpw_hash('password', $hash1), 'password validates with first hash');
348 ok(C4::Auth::checkpw_hash('password', $hash2), 'password validates with second hash');
350 subtest 'Check value of login_attempts in checkpw' => sub {
351 plan tests => 11;
353 t::lib::Mocks::mock_preference('FailedLoginAttempts', 3);
355 # Only interested here in regular login
356 $C4::Auth::cas = 0;
357 $C4::Auth::ldap = 0;
359 my $patron = $builder->build_object({ class => 'Koha::Patrons' });
360 $patron->login_attempts(2);
361 $patron->password('123')->store; # yes, deliberately not hashed
363 is( $patron->account_locked, 0, 'Patron not locked' );
364 my @test = checkpw( $dbh, $patron->userid, '123', undef, 'opac', 1 );
365 # Note: 123 will not be hashed to 123 !
366 is( $test[0], 0, 'checkpw should have failed' );
367 $patron->discard_changes; # refresh
368 is( $patron->login_attempts, 3, 'Login attempts increased' );
369 is( $patron->account_locked, 1, 'Check locked status' );
371 # And another try to go over the limit: different return value!
372 @test = checkpw( $dbh, $patron->userid, '123', undef, 'opac', 1 );
373 is( @test, 0, 'checkpw failed again and returns nothing now' );
374 $patron->discard_changes; # refresh
375 is( $patron->login_attempts, 3, 'Login attempts not increased anymore' );
377 # Administrative lockout cannot be undone?
378 # Pass the right password now (or: add a nice mock).
379 my $auth = Test::MockModule->new( 'C4::Auth' );
380 $auth->mock( 'checkpw_hash', sub { return 1; } ); # not for production :)
381 $patron->login_attempts(0)->store;
382 @test = checkpw( $dbh, $patron->userid, '123', undef, 'opac', 1 );
383 is( $test[0], 1, 'Build confidence in the mock' );
384 $patron->login_attempts(-1)->store;
385 is( $patron->account_locked, 1, 'Check administrative lockout' );
386 @test = checkpw( $dbh, $patron->userid, '123', undef, 'opac', 1 );
387 is( @test, 0, 'checkpw gave red' );
388 $patron->discard_changes; # refresh
389 is( $patron->login_attempts, -1, 'Still locked out' );
390 t::lib::Mocks::mock_preference('FailedLoginAttempts', ''); # disable
391 is( $patron->account_locked, 1, 'Check administrative lockout without pref' );
394 subtest '_timeout_syspref' => sub {
395 plan tests => 5;
397 t::lib::Mocks::mock_preference('timeout', "100");
398 is( C4::Auth::_timeout_syspref, 100, );
400 t::lib::Mocks::mock_preference('timeout', "2d");
401 is( C4::Auth::_timeout_syspref, 2*86400, );
403 t::lib::Mocks::mock_preference('timeout', "2D");
404 is( C4::Auth::_timeout_syspref, 2*86400, );
406 t::lib::Mocks::mock_preference('timeout', "10h");
407 is( C4::Auth::_timeout_syspref, 10*3600, );
409 t::lib::Mocks::mock_preference('timeout', "10x");
410 is( C4::Auth::_timeout_syspref, 600, );
413 $schema->storage->txn_rollback;