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