Bug 30588: Add tests for C4::checkauth
[koha-ffzg.git] / t / db_dependent / Auth.t
1 #!/usr/bin/perl
2 #
3 # This Koha test module is a stub!  
4 # Add more tests here!!!
5
6 use Modern::Perl;
7
8 use CGI qw ( -utf8 );
9
10 use Test::MockObject;
11 use Test::MockModule;
12 use List::MoreUtils qw/all any none/;
13 use Test::More tests => 16;
14 use Test::Warn;
15 use t::lib::Mocks;
16 use t::lib::TestBuilder;
17
18 use C4::Auth;
19 use C4::Members;
20 use Koha::AuthUtils qw/hash_password/;
21 use Koha::Database;
22 use Koha::Patrons;
23 use Koha::Auth::TwoFactorAuth;
24
25 BEGIN {
26     use_ok('C4::Auth', qw( checkauth haspermission track_login_daily checkpw get_template_and_user checkpw_hash ));
27 }
28
29 my $schema  = Koha::Database->schema;
30 my $builder = t::lib::TestBuilder->new;
31
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
36
37 # To silence useless warnings
38 $ENV{REMOTE_ADDR} = '127.0.0.1';
39
40 $schema->storage->txn_begin;
41
42 subtest 'checkauth() tests' => sub {
43
44     plan tests => 6;
45
46     my $patron = $builder->build_object({ class => 'Koha::Patrons', value => { flags => undef } });
47
48     # Mock a CGI object with real userid param
49     my $cgi = Test::MockObject->new();
50     $cgi->mock(
51         'param',
52         sub {
53             my $var = shift;
54             if ( $var eq 'userid' ) { return $patron->userid; }
55         }
56     );
57     $cgi->mock( 'cookie', sub { return; } );
58     $cgi->mock( 'request_method', sub { return 'POST' } );
59
60     my $authnotrequired = 1;
61     my ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, $authnotrequired );
62
63     is( $userid, undef, 'checkauth() returns undef for userid if no logged in user (Bug 18275)' );
64
65     my $db_user_id = C4::Context->config('user');
66     my $db_user_pass = C4::Context->config('pass');
67     $cgi = Test::MockObject->new();
68     $cgi->mock( 'cookie', sub { return; } );
69     $cgi->mock( 'param', sub {
70             my ( $self, $param ) = @_;
71             if ( $param eq 'userid' ) { return $db_user_id; }
72             elsif ( $param eq 'password' ) { return $db_user_pass; }
73             else { return; }
74         });
75     $cgi->mock( 'request_method', sub { return 'POST' } );
76     ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, $authnotrequired );
77     is ( $userid, undef, 'If DB user is used, it should not be logged in' );
78
79     my $is_allowed = C4::Auth::haspermission( $db_user_id, { can_do => 'everything' } );
80
81     # FIXME This belongs to t/db_dependent/Auth/haspermission.t but we do not want to c/p the pervious mock statements
82     ok( !$is_allowed, 'DB user should not have any permissions');
83
84     subtest 'Prevent authentication when sending credential via GET' => sub {
85
86         plan tests => 2;
87
88         my $patron = $builder->build_object(
89             { class => 'Koha::Patrons', value => { flags => 1 } } );
90         my $password = 'password';
91         t::lib::Mocks::mock_preference( 'RequireStrongPassword', 0 );
92         $patron->set_password( { password => $password } );
93         $cgi = Test::MockObject->new();
94         $cgi->mock( 'cookie', sub { return; } );
95         $cgi->mock(
96             'param',
97             sub {
98                 my ( $self, $param ) = @_;
99                 if    ( $param eq 'userid' )   { return $patron->userid; }
100                 elsif ( $param eq 'password' ) { return $password; }
101                 else                           { return; }
102             }
103         );
104
105         $cgi->mock( 'request_method', sub { return 'POST' } );
106         ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired' );
107         is( $userid, $patron->userid, 'If librarian user is used and password with POST, they should be logged in' );
108
109         $cgi->mock( 'request_method', sub { return 'GET' } );
110         ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired' );
111         is( $userid, undef, 'If librarian user is used and password with GET, they should not be logged in' );
112     };
113
114     subtest 'Template params tests (password_expired)' => sub {
115
116         plan tests => 1;
117
118         my $password_expired;
119
120         my $patron_class = Test::MockModule->new('Koha::Patron');
121         $patron_class->mock( 'password_expired', sub { return $password_expired; } );
122
123         my $patron = $builder->build_object({ class => 'Koha::Patrons', value => { flags => 1 } });
124         my $password = 'password';
125         t::lib::Mocks::mock_preference( 'RequireStrongPassword', 0 );
126         $patron->set_password( { password => $password } );
127
128         my $cgi_mock = Test::MockModule->new('CGI')->mock( 'request_method', 'POST' );
129         my $cgi = CGI->new;
130         $cgi->param( -name => 'userid',   -value => $patron->userid );
131         $cgi->param( -name => 'password', -value => $password );
132
133         my $auth = Test::MockModule->new( 'C4::Auth' );
134         # Tests will fail if we hit safe_exit
135         $auth->mock( 'safe_exit', sub { return } );
136
137         my ( $userid, $cookie, $sessionID, $flags );
138
139         {
140             t::lib::Mocks::mock_preference( 'DumpTemplateVarsOpac', 1 );
141             # checkauth will redirect and safe_exit if not authenticated and not authorized
142             local *STDOUT;
143             my $stdout;
144             open STDOUT, '>', \$stdout;
145
146             # Password has expired
147             $password_expired = 1;
148             C4::Auth::checkauth( $cgi, 0, { catalogue => 1 } );
149             like( $stdout, qr{'password_has_expired' => 1}, 'password_has_expired is set to 1' );
150
151             close STDOUT;
152         };
153     };
154
155     subtest 'Two-factor authentication' => sub {
156
157         my $patron = $builder->build_object(
158             { class => 'Koha::Patrons', value => { flags => 1 } } );
159         my $password = 'password';
160         $patron->set_password( { password => $password } );
161         $cgi = Test::MockObject->new();
162
163         my $otp_token;
164         our ( $logout, $sessionID, $verified );
165         $cgi->mock(
166             'param',
167             sub {
168                 my ( $self, $param ) = @_;
169                 if    ( $param eq 'userid' )    { return $patron->userid; }
170                 elsif ( $param eq 'password' )  { return $password; }
171                 elsif ( $param eq 'otp_token' ) { return $otp_token; }
172                 elsif ( $param eq 'logout.x' )  { return $logout; }
173                 else                            { return; }
174             }
175         );
176         $cgi->mock( 'request_method', sub { return 'POST' } );
177         $cgi->mock( 'cookie', sub { return $sessionID } );
178
179         my $two_factor_auth = Test::MockModule->new( 'Koha::Auth::TwoFactorAuth' );
180         $two_factor_auth->mock( 'verify', sub {$verified} );
181
182         my ( $userid, $cookie, $flags );
183         ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired', undef, 'intranet' );
184
185         sub logout {
186             my $cgi = shift;
187             $logout = 1;
188             undef $sessionID;
189             C4::Auth::checkauth( $cgi, 'authrequired', undef, 'intranet' );
190             $logout = 0;
191         }
192
193         t::lib::Mocks::mock_preference( 'TwoFactorAuthentication', 'disabled' );
194         $patron->auth_method('password')->store;
195         ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired', undef, 'intranet' );
196         is( $userid, $patron->userid, 'Succesful login' );
197         is( C4::Auth::get_session($sessionID)->param('waiting-for-2FA'), undef, 'Second auth not required' );
198         logout($cgi);
199
200         $patron->auth_method('two-factor')->store;
201         ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired', undef, 'intranet' );
202         is( $userid, $patron->userid, 'Succesful login' );
203         is( C4::Auth::get_session($sessionID)->param('waiting-for-2FA'), undef, 'Second auth not required' );
204         logout($cgi);
205
206         t::lib::Mocks::mock_preference( 'TwoFactorAuthentication', 'enabled' );
207         t::lib::Mocks::mock_config('encryption_key', '1234tH1s=t&st');
208         $patron->auth_method('password')->store;
209         ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired', undef, 'intranet' );
210         is( $userid, $patron->userid, 'Succesful login' );
211         is( C4::Auth::get_session($sessionID)->param('waiting-for-2FA'), undef, 'Second auth not required' );
212         logout($cgi);
213
214         $patron->encode_secret('one_secret');
215         $patron->auth_method('two-factor');
216         $patron->store;
217         ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired', undef, 'intranet' );
218         is( $userid, $patron->userid, 'Succesful login' );
219         my $session = C4::Auth::get_session($sessionID);
220         is( C4::Auth::get_session($sessionID)->param('waiting-for-2FA'), 1, 'Second auth required' );
221
222         # Wrong OTP token
223         $otp_token = "wrong";
224         $verified = 0;
225         $patron->auth_method('two-factor')->store;
226         ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired', undef, 'intranet' );
227         is( $userid, $patron->userid, 'Succesful login' );
228         is( C4::Auth::get_session($sessionID)->param('waiting-for-2FA'), 1, 'Second auth still required after wrong OTP token' );
229
230         $otp_token = "good";
231         $verified = 1;
232         ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired', undef, 'intranet' );
233         is( $userid, $patron->userid, 'Succesful login' );
234         is( C4::Auth::get_session($sessionID)->param('waiting-for-2FA'), 0, 'Second auth no longer required if OTP token has been verified' );
235         logout($cgi);
236
237         t::lib::Mocks::mock_preference( 'TwoFactorAuthentication', 'enforced' );
238         $patron->auth_method('password')->store;
239         ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired', undef, 'intranet' );
240         is( $userid, $patron->userid, 'Succesful login' );
241         is( C4::Auth::get_session($sessionID)->param('waiting-for-2FA-setup'), 1, 'Setup 2FA required' );
242         logout($cgi);
243
244         logout($cgi);
245         ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired', undef, 'opac' );
246         is( $userid, $patron->userid, 'Succesful login at the OPAC' );
247         is( C4::Auth::get_session($sessionID)->param('waiting-for-2FA'), undef, 'No second auth required at the OPAC' );
248
249         t::lib::Mocks::mock_preference( 'TwoFactorAuthentication', 'disabled' );
250     };
251
252     C4::Context->_new_userenv; # For next tests
253
254 };
255
256 subtest 'track_login_daily tests' => sub {
257
258     plan tests => 5;
259
260     my $patron = $builder->build_object({ class => 'Koha::Patrons' });
261     my $userid = $patron->userid;
262
263     $patron->lastseen( undef );
264     $patron->store();
265
266     my $cache     = Koha::Caches->get_instance();
267     my $cache_key = "track_login_" . $patron->userid;
268     $cache->clear_from_cache($cache_key);
269
270     t::lib::Mocks::mock_preference( 'TrackLastPatronActivity', '1' );
271
272     is( $patron->lastseen, undef, 'Patron should have not last seen when newly created' );
273
274     C4::Auth::track_login_daily( $userid );
275     $patron->_result()->discard_changes();
276     isnt( $patron->lastseen, undef, 'Patron should have last seen set when TrackLastPatronActivity = 1' );
277
278     sleep(1); # We need to wait a tiny bit to make sure the timestamp will be different
279     my $last_seen = $patron->lastseen;
280     C4::Auth::track_login_daily( $userid );
281     $patron->_result()->discard_changes();
282     is( $patron->lastseen, $last_seen, 'Patron last seen should still be unchanged' );
283
284     $cache->clear_from_cache($cache_key);
285     C4::Auth::track_login_daily( $userid );
286     $patron->_result()->discard_changes();
287     isnt( $patron->lastseen, $last_seen, 'Patron last seen should be changed if we cleared the cache' );
288
289     t::lib::Mocks::mock_preference( 'TrackLastPatronActivity', '0' );
290     $patron->lastseen( undef )->store;
291     $cache->clear_from_cache($cache_key);
292     C4::Auth::track_login_daily( $userid );
293     $patron->_result()->discard_changes();
294     is( $patron->lastseen, undef, 'Patron should still have last seen unchanged when TrackLastPatronActivity = 0' );
295
296 };
297
298 subtest 'no_set_userenv parameter tests' => sub {
299
300     plan tests => 7;
301
302     my $library = $builder->build_object( { class => 'Koha::Libraries' } );
303     my $patron  = $builder->build_object( { class => 'Koha::Patrons' } );
304     my $password = 'password';
305
306     t::lib::Mocks::mock_preference( 'RequireStrongPassword', 0 );
307     $patron->set_password({ password => $password });
308
309     ok( checkpw( $patron->userid, $password, undef, undef, 1 ), 'checkpw returns true' );
310     is( C4::Context->userenv, undef, 'Userenv should be undef as required' );
311     C4::Context->_new_userenv('DUMMY SESSION');
312     C4::Context->set_userenv(0,0,0,'firstname','surname', $library->branchcode, 'Library 1', 0, '', '');
313     is( C4::Context->userenv->{branch}, $library->branchcode, 'Userenv gives correct branch' );
314     ok( checkpw( $patron->userid, $password, undef, undef, 1 ), 'checkpw returns true' );
315     is( C4::Context->userenv->{branch}, $library->branchcode, 'Userenv branch is preserved if no_set_userenv is true' );
316     ok( checkpw( $patron->userid, $password, undef, undef, 0 ), 'checkpw still returns true' );
317     isnt( C4::Context->userenv->{branch}, $library->branchcode, 'Userenv branch is overwritten if no_set_userenv is false' );
318 };
319
320 subtest 'checkpw lockout tests' => sub {
321
322     plan tests => 5;
323
324     my $library = $builder->build_object( { class => 'Koha::Libraries' } );
325     my $patron  = $builder->build_object( { class => 'Koha::Patrons' } );
326     my $password = 'password';
327     t::lib::Mocks::mock_preference( 'RequireStrongPassword', 0 );
328     t::lib::Mocks::mock_preference( 'FailedLoginAttempts', 1 );
329     $patron->set_password({ password => $password });
330
331     my ( $checkpw, undef, undef ) = checkpw( $patron->cardnumber, $password, undef, undef, 1 );
332     ok( $checkpw, 'checkpw returns true with right password when logging in via cardnumber' );
333     ( $checkpw, undef, undef ) = checkpw( $patron->userid, "wrong_password", undef, undef, 1 );
334     is( $checkpw, 0, 'checkpw returns false when given wrong password' );
335     $patron = $patron->get_from_storage;
336     is( $patron->account_locked, 1, "Account is locked from failed login");
337     ( $checkpw, undef, undef ) = checkpw( $patron->userid, $password, undef, undef, 1 );
338     is( $checkpw, undef, 'checkpw returns undef with right password when account locked' );
339     ( $checkpw, undef, undef ) = checkpw( $patron->cardnumber, $password, undef, undef, 1 );
340     is( $checkpw, undef, 'checkpw returns undefwith right password when logging in via cardnumber if account locked' );
341
342 };
343
344 # get_template_and_user tests
345
346 subtest 'get_template_and_user' => sub {   # Tests for the language URL parameter
347
348     sub MockedCheckauth {
349         my ($query,$authnotrequired,$flagsrequired,$type) = @_;
350         # return vars
351         my $userid = 'cobain';
352         my $sessionID = 234;
353         # we don't need to bother about permissions for this test
354         my $flags = {
355             superlibrarian    => 1, acquisition       => 0,
356             borrowers         => 0,
357             catalogue         => 1, circulate         => 0,
358             coursereserves    => 0, editauthorities   => 0,
359             editcatalogue     => 0,
360             parameters        => 0, permissions       => 0,
361             plugins           => 0, reports           => 0,
362             reserveforothers  => 0, serials           => 0,
363             staffaccess       => 0, tools             => 0,
364             updatecharges     => 0
365         };
366
367         my $session_cookie = $query->cookie(
368             -name => 'CGISESSID',
369             -value    => 'nirvana',
370             -HttpOnly => 1
371         );
372
373         return ( $userid, [ $session_cookie ], $sessionID, $flags );
374     }
375
376     # Mock checkauth, build the scenario
377     my $auth = Test::MockModule->new( 'C4::Auth' );
378     $auth->mock( 'checkauth', \&MockedCheckauth );
379
380     # Make sure 'EnableOpacSearchHistory' is set
381     t::lib::Mocks::mock_preference('EnableOpacSearchHistory',1);
382     # Enable es-ES for the OPAC and staff interfaces
383     t::lib::Mocks::mock_preference('OPACLanguages','en,es-ES');
384     t::lib::Mocks::mock_preference('language','en,es-ES');
385
386     # we need a session cookie
387     $ENV{"SERVER_PORT"} = 80;
388     $ENV{"HTTP_COOKIE"} = 'CGISESSID=nirvana';
389
390     my $query = CGI->new;
391     $query->param('language','es-ES');
392
393     my ( $template, $loggedinuser, $cookies ) = get_template_and_user(
394         {
395             template_name   => "about.tt",
396             query           => $query,
397             type            => "opac",
398             authnotrequired => 1,
399             flagsrequired   => { catalogue => 1 },
400             debug           => 1
401         }
402     );
403
404     ok ( ( all { ref($_) eq 'CGI::Cookie' } @$cookies ),
405             'BZ9735: the cookies array is flat' );
406
407     # new query, with non-existent language (we only have en and es-ES)
408     $query->param('language','tomas');
409
410     ( $template, $loggedinuser, $cookies ) = get_template_and_user(
411         {
412             template_name   => "about.tt",
413             query           => $query,
414             type            => "opac",
415             authnotrequired => 1,
416             flagsrequired   => { catalogue => 1 },
417             debug           => 1
418         }
419     );
420
421     ok( ( none { $_->name eq 'KohaOpacLanguage' and $_->value eq 'tomas' } @$cookies ),
422         'BZ9735: invalid language, it is not set');
423
424     ok( ( any { $_->name eq 'KohaOpacLanguage' and $_->value eq 'en' } @$cookies ),
425         'BZ9735: invalid language, then default to en');
426
427     for my $template_name (
428         qw(
429             ../../../../../../../../../../../../../../../etc/passwd
430             test/../../../../../../../../../../../../../../etc/passwd
431             /etc/passwd
432             test/does_not_finished_by_tt_t
433         )
434     ) {
435         eval {
436             ( $template, $loggedinuser, $cookies ) = get_template_and_user(
437                 {
438                     template_name   => $template_name,
439                     query           => $query,
440                     type            => "intranet",
441                     authnotrequired => 1,
442                     flagsrequired   => { catalogue => 1 },
443                 }
444             );
445         };
446         like ( $@, qr(bad template path), "The file $template_name should not be accessible" );
447     }
448     ( $template, $loggedinuser, $cookies ) = get_template_and_user(
449         {
450             template_name   => 'errors/errorpage.tt',
451             query           => $query,
452             type            => "intranet",
453             authnotrequired => 1,
454             flagsrequired   => { catalogue => 1 },
455         }
456     );
457     my $file_exists = ( -f $template->{filename} ) ? 1 : 0;
458     is ( $file_exists, 1, 'The file errors/errorpage.tt should be accessible (contains integers)' );
459
460     # Regression test for env opac search limit override
461     $ENV{"OPAC_SEARCH_LIMIT"} = "branch:CPL";
462     $ENV{"OPAC_LIMIT_OVERRIDE"} = 1;
463
464     ( $template, $loggedinuser, $cookies) = get_template_and_user(
465         {
466             template_name => 'opac-main.tt',
467             query => $query,
468             type => 'opac',
469             authnotrequired => 1,
470         }
471     );
472     is($template->{VARS}->{'opac_name'}, "CPL", "Opac name was set correctly");
473     is($template->{VARS}->{'opac_search_limit'}, "branch:CPL", "Search limit was set correctly");
474
475     $ENV{"OPAC_SEARCH_LIMIT"} = "branch:multibranch-19";
476
477     ( $template, $loggedinuser, $cookies) = get_template_and_user(
478         {
479             template_name => 'opac-main.tt',
480             query => $query,
481             type => 'opac',
482             authnotrequired => 1,
483         }
484     );
485     is($template->{VARS}->{'opac_name'}, "multibranch-19", "Opac name was set correctly");
486     is($template->{VARS}->{'opac_search_limit'}, "branch:multibranch-19", "Search limit was set correctly");
487
488     delete $ENV{"HTTP_COOKIE"};
489 };
490
491 # Check that there is always an OPACBaseURL set.
492 my $input = CGI->new();
493 my ( $template1, $borrowernumber, $cookie );
494 ( $template1, $borrowernumber, $cookie ) = get_template_and_user(
495     {
496         template_name => "opac-detail.tt",
497         type => "opac",
498         query => $input,
499         authnotrequired => 1,
500     }
501 );
502
503 ok( ( any { 'OPACBaseURL' eq $_ } keys %{$template1->{VARS}} ),
504     'OPACBaseURL is in OPAC template' );
505
506 my ( $template2 );
507 ( $template2, $borrowernumber, $cookie ) = get_template_and_user(
508     {
509         template_name => "catalogue/detail.tt",
510         type => "intranet",
511         query => $input,
512         authnotrequired => 1,
513     }
514 );
515
516 ok( ( any { 'OPACBaseURL' eq $_ } keys %{$template2->{VARS}} ),
517     'OPACBaseURL is in Staff template' );
518
519 my $hash1 = hash_password('password');
520 my $hash2 = hash_password('password');
521
522 ok(C4::Auth::checkpw_hash('password', $hash1), 'password validates with first hash');
523 ok(C4::Auth::checkpw_hash('password', $hash2), 'password validates with second hash');
524
525 subtest 'Check value of login_attempts in checkpw' => sub {
526     plan tests => 11;
527
528     t::lib::Mocks::mock_preference('FailedLoginAttempts', 3);
529
530     # Only interested here in regular login
531     $C4::Auth::cas  = 0;
532     $C4::Auth::ldap = 0;
533
534     my $patron = $builder->build_object({ class => 'Koha::Patrons' });
535     $patron->login_attempts(2);
536     $patron->password('123')->store; # yes, deliberately not hashed
537
538     is( $patron->account_locked, 0, 'Patron not locked' );
539     my @test = checkpw( $patron->userid, '123', undef, 'opac', 1 );
540         # Note: 123 will not be hashed to 123 !
541     is( $test[0], 0, 'checkpw should have failed' );
542     $patron->discard_changes; # refresh
543     is( $patron->login_attempts, 3, 'Login attempts increased' );
544     is( $patron->account_locked, 1, 'Check locked status' );
545
546     # And another try to go over the limit: different return value!
547     @test = checkpw( $patron->userid, '123', undef, 'opac', 1 );
548     is( @test, 0, 'checkpw failed again and returns nothing now' );
549     $patron->discard_changes; # refresh
550     is( $patron->login_attempts, 3, 'Login attempts not increased anymore' );
551
552     # Administrative lockout cannot be undone?
553     # Pass the right password now (or: add a nice mock).
554     my $auth = Test::MockModule->new( 'C4::Auth' );
555     $auth->mock( 'checkpw_hash', sub { return 1; } ); # not for production :)
556     $patron->login_attempts(0)->store;
557     @test = checkpw( $patron->userid, '123', undef, 'opac', 1 );
558     is( $test[0], 1, 'Build confidence in the mock' );
559     $patron->login_attempts(-1)->store;
560     is( $patron->account_locked, 1, 'Check administrative lockout' );
561     @test = checkpw( $patron->userid, '123', undef, 'opac', 1 );
562     is( @test, 0, 'checkpw gave red' );
563     $patron->discard_changes; # refresh
564     is( $patron->login_attempts, -1, 'Still locked out' );
565     t::lib::Mocks::mock_preference('FailedLoginAttempts', ''); # disable
566     is( $patron->account_locked, 1, 'Check administrative lockout without pref' );
567 };
568
569 subtest 'Check value of login_attempts in checkpw' => sub {
570     plan tests => 2;
571
572     t::lib::Mocks::mock_preference('FailedLoginAttempts', 3);
573     my $patron = $builder->build_object({ class => 'Koha::Patrons' });
574     $patron->set_password({ password => '123', skip_validation => 1 });
575
576     my @test = checkpw( $patron->userid, '123', undef, 'opac', 1 );
577     is( $test[0], 1, 'Patron authenticated correctly' );
578
579     $patron->password_expiration_date('2020-01-01')->store;
580     @test = checkpw( $patron->userid, '123', undef, 'opac', 1 );
581     is( $test[0], -2, 'Patron returned as expired correctly' );
582
583 };
584
585 subtest '_timeout_syspref' => sub {
586
587     plan tests => 6;
588
589     t::lib::Mocks::mock_preference('timeout', "100");
590     is( C4::Auth::_timeout_syspref, 100, );
591
592     t::lib::Mocks::mock_preference('timeout', "2d");
593     is( C4::Auth::_timeout_syspref, 2*86400, );
594
595     t::lib::Mocks::mock_preference('timeout', "2D");
596     is( C4::Auth::_timeout_syspref, 2*86400, );
597
598     t::lib::Mocks::mock_preference('timeout', "10h");
599     is( C4::Auth::_timeout_syspref, 10*3600, );
600
601     t::lib::Mocks::mock_preference('timeout', "10x");
602     warning_is
603         { is( C4::Auth::_timeout_syspref, 600, ); }
604         "The value of the system preference 'timeout' is not correct, defaulting to 600",
605         'Bad values throw a warning and fallback to 600';
606 };
607
608 subtest 'check_cookie_auth' => sub {
609     plan tests => 4;
610
611     t::lib::Mocks::mock_preference('timeout', "1d"); # back to default
612
613     my $patron = $builder->build_object({ class => 'Koha::Patrons', value => { flags => 1 } });
614
615     # Mock a CGI object with real userid param
616     my $cgi = Test::MockObject->new();
617     $cgi->mock(
618         'param',
619         sub {
620             my $var = shift;
621             if ( $var eq 'userid' ) { return $patron->userid; }
622         }
623     );
624     $cgi->mock('multi_param', sub {return q{}} );
625     $cgi->mock( 'cookie', sub { return; } );
626     $cgi->mock( 'request_method', sub { return 'POST' } );
627
628     $ENV{REMOTE_ADDR} = '127.0.0.1';
629
630     # Setting authnotrequired=1 or we wont' hit the return but the end of the sub that prints headers
631     my ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 1 );
632
633     my ($auth_status, $session) = C4::Auth::check_cookie_auth($sessionID);
634     isnt( $auth_status, 'ok', 'check_cookie_auth should not return ok if the user has not been authenticated before if no permissions needed' );
635     is( $auth_status, 'anon', 'check_cookie_auth should return anon if the user has not been authenticated before and no permissions needed' );
636
637     ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 1 );
638
639     ($auth_status, $session) = C4::Auth::check_cookie_auth($sessionID, {catalogue => 1});
640     isnt( $auth_status, 'ok', 'check_cookie_auth should not return ok if the user has not been authenticated before and permissions needed' );
641     is( $auth_status, 'anon', 'check_cookie_auth should return anon if the user has not been authenticated before and permissions needed' );
642
643     #FIXME We should have a test to cover 'failed' status when a user has logged in, but doesn't have permission
644 };
645
646 subtest 'checkauth & check_cookie_auth' => sub {
647     plan tests => 31;
648
649     # flags = 4 => { catalogue => 1 }
650     my $patron = $builder->build_object({ class => 'Koha::Patrons', value => { flags => 4 } });
651     my $password = 'password';
652     t::lib::Mocks::mock_preference( 'RequireStrongPassword', 0 );
653     $patron->set_password( { password => $password } );
654
655     my $cgi_mock = Test::MockModule->new('CGI');
656     $cgi_mock->mock( 'request_method', sub { return 'POST' } );
657
658     my $cgi = CGI->new;
659
660     my $auth = Test::MockModule->new( 'C4::Auth' );
661     # Tests will fail if we hit safe_exit
662     $auth->mock( 'safe_exit', sub { return } );
663
664     my ( $userid, $cookie, $sessionID, $flags );
665     {
666         # checkauth will redirect and safe_exit if not authenticated and not authorized
667         local *STDOUT;
668         my $stdout;
669         open STDOUT, '>', \$stdout;
670         C4::Auth::checkauth($cgi, 0, {catalogue => 1});
671         like( $stdout, qr{<title>\s*Log in to your account} );
672         $sessionID = ( $stdout =~ m{Set-Cookie: CGISESSID=((\d|\w)+);} ) ? $1 : undef;
673         ok($sessionID);
674         close STDOUT;
675     };
676
677     my $first_sessionID = $sessionID;
678
679     $ENV{"HTTP_COOKIE"} = "CGISESSID=$sessionID";
680     # Not authenticated yet, checkauth didn't return the session
681     {
682         local *STDOUT;
683         my $stdout;
684         open STDOUT, '>', \$stdout;
685         ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 0, {catalogue => 1} );
686         close STDOUT;
687     }
688     is( $sessionID, undef);
689     is( $userid, undef);
690
691     # Sending undefined fails obviously
692     my ( $auth_status, $session ) = C4::Auth::check_cookie_auth($sessionID, {catalogue => 1} );
693     is( $auth_status, 'failed' );
694     is( $session, undef );
695
696     # Simulating the login form submission
697     $cgi->param('userid', $patron->userid);
698     $cgi->param('password', $password);
699
700     # Logged in!
701     ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 0, {catalogue => 1});
702     is( $sessionID, $first_sessionID );
703     is( $userid, $patron->userid );
704
705     ( $auth_status, $session ) = C4::Auth::check_cookie_auth($sessionID, {catalogue => 1});
706     is( $auth_status, 'ok' );
707     is( $session->id, $first_sessionID );
708
709     # Logging out!
710     $cgi->param('logout.x', 1);
711     $cgi->delete( 'userid', 'password' );
712     {
713         local *STDOUT;
714         my $stdout;
715         open STDOUT, '>', \$stdout;
716         ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 0, {catalogue => 1});
717         close STDOUT;
718     }
719     is( $sessionID, undef );
720     is( $ENV{"HTTP_COOKIE"}, "CGISESSID=$first_sessionID", 'HTTP_COOKIE not unset' );
721     ( $auth_status, $session) = C4::Auth::check_cookie_auth( $first_sessionID, {catalogue => 1} );
722     is( $auth_status, "expired");
723     is( $session, undef );
724
725     {
726         # Trying to access without sessionID
727         $cgi = CGI->new;
728         ( $auth_status, $session) = C4::Auth::check_cookie_auth(undef, {catalogue => 1});
729         is( $auth_status, 'failed' );
730         is( $session, undef );
731
732         # This will fail on permissions
733         undef $ENV{"HTTP_COOKIE"};
734         {
735             local *STDOUT;
736             my $stdout;
737             open STDOUT, '>', \$stdout;
738             ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 0, {catalogue => 1} );
739             close STDOUT;
740         }
741         is( $userid, undef );
742         is( $sessionID, undef );
743     }
744
745     {
746         # First logging in
747         $cgi = CGI->new;
748         $cgi->param('userid', $patron->userid);
749         $cgi->param('password', $password);
750         ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 0, {catalogue => 1});
751         is( $userid, $patron->userid );
752         $first_sessionID = $sessionID;
753
754         # Patron does not have the borrowers permission
755         # $ENV{"HTTP_COOKIE"} = "CGISESSID=$sessionID"; # not needed, we use $cgi here
756         {
757             local *STDOUT;
758             my $stdout;
759             open STDOUT, '>', \$stdout;
760             ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 0, {borrowers => 1} );
761             close STDOUT;
762         }
763         is( $userid, undef );
764         is( $sessionID, undef );
765
766         # When calling check_cookie_auth, the session will be deleted
767         ( $auth_status, $session) = C4::Auth::check_cookie_auth( $first_sessionID, { borrowers => 1 } );
768         is( $auth_status, "failed" );
769         is( $session, undef );
770         ( $auth_status, $session) = C4::Auth::check_cookie_auth( $first_sessionID, { borrowers => 1 } );
771         is( $auth_status, 'expired', 'Session no longer exists' );
772
773         # NOTE: It is not what the UI is doing.
774         # From the UI we are allowed to hit an unauthorized page then reuse the session to hit back authorized area.
775         # It is because check_cookie_auth is ALWAYS called from checkauth WITHOUT $flagsrequired
776         # It then return "ok", when the previous called got "failed"
777
778         # Try reusing the deleted session: since it does not exist, we should get a new one now when passing correct permissions
779         $cgi->cookie( -name => 'CGISESSID', value => $first_sessionID );
780         ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 0, {catalogue => 1});
781         is( $userid, $patron->userid );
782         isnt( $sessionID, undef, 'Check if we have a sessionID' );
783         isnt( $sessionID, $first_sessionID, 'New value expected' );
784         ( $auth_status, $session) = C4::Auth::check_cookie_auth( $sessionID, {catalogue => 1} );
785         is( $auth_status, "ok" );
786         is( $session->id, $sessionID, 'Same session' );
787         # Two additional tests on userenv
788         is( $C4::Context::context->{activeuser}, $session->id, 'Check if environment has been setup for session' );
789         is( C4::Context->userenv->{id}, $userid, 'Check userid in userenv' );
790     }
791 };
792
793 subtest 'Userenv clearing in check_cookie_auth' => sub {
794     # Note: We did already test userenv for a logged-in user in previous subtest
795     plan tests => 9;
796
797     t::lib::Mocks::mock_preference( 'timeout', 600 );
798     my $cgi = CGI->new;
799
800     # Create a new anonymous session by passing a fake session ID
801     $cgi->cookie( -name => 'CGISESSID', -value => 'fake_sessionID' );
802     my ($userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 1);
803     my ( $auth_status, $session) = C4::Auth::check_cookie_auth( $sessionID );
804     is( $auth_status, 'anon', 'Should be anonymous' );
805     is( $C4::Context::context->{activeuser}, $session->id, 'Check activeuser' );
806     is( defined C4::Context->userenv, 1, 'There should be a userenv' );
807     is(  C4::Context->userenv->{id}, q{}, 'userid should be empty string' );
808
809     # Make the session expire now, check_cookie_auth will delete it
810     $session->param('lasttime', time() - 1200 );
811     $session->flush;
812     ( $auth_status, $session) = C4::Auth::check_cookie_auth( $sessionID );
813     is( $auth_status, 'expired', 'Should be expired' );
814     is( C4::Context->userenv, undef, 'Environment should be cleared too' );
815
816     # Show that we clear the userenv again: set up env and check deleted session
817     C4::Context->_new_userenv( $sessionID );
818     C4::Context->set_userenv; # empty
819     is( defined C4::Context->userenv, 1, 'There should be an empty userenv again' );
820     ( $auth_status, $session) = C4::Auth::check_cookie_auth( $sessionID );
821     is( $auth_status, 'expired', 'Should be expired already' );
822     is( C4::Context->userenv, undef, 'Environment should be cleared again' );
823 };
824
825 $schema->storage->txn_rollback;