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