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