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