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