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