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