Bug 29957: Clear cookies on logout
[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 => 15;
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
24 BEGIN {
25     use_ok('C4::Auth', qw( checkauth haspermission track_login_daily checkpw get_template_and_user checkpw_hash ));
26 }
27
28 my $schema  = Koha::Database->schema;
29 my $builder = t::lib::TestBuilder->new;
30 my $dbh     = C4::Context->dbh;
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 $schema->storage->txn_begin;
38
39 subtest 'checkauth() tests' => sub {
40
41     plan tests => 4;
42
43     my $patron = $builder->build_object({ class => 'Koha::Patrons', value => { flags => undef } });
44
45     # Mock a CGI object with real userid param
46     my $cgi = Test::MockObject->new();
47     $cgi->mock(
48         'param',
49         sub {
50             my $var = shift;
51             if ( $var eq 'userid' ) { return $patron->userid; }
52         }
53     );
54     $cgi->mock( 'cookie', sub { return; } );
55     $cgi->mock( 'request_method', sub { return 'POST' } );
56
57     my $authnotrequired = 1;
58     my ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, $authnotrequired );
59
60     is( $userid, undef, 'checkauth() returns undef for userid if no logged in user (Bug 18275)' );
61
62     my $db_user_id = C4::Context->config('user');
63     my $db_user_pass = C4::Context->config('pass');
64     $cgi = Test::MockObject->new();
65     $cgi->mock( 'cookie', sub { return; } );
66     $cgi->mock( 'param', sub {
67             my ( $self, $param ) = @_;
68             if ( $param eq 'userid' ) { return $db_user_id; }
69             elsif ( $param eq 'password' ) { return $db_user_pass; }
70             else { return; }
71         });
72     $cgi->mock( 'request_method', sub { return 'POST' } );
73     ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, $authnotrequired );
74     is ( $userid, undef, 'If DB user is used, it should not be logged in' );
75
76     my $is_allowed = C4::Auth::haspermission( $db_user_id, { can_do => 'everything' } );
77
78     # FIXME This belongs to t/db_dependent/Auth/haspermission.t but we do not want to c/p the pervious mock statements
79     ok( !$is_allowed, 'DB user should not have any permissions');
80
81     subtest 'Prevent authentication when sending credential via GET' => sub {
82
83         plan tests => 2;
84
85         my $patron = $builder->build_object(
86             { class => 'Koha::Patrons', value => { flags => 1 } } );
87         my $password = 'password';
88         t::lib::Mocks::mock_preference( 'RequireStrongPassword', 0 );
89         $patron->set_password( { password => $password } );
90         $cgi = Test::MockObject->new();
91         $cgi->mock( 'cookie', sub { return; } );
92         $cgi->mock(
93             'param',
94             sub {
95                 my ( $self, $param ) = @_;
96                 if    ( $param eq 'userid' )   { return $patron->userid; }
97                 elsif ( $param eq 'password' ) { return $password; }
98                 else                           { return; }
99             }
100         );
101
102         $cgi->mock( 'request_method', sub { return 'POST' } );
103         ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired' );
104         is( $userid, $patron->userid, 'If librarian user is used and password with POST, they should be logged in' );
105
106         $cgi->mock( 'request_method', sub { return 'GET' } );
107         ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 'authrequired' );
108         is( $userid, undef, 'If librarian user is used and password with GET, they should not be logged in' );
109     };
110
111     C4::Context->_new_userenv; # For next tests
112
113 };
114
115 subtest 'track_login_daily tests' => sub {
116
117     plan tests => 5;
118
119     my $patron = $builder->build_object({ class => 'Koha::Patrons' });
120     my $userid = $patron->userid;
121
122     $patron->lastseen( undef );
123     $patron->store();
124
125     my $cache     = Koha::Caches->get_instance();
126     my $cache_key = "track_login_" . $patron->userid;
127     $cache->clear_from_cache($cache_key);
128
129     t::lib::Mocks::mock_preference( 'TrackLastPatronActivity', '1' );
130
131     is( $patron->lastseen, undef, 'Patron should have not last seen when newly created' );
132
133     C4::Auth::track_login_daily( $userid );
134     $patron->_result()->discard_changes();
135     isnt( $patron->lastseen, undef, 'Patron should have last seen set when TrackLastPatronActivity = 1' );
136
137     sleep(1); # We need to wait a tiny bit to make sure the timestamp will be different
138     my $last_seen = $patron->lastseen;
139     C4::Auth::track_login_daily( $userid );
140     $patron->_result()->discard_changes();
141     is( $patron->lastseen, $last_seen, 'Patron last seen should still be unchanged' );
142
143     $cache->clear_from_cache($cache_key);
144     C4::Auth::track_login_daily( $userid );
145     $patron->_result()->discard_changes();
146     isnt( $patron->lastseen, $last_seen, 'Patron last seen should be changed if we cleared the cache' );
147
148     t::lib::Mocks::mock_preference( 'TrackLastPatronActivity', '0' );
149     $patron->lastseen( undef )->store;
150     $cache->clear_from_cache($cache_key);
151     C4::Auth::track_login_daily( $userid );
152     $patron->_result()->discard_changes();
153     is( $patron->lastseen, undef, 'Patron should still have last seen unchanged when TrackLastPatronActivity = 0' );
154
155 };
156
157 subtest 'no_set_userenv parameter tests' => sub {
158
159     plan tests => 7;
160
161     my $library = $builder->build_object( { class => 'Koha::Libraries' } );
162     my $patron  = $builder->build_object( { class => 'Koha::Patrons' } );
163     my $password = 'password';
164
165     t::lib::Mocks::mock_preference( 'RequireStrongPassword', 0 );
166     $patron->set_password({ password => $password });
167
168     ok( checkpw( $dbh, $patron->userid, $password, undef, undef, 1 ), 'checkpw returns true' );
169     is( C4::Context->userenv, undef, 'Userenv should be undef as required' );
170     C4::Context->_new_userenv('DUMMY SESSION');
171     C4::Context->set_userenv(0,0,0,'firstname','surname', $library->branchcode, 'Library 1', 0, '', '');
172     is( C4::Context->userenv->{branch}, $library->branchcode, 'Userenv gives correct branch' );
173     ok( checkpw( $dbh, $patron->userid, $password, undef, undef, 1 ), 'checkpw returns true' );
174     is( C4::Context->userenv->{branch}, $library->branchcode, 'Userenv branch is preserved if no_set_userenv is true' );
175     ok( checkpw( $dbh, $patron->userid, $password, undef, undef, 0 ), 'checkpw still returns true' );
176     isnt( C4::Context->userenv->{branch}, $library->branchcode, 'Userenv branch is overwritten if no_set_userenv is false' );
177 };
178
179 subtest 'checkpw lockout tests' => sub {
180
181     plan tests => 5;
182
183     my $library = $builder->build_object( { class => 'Koha::Libraries' } );
184     my $patron  = $builder->build_object( { class => 'Koha::Patrons' } );
185     my $password = 'password';
186     t::lib::Mocks::mock_preference( 'RequireStrongPassword', 0 );
187     t::lib::Mocks::mock_preference( 'FailedLoginAttempts', 1 );
188     $patron->set_password({ password => $password });
189
190     my ( $checkpw, undef, undef ) = checkpw( $dbh, $patron->cardnumber, $password, undef, undef, 1 );
191     ok( $checkpw, 'checkpw returns true with right password when logging in via cardnumber' );
192     ( $checkpw, undef, undef ) = checkpw( $dbh, $patron->userid, "wrong_password", undef, undef, 1 );
193     is( $checkpw, 0, 'checkpw returns false when given wrong password' );
194     $patron = $patron->get_from_storage;
195     is( $patron->account_locked, 1, "Account is locked from failed login");
196     ( $checkpw, undef, undef ) = checkpw( $dbh, $patron->userid, $password, undef, undef, 1 );
197     is( $checkpw, undef, 'checkpw returns undef with right password when account locked' );
198     ( $checkpw, undef, undef ) = checkpw( $dbh, $patron->cardnumber, $password, undef, undef, 1 );
199     is( $checkpw, undef, 'checkpw returns undefwith right password when logging in via cardnumber if account locked' );
200
201 };
202
203 # get_template_and_user tests
204
205 subtest 'get_template_and_user' => sub {   # Tests for the language URL parameter
206
207     sub MockedCheckauth {
208         my ($query,$authnotrequired,$flagsrequired,$type) = @_;
209         # return vars
210         my $userid = 'cobain';
211         my $sessionID = 234;
212         # we don't need to bother about permissions for this test
213         my $flags = {
214             superlibrarian    => 1, acquisition       => 0,
215             borrowers         => 0,
216             catalogue         => 1, circulate         => 0,
217             coursereserves    => 0, editauthorities   => 0,
218             editcatalogue     => 0,
219             parameters        => 0, permissions       => 0,
220             plugins           => 0, reports           => 0,
221             reserveforothers  => 0, serials           => 0,
222             staffaccess       => 0, tools             => 0,
223             updatecharges     => 0
224         };
225
226         my $session_cookie = $query->cookie(
227             -name => 'CGISESSID',
228             -value    => 'nirvana',
229             -HttpOnly => 1
230         );
231
232         return ( $userid, [ $session_cookie ], $sessionID, $flags );
233     }
234
235     # Mock checkauth, build the scenario
236     my $auth = Test::MockModule->new( 'C4::Auth' );
237     $auth->mock( 'checkauth', \&MockedCheckauth );
238
239     # Make sure 'EnableOpacSearchHistory' is set
240     t::lib::Mocks::mock_preference('EnableOpacSearchHistory',1);
241     # Enable es-ES for the OPAC and staff interfaces
242     t::lib::Mocks::mock_preference('OPACLanguages','en,es-ES');
243     t::lib::Mocks::mock_preference('language','en,es-ES');
244
245     # we need a session cookie
246     $ENV{"SERVER_PORT"} = 80;
247     $ENV{"HTTP_COOKIE"} = 'CGISESSID=nirvana';
248
249     my $query = CGI->new;
250     $query->param('language','es-ES');
251
252     my ( $template, $loggedinuser, $cookies ) = get_template_and_user(
253         {
254             template_name   => "about.tt",
255             query           => $query,
256             type            => "opac",
257             authnotrequired => 1,
258             flagsrequired   => { catalogue => 1 },
259             debug           => 1
260         }
261     );
262
263     ok ( ( all { ref($_) eq 'CGI::Cookie' } @$cookies ),
264             'BZ9735: the cookies array is flat' );
265
266     # new query, with non-existent language (we only have en and es-ES)
267     $query->param('language','tomas');
268
269     ( $template, $loggedinuser, $cookies ) = get_template_and_user(
270         {
271             template_name   => "about.tt",
272             query           => $query,
273             type            => "opac",
274             authnotrequired => 1,
275             flagsrequired   => { catalogue => 1 },
276             debug           => 1
277         }
278     );
279
280     ok( ( none { $_->name eq 'KohaOpacLanguage' and $_->value eq 'tomas' } @$cookies ),
281         'BZ9735: invalid language, it is not set');
282
283     ok( ( any { $_->name eq 'KohaOpacLanguage' and $_->value eq 'en' } @$cookies ),
284         'BZ9735: invalid language, then default to en');
285
286     for my $template_name (
287         qw(
288             ../../../../../../../../../../../../../../../etc/passwd
289             test/../../../../../../../../../../../../../../etc/passwd
290             /etc/passwd
291             test/does_not_finished_by_tt_t
292         )
293     ) {
294         eval {
295             ( $template, $loggedinuser, $cookies ) = get_template_and_user(
296                 {
297                     template_name   => $template_name,
298                     query           => $query,
299                     type            => "intranet",
300                     authnotrequired => 1,
301                     flagsrequired   => { catalogue => 1 },
302                 }
303             );
304         };
305         like ( $@, qr(bad template path), "The file $template_name should not be accessible" );
306     }
307     ( $template, $loggedinuser, $cookies ) = get_template_and_user(
308         {
309             template_name   => 'errors/errorpage.tt',
310             query           => $query,
311             type            => "intranet",
312             authnotrequired => 1,
313             flagsrequired   => { catalogue => 1 },
314         }
315     );
316     my $file_exists = ( -f $template->{filename} ) ? 1 : 0;
317     is ( $file_exists, 1, 'The file errors/errorpage.tt should be accessible (contains integers)' );
318
319     # Regression test for env opac search limit override
320     $ENV{"OPAC_SEARCH_LIMIT"} = "branch:CPL";
321     $ENV{"OPAC_LIMIT_OVERRIDE"} = 1;
322
323     ( $template, $loggedinuser, $cookies) = get_template_and_user(
324         {
325             template_name => 'opac-main.tt',
326             query => $query,
327             type => 'opac',
328             authnotrequired => 1,
329         }
330     );
331     is($template->{VARS}->{'opac_name'}, "CPL", "Opac name was set correctly");
332     is($template->{VARS}->{'opac_search_limit'}, "branch:CPL", "Search limit was set correctly");
333
334     $ENV{"OPAC_SEARCH_LIMIT"} = "branch:multibranch-19";
335
336     ( $template, $loggedinuser, $cookies) = get_template_and_user(
337         {
338             template_name => 'opac-main.tt',
339             query => $query,
340             type => 'opac',
341             authnotrequired => 1,
342         }
343     );
344     is($template->{VARS}->{'opac_name'}, "multibranch-19", "Opac name was set correctly");
345     is($template->{VARS}->{'opac_search_limit'}, "branch:multibranch-19", "Search limit was set correctly");
346
347     delete $ENV{"HTTP_COOKIE"};
348 };
349
350 # Check that there is always an OPACBaseURL set.
351 my $input = CGI->new();
352 my ( $template1, $borrowernumber, $cookie );
353 ( $template1, $borrowernumber, $cookie ) = get_template_and_user(
354     {
355         template_name => "opac-detail.tt",
356         type => "opac",
357         query => $input,
358         authnotrequired => 1,
359     }
360 );
361
362 ok( ( any { 'OPACBaseURL' eq $_ } keys %{$template1->{VARS}} ),
363     'OPACBaseURL is in OPAC template' );
364
365 my ( $template2 );
366 ( $template2, $borrowernumber, $cookie ) = get_template_and_user(
367     {
368         template_name => "catalogue/detail.tt",
369         type => "intranet",
370         query => $input,
371         authnotrequired => 1,
372     }
373 );
374
375 ok( ( any { 'OPACBaseURL' eq $_ } keys %{$template2->{VARS}} ),
376     'OPACBaseURL is in Staff template' );
377
378 my $hash1 = hash_password('password');
379 my $hash2 = hash_password('password');
380
381 ok(C4::Auth::checkpw_hash('password', $hash1), 'password validates with first hash');
382 ok(C4::Auth::checkpw_hash('password', $hash2), 'password validates with second hash');
383
384 subtest 'Check value of login_attempts in checkpw' => sub {
385     plan tests => 11;
386
387     t::lib::Mocks::mock_preference('FailedLoginAttempts', 3);
388
389     # Only interested here in regular login
390     $C4::Auth::cas  = 0;
391     $C4::Auth::ldap = 0;
392
393     my $patron = $builder->build_object({ class => 'Koha::Patrons' });
394     $patron->login_attempts(2);
395     $patron->password('123')->store; # yes, deliberately not hashed
396
397     is( $patron->account_locked, 0, 'Patron not locked' );
398     my @test = checkpw( $dbh, $patron->userid, '123', undef, 'opac', 1 );
399         # Note: 123 will not be hashed to 123 !
400     is( $test[0], 0, 'checkpw should have failed' );
401     $patron->discard_changes; # refresh
402     is( $patron->login_attempts, 3, 'Login attempts increased' );
403     is( $patron->account_locked, 1, 'Check locked status' );
404
405     # And another try to go over the limit: different return value!
406     @test = checkpw( $dbh, $patron->userid, '123', undef, 'opac', 1 );
407     is( @test, 0, 'checkpw failed again and returns nothing now' );
408     $patron->discard_changes; # refresh
409     is( $patron->login_attempts, 3, 'Login attempts not increased anymore' );
410
411     # Administrative lockout cannot be undone?
412     # Pass the right password now (or: add a nice mock).
413     my $auth = Test::MockModule->new( 'C4::Auth' );
414     $auth->mock( 'checkpw_hash', sub { return 1; } ); # not for production :)
415     $patron->login_attempts(0)->store;
416     @test = checkpw( $dbh, $patron->userid, '123', undef, 'opac', 1 );
417     is( $test[0], 1, 'Build confidence in the mock' );
418     $patron->login_attempts(-1)->store;
419     is( $patron->account_locked, 1, 'Check administrative lockout' );
420     @test = checkpw( $dbh, $patron->userid, '123', undef, 'opac', 1 );
421     is( @test, 0, 'checkpw gave red' );
422     $patron->discard_changes; # refresh
423     is( $patron->login_attempts, -1, 'Still locked out' );
424     t::lib::Mocks::mock_preference('FailedLoginAttempts', ''); # disable
425     is( $patron->account_locked, 1, 'Check administrative lockout without pref' );
426 };
427
428 subtest '_timeout_syspref' => sub {
429     plan tests => 5;
430
431     t::lib::Mocks::mock_preference('timeout', "100");
432     is( C4::Auth::_timeout_syspref, 100, );
433
434     t::lib::Mocks::mock_preference('timeout', "2d");
435     is( C4::Auth::_timeout_syspref, 2*86400, );
436
437     t::lib::Mocks::mock_preference('timeout', "2D");
438     is( C4::Auth::_timeout_syspref, 2*86400, );
439
440     t::lib::Mocks::mock_preference('timeout', "10h");
441     is( C4::Auth::_timeout_syspref, 10*3600, );
442
443     t::lib::Mocks::mock_preference('timeout', "10x");
444     is( C4::Auth::_timeout_syspref, 600, );
445 };
446
447 subtest 'check_cookie_auth' => sub {
448     plan tests => 4;
449
450     t::lib::Mocks::mock_preference('timeout', "1d"); # back to default
451
452     my $patron = $builder->build_object({ class => 'Koha::Patrons', value => { flags => 1 } });
453
454     # Mock a CGI object with real userid param
455     my $cgi = Test::MockObject->new();
456     $cgi->mock(
457         'param',
458         sub {
459             my $var = shift;
460             if ( $var eq 'userid' ) { return $patron->userid; }
461         }
462     );
463     $cgi->mock('multi_param', sub {return q{}} );
464     $cgi->mock( 'cookie', sub { return; } );
465     $cgi->mock( 'request_method', sub { return 'POST' } );
466
467     $ENV{REMOTE_ADDR} = '127.0.0.1';
468
469     # Setting authnotrequired=1 or we wont' hit the return but the end of the sub that prints headers
470     my ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 1 );
471
472     my ($auth_status, $session) = C4::Auth::check_cookie_auth($sessionID);
473     isnt( $auth_status, 'ok', 'check_cookie_auth should not return ok if the user has not been authenticated before if no permissions needed' );
474     is( $auth_status, 'anon', 'check_cookie_auth should return anon if the user has not been authenticated before and no permissions needed' );
475
476     ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, 1 );
477
478     ($auth_status, $session) = C4::Auth::check_cookie_auth($sessionID, {catalogue => 1});
479     isnt( $auth_status, 'ok', 'check_cookie_auth should not return ok if the user has not been authenticated before and permissions needed' );
480     is( $auth_status, 'anon', 'check_cookie_auth should return anon if the user has not been authenticated before and permissions needed' );
481
482     #FIXME We should have a test to cover 'failed' status when a user has logged in, but doesn't have permission
483 };
484
485 subtest 'checkauth & check_cookie_auth' => sub {
486     plan tests => 31;
487
488     # flags = 4 => { catalogue => 1 }
489     my $patron = $builder->build_object({ class => 'Koha::Patrons', value => { flags => 4 } });
490     my $password = 'password';
491     t::lib::Mocks::mock_preference( 'RequireStrongPassword', 0 );
492     $patron->set_password( { password => $password } );
493
494     my $cgi_mock = Test::MockModule->new('CGI');
495     $cgi_mock->mock( 'request_method', sub { return 'POST' } );
496
497     my $cgi = CGI->new;
498
499     my $auth = Test::MockModule->new( 'C4::Auth' );
500     # Tests will fail if we hit safe_exit
501     $auth->mock( 'safe_exit', sub { return } );
502
503     my ( $userid, $cookie, $sessionID, $flags );
504     {
505         # checkauth will redirect and safe_exit if not authenticated and not authorized
506         local *STDOUT;
507         my $stdout;
508         open STDOUT, '>', \$stdout;
509         C4::Auth::checkauth($cgi, 0, {catalogue => 1});
510         like( $stdout, qr{<title>\s*Log in to your account} );
511         $sessionID = ( $stdout =~ m{Set-Cookie: CGISESSID=((\d|\w)+);} ) ? $1 : undef;
512         ok($sessionID);
513         close STDOUT;
514     };
515
516     my $first_sessionID = $sessionID;
517
518     $ENV{"HTTP_COOKIE"} = "CGISESSID=$sessionID";
519     # Not authenticated yet, checkauth didn't return the session
520     {
521         local *STDOUT;
522         my $stdout;
523         open STDOUT, '>', \$stdout;
524         ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 0, {catalogue => 1} );
525         close STDOUT;
526     }
527     is( $sessionID, undef);
528     is( $userid, undef);
529
530     # Sending undefined fails obviously
531     my ( $auth_status, $session ) = C4::Auth::check_cookie_auth($sessionID, {catalogue => 1} );
532     is( $auth_status, 'failed' );
533     is( $session, undef );
534
535     # Simulating the login form submission
536     $cgi->param('userid', $patron->userid);
537     $cgi->param('password', $password);
538
539     # Logged in!
540     ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 0, {catalogue => 1});
541     is( $sessionID, $first_sessionID );
542     is( $userid, $patron->userid );
543
544     ( $auth_status, $session ) = C4::Auth::check_cookie_auth($sessionID, {catalogue => 1});
545     is( $auth_status, 'ok' );
546     is( $session->id, $first_sessionID );
547
548     # Logging out!
549     $cgi->param('logout.x', 1);
550     $cgi->delete( 'userid', 'password' );
551     {
552         local *STDOUT;
553         my $stdout;
554         open STDOUT, '>', \$stdout;
555         ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 0, {catalogue => 1});
556         close STDOUT;
557     }
558     is( $sessionID, undef );
559     is( $ENV{"HTTP_COOKIE"}, "CGISESSID=$first_sessionID", 'HTTP_COOKIE not unset' );
560     ( $auth_status, $session) = C4::Auth::check_cookie_auth( $first_sessionID, {catalogue => 1} );
561     is( $auth_status, "expired");
562     is( $session, undef );
563
564     {
565         # Trying to access without sessionID
566         $cgi = CGI->new;
567         ( $auth_status, $session) = C4::Auth::check_cookie_auth(undef, {catalogue => 1});
568         is( $auth_status, 'failed' );
569         is( $session, undef );
570
571         # This will fail on permissions
572         undef $ENV{"HTTP_COOKIE"};
573         {
574             local *STDOUT;
575             my $stdout;
576             open STDOUT, '>', \$stdout;
577             ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 0, {catalogue => 1} );
578             close STDOUT;
579         }
580         is( $userid, undef );
581         is( $sessionID, undef );
582     }
583
584     {
585         # First logging in
586         $cgi = CGI->new;
587         $cgi->param('userid', $patron->userid);
588         $cgi->param('password', $password);
589         ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 0, {catalogue => 1});
590         is( $userid, $patron->userid );
591         $first_sessionID = $sessionID;
592
593         # Patron does not have the borrowers permission
594         # $ENV{"HTTP_COOKIE"} = "CGISESSID=$sessionID"; # not needed, we use $cgi here
595         {
596             local *STDOUT;
597             my $stdout;
598             open STDOUT, '>', \$stdout;
599             ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 0, {borrowers => 1} );
600             close STDOUT;
601         }
602         is( $userid, undef );
603         is( $sessionID, undef );
604
605         # When calling check_cookie_auth, the session will be deleted
606         ( $auth_status, $session) = C4::Auth::check_cookie_auth( $first_sessionID, { borrowers => 1 } );
607         is( $auth_status, "failed" );
608         is( $session, undef );
609         ( $auth_status, $session) = C4::Auth::check_cookie_auth( $first_sessionID, { borrowers => 1 } );
610         is( $auth_status, 'expired', 'Session no longer exists' );
611
612         # NOTE: It is not what the UI is doing.
613         # From the UI we are allowed to hit an unauthorized page then reuse the session to hit back authorized area.
614         # It is because check_cookie_auth is ALWAYS called from checkauth WITHOUT $flagsrequired
615         # It then return "ok", when the previous called got "failed"
616
617         # Try reusing the deleted session: since it does not exist, we should get a new one now when passing correct permissions
618         $cgi->cookie( -name => 'CGISESSID', value => $first_sessionID );
619         ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 0, {catalogue => 1});
620         is( $userid, $patron->userid );
621         isnt( $sessionID, undef, 'Check if we have a sessionID' );
622         isnt( $sessionID, $first_sessionID, 'New value expected' );
623         ( $auth_status, $session) = C4::Auth::check_cookie_auth( $sessionID, {catalogue => 1} );
624         is( $auth_status, "ok" );
625         is( $session->id, $sessionID, 'Same session' );
626         # Two additional tests on userenv
627         is( $C4::Context::context->{activeuser}, $session->id, 'Check if environment has been setup for session' );
628         is( C4::Context->userenv->{id}, $userid, 'Check userid in userenv' );
629     }
630 };
631
632 subtest 'Userenv clearing in check_cookie_auth' => sub {
633     # Note: We did already test userenv for a logged-in user in previous subtest
634     plan tests => 9;
635
636     t::lib::Mocks::mock_preference( 'timeout', 600 );
637     my $cgi = CGI->new;
638
639     # Create a new anonymous session by passing a fake session ID
640     $cgi->cookie( -name => 'CGISESSID', -value => 'fake_sessionID' );
641     my ($userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth($cgi, 1);
642     my ( $auth_status, $session) = C4::Auth::check_cookie_auth( $sessionID );
643     is( $auth_status, 'anon', 'Should be anonymous' );
644     is( $C4::Context::context->{activeuser}, $session->id, 'Check activeuser' );
645     is( defined C4::Context->userenv, 1, 'There should be a userenv' );
646     is(  C4::Context->userenv->{id}, q{}, 'userid should be empty string' );
647
648     # Make the session expire now, check_cookie_auth will delete it
649     $session->param('lasttime', time() - 1200 );
650     $session->flush;
651     ( $auth_status, $session) = C4::Auth::check_cookie_auth( $sessionID );
652     is( $auth_status, 'expired', 'Should be expired' );
653     is( C4::Context->userenv, undef, 'Environment should be cleared too' );
654
655     # Show that we clear the userenv again: set up env and check deleted session
656     C4::Context->_new_userenv( $sessionID );
657     C4::Context->set_userenv; # empty
658     is( defined C4::Context->userenv, 1, 'There should be an empty userenv again' );
659     ( $auth_status, $session) = C4::Auth::check_cookie_auth( $sessionID );
660     is( $auth_status, 'expired', 'Should be expired already' );
661     is( C4::Context->userenv, undef, 'Environment should be cleared again' );
662 };
663
664 $schema->storage->txn_rollback;