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