Bug 21395: Make perlcritic happy
[koha.git] / C4 / InstallAuth.pm
1 package C4::InstallAuth;
2
3 # Copyright 2000-2002 Katipo Communications
4 #
5 # This file is part of Koha.
6 #
7 # Koha is free software; you can redistribute it and/or modify it
8 # under the terms of the GNU General Public License as published by
9 # the Free Software Foundation; either version 3 of the License, or
10 # (at your option) any later version.
11 #
12 # Koha is distributed in the hope that it will be useful, but
13 # WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU General Public License for more details.
16 #
17 # You should have received a copy of the GNU General Public License
18 # along with Koha; if not, see <http://www.gnu.org/licenses>.
19
20 use Modern::Perl;
21 use Digest::MD5 qw(md5_base64);
22 use CGI::Session;
23 use File::Spec;
24
25 require Exporter;
26
27 use C4::Context;
28 use C4::Output;
29 use C4::Templates;
30 use C4::Koha;
31
32 use vars qw(@ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
33
34
35 =head1 NAME
36
37 InstallAuth - Authenticates Koha users for Install process
38
39 =head1 SYNOPSIS
40
41   use CGI qw ( -utf8 );
42   use InstallAuth;
43   use C4::Output;
44
45   my $query = new CGI;
46
47     my ( $template, $borrowernumber, $cookie ) = get_template_and_user(
48         {   template_name   => "opac-main.tt",
49             query           => $query,
50             type            => "opac",
51             authnotrequired => 1,
52             flagsrequired   => { acquisition => '*' },
53         }
54     );
55
56   output_html_with_http_headers $query, $cookie, $template->output;
57
58 =head1 DESCRIPTION
59
60     The main function of this module is to provide
61     authentification. However the get_template_and_user function has
62     been provided so that a users login information is passed along
63     automatically. This gets loaded into the template.
64     This package is different from C4::Auth in so far as 
65     C4::Auth uses many preferences which are supposed NOT to be obtainable when installing the database.
66     
67     As in C4::Auth, Authentication is based on cookies.
68
69 =head1 FUNCTIONS
70
71 =over 2
72
73 =cut
74
75 @ISA    = qw(Exporter);
76 @EXPORT = qw(
77   &checkauth
78   &get_template_and_user
79 );
80
81 =item get_template_and_user
82
83     my ( $template, $borrowernumber, $cookie ) = get_template_and_user(
84         {   template_name   => "opac-main.tt",
85             query           => $query,
86             type            => "opac",
87             authnotrequired => 1,
88             flagsrequired   => { acquisition => '*' },
89         }
90     );
91
92     This call passes the C<query>, C<flagsrequired> and C<authnotrequired>
93     to C<&checkauth> (in this module) to perform authentification.
94     See C<&checkauth> for an explanation of these parameters.
95
96     The C<template_name> is then used to find the correct template for
97     the page. The authenticated users details are loaded onto the
98     template in the logged_in_user variable (which is a Koha::Patron object). Also the
99     C<sessionID> is passed to the template. This can be used in templates
100     if cookies are disabled. It needs to be put as and input to every
101     authenticated page.
102
103     More information on the C<gettemplate> sub can be found in the
104     Templates.pm module.
105
106 =cut
107
108 sub get_template_and_user {
109     my $in       = shift;
110     my $query    = $in->{'query'};
111     my $language =_get_template_language($query->cookie('KohaOpacLanguage'));
112     my $path     = C4::Context->config('intrahtdocs'). "/prog/". $language;
113
114     my $tmplbase = $in->{template_name};
115     my $filename = "$path/modules/" . $tmplbase;
116     my $interface = 'intranet';
117     my $template = C4::Templates->new( $interface, $filename, $tmplbase, $query);
118     
119     my ( $user, $cookie, $sessionID, $flags ) = checkauth(
120         $in->{'query'},
121         $in->{'authnotrequired'},
122         $in->{'flagsrequired'},
123         $in->{'type'}
124     );
125
126     #     use Data::Dumper;warn "utilisateur $user cookie : ".Dumper($cookie);
127
128     my $borrowernumber;
129     if ($user) {
130         $template->param( loggedinusername => $user );
131         $template->param( sessionID        => $sessionID );
132
133         # We are going to use the $flags returned by checkauth
134         # to create the template's parameters that will indicate
135         # which menus the user can access.
136         if ( ( $flags && $flags->{superlibrarian} == 1 ) ) {
137             $template->param( CAN_user_circulate        => 1 );
138             $template->param( CAN_user_catalogue        => 1 );
139             $template->param( CAN_user_parameters       => 1 );
140             $template->param( CAN_user_borrowers        => 1 );
141             $template->param( CAN_user_permission       => 1 );
142             $template->param( CAN_user_reserveforothers => 1 );
143             $template->param( CAN_user_editcatalogue    => 1 );
144             $template->param( CAN_user_updatecharges    => 1 );
145             $template->param( CAN_user_acquisition      => 1 );
146             $template->param( CAN_user_tools            => 1 );
147             $template->param( CAN_user_editauthorities  => 1 );
148             $template->param( CAN_user_serials          => 1 );
149             $template->param( CAN_user_reports          => 1 );
150             $template->param( CAN_user_problem_reports   => 1 );
151         }
152
153         my $minPasswordLength = C4::Context->preference('minPasswordLength');
154         $minPasswordLength = 3 if not $minPasswordLength or $minPasswordLength < 3;
155         $template->param(minPasswordLength => $minPasswordLength,);
156     }
157     return ( $template, $borrowernumber, $cookie );
158 }
159
160 sub _get_template_language {
161
162     #verify if opac language exists in staff (bug 5660)
163     #conditions are 1) dir exists and 2) enabled in prefs
164     my ($opaclang) = @_;
165     return 'en' unless $opaclang;
166     $opaclang =~ s/[^a-zA-Z_-]*//g;
167     my $path = C4::Context->config('intrahtdocs') . "/prog/$opaclang";
168     -d $path ? $opaclang : 'en';
169 }
170
171 =item checkauth
172
173   ($userid, $cookie, $sessionID) = &checkauth($query, $noauth, $flagsrequired, $type);
174
175 Verifies that the user is authorized to run this script.  If
176 the user is authorized, a (userid, cookie, session-id, flags)
177 quadruple is returned.  If the user is not authorized but does
178 not have the required privilege (see $flagsrequired below), it
179 displays an error page and exits.  Otherwise, it displays the
180 login page and exits.
181
182 Note that C<&checkauth> will return if and only if the user
183 is authorized, so it should be called early on, before any
184 unfinished operations (e.g., if you've opened a file, then
185 C<&checkauth> won't close it for you).
186
187 C<$query> is the CGI object for the script calling C<&checkauth>.
188
189 The C<$noauth> argument is optional. If it is set, then no
190 authorization is required for the script.
191
192 C<&checkauth> fetches user and session information from C<$query> and
193 ensures that the user is authorized to run scripts that require
194 authorization.
195
196 The C<$flagsrequired> argument specifies the required privileges
197 the user must have if the username and password are correct.
198 It should be specified as a reference-to-hash; keys in the hash
199 should be the "flags" for the user, as specified in the Members
200 intranet module. Any key specified must correspond to a "flag"
201 in the userflags table. E.g., { circulate => 1 } would specify
202 that the user must have the "circulate" privilege in order to
203 proceed. To make sure that access control is correct, the
204 C<$flagsrequired> parameter must be specified correctly.
205
206 The C<$type> argument specifies whether the template should be
207 retrieved from the opac or intranet directory tree.  "opac" is
208 assumed if it is not specified; however, if C<$type> is specified,
209 "intranet" is assumed if it is not "opac".
210
211 If C<$query> does not have a valid session ID associated with it
212 (i.e., the user has not logged in) or if the session has expired,
213 C<&checkauth> presents the user with a login page (from the point of
214 view of the original script, C<&checkauth> does not return). Once the
215 user has authenticated, C<&checkauth> restarts the original script
216 (this time, C<&checkauth> returns).
217
218 The login page is provided using a HTML::Template, which is set in the
219 systempreferences table or at the top of this file. The variable C<$type>
220 selects which template to use, either the opac or the intranet 
221 authentification template.
222
223 C<&checkauth> returns a user ID, a cookie, and a session ID. The
224 cookie should be sent back to the browser; it verifies that the user
225 has authenticated.
226
227 =cut
228
229 sub checkauth {
230     my $query = shift;
231
232 # $authnotrequired will be set for scripts which will run without authentication
233     my $authnotrequired = shift;
234     my $flagsrequired   = shift;
235     my $type            = shift;
236     $type = 'intranet' unless $type;
237
238     my $dbh = C4::Context->dbh();
239     my $template_name;
240     $template_name = "installer/auth.tt";
241     my $sessdir = File::Spec->catdir( C4::Context::temporary_directory, 'cgisess_' . C4::Context->config('database') ); # same construction as in C4/Auth
242
243     # state variables
244     my $loggedin = 0;
245     my %info;
246     my ( $userid, $cookie, $sessionID, $flags, $envcookie );
247     my $logout = $query->param('logout.x');
248     if ( $sessionID = $query->cookie("CGISESSID") ) {
249         C4::Context->_new_userenv($sessionID);
250         my $session =
251           new CGI::Session( "driver:File;serializer:yaml", $sessionID,
252             { Directory => $sessdir } );
253         if ( $session->param('cardnumber') ) {
254             C4::Context->set_userenv(
255                 $session->param('number'),
256                 $session->param('id'),
257                 $session->param('cardnumber'),
258                 $session->param('firstname'),
259                 $session->param('surname'),
260                 $session->param('branch'),
261                 $session->param('branchname'),
262                 $session->param('flags'),
263                 $session->param('emailaddress')
264             );
265             $cookie = $query->cookie(
266                 -name     => 'CGISESSID',
267                 -value    => $session->id,
268                 -HttpOnly => 1,
269             );
270             $loggedin = 1;
271             $userid   = $session->param('cardnumber');
272         }
273
274         if ($logout) {
275
276             # voluntary logout the user
277             C4::Context->_unset_userenv($sessionID);
278             $sessionID = undef;
279             $userid    = undef;
280            # Commented out due to its lack of usefulness
281            # open L, ">>/tmp/sessionlog";
282            # my $time = localtime( time() );
283            # printf L "%20s from %16s logged out at %30s (manually).\n", $userid,
284            #   $ip, $time;
285            # close L;
286         }
287     }
288     unless ($userid) {
289         my $session =
290           new CGI::Session( "driver:File;serializer:yaml", undef, { Directory => $sessdir } );
291         $sessionID = $session->id;
292         $userid    = $query->param('userid');
293         C4::Context->_new_userenv($sessionID);
294         my $password = $query->param('password');
295         C4::Context->_new_userenv($sessionID);
296         my ( $return, $cardnumber ) = checkpw( $userid, $password );
297         if ($return) {
298             $loggedin = 1;
299             # open L, ">>/tmp/sessionlog";
300             # my $time = localtime( time() );
301             # printf L "%20s from %16s logged in  at %30s.\n", $userid,
302             #  $ENV{'REMOTE_ADDR'}, $time;
303             # close L;
304             $cookie = $query->cookie(
305                 -name     => 'CGISESSID',
306                 -value    => $sessionID,
307                 -HttpOnly => 1,
308             );
309             if ( $return == 2 ) {
310
311            #Only superlibrarian should have access to this page.
312            #Since if it is a user, it is supposed that there is a borrower table
313            #And thus that data structure is loaded.
314                 my $hash = C4::Context->set_userenv(
315                     0,                           0,
316                     C4::Context->config('user'), C4::Context->config('user'),
317                     C4::Context->config('user'), "",
318                     "NO_LIBRARY_SET",            1,
319                     ""
320                 );
321                 $session->param( 'number',     0 );
322                 $session->param( 'id',         C4::Context->config('user') );
323                 $session->param( 'cardnumber', C4::Context->config('user') );
324                 $session->param( 'firstname',  C4::Context->config('user') );
325                 $session->param( 'surname',    C4::Context->config('user'), );
326                 $session->param( 'branch',     'NO_LIBRARY_SET' );
327                 $session->param( 'branchname', 'NO_LIBRARY_SET' );
328                 $session->param( 'flags',      1 );
329                 $session->param( 'emailaddress',
330                     C4::Context->preference('KohaAdminEmailAddress') );
331                 $session->param( 'ip',       $session->remote_addr() );
332                 $session->param( 'lasttime', time() );
333                 $userid = C4::Context->config('user');
334             }
335         }
336         else {
337             if ($userid) {
338                 $info{'invalid_username_or_password'} = 1;
339                 C4::Context->_unset_userenv($sessionID);
340             }
341         }
342     }
343
344     # finished authentification, now respond
345     if ($loggedin) {
346
347         # successful login
348         unless ($cookie) {
349             $cookie = $query->cookie(
350                 -name    => 'CGISESSID',
351                 -value   => '',
352                 -HttpOnly => 1,
353                 -expires => ''
354             );
355         }
356         if ($envcookie) {
357             return ( $userid, [ $cookie, $envcookie ], $sessionID, $flags );
358         }
359         else {
360             return ( $userid, $cookie, $sessionID, $flags );
361         }
362     }
363
364     # else we have a problem...
365     # get the inputs from the incoming query
366     my @inputs = ();
367     foreach my $name ( param $query) {
368         (next) if ( $name eq 'userid' || $name eq 'password' );
369         my $value = $query->param($name);
370         push @inputs, { name => $name, value => $value };
371     }
372
373     my $path =
374       C4::Context->config('intrahtdocs') . "/prog/"
375       . ( $query->param('language') ? $query->param('language') : "en" );
376     my $filename = "$path/modules/$template_name";
377     my $interface = 'intranet';
378     my $template = C4::Templates->new( $interface, $filename, '', $query);
379     $template->param(
380         INPUTS => \@inputs,
381
382     );
383     $template->param( login => 1 );
384     $template->param( loginprompt => 1 ) unless $info{'nopermission'};
385
386     if ($info{'invalid_username_or_password'} && $info{'invalid_username_or_password'} == 1) {
387                 $template->param( 'invalid_username_or_password' => $info{'invalid_username_or_password'});
388     }
389
390     $template->param( \%info );
391     $cookie = $query->cookie(
392         -name    => 'CGISESSID',
393         -value   => $sessionID,
394         -HttpOnly => 1,
395         -expires => ''
396     );
397     print $query->header(
398         -type    => 'text/html; charset=utf-8',
399         -cookie  => $cookie
400       ),
401       $template->output;
402     exit;
403 }
404
405 sub checkpw {
406
407     my ( $userid, $password ) = @_;
408
409     if (   $userid
410         && $userid     eq C4::Context->config('user')
411         && "$password" eq C4::Context->config('pass') )
412     {
413
414         # Koha superuser account
415         C4::Context->set_userenv(
416             0, 0,
417             C4::Context->config('user'),
418             C4::Context->config('user'),
419             C4::Context->config('user'),
420             "", "NO_LIBRARY_SET", 1
421         );
422         return 2;
423     }
424     return 0;
425 }
426
427 END { }    # module clean-up code here (global destructor)
428 1;
429 __END__
430
431 =back
432
433 =head1 SEE ALSO
434
435 CGI(3)
436
437 C4::Output(3)
438
439 Digest::MD5(3)
440
441 =cut