Bug 34893: Unit tests for C4::Auth::checkpw
[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 my $dbh     = C4::Context->dbh;
32
33 # FIXME: SessionStorage defaults to mysql, but it seems to break transaction
34 # handling
35 t::lib::Mocks::mock_preference( 'SessionStorage', 'tmp' );
36 t::lib::Mocks::mock_preference( 'GDPR_Policy', '' ); # Disabled
37
38 # To silence useless warnings
39 $ENV{REMOTE_ADDR} = '127.0.0.1';
40
41 $schema->storage->txn_begin;
42
43 subtest 'checkauth() tests' => sub {
44
45     plan tests => 8;
46
47     my $patron = $builder->build_object({ class => 'Koha::Patrons', value => { flags => undef } });
48
49     # Mock a CGI object with real userid param
50     my $cgi = Test::MockObject->new();
51     $cgi->mock(
52         'param',
53         sub {
54             my $var = shift;
55             if ( $var eq 'userid' ) { return $patron->userid; }
56         }
57     );
58     $cgi->mock( 'cookie', sub { return; } );
59     $cgi->mock( 'request_method', sub { return 'POST' } );
60
61     my $authnotrequired = 1;
62     my ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, $authnotrequired );
63
64     is( $userid, undef, 'checkauth() returns undef for userid if no logged in user (Bug 18275)' );
65
66     my $db_user_id = C4::Context->config('user');
67     my $db_user_pass = C4::Context->config('pass');
68     $cgi = Test::MockObject->new();
69     $cgi->mock( 'cookie', sub { return; } );
70     $cgi->mock( 'param', sub {
71             my ( $self, $param ) = @_;
72             if ( $param eq 'userid' ) { return $db_user_id; }
73             elsif ( $param eq 'password' ) { return $db_user_pass; }
74             else { return; }
75         });
76     $cgi->mock( 'request_method', sub { return 'POST' } );
77     ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, $authnotrequired );
78     is ( $userid, undef, 'If DB user is used, it should not be logged in' );
79
80     my $is_allowed = C4::Auth::haspermission( $db_user_id, { can_do => 'everything' } );
81
82     # FIXME This belongs to t/db_dependent/Auth/haspermission.t but we do not want to c/p the pervious mock statements
83     ok( !$is_allowed, 'DB user should not have any permissions');
84
85     subtest 'Prevent authentication when sending credential via GET' => sub {
86
87         plan tests => 2;
88
89         my $patron = $builder->build_object(
90             { class => 'Koha::Patrons', value => { flags => 1 } } );
91         my $password = 'password';
92         t::lib::Mocks::mock_preference( 'RequireStrongPassword', 0 );
93         $patron->set_password( { password => $password } );
94         $cgi = Test::MockObject->new();
95         $cgi->mock( 'cookie', sub { return; } );
96         $cgi->mock(
97             'param',
98             sub {
99                 my ( $self, $param ) = @_;
100                 if    ( $param eq 'userid' )   { return $patron->userid; }
101                 elsif ( $param eq 'password' ) { return $password; }
102                 else                           { return; }
103             }
104         );
105
106         $cgi->mock( 'request_method', sub { return 'POST' } );
107         ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired' );
108         is( $userid, $patron->userid, 'If librarian user is used and password with POST, they should be logged in' );
109
110         $cgi->mock( 'request_method', sub { return 'GET' } );
111         ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired' );
112         is( $userid, undef, 'If librarian user is used and password with GET, they should not be logged in' );
113     };
114
115     subtest 'Template params tests (password_expired)' => sub {
116
117         plan tests => 1;
118
119         my $password_expired;
120
121         my $patron_class = Test::MockModule->new('Koha::Patron');
122         $patron_class->mock( 'password_expired', sub { return $password_expired; } );
123
124         my $patron = $builder->build_object({ class => 'Koha::Patrons', value => { flags => 1 } });
125         my $password = 'password';
126         t::lib::Mocks::mock_preference( 'RequireStrongPassword', 0 );
127         $patron->set_password( { password => $password } );
128
129         my $cgi_mock = Test::MockModule->new('CGI')->mock( 'request_method', 'POST' );
130         my $cgi = CGI->new;
131         $cgi->param( -name => 'userid',   -value => $patron->userid );
132         $cgi->param( -name => 'password', -value => $password );
133
134         my $auth = Test::MockModule->new( 'C4::Auth' );
135         # Tests will fail if we hit safe_exit
136         $auth->mock( 'safe_exit', sub { return } );
137
138         my ( $userid, $cookie, $sessionID, $flags );
139
140         {
141             t::lib::Mocks::mock_preference( 'DumpTemplateVarsOpac', 1 );
142             # checkauth will redirect and safe_exit if not authenticated and not authorized
143             local *STDOUT;
144             my $stdout;
145             open STDOUT, '>', \$stdout;
146
147             # Password has expired
148             $password_expired = 1;
149             C4::Auth::checkauth( $cgi, 0, { catalogue => 1 } );
150             like( $stdout, qr{'password_has_expired' => 1}, 'password_has_expired is set to 1' );
151
152             close STDOUT;
153         };
154     };
155
156     subtest 'Reset auth state when changing users' => sub {
157
158         #NOTE: It's easiest to detect this when changing to a non-existent user, since
159         #that should trigger a redirect to login (instead of returning a session cookie)
160         plan tests => 2;
161         my $patron = $builder->build_object( { class => 'Koha::Patrons', value => { flags => undef } } );
162
163         my $session = C4::Auth::get_session();
164         $session->param( 'number',    $patron->id );
165         $session->param( 'id',        $patron->userid );
166         $session->param( 'ip',        '1.2.3.4' );
167         $session->param( 'lasttime',  time() );
168         $session->param( 'interface', 'intranet' );
169         $session->flush;
170         my $sessionID = $session->id;
171         C4::Context->_new_userenv($sessionID);
172
173         my ($return) =
174             C4::Auth::check_cookie_auth( $sessionID, undef, { skip_version_check => 1, remote_addr => '1.2.3.4' } );
175         is( $return, 'ok', 'Patron authenticated' );
176
177         my $mock1 = Test::MockModule->new('C4::Auth');
178         $mock1->mock( 'safe_exit', sub { return 'safe_exit_redirect' } );
179         my $mock2 = Test::MockModule->new('CGI');
180         $mock2->mock( 'request_method', 'POST' );
181         $mock2->mock( 'cookie',         sub { return $sessionID; } );    # oversimplified..
182         my $cgi = CGI->new;
183
184         $cgi->param( -name => 'userid',             -value => 'Bond' );
185         $cgi->param( -name => 'password',           -value => 'James Bond' );
186         $cgi->param( -name => 'koha_login_context', -value => 1 );
187         my ( @return, $stdout );
188         {
189             local *STDOUT;
190             local %ENV;
191             $ENV{REMOTE_ADDR} = '1.2.3.4';
192             open STDOUT, '>', \$stdout;
193             @return = C4::Auth::checkauth( $cgi, 0, {} );
194             close STDOUT;
195         }
196         is( $return[0], 'safe_exit_redirect', 'Changing to non-existent user causes a redirect to login' );
197     };
198
199
200     subtest 'While still logged in, relogin with another user' => sub {
201         plan tests => 6;
202
203         my $patron = $builder->build_object({ class => 'Koha::Patrons', value => {} });
204         my $patron2 = $builder->build_object({ class => 'Koha::Patrons', value => {} });
205         # Create 'former' session
206         my $session = C4::Auth::get_session();
207         $session->param( 'number',       $patron->id );
208         $session->param( 'id',           $patron->userid );
209         $session->param( 'ip',           '1.2.3.4' );
210         $session->param( 'lasttime',     time() );
211         $session->param( 'interface',    'opac' );
212         $session->flush;
213         my $sessionID = $session->id;
214         C4::Context->_new_userenv($sessionID);
215
216         my ( $return ) = C4::Auth::check_cookie_auth( $sessionID, undef, { skip_version_check => 1, remote_addr => '1.2.3.4' } );
217         is( $return, 'ok', 'Former session in shape now' );
218
219         my $mock1 = Test::MockModule->new('C4::Auth');
220         $mock1->mock( 'safe_exit', sub {} );
221         my $mock2 = Test::MockModule->new('CGI');
222         $mock2->mock( 'request_method', 'POST' );
223         $mock2->mock( 'cookie', sub { return $sessionID; } ); # oversimplified..
224         my $cgi = CGI->new;
225         my $password = 'Incr3d1blyZtr@ng93$';
226         $patron2->set_password({ password => $password });
227         $cgi->param( -name => 'userid',             -value => $patron2->userid );
228         $cgi->param( -name => 'password',           -value => $password );
229         $cgi->param( -name => 'koha_login_context', -value => 1 );
230         my ( @return, $stdout );
231         {
232             local *STDOUT;
233             local %ENV;
234             $ENV{REMOTE_ADDR} = '1.2.3.4';
235             open STDOUT, '>', \$stdout;
236             @return = C4::Auth::checkauth( $cgi, 0, {} );
237             close STDOUT;
238         }
239         # Note: We can test return values from checkauth here since we mocked the safe_exit after the Redirect 303
240         is( $return[0], $patron2->userid, 'Login of patron2 approved' );
241         isnt( $return[2], $sessionID, 'Did not return previous session ID' );
242         ok( $return[2], 'New session ID not empty' );
243
244         # Similar situation: Relogin with former session of $patron, new user $patron2 has no permissions
245         $patron2->flags(undef)->store;
246         $session->param( 'number',       $patron->id );
247         $session->param( 'id',           $patron->userid );
248         $session->param( 'interface',    'intranet' );
249         $session->flush;
250         $sessionID = $session->id;
251         C4::Context->_new_userenv($sessionID);
252         $cgi->param( -name => 'userid',             -value => $patron2->userid );
253         $cgi->param( -name => 'password',           -value => $password );
254         $cgi->param( -name => 'koha_login_context', -value => 1 );
255         {
256             local *STDOUT;
257             local %ENV;
258             $ENV{REMOTE_ADDR} = '1.2.3.4';
259             $stdout = q{};
260             open STDOUT, '>', \$stdout;
261             @return = C4::Auth::checkauth( $cgi, 0, { catalogue => 1 }, 'intranet' ); # patron2 has no catalogue perm
262             close STDOUT;
263         }
264         like( $stdout, qr/You do not have permission to access this page/, 'No permission response' );
265         is( @return, 0, 'checkauth returned failure' );
266     };
267
268     subtest 'Two-factor authentication' => sub {
269
270         my $patron = $builder->build_object(
271             { class => 'Koha::Patrons', value => { flags => 1 } } );
272         my $password = 'password';
273         $patron->set_password( { password => $password } );
274         $cgi = Test::MockObject->new();
275
276         my $otp_token;
277         our ( $logout, $sessionID, $verified );
278         $cgi->mock(
279             'param',
280             sub {
281                 my ( $self, $param ) = @_;
282                 if    ( $param eq 'userid' )    { return $patron->userid; }
283                 elsif ( $param eq 'password' )  { return $password; }
284                 elsif ( $param eq 'otp_token' ) { return $otp_token; }
285                 elsif ( $param eq 'logout.x' )  { return $logout; }
286                 else                            { return; }
287             }
288         );
289         $cgi->mock( 'request_method', sub { return 'POST' } );
290         $cgi->mock( 'cookie', sub { return $sessionID } );
291
292         my $two_factor_auth = Test::MockModule->new( 'Koha::Auth::TwoFactorAuth' );
293         $two_factor_auth->mock( 'verify', sub {$verified} );
294
295         my ( $userid, $cookie, $flags );
296         ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired', undef, 'intranet' );
297
298         sub logout {
299             my $cgi = shift;
300             $logout = 1;
301             undef $sessionID;
302             C4::Auth::checkauth( $cgi, 'authrequired', undef, 'intranet' );
303             $logout = 0;
304         }
305
306         t::lib::Mocks::mock_preference( 'TwoFactorAuthentication', 0 );
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'), undef, 'Second auth not required' );
311         logout($cgi);
312
313         $patron->auth_method('two-factor')->store;
314         ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired', undef, 'intranet' );
315         is( $userid, $patron->userid, 'Succesful login' );
316         is( C4::Auth::get_session($sessionID)->param('waiting-for-2FA'), undef, 'Second auth not required' );
317         logout($cgi);
318
319         t::lib::Mocks::mock_preference( 'TwoFactorAuthentication', 1 );
320         t::lib::Mocks::mock_config('encryption_key', '1234tH1s=t&st');
321         $patron->auth_method('password')->store;
322         ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired', undef, 'intranet' );
323         is( $userid, $patron->userid, 'Succesful login' );
324         is( C4::Auth::get_session($sessionID)->param('waiting-for-2FA'), undef, 'Second auth not required' );
325         logout($cgi);
326
327         $patron->encode_secret('one_secret');
328         $patron->auth_method('two-factor');
329         $patron->store;
330         ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired', undef, 'intranet' );
331         is( $userid, $patron->userid, 'Succesful login' );
332         my $session = C4::Auth::get_session($sessionID);
333         is( C4::Auth::get_session($sessionID)->param('waiting-for-2FA'), 1, 'Second auth required' );
334
335         # Wrong OTP token
336         $otp_token = "wrong";
337         $verified = 0;
338         $patron->auth_method('two-factor')->store;
339         ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired', undef, 'intranet' );
340         is( $userid, $patron->userid, 'Succesful login' );
341         is( C4::Auth::get_session($sessionID)->param('waiting-for-2FA'), 1, 'Second auth still required after wrong OTP token' );
342
343         $otp_token = "good";
344         $verified = 1;
345         ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired', undef, 'intranet' );
346         is( $userid, $patron->userid, 'Succesful login' );
347         is( C4::Auth::get_session($sessionID)->param('waiting-for-2FA'), 0, 'Second auth no longer required if OTP token has been verified' );
348
349         logout($cgi);
350         ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired', undef, 'opac' );
351         is( $userid, $patron->userid, 'Succesful login at the OPAC' );
352         is( C4::Auth::get_session($sessionID)->param('waiting-for-2FA'), undef, 'No second auth required at the OPAC' );
353
354         t::lib::Mocks::mock_preference( 'TwoFactorAuthentication', 0 );
355     };
356
357     C4::Context->_new_userenv; # For next tests
358
359 };
360
361 subtest 'track_login_daily tests' => sub {
362
363     plan tests => 5;
364
365     my $patron = $builder->build_object({ class => 'Koha::Patrons' });
366     my $userid = $patron->userid;
367
368     $patron->lastseen( undef );
369     $patron->store();
370
371     my $cache     = Koha::Caches->get_instance();
372     my $cache_key = "track_login_" . $patron->userid;
373     $cache->clear_from_cache($cache_key);
374
375     t::lib::Mocks::mock_preference( 'TrackLastPatronActivity', '1' );
376
377     is( $patron->lastseen, undef, 'Patron should have not last seen when newly created' );
378
379     C4::Auth::track_login_daily( $userid );
380     $patron->_result()->discard_changes();
381     isnt( $patron->lastseen, undef, 'Patron should have last seen set when TrackLastPatronActivity = 1' );
382
383     sleep(1); # We need to wait a tiny bit to make sure the timestamp will be different
384     my $last_seen = $patron->lastseen;
385     C4::Auth::track_login_daily( $userid );
386     $patron->_result()->discard_changes();
387     is( $patron->lastseen, $last_seen, 'Patron last seen should still be unchanged' );
388
389     $cache->clear_from_cache($cache_key);
390     C4::Auth::track_login_daily( $userid );
391     $patron->_result()->discard_changes();
392     isnt( $patron->lastseen, $last_seen, 'Patron last seen should be changed if we cleared the cache' );
393
394     t::lib::Mocks::mock_preference( 'TrackLastPatronActivity', '0' );
395     $patron->lastseen( undef )->store;
396     $cache->clear_from_cache($cache_key);
397     C4::Auth::track_login_daily( $userid );
398     $patron->_result()->discard_changes();
399     is( $patron->lastseen, undef, 'Patron should still have last seen unchanged when TrackLastPatronActivity = 0' );
400
401 };
402
403 subtest 'no_set_userenv parameter tests' => sub {
404
405     plan tests => 7;
406
407     my $library = $builder->build_object( { class => 'Koha::Libraries' } );
408     my $patron  = $builder->build_object( { class => 'Koha::Patrons' } );
409     my $password = 'password';
410
411     t::lib::Mocks::mock_preference( 'RequireStrongPassword', 0 );
412     $patron->set_password({ password => $password });
413
414     ok( checkpw( $dbh, $patron->userid, $password, undef, undef, 1 ), 'checkpw returns true' );
415     is( C4::Context->userenv, undef, 'Userenv should be undef as required' );
416     C4::Context->_new_userenv('DUMMY SESSION');
417     C4::Context->set_userenv(0,0,0,'firstname','surname', $library->branchcode, 'Library 1', 0, '', '');
418     is( C4::Context->userenv->{branch}, $library->branchcode, 'Userenv gives correct branch' );
419     ok( checkpw( $dbh, $patron->userid, $password, undef, undef, 1 ), 'checkpw returns true' );
420     is( C4::Context->userenv->{branch}, $library->branchcode, 'Userenv branch is preserved if no_set_userenv is true' );
421     ok( checkpw( $dbh, $patron->userid, $password, undef, undef, 0 ), 'checkpw still returns true' );
422     isnt( C4::Context->userenv->{branch}, $library->branchcode, 'Userenv branch is overwritten if no_set_userenv is false' );
423 };
424
425 subtest 'checkpw lockout tests' => sub {
426
427     plan tests => 5;
428
429     my $library = $builder->build_object( { class => 'Koha::Libraries' } );
430     my $patron  = $builder->build_object( { class => 'Koha::Patrons' } );
431     my $password = 'password';
432     t::lib::Mocks::mock_preference( 'RequireStrongPassword', 0 );
433     t::lib::Mocks::mock_preference( 'FailedLoginAttempts', 1 );
434     $patron->set_password({ password => $password });
435
436     my ( $checkpw, undef, undef ) = checkpw( $dbh, $patron->cardnumber, $password, undef, undef, 1 );
437     ok( $checkpw, 'checkpw returns true with right password when logging in via cardnumber' );
438     ( $checkpw, undef, undef ) = checkpw( $dbh, $patron->userid, "wrong_password", undef, undef, 1 );
439     is( $checkpw, 0, 'checkpw returns false when given wrong password' );
440     $patron = $patron->get_from_storage;
441     is( $patron->account_locked, 1, "Account is locked from failed login");
442     ( $checkpw, undef, undef ) = checkpw( $dbh, $patron->userid, $password, undef, undef, 1 );
443     is( $checkpw, undef, 'checkpw returns undef with right password when account locked' );
444     ( $checkpw, undef, undef ) = checkpw( $dbh, $patron->cardnumber, $password, undef, undef, 1 );
445     is( $checkpw, undef, 'checkpw returns undefwith right password when logging in via cardnumber if account locked' );
446
447 };
448
449 # get_template_and_user tests
450
451 subtest 'get_template_and_user' => sub {   # Tests for the language URL parameter
452
453     sub MockedCheckauth {
454         my ($query,$authnotrequired,$flagsrequired,$type) = @_;
455         # return vars
456         my $userid = 'cobain';
457         my $sessionID = 234;
458         # we don't need to bother about permissions for this test
459         my $flags = {
460             superlibrarian    => 1, acquisition       => 0,
461             borrowers         => 0,
462             catalogue         => 1, circulate         => 0,
463             coursereserves    => 0, editauthorities   => 0,
464             editcatalogue     => 0,
465             parameters        => 0, permissions       => 0,
466             plugins           => 0, reports           => 0,
467             reserveforothers  => 0, serials           => 0,
468             staffaccess       => 0, tools             => 0,
469             updatecharges     => 0
470         };
471
472         my $session_cookie = $query->cookie(
473             -name => 'CGISESSID',
474             -value    => 'nirvana',
475             -HttpOnly => 1
476         );
477
478         return ( $userid, [ $session_cookie ], $sessionID, $flags );
479     }
480
481     # Mock checkauth, build the scenario
482     my $auth = Test::MockModule->new( 'C4::Auth' );
483     $auth->mock( 'checkauth', \&MockedCheckauth );
484
485     # Make sure 'EnableOpacSearchHistory' is set
486     t::lib::Mocks::mock_preference('EnableOpacSearchHistory',1);
487     # Enable es-ES for the OPAC and staff interfaces
488     t::lib::Mocks::mock_preference('OPACLanguages','en,es-ES');
489     t::lib::Mocks::mock_preference('language','en,es-ES');
490
491     # we need a session cookie
492     $ENV{"SERVER_PORT"} = 80;
493     $ENV{"HTTP_COOKIE"} = 'CGISESSID=nirvana';
494
495     my $query = CGI->new;
496     $query->param('language','es-ES');
497
498     my ( $template, $loggedinuser, $cookies ) = get_template_and_user(
499         {
500             template_name   => "about.tt",
501             query           => $query,
502             type            => "opac",
503             authnotrequired => 1,
504             flagsrequired   => { catalogue => 1 },
505             debug           => 1
506         }
507     );
508
509     ok ( ( all { ref($_) eq 'CGI::Cookie' } @$cookies ),
510             'BZ9735: the cookies array is flat' );
511
512     # new query, with non-existent language (we only have en and es-ES)
513     $query->param('language','tomas');
514
515     ( $template, $loggedinuser, $cookies ) = get_template_and_user(
516         {
517             template_name   => "about.tt",
518             query           => $query,
519             type            => "opac",
520             authnotrequired => 1,
521             flagsrequired   => { catalogue => 1 },
522             debug           => 1
523         }
524     );
525
526     ok( ( none { $_->name eq 'KohaOpacLanguage' and $_->value eq 'tomas' } @$cookies ),
527         'BZ9735: invalid language, it is not set');
528
529     ok( ( any { $_->name eq 'KohaOpacLanguage' and $_->value eq 'en' } @$cookies ),
530         'BZ9735: invalid language, then default to en');
531
532     for my $template_name (
533         qw(
534             ../../../../../../../../../../../../../../../etc/passwd
535             test/../../../../../../../../../../../../../../etc/passwd
536             /etc/passwd
537             test/does_not_finished_by_tt_t
538         )
539     ) {
540         eval {
541             ( $template, $loggedinuser, $cookies ) = get_template_and_user(
542                 {
543                     template_name   => $template_name,
544                     query           => $query,
545                     type            => "intranet",
546                     authnotrequired => 1,
547                     flagsrequired   => { catalogue => 1 },
548                 }
549             );
550         };
551         like ( $@, qr(bad template path), "The file $template_name should not be accessible" );
552     }
553     ( $template, $loggedinuser, $cookies ) = get_template_and_user(
554         {
555             template_name   => 'errors/errorpage.tt',
556             query           => $query,
557             type            => "intranet",
558             authnotrequired => 1,
559             flagsrequired   => { catalogue => 1 },
560         }
561     );
562     my $file_exists = ( -f $template->{filename} ) ? 1 : 0;
563     is ( $file_exists, 1, 'The file errors/errorpage.tt should be accessible (contains integers)' );
564
565     # Regression test for env opac search limit override
566     $ENV{"OPAC_SEARCH_LIMIT"} = "branch:CPL";
567     $ENV{"OPAC_LIMIT_OVERRIDE"} = 1;
568
569     ( $template, $loggedinuser, $cookies) = get_template_and_user(
570         {
571             template_name => 'opac-main.tt',
572             query => $query,
573             type => 'opac',
574             authnotrequired => 1,
575         }
576     );
577     is($template->{VARS}->{'opac_name'}, "CPL", "Opac name was set correctly");
578     is($template->{VARS}->{'opac_search_limit'}, "branch:CPL", "Search limit was set correctly");
579
580     $ENV{"OPAC_SEARCH_LIMIT"} = "branch:multibranch-19";
581
582     ( $template, $loggedinuser, $cookies) = get_template_and_user(
583         {
584             template_name => 'opac-main.tt',
585             query => $query,
586             type => 'opac',
587             authnotrequired => 1,
588         }
589     );
590     is($template->{VARS}->{'opac_name'}, "multibranch-19", "Opac name was set correctly");
591     is($template->{VARS}->{'opac_search_limit'}, "branch:multibranch-19", "Search limit was set correctly");
592     ok(defined($template->{VARS}->{'csrf_token'}), "CSRF token returned");
593
594     delete $ENV{"HTTP_COOKIE"};
595 };
596
597 # Check that there is always an OPACBaseURL set.
598 my $input = CGI->new();
599 my ( $template1, $borrowernumber, $cookie );
600 ( $template1, $borrowernumber, $cookie ) = get_template_and_user(
601     {
602         template_name => "opac-detail.tt",
603         type => "opac",
604         query => $input,
605         authnotrequired => 1,
606     }
607 );
608
609 ok( ( any { 'OPACBaseURL' eq $_ } keys %{$template1->{VARS}} ),
610     'OPACBaseURL is in OPAC template' );
611
612 my ( $template2 );
613 ( $template2, $borrowernumber, $cookie ) = get_template_and_user(
614     {
615         template_name => "catalogue/detail.tt",
616         type => "intranet",
617         query => $input,
618         authnotrequired => 1,
619     }
620 );
621
622 ok( ( any { 'OPACBaseURL' eq $_ } keys %{$template2->{VARS}} ),
623     'OPACBaseURL is in Staff template' );
624
625 my $hash1 = hash_password('password');
626 my $hash2 = hash_password('password');
627
628 ok(C4::Auth::checkpw_hash('password', $hash1), 'password validates with first hash');
629 ok(C4::Auth::checkpw_hash('password', $hash2), 'password validates with second hash');
630
631 subtest 'Check value of login_attempts in checkpw' => sub {
632     plan tests => 11;
633
634     t::lib::Mocks::mock_preference('FailedLoginAttempts', 3);
635
636     # Only interested here in regular login
637     $C4::Auth::cas  = 0;
638     $C4::Auth::ldap = 0;
639
640     my $patron = $builder->build_object({ class => 'Koha::Patrons' });
641     $patron->login_attempts(2);
642     $patron->password('123')->store; # yes, deliberately not hashed
643
644     is( $patron->account_locked, 0, 'Patron not locked' );
645     my @test = checkpw( $dbh, $patron->userid, '123', undef, 'opac', 1 );
646         # Note: 123 will not be hashed to 123 !
647     is( $test[0], 0, 'checkpw should have failed' );
648     $patron->discard_changes; # refresh
649     is( $patron->login_attempts, 3, 'Login attempts increased' );
650     is( $patron->account_locked, 1, 'Check locked status' );
651
652     # And another try to go over the limit: different return value!
653     @test = checkpw( $dbh, $patron->userid, '123', undef, 'opac', 1 );
654     is( @test, 0, 'checkpw failed again and returns nothing now' );
655     $patron->discard_changes; # refresh
656     is( $patron->login_attempts, 3, 'Login attempts not increased anymore' );
657
658     # Administrative lockout cannot be undone?
659     # Pass the right password now (or: add a nice mock).
660     my $auth = Test::MockModule->new( 'C4::Auth' );
661     $auth->mock( 'checkpw_hash', sub { return 1; } ); # not for production :)
662     $patron->login_attempts(0)->store;
663     @test = checkpw( $dbh, $patron->userid, '123', undef, 'opac', 1 );
664     is( $test[0], 1, 'Build confidence in the mock' );
665     $patron->login_attempts(-1)->store;
666     is( $patron->account_locked, 1, 'Check administrative lockout' );
667     @test = checkpw( $dbh, $patron->userid, '123', undef, 'opac', 1 );
668     is( @test, 0, 'checkpw gave red' );
669     $patron->discard_changes; # refresh
670     is( $patron->login_attempts, -1, 'Still locked out' );
671     t::lib::Mocks::mock_preference('FailedLoginAttempts', ''); # disable
672     is( $patron->account_locked, 1, 'Check administrative lockout without pref' );
673 };
674
675 subtest 'Check value of login_attempts in checkpw' => sub {
676     plan tests => 2;
677
678     t::lib::Mocks::mock_preference('FailedLoginAttempts', 3);
679     my $patron = $builder->build_object({ class => 'Koha::Patrons' });
680     $patron->set_password({ password => '123', skip_validation => 1 });
681
682     my @test = checkpw( $dbh, $patron->userid, '123', undef, 'opac', 1 );
683     is( $test[0], 1, 'Patron authenticated correctly' );
684
685     $patron->password_expiration_date('2020-01-01')->store;
686     @test = checkpw( $dbh, $patron->userid, '123', undef, 'opac', 1 );
687     is( $test[0], -2, 'Patron returned as expired correctly' );
688
689 };
690
691 subtest '_timeout_syspref' => sub {
692
693     plan tests => 6;
694
695     t::lib::Mocks::mock_preference('timeout', "100");
696     is( C4::Auth::_timeout_syspref, 100, );
697
698     t::lib::Mocks::mock_preference('timeout', "2d");
699     is( C4::Auth::_timeout_syspref, 2*86400, );
700
701     t::lib::Mocks::mock_preference('timeout', "2D");
702     is( C4::Auth::_timeout_syspref, 2*86400, );
703
704     t::lib::Mocks::mock_preference('timeout', "10h");
705     is( C4::Auth::_timeout_syspref, 10*3600, );
706
707     t::lib::Mocks::mock_preference('timeout', "10x");
708     warning_is
709         { is( C4::Auth::_timeout_syspref, 600, ); }
710         "The value of the system preference 'timeout' is not correct, defaulting to 600",
711         'Bad values throw a warning and fallback to 600';
712 };
713
714 subtest 'check_cookie_auth' => sub {
715     plan tests => 4;
716
717     t::lib::Mocks::mock_preference('timeout', "1d"); # back to default
718
719     my $patron = $builder->build_object({ class => 'Koha::Patrons', value => { flags => 1 } });
720
721     # Mock a CGI object with real userid param
722     my $cgi = Test::MockObject->new();
723     $cgi->mock(
724         'param',
725         sub {
726             my $var = shift;
727             if ( $var eq 'userid' ) { return $patron->userid; }
728         }
729     );
730     $cgi->mock('multi_param', sub {return q{}} );
731     $cgi->mock( 'cookie', sub { return; } );
732     $cgi->mock( 'request_method', sub { return 'POST' } );
733
734     $ENV{REMOTE_ADDR} = '127.0.0.1';
735
736     # Setting authnotrequired=1 or we wont' hit the return but the end of the sub that prints headers
737     my ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 1 );
738
739     my ($auth_status, $session) = C4::Auth::check_cookie_auth($sessionID);
740     isnt( $auth_status, 'ok', 'check_cookie_auth should not return ok if the user has not been authenticated before if no permissions needed' );
741     is( $auth_status, 'anon', 'check_cookie_auth should return anon if the user has not been authenticated before and no permissions needed' );
742
743     ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 1 );
744
745     ($auth_status, $session) = C4::Auth::check_cookie_auth($sessionID, {catalogue => 1});
746     isnt( $auth_status, 'ok', 'check_cookie_auth should not return ok if the user has not been authenticated before and permissions needed' );
747     is( $auth_status, 'anon', 'check_cookie_auth should return anon if the user has not been authenticated before and permissions needed' );
748
749     #FIXME We should have a test to cover 'failed' status when a user has logged in, but doesn't have permission
750 };
751
752 subtest 'checkauth & check_cookie_auth' => sub {
753     plan tests => 31;
754
755     # flags = 4 => { catalogue => 1 }
756     my $patron = $builder->build_object({ class => 'Koha::Patrons', value => { flags => 4 } });
757     my $password = 'password';
758     t::lib::Mocks::mock_preference( 'RequireStrongPassword', 0 );
759     $patron->set_password( { password => $password } );
760
761     my $cgi_mock = Test::MockModule->new('CGI');
762     $cgi_mock->mock( 'request_method', sub { return 'POST' } );
763
764     my $cgi = CGI->new;
765
766     my $auth = Test::MockModule->new( 'C4::Auth' );
767     # Tests will fail if we hit safe_exit
768     $auth->mock( 'safe_exit', sub { return } );
769
770     my ( $userid, $cookie, $sessionID, $flags );
771     {
772         # checkauth will redirect and safe_exit if not authenticated and not authorized
773         local *STDOUT;
774         my $stdout;
775         open STDOUT, '>', \$stdout;
776         C4::Auth::checkauth($cgi, 0, {catalogue => 1});
777         like( $stdout, qr{<title>\s*Log in to your account} );
778         $sessionID = ( $stdout =~ m{Set-Cookie: CGISESSID=((\d|\w)+);} ) ? $1 : undef;
779         ok($sessionID);
780         close STDOUT;
781     };
782
783     my $first_sessionID = $sessionID;
784
785     $ENV{"HTTP_COOKIE"} = "CGISESSID=$sessionID";
786     # Not authenticated yet, checkauth didn't return the session
787     {
788         local *STDOUT;
789         my $stdout;
790         open STDOUT, '>', \$stdout;
791         ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 0, {catalogue => 1} );
792         close STDOUT;
793     }
794     is( $sessionID, undef);
795     is( $userid, undef);
796
797     # Sending undefined fails obviously
798     my ( $auth_status, $session ) = C4::Auth::check_cookie_auth($sessionID, {catalogue => 1} );
799     is( $auth_status, 'failed' );
800     is( $session, undef );
801
802     # Simulating the login form submission
803     $cgi->param('userid', $patron->userid);
804     $cgi->param('password', $password);
805
806     # Logged in!
807     ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 0, {catalogue => 1});
808     is( $sessionID, $first_sessionID );
809     is( $userid, $patron->userid );
810
811     ( $auth_status, $session ) = C4::Auth::check_cookie_auth($sessionID, {catalogue => 1});
812     is( $auth_status, 'ok' );
813     is( $session->id, $first_sessionID );
814
815     # Logging out!
816     $cgi->param('logout.x', 1);
817     $cgi->delete( 'userid', 'password' );
818     {
819         local *STDOUT;
820         my $stdout;
821         open STDOUT, '>', \$stdout;
822         ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 0, {catalogue => 1});
823         close STDOUT;
824     }
825     is( $sessionID, undef );
826     is( $ENV{"HTTP_COOKIE"}, "CGISESSID=$first_sessionID", 'HTTP_COOKIE not unset' );
827     ( $auth_status, $session) = C4::Auth::check_cookie_auth( $first_sessionID, {catalogue => 1} );
828     is( $auth_status, "expired");
829     is( $session, undef );
830
831     {
832         # Trying to access without sessionID
833         $cgi = CGI->new;
834         ( $auth_status, $session) = C4::Auth::check_cookie_auth(undef, {catalogue => 1});
835         is( $auth_status, 'failed' );
836         is( $session, undef );
837
838         # This will fail on permissions
839         undef $ENV{"HTTP_COOKIE"};
840         {
841             local *STDOUT;
842             my $stdout;
843             open STDOUT, '>', \$stdout;
844             ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 0, {catalogue => 1} );
845             close STDOUT;
846         }
847         is( $userid, undef );
848         is( $sessionID, undef );
849     }
850
851     {
852         # First logging in
853         $cgi = CGI->new;
854         $cgi->param('userid', $patron->userid);
855         $cgi->param('password', $password);
856         ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 0, {catalogue => 1});
857         is( $userid, $patron->userid );
858         $first_sessionID = $sessionID;
859
860         # Patron does not have the borrowers permission
861         # $ENV{"HTTP_COOKIE"} = "CGISESSID=$sessionID"; # not needed, we use $cgi here
862         {
863             local *STDOUT;
864             my $stdout;
865             open STDOUT, '>', \$stdout;
866             ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 0, {borrowers => 1} );
867             close STDOUT;
868         }
869         is( $userid, undef );
870         is( $sessionID, undef );
871
872         # When calling check_cookie_auth, the session will be deleted
873         ( $auth_status, $session) = C4::Auth::check_cookie_auth( $first_sessionID, { borrowers => 1 } );
874         is( $auth_status, "failed" );
875         is( $session, undef );
876         ( $auth_status, $session) = C4::Auth::check_cookie_auth( $first_sessionID, { borrowers => 1 } );
877         is( $auth_status, 'expired', 'Session no longer exists' );
878
879         # NOTE: It is not what the UI is doing.
880         # From the UI we are allowed to hit an unauthorized page then reuse the session to hit back authorized area.
881         # It is because check_cookie_auth is ALWAYS called from checkauth WITHOUT $flagsrequired
882         # It then return "ok", when the previous called got "failed"
883
884         # Try reusing the deleted session: since it does not exist, we should get a new one now when passing correct permissions
885         $cgi->cookie( -name => 'CGISESSID', value => $first_sessionID );
886         ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 0, {catalogue => 1});
887         is( $userid, $patron->userid );
888         isnt( $sessionID, undef, 'Check if we have a sessionID' );
889         isnt( $sessionID, $first_sessionID, 'New value expected' );
890         ( $auth_status, $session) = C4::Auth::check_cookie_auth( $sessionID, {catalogue => 1} );
891         is( $auth_status, "ok" );
892         is( $session->id, $sessionID, 'Same session' );
893         # Two additional tests on userenv
894         is( $C4::Context::context->{activeuser}, $session->id, 'Check if environment has been setup for session' );
895         is( C4::Context->userenv->{id}, $userid, 'Check userid in userenv' );
896     }
897 };
898
899 subtest 'Userenv clearing in check_cookie_auth' => sub {
900     # Note: We did already test userenv for a logged-in user in previous subtest
901     plan tests => 9;
902
903     t::lib::Mocks::mock_preference( 'timeout', 600 );
904     my $cgi = CGI->new;
905
906     # Create a new anonymous session by passing a fake session ID
907     $cgi->cookie( -name => 'CGISESSID', -value => 'fake_sessionID' );
908     my ($userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 1);
909     my ( $auth_status, $session) = C4::Auth::check_cookie_auth( $sessionID );
910     is( $auth_status, 'anon', 'Should be anonymous' );
911     is( $C4::Context::context->{activeuser}, $session->id, 'Check activeuser' );
912     is( defined C4::Context->userenv, 1, 'There should be a userenv' );
913     is(  C4::Context->userenv->{id}, q{}, 'userid should be empty string' );
914
915     # Make the session expire now, check_cookie_auth will delete it
916     $session->param('lasttime', time() - 1200 );
917     $session->flush;
918     ( $auth_status, $session) = C4::Auth::check_cookie_auth( $sessionID );
919     is( $auth_status, 'expired', 'Should be expired' );
920     is( C4::Context->userenv, undef, 'Environment should be cleared too' );
921
922     # Show that we clear the userenv again: set up env and check deleted session
923     C4::Context->_new_userenv( $sessionID );
924     C4::Context->set_userenv; # empty
925     is( defined C4::Context->userenv, 1, 'There should be an empty userenv again' );
926     ( $auth_status, $session) = C4::Auth::check_cookie_auth( $sessionID );
927     is( $auth_status, 'expired', 'Should be expired already' );
928     is( C4::Context->userenv, undef, 'Environment should be cleared again' );
929 };
930
931 $schema->storage->txn_rollback;
932
933 subtest 'checkpw() return values tests' => sub {
934
935     plan tests => 3;
936
937     subtest 'Internal check tests' => sub {
938
939         plan tests => 25;
940
941         $schema->storage->txn_begin;
942
943         my $account_locked;
944         my $password_expired;
945
946         my $mock_patron = Test::MockModule->new('Koha::Patron');
947         $mock_patron->mock( 'account_locked',   sub { return $account_locked; } );
948         $mock_patron->mock( 'password_expired', sub { return $password_expired; } );
949
950         # Only interested here in regular login
951         t::lib::Mocks::mock_config( 'useshibboleth', undef );
952         $C4::Auth::cas  = 0;
953         $C4::Auth::ldap = 0;
954
955         my $patron   = $builder->build_object( { class => 'Koha::Patrons' } );
956         my $password = 'thePassword123';
957         $patron->set_password( { password => $password, skip_validation => 1 } );
958
959         my $patron_to_delete  = $builder->build_object( { class => 'Koha::Patrons' } );
960         my $unused_userid     = $patron_to_delete->userid;
961         my $unused_cardnumber = $patron_to_delete->cardnumber;
962         $patron_to_delete->delete;
963
964         $account_locked = 1;
965         my @return = checkpw( $patron->userid, $password, undef, );
966         is_deeply( \@return, [], 'If the account is locked, empty list is returned' );
967
968         $account_locked = 0;
969
970         my @matchpoints = qw(userid cardnumber);
971         foreach my $matchpoint (@matchpoints) {
972
973             @return = checkpw( $patron->$matchpoint, $password, undef, );
974
975             is( $return[0],        1,                   "Password validation successful returns 1 ($matchpoint)" );
976             is( $return[1],        $patron->cardnumber, '`cardnumber` returned' );
977             is( $return[2],        $patron->userid,     '`userid` returned' );
978             is( ref( $return[3] ), 'Koha::Patron',      'Koha::Patron object reference returned' );
979             is( $return[3]->id,    $patron->id,         'Correct patron returned' );
980         }
981
982         @return = checkpw( $patron->userid, $password . 'hey', undef, );
983
984         is( scalar @return,    2, "Two results on invalid password scenario" );
985         is( $return[0],        0, '0 returned on invalid password' );
986         is( ref( $return[1] ), 'Koha::Patron' );
987         is( $return[1]->id,    $patron->id, 'Patron matched correctly' );
988
989         $password_expired = 1;
990         @return           = checkpw( $patron->userid, $password, undef, );
991
992         is( scalar @return,    2,  "Two results on expired password scenario" );
993         is( $return[0],        -2, '-2 returned' );
994         is( ref( $return[1] ), 'Koha::Patron' );
995         is( $return[1]->id,    $patron->id, 'Patron matched correctly' );
996
997         @return = checkpw( $unused_userid, $password, undef, );
998
999         is( scalar @return, 2,     "Two results on non-existing userid scenario" );
1000         is( $return[0],     0,     '0 returned' );
1001         is( $return[1],     undef, 'Undef returned, representing no match' );
1002
1003         @return = checkpw( $unused_cardnumber, $password, undef, );
1004
1005         is( scalar @return, 2,     "Only one result on non-existing cardnumber scenario" );
1006         is( $return[0],     0,     '0 returned' );
1007         is( $return[1],     undef, 'Undef returned, representing no match' );
1008
1009         $schema->storage->txn_rollback;
1010     };
1011
1012     subtest 'CAS check (mocked) tests' => sub {
1013
1014         plan tests => 25;
1015
1016         $schema->storage->txn_begin;
1017
1018         my $account_locked;
1019         my $password_expired;
1020
1021         my $mock_patron = Test::MockModule->new('Koha::Patron');
1022         $mock_patron->mock( 'account_locked',   sub { return $account_locked; } );
1023         $mock_patron->mock( 'password_expired', sub { return $password_expired; } );
1024
1025         # Only interested here in regular login
1026         t::lib::Mocks::mock_config( 'useshibboleth', undef );
1027         $C4::Auth::cas  = 1;
1028         $C4::Auth::ldap = 0;
1029
1030         my $patron   = $builder->build_object( { class => 'Koha::Patrons' } );
1031         my $password = 'thePassword123';
1032         $patron->set_password( { password => $password, skip_validation => 1 } );
1033
1034         my $patron_to_delete  = $builder->build_object( { class => 'Koha::Patrons' } );
1035         my $unused_userid     = $patron_to_delete->userid;
1036         my $unused_cardnumber = $patron_to_delete->cardnumber;
1037         $patron_to_delete->delete;
1038
1039         my $ticket = '123456';
1040         my $query  = CGI->new;
1041         $query->param( -name => 'ticket', -value => $ticket );
1042
1043         my @cas_return = ( 1, $patron->cardnumber, $patron->userid, $ticket, Koha::Patrons->find( $patron->id ) );
1044
1045         my $cas_mock = Test::MockModule->new('C4::Auth');
1046         $cas_mock->mock( 'checkpw_cas', sub { return @cas_return; } );
1047
1048         $account_locked = 1;
1049         my @return = checkpw( $patron->userid, $password, $query, );
1050         is_deeply( \@return, [], 'If the account is locked, empty list is returned' );
1051
1052         $account_locked = 0;
1053
1054         my @matchpoints = qw(userid cardnumber);
1055         foreach my $matchpoint (@matchpoints) {
1056
1057             @return = checkpw( $patron->$matchpoint, $password, $query, );
1058
1059             is( $return[0],        1,                   "Password validation successful returns 1 ($matchpoint)" );
1060             is( $return[1],        $patron->cardnumber, '`cardnumber` returned' );
1061             is( $return[2],        $patron->userid,     '`userid` returned' );
1062             is( ref( $return[3] ), 'Koha::Patron',      'Koha::Patron object reference returned' );
1063             is( $return[3]->id,    $patron->id,         'Correct patron returned' );
1064         }
1065
1066         @return = checkpw( $patron->userid, $password . 'hey', $query, );
1067
1068         is( scalar @return,    2, "Two results on invalid password scenario" );
1069         is( $return[0],        0, '0 returned on invalid password' );
1070         is( ref( $return[1] ), 'Koha::Patron' );
1071         is( $return[1]->id,    $patron->id, 'Patron matched correctly' );
1072
1073         $password_expired = 1;
1074         @return           = checkpw( $patron->userid, $password, $query, );
1075
1076         is( scalar @return,    2,  "Two results on expired password scenario" );
1077         is( $return[0],        -2, '-2 returned' );
1078         is( ref( $return[1] ), 'Koha::Patron' );
1079         is( $return[1]->id,    $patron->id, 'Patron matched correctly' );
1080
1081         @return = checkpw( $unused_userid, $password, $query, );
1082
1083         is( scalar @return, 2,     "Two results on non-existing userid scenario" );
1084         is( $return[0],     0,     '0 returned' );
1085         is( $return[1],     undef, 'Undef returned, representing no match' );
1086
1087         @return = checkpw( $unused_cardnumber, $password, $query, );
1088
1089         is( scalar @return, 2,     "Only one result on non-existing cardnumber scenario" );
1090         is( $return[0],     0,     '0 returned' );
1091         is( $return[1],     undef, 'Undef returned, representing no match' );
1092
1093         $schema->storage->txn_rollback;
1094     };
1095
1096     subtest 'Shibboleth check (mocked) tests' => sub {
1097
1098         plan tests => 6;
1099
1100         $schema->storage->txn_begin;
1101
1102         my $account_locked;
1103         my $password_expired;
1104
1105         my $mock_patron = Test::MockModule->new('Koha::Patron');
1106         $mock_patron->mock( 'account_locked',   sub { return $account_locked; } );
1107         $mock_patron->mock( 'password_expired', sub { return $password_expired; } );
1108
1109         # Only interested here in regular login
1110         t::lib::Mocks::mock_config( 'useshibboleth', 1 );
1111         $C4::Auth::cas  = 0;
1112         $C4::Auth::ldap = 0;
1113
1114         my $patron   = $builder->build_object( { class => 'Koha::Patrons' } );
1115         my $password = 'thePassword123';
1116         $patron->set_password( { password => $password, skip_validation => 1 } );
1117
1118         my $patron_to_delete  = $builder->build_object( { class => 'Koha::Patrons' } );
1119         my $unused_userid     = $patron_to_delete->userid;
1120         my $unused_cardnumber = $patron_to_delete->cardnumber;
1121         $patron_to_delete->delete;
1122
1123         my @shib_return = ( 1, $patron->cardnumber, $patron->userid, Koha::Patrons->find( $patron->id ) );
1124
1125         my $auth_mock = Test::MockModule->new('C4::Auth');
1126         $auth_mock->mock( 'shib_ok',        1 );
1127         $auth_mock->mock( 'get_login_shib', 1 );
1128
1129         my $shib_mock = Test::MockModule->new('C4::Auth_with_shibboleth');
1130         $shib_mock->mock( 'checkpw_shib', sub { return @shib_return; } );
1131
1132         $account_locked = 1;
1133         my @return = checkpw( $patron->userid );
1134         is_deeply( \@return, [], 'If the account is locked, empty list is returned' );
1135
1136         $account_locked = 0;
1137
1138         @return = checkpw();
1139
1140         is( $return[0],        1,                   "Password validation successful returns 1" );
1141         is( $return[1],        $patron->cardnumber, '`cardnumber` returned' );
1142         is( $return[2],        $patron->userid,     '`userid` returned' );
1143         is( ref( $return[3] ), 'Koha::Patron',      'Koha::Patron object reference returned' );
1144         is( $return[3]->id,    $patron->id,         'Correct patron returned' );
1145
1146         $schema->storage->txn_rollback;
1147     };
1148 };