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