Bug 21336: Do not increase login_attempts after locking
[koha-equinox.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 => 21;
14 use Test::Warn;
15 use t::lib::Mocks;
16 use t::lib::TestBuilder;
17
18 use C4::Auth qw(checkpw);
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');
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 => 3;
42
43     my $patron = $builder->build({ source => 'Borrower', value => { flags => undef } })->{userid};
44
45     # Mock a CGI object with real userid param
46     my $cgi = Test::MockObject->new();
47     $cgi->mock( 'param', sub { return $patron; } );
48     $cgi->mock( 'cookie', sub { return; } );
49
50     my $authnotrequired = 1;
51     my ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, $authnotrequired );
52
53     is( $userid, undef, 'checkauth() returns undef for userid if no logged in user (Bug 18275)' );
54
55     my $db_user_id = C4::Context->config('user');
56     my $db_user_pass = C4::Context->config('pass');
57     $cgi = Test::MockObject->new();
58     $cgi->mock( 'cookie', sub { return; } );
59     $cgi->mock( 'param', sub {
60             my ( $self, $param ) = @_;
61             if ( $param eq 'userid' ) { return $db_user_id; }
62             elsif ( $param eq 'password' ) { return $db_user_pass; }
63             else { return; }
64         });
65     ( $userid, $cookie, $sessionID, $flags ) = C4::Auth::checkauth( $cgi, $authnotrequired );
66     is ( $userid, undef, 'If DB user is used, it should not be logged in' );
67
68     my $is_allowed = C4::Auth::haspermission( $db_user_id, { can_do => 'everything' } );
69
70     # FIXME This belongs to t/db_dependent/Auth/haspermission.t but we do not want to c/p the pervious mock statements
71     ok( !$is_allowed, 'DB user should not have any permissions');
72
73     C4::Context->_new_userenv; # For next tests
74
75 };
76
77 subtest 'track_login_daily tests' => sub {
78
79     plan tests => 5;
80
81     my $patron = $builder->build_object({ class => 'Koha::Patrons' });
82     my $userid = $patron->userid;
83
84     $patron->lastseen( undef );
85     $patron->store();
86
87     my $cache     = Koha::Caches->get_instance();
88     my $cache_key = "track_login_" . $patron->userid;
89     $cache->clear_from_cache($cache_key);
90
91     t::lib::Mocks::mock_preference( 'TrackLastPatronActivity', '1' );
92
93     is( $patron->lastseen, undef, 'Patron should have not last seen when newly created' );
94
95     C4::Auth::track_login_daily( $userid );
96     $patron->_result()->discard_changes();
97     isnt( $patron->lastseen, undef, 'Patron should have last seen set when TrackLastPatronActivity = 1' );
98
99     sleep(1); # We need to wait a tiny bit to make sure the timestamp will be different
100     my $last_seen = $patron->lastseen;
101     C4::Auth::track_login_daily( $userid );
102     $patron->_result()->discard_changes();
103     is( $patron->lastseen, $last_seen, 'Patron last seen should still be unchanged' );
104
105     $cache->clear_from_cache($cache_key);
106     C4::Auth::track_login_daily( $userid );
107     $patron->_result()->discard_changes();
108     isnt( $patron->lastseen, $last_seen, 'Patron last seen should be changed if we cleared the cache' );
109
110     t::lib::Mocks::mock_preference( 'TrackLastPatronActivity', '0' );
111     $patron->lastseen( undef )->store;
112     $cache->clear_from_cache($cache_key);
113     C4::Auth::track_login_daily( $userid );
114     $patron->_result()->discard_changes();
115     is( $patron->lastseen, undef, 'Patron should still have last seen unchanged when TrackLastPatronActivity = 0' );
116
117 };
118
119 subtest 'no_set_userenv parameter tests' => sub {
120
121     plan tests => 7;
122
123     my $library = $builder->build_object( { class => 'Koha::Libraries' } );
124     my $patron  = $builder->build_object( { class => 'Koha::Patrons' } );
125     my $password = 'password';
126
127     t::lib::Mocks::mock_preference( 'RequireStrongPassword', 0 );
128     $patron->set_password({ password => $password });
129
130     ok( checkpw( $dbh, $patron->userid, $password, undef, undef, 1 ), 'checkpw returns true' );
131     is( C4::Context->userenv, undef, 'Userenv should be undef as required' );
132     C4::Context->_new_userenv('DUMMY SESSION');
133     C4::Context->set_userenv(0,0,0,'firstname','surname', $library->branchcode, 'Library 1', 0, '', '');
134     is( C4::Context->userenv->{branch}, $library->branchcode, 'Userenv gives correct branch' );
135     ok( checkpw( $dbh, $patron->userid, $password, undef, undef, 1 ), 'checkpw returns true' );
136     is( C4::Context->userenv->{branch}, $library->branchcode, 'Userenv branch is preserved if no_set_userenv is true' );
137     ok( checkpw( $dbh, $patron->userid, $password, undef, undef, 0 ), 'checkpw still returns true' );
138     isnt( C4::Context->userenv->{branch}, $library->branchcode, 'Userenv branch is overwritten if no_set_userenv is false' );
139 };
140
141 # get_template_and_user tests
142
143 {   # Tests for the language URL parameter
144
145     sub MockedCheckauth {
146         my ($query,$authnotrequired,$flagsrequired,$type) = @_;
147         # return vars
148         my $userid = 'cobain';
149         my $sessionID = 234;
150         # we don't need to bother about permissions for this test
151         my $flags = {
152             superlibrarian    => 1, acquisition       => 0,
153             borrowers         => 0,
154             catalogue         => 1, circulate         => 0,
155             coursereserves    => 0, editauthorities   => 0,
156             editcatalogue     => 0,
157             parameters        => 0, permissions       => 0,
158             plugins           => 0, reports           => 0,
159             reserveforothers  => 0, serials           => 0,
160             staffaccess       => 0, tools             => 0,
161             updatecharges     => 0
162         };
163
164         my $session_cookie = $query->cookie(
165             -name => 'CGISESSID',
166             -value    => 'nirvana',
167             -HttpOnly => 1
168         );
169
170         return ( $userid, $session_cookie, $sessionID, $flags );
171     }
172
173     # Mock checkauth, build the scenario
174     my $auth = new Test::MockModule( 'C4::Auth' );
175     $auth->mock( 'checkauth', \&MockedCheckauth );
176
177     # Make sure 'EnableOpacSearchHistory' is set
178     t::lib::Mocks::mock_preference('EnableOpacSearchHistory',1);
179     # Enable es-ES for the OPAC and staff interfaces
180     t::lib::Mocks::mock_preference('opaclanguages','en,es-ES');
181     t::lib::Mocks::mock_preference('language','en,es-ES');
182
183     # we need a session cookie
184     $ENV{"SERVER_PORT"} = 80;
185     $ENV{"HTTP_COOKIE"} = 'CGISESSID=nirvana';
186
187     my $query = new CGI;
188     $query->param('language','es-ES');
189
190     my ( $template, $loggedinuser, $cookies ) = get_template_and_user(
191         {
192             template_name   => "about.tt",
193             query           => $query,
194             type            => "opac",
195             authnotrequired => 1,
196             flagsrequired   => { catalogue => 1 },
197             debug           => 1
198         }
199     );
200
201     ok ( ( all { ref($_) eq 'CGI::Cookie' } @$cookies ),
202             'BZ9735: the cookies array is flat' );
203
204     # new query, with non-existent language (we only have en and es-ES)
205     $query->param('language','tomas');
206
207     ( $template, $loggedinuser, $cookies ) = get_template_and_user(
208         {
209             template_name   => "about.tt",
210             query           => $query,
211             type            => "opac",
212             authnotrequired => 1,
213             flagsrequired   => { catalogue => 1 },
214             debug           => 1
215         }
216     );
217
218     ok( ( none { $_->name eq 'KohaOpacLanguage' and $_->value eq 'tomas' } @$cookies ),
219         'BZ9735: invalid language, it is not set');
220
221     ok( ( any { $_->name eq 'KohaOpacLanguage' and $_->value eq 'en' } @$cookies ),
222         'BZ9735: invalid language, then default to en');
223
224     for my $template_name (
225         qw(
226             ../../../../../../../../../../../../../../../etc/passwd
227             test/../../../../../../../../../../../../../../etc/passwd
228             /etc/passwd
229             test/does_not_finished_by_tt_t
230         )
231     ) {
232         eval {
233             ( $template, $loggedinuser, $cookies ) = get_template_and_user(
234                 {
235                     template_name   => $template_name,
236                     query           => $query,
237                     type            => "intranet",
238                     authnotrequired => 1,
239                     flagsrequired   => { catalogue => 1 },
240                 }
241             );
242         };
243         like ( $@, qr(^bad template path), "The file $template_name should not be accessible" );
244     }
245     ( $template, $loggedinuser, $cookies ) = get_template_and_user(
246         {
247             template_name   => 'errors/errorpage.tt',
248             query           => $query,
249             type            => "intranet",
250             authnotrequired => 1,
251             flagsrequired   => { catalogue => 1 },
252         }
253     );
254     my $file_exists = ( -f $template->{filename} ) ? 1 : 0;
255     is ( $file_exists, 1, 'The file errors/errorpage.tt should be accessible (contains integers)' );
256
257     # Regression test for env opac search limit override
258     $ENV{"OPAC_SEARCH_LIMIT"} = "branch:CPL";
259     $ENV{"OPAC_LIMIT_OVERRIDE"} = 1;
260
261     ( $template, $loggedinuser, $cookies) = get_template_and_user(
262         {
263             template_name => 'opac-main.tt',
264             query => $query,
265             type => 'opac',
266             authnotrequired => 1,
267         }
268     );
269     is($template->{VARS}->{'opac_name'}, "CPL", "Opac name was set correctly");
270     is($template->{VARS}->{'opac_search_limit'}, "branch:CPL", "Search limit was set correctly");
271
272     $ENV{"OPAC_SEARCH_LIMIT"} = "branch:multibranch-19";
273
274     ( $template, $loggedinuser, $cookies) = get_template_and_user(
275         {
276             template_name => 'opac-main.tt',
277             query => $query,
278             type => 'opac',
279             authnotrequired => 1,
280         }
281     );
282     is($template->{VARS}->{'opac_name'}, "multibranch-19", "Opac name was set correctly");
283     is($template->{VARS}->{'opac_search_limit'}, "branch:multibranch-19", "Search limit was set correctly");
284 }
285
286 # Check that there is always an OPACBaseURL set.
287 my $input = CGI->new();
288 my ( $template1, $borrowernumber, $cookie );
289 ( $template1, $borrowernumber, $cookie ) = get_template_and_user(
290     {
291         template_name => "opac-detail.tt",
292         type => "opac",
293         query => $input,
294         authnotrequired => 1,
295     }
296 );
297
298 ok( ( any { 'OPACBaseURL' eq $_ } keys %{$template1->{VARS}} ),
299     'OPACBaseURL is in OPAC template' );
300
301 my ( $template2 );
302 ( $template2, $borrowernumber, $cookie ) = get_template_and_user(
303     {
304         template_name => "catalogue/detail.tt",
305         type => "intranet",
306         query => $input,
307         authnotrequired => 1,
308     }
309 );
310
311 ok( ( any { 'OPACBaseURL' eq $_ } keys %{$template2->{VARS}} ),
312     'OPACBaseURL is in Staff template' );
313
314 my $hash1 = hash_password('password');
315 my $hash2 = hash_password('password');
316
317 ok(C4::Auth::checkpw_hash('password', $hash1), 'password validates with first hash');
318 ok(C4::Auth::checkpw_hash('password', $hash2), 'password validates with second hash');
319
320 subtest 'Check value of login_attempts in checkpw' => sub {
321     plan tests => 6;
322
323     t::lib::Mocks::mock_preference('FailedLoginAttempts', 3);
324
325     # Only interested here in regular login
326     $C4::Auth::cas  = 0;
327     $C4::Auth::ldap = 0;
328
329     my $patron = $builder->build_object({ class => 'Koha::Patrons' });
330     $patron->login_attempts(2);
331     $patron->password('123')->store; # yes, deliberately not hashed
332
333     is( $patron->account_locked, 0, 'Patron not locked' );
334     my @test = checkpw( $dbh, $patron->userid, '123', undef, 'opac', 1 );
335         # Note: 123 will not be hashed to 123 !
336     is( $test[0], 0, 'checkpw should have failed' );
337     $patron->discard_changes; # refresh
338     is( $patron->login_attempts, 3, 'Login attempts increased' );
339     is( $patron->account_locked, 1, 'Check locked status' );
340
341     # And another try to go over the limit: different return value!
342     @test = checkpw( $dbh, $patron->userid, '123', undef, 'opac', 1 );
343     is( @test, 0, 'checkpw failed again and returns nothing now' );
344     $patron->discard_changes; # refresh
345     is( $patron->login_attempts, 3, 'Login attempts not increased anymore' );
346 };
347
348 $schema->storage->txn_rollback;