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