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