Bug 18677: Remove new issue_id param from charlostitem
[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 => 22;
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 => 2;
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, $db_user_id, 'If DB user is logging in, it should be considered as logged in, i.e. checkauth return the relevant userid' );
66     C4::Context->_new_userenv; # For next tests
67
68 };
69
70 subtest 'track_login_daily tests' => sub {
71
72     plan tests => 5;
73
74     my $patron = $builder->build_object({ class => 'Koha::Patrons' });
75     my $userid = $patron->userid;
76
77     $patron->lastseen( undef );
78     $patron->store();
79
80     my $cache     = Koha::Caches->get_instance();
81     my $cache_key = "track_login_" . $patron->userid;
82     $cache->clear_from_cache($cache_key);
83
84     t::lib::Mocks::mock_preference( 'TrackLastPatronActivity', '1' );
85
86     is( $patron->lastseen, undef, 'Patron should have not last seen when newly created' );
87
88     C4::Auth::track_login_daily( $userid );
89     $patron->_result()->discard_changes();
90     isnt( $patron->lastseen, undef, 'Patron should have last seen set when TrackLastPatronActivity = 1' );
91
92     sleep(1); # We need to wait a tiny bit to make sure the timestamp will be different
93     my $last_seen = $patron->lastseen;
94     C4::Auth::track_login_daily( $userid );
95     $patron->_result()->discard_changes();
96     is( $patron->lastseen, $last_seen, 'Patron last seen should still be unchanged' );
97
98     $cache->clear_from_cache($cache_key);
99     C4::Auth::track_login_daily( $userid );
100     $patron->_result()->discard_changes();
101     isnt( $patron->lastseen, $last_seen, 'Patron last seen should be changed if we cleared the cache' );
102
103     t::lib::Mocks::mock_preference( 'TrackLastPatronActivity', '0' );
104     $patron->lastseen( undef )->store;
105     $cache->clear_from_cache($cache_key);
106     C4::Auth::track_login_daily( $userid );
107     $patron->_result()->discard_changes();
108     is( $patron->lastseen, undef, 'Patron should still have last seen unchanged when TrackLastPatronActivity = 0' );
109
110 };
111
112 my $hash1 = hash_password('password');
113 my $hash2 = hash_password('password');
114
115 { # tests no_set_userenv parameter
116     my $patron = $builder->build( { source => 'Borrower' } );
117     Koha::Patrons->find( $patron->{borrowernumber} )->update_password( $patron->{userid}, $hash1 );
118     my $library = $builder->build(
119         {
120             source => 'Branch',
121         }
122     );
123
124     ok( checkpw( $dbh, $patron->{userid}, 'password', undef, undef, 1 ), 'checkpw returns true' );
125     is( C4::Context->userenv, undef, 'Userenv should be undef as required' );
126     C4::Context->_new_userenv('DUMMY SESSION');
127     C4::Context->set_userenv(0,0,0,'firstname','surname', $library->{branchcode}, 'Library 1', 0, '', '');
128     is( C4::Context->userenv->{branch}, $library->{branchcode}, 'Userenv gives correct branch' );
129     ok( checkpw( $dbh, $patron->{userid}, 'password', undef, undef, 1 ), 'checkpw returns true' );
130     is( C4::Context->userenv->{branch}, $library->{branchcode}, 'Userenv branch is preserved if no_set_userenv is true' );
131     ok( checkpw( $dbh, $patron->{userid}, 'password', undef, undef, 0 ), 'checkpw still returns true' );
132     isnt( C4::Context->userenv->{branch}, $library->{branchcode}, 'Userenv branch is overwritten if no_set_userenv is false' );
133 }
134
135 # get_template_and_user tests
136
137 {   # Tests for the language URL parameter
138
139     sub MockedCheckauth {
140         my ($query,$authnotrequired,$flagsrequired,$type) = @_;
141         # return vars
142         my $userid = 'cobain';
143         my $sessionID = 234;
144         # we don't need to bother about permissions for this test
145         my $flags = {
146             superlibrarian    => 1, acquisition       => 0,
147             borrowers         => 0,
148             catalogue         => 1, circulate         => 0,
149             coursereserves    => 0, editauthorities   => 0,
150             editcatalogue     => 0, management        => 0,
151             parameters        => 0, permissions       => 0,
152             plugins           => 0, reports           => 0,
153             reserveforothers  => 0, serials           => 0,
154             staffaccess       => 0, tools             => 0,
155             updatecharges     => 0
156         };
157
158         my $session_cookie = $query->cookie(
159             -name => 'CGISESSID',
160             -value    => 'nirvana',
161             -HttpOnly => 1
162         );
163
164         return ( $userid, $session_cookie, $sessionID, $flags );
165     }
166
167     # Mock checkauth, build the scenario
168     my $auth = new Test::MockModule( 'C4::Auth' );
169     $auth->mock( 'checkauth', \&MockedCheckauth );
170
171     # Make sure 'EnableOpacSearchHistory' is set
172     t::lib::Mocks::mock_preference('EnableOpacSearchHistory',1);
173     # Enable es-ES for the OPAC and staff interfaces
174     t::lib::Mocks::mock_preference('opaclanguages','en,es-ES');
175     t::lib::Mocks::mock_preference('language','en,es-ES');
176
177     # we need a session cookie
178     $ENV{"SERVER_PORT"} = 80;
179     $ENV{"HTTP_COOKIE"} = 'CGISESSID=nirvana';
180
181     my $query = new CGI;
182     $query->param('language','es-ES');
183
184     my ( $template, $loggedinuser, $cookies ) = get_template_and_user(
185         {
186             template_name   => "about.tt",
187             query           => $query,
188             type            => "opac",
189             authnotrequired => 1,
190             flagsrequired   => { catalogue => 1 },
191             debug           => 1
192         }
193     );
194
195     ok ( ( all { ref($_) eq 'CGI::Cookie' } @$cookies ),
196             'BZ9735: the cookies array is flat' );
197
198     # new query, with non-existent language (we only have en and es-ES)
199     $query->param('language','tomas');
200
201     ( $template, $loggedinuser, $cookies ) = get_template_and_user(
202         {
203             template_name   => "about.tt",
204             query           => $query,
205             type            => "opac",
206             authnotrequired => 1,
207             flagsrequired   => { catalogue => 1 },
208             debug           => 1
209         }
210     );
211
212     ok( ( none { $_->name eq 'KohaOpacLanguage' and $_->value eq 'tomas' } @$cookies ),
213         'BZ9735: invalid language, it is not set');
214
215     ok( ( any { $_->name eq 'KohaOpacLanguage' and $_->value eq 'en' } @$cookies ),
216         'BZ9735: invalid language, then default to en');
217
218     for my $template_name (
219         qw(
220             ../../../../../../../../../../../../../../../etc/passwd
221             test/../../../../../../../../../../../../../../etc/passwd
222             /etc/passwd
223             test/does_not_finished_by_tt_t
224         )
225     ) {
226         eval {
227             ( $template, $loggedinuser, $cookies ) = get_template_and_user(
228                 {
229                     template_name   => $template_name,
230                     query           => $query,
231                     type            => "intranet",
232                     authnotrequired => 1,
233                     flagsrequired   => { catalogue => 1 },
234                 }
235             );
236         };
237         like ( $@, qr(^bad template path), "The file $template_name should not be accessible" );
238     }
239     ( $template, $loggedinuser, $cookies ) = get_template_and_user(
240         {
241             template_name   => 'errors/errorpage.tt',
242             query           => $query,
243             type            => "intranet",
244             authnotrequired => 1,
245             flagsrequired   => { catalogue => 1 },
246         }
247     );
248     my $file_exists = ( -f $template->{filename} ) ? 1 : 0;
249     is ( $file_exists, 1, 'The file errors/errorpage.tt should be accessible (contains integers)' );
250 }
251
252 # Check that there is always an OPACBaseURL set.
253 my $input = CGI->new();
254 my ( $template1, $borrowernumber, $cookie );
255 ( $template1, $borrowernumber, $cookie ) = get_template_and_user(
256     {
257         template_name => "opac-detail.tt",
258         type => "opac",
259         query => $input,
260         authnotrequired => 1,
261     }
262 );
263
264 ok( ( any { 'OPACBaseURL' eq $_ } keys %{$template1->{VARS}} ),
265     'OPACBaseURL is in OPAC template' );
266
267 my ( $template2 );
268 ( $template2, $borrowernumber, $cookie ) = get_template_and_user(
269     {
270         template_name => "catalogue/detail.tt",
271         type => "intranet",
272         query => $input,
273         authnotrequired => 1,
274     }
275 );
276
277 ok( ( any { 'OPACBaseURL' eq $_ } keys %{$template2->{VARS}} ),
278     'OPACBaseURL is in Staff template' );
279
280 ok(C4::Auth::checkpw_hash('password', $hash1), 'password validates with first hash');
281 ok(C4::Auth::checkpw_hash('password', $hash2), 'password validates with second hash');