2 # NOTE: This file uses 8-character tabs; do not change the tab size!
6 # Copyright 2000-2002 Katipo Communications
8 # This file is part of Koha.
10 # Koha is free software; you can redistribute it and/or modify it under the
11 # terms of the GNU General Public License as published by the Free Software
12 # Foundation; either version 2 of the License, or (at your option) any later
15 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
16 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
17 # A PARTICULAR PURPOSE. See the GNU General Public License for more details.
19 # You should have received a copy of the GNU General Public License along with
20 # Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
21 # Suite 330, Boston, MA 02111-1307 USA
24 use Digest::MD5 qw(md5_base64);
28 use C4::Output; # to get the template
29 use C4::Interface::CGI::Output;
30 use C4::Circulation::Circ2; # getpatroninformation
34 # use Net::LDAP qw(:all);
36 use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
38 # set the version for version checking
43 C4::Auth - Authenticates Koha users
52 my ($template, $borrowernumber, $cookie)
53 = get_template_and_user({template_name => "opac-main.tmpl",
57 flagsrequired => {borrow => 1},
61 -type => guesstype($template->output),
68 The main function of this module is to provide
69 authentification. However the get_template_and_user function has
70 been provided so that a users login information is passed along
71 automatically. This gets loaded into the template.
82 &get_template_and_user
85 =item get_template_and_user
87 my ($template, $borrowernumber, $cookie)
88 = get_template_and_user({template_name => "opac-main.tmpl",
92 flagsrequired => {borrow => 1},
95 This call passes the C<query>, C<flagsrequired> and C<authnotrequired>
96 to C<&checkauth> (in this module) to perform authentification.
97 See C<&checkauth> for an explanation of these parameters.
99 The C<template_name> is then used to find the correct template for
100 the page. The authenticated users details are loaded onto the
101 template in the HTML::Template LOOP variable C<USER_INFO>. Also the
102 C<sessionID> is passed to the template. This can be used in templates
103 if cookies are disabled. It needs to be put as and input to every
106 More information on the C<gettemplate> sub can be found in the
111 sub get_template_and_user {
114 gettemplate( $in->{'template_name'}, $in->{'type'}, $in->{'query'} );
115 my ( $user, $cookie, $sessionID, $flags ) = checkauth(
117 $in->{'authnotrequired'},
118 $in->{'flagsrequired'},
124 $template->param( loggedinusername => $user );
125 $template->param( sessionID => $sessionID );
127 $borrowernumber = getborrowernumber($user);
128 my ( $borr, $alternativeflags ) =
129 getpatroninformation( undef, $borrowernumber );
132 $template->param( USER_INFO => \@bordat, );
134 # We are going to use the $flags returned by checkauth
135 # to create the template's parameters that will indicate
136 # which menus the user can access.
137 if ( $flags && $flags->{superlibrarian} == 1 ) {
138 $template->param( CAN_user_circulate => 1 );
139 $template->param( CAN_user_catalogue => 1 );
140 $template->param( CAN_user_parameters => 1 );
141 $template->param( CAN_user_borrowers => 1 );
142 $template->param( CAN_user_permission => 1 );
143 $template->param( CAN_user_reserveforothers => 1 );
144 $template->param( CAN_user_borrow => 1 );
145 $template->param( CAN_user_reserveforself => 1 );
146 $template->param( CAN_user_editcatalogue => 1 );
147 $template->param( CAN_user_updatecharge => 1 );
148 $template->param( CAN_user_acquisition => 1 );
149 $template->param( CAN_user_management => 1 );
150 $template->param( CAN_user_tools => 1 );
153 if ( $flags && $flags->{circulate} == 1 ) {
154 $template->param( CAN_user_circulate => 1 );
157 if ( $flags && $flags->{catalogue} == 1 ) {
158 $template->param( CAN_user_catalogue => 1 );
161 if ( $flags && $flags->{parameters} == 1 ) {
162 $template->param( CAN_user_parameters => 1 );
163 $template->param( CAN_user_management => 1 );
164 $template->param( CAN_user_tools => 1 );
167 if ( $flags && $flags->{borrowers} == 1 ) {
168 $template->param( CAN_user_borrowers => 1 );
171 if ( $flags && $flags->{permissions} == 1 ) {
172 $template->param( CAN_user_permission => 1 );
175 if ( $flags && $flags->{reserveforothers} == 1 ) {
176 $template->param( CAN_user_reserveforothers => 1 );
179 if ( $flags && $flags->{borrow} == 1 ) {
180 $template->param( CAN_user_borrow => 1 );
183 if ( $flags && $flags->{reserveforself} == 1 ) {
184 $template->param( CAN_user_reserveforself => 1 );
187 if ( $flags && $flags->{editcatalogue} == 1 ) {
188 $template->param( CAN_user_editcatalogue => 1 );
191 if ( $flags && $flags->{updatecharges} == 1 ) {
192 $template->param( CAN_user_updatecharge => 1 );
195 if ( $flags && $flags->{acquisition} == 1 ) {
196 $template->param( CAN_user_acquisition => 1 );
199 if ( $flags && $flags->{management} == 1 ) {
200 $template->param( CAN_user_management => 1 );
201 $template->param( CAN_user_tools => 1 );
204 if ( $flags && $flags->{tools} == 1 ) {
205 $template->param( CAN_user_tools => 1 );
209 unless ( $in->{'type'} eq "intranet" ) {
211 suggestion => C4::Context->preference("suggestion"),
212 virtualshelves => C4::Context->preference("virtualshelves"),
213 OpacNav => C4::Context->preference("OpacNav"),
214 opacheader => C4::Context->preference("opacheader"),
215 opaccredits => C4::Context->preference("opaccredits"),
216 opacsmallimage => C4::Context->preference("opacsmallimage"),
217 opaclayoutstylesheet =>
218 C4::Context->preference("opaclayoutstylesheet"),
219 opaccolorstylesheet =>
220 C4::Context->preference("opaccolorstylesheet"),
221 opaclanguagesdisplay =>
222 C4::Context->preference("opaclanguagesdisplay"),
223 TemplateEncoding => C4::Context->preference("TemplateEncoding"),
224 opacuserlogin => C4::Context->preference("opacuserlogin"),
225 opacbookbag => C4::Context->preference("opacbookbag"),
229 TemplateEncoding => C4::Context->preference("TemplateEncoding"),
230 AmazonContent => C4::Context->preference("AmazonContent"),
231 LibraryName => C4::Context->preference("LibraryName"),
232 branchname => C4::Context->userenv->{'branchname'},
234 return ( $template, $borrowernumber, $cookie );
239 ($userid, $cookie, $sessionID) = &checkauth($query, $noauth, $flagsrequired, $type);
241 Verifies that the user is authorized to run this script. If
242 the user is authorized, a (userid, cookie, session-id, flags)
243 quadruple is returned. If the user is not authorized but does
244 not have the required privilege (see $flagsrequired below), it
245 displays an error page and exits. Otherwise, it displays the
246 login page and exits.
248 Note that C<&checkauth> will return if and only if the user
249 is authorized, so it should be called early on, before any
250 unfinished operations (e.g., if you've opened a file, then
251 C<&checkauth> won't close it for you).
253 C<$query> is the CGI object for the script calling C<&checkauth>.
255 The C<$noauth> argument is optional. If it is set, then no
256 authorization is required for the script.
258 C<&checkauth> fetches user and session information from C<$query> and
259 ensures that the user is authorized to run scripts that require
262 The C<$flagsrequired> argument specifies the required privileges
263 the user must have if the username and password are correct.
264 It should be specified as a reference-to-hash; keys in the hash
265 should be the "flags" for the user, as specified in the Members
266 intranet module. Any key specified must correspond to a "flag"
267 in the userflags table. E.g., { circulate => 1 } would specify
268 that the user must have the "circulate" privilege in order to
269 proceed. To make sure that access control is correct, the
270 C<$flagsrequired> parameter must be specified correctly.
272 The C<$type> argument specifies whether the template should be
273 retrieved from the opac or intranet directory tree. "opac" is
274 assumed if it is not specified; however, if C<$type> is specified,
275 "intranet" is assumed if it is not "opac".
277 If C<$query> does not have a valid session ID associated with it
278 (i.e., the user has not logged in) or if the session has expired,
279 C<&checkauth> presents the user with a login page (from the point of
280 view of the original script, C<&checkauth> does not return). Once the
281 user has authenticated, C<&checkauth> restarts the original script
282 (this time, C<&checkauth> returns).
284 The login page is provided using a HTML::Template, which is set in the
285 systempreferences table or at the top of this file. The variable C<$type>
286 selects which template to use, either the opac or the intranet
287 authentification template.
289 C<&checkauth> returns a user ID, a cookie, and a session ID. The
290 cookie should be sent back to the browser; it verifies that the user
298 # $authnotrequired will be set for scripts which will run without authentication
299 my $authnotrequired = shift;
300 my $flagsrequired = shift;
302 $type = 'opac' unless $type;
304 my $dbh = C4::Context->dbh;
305 my $timeout = C4::Context->preference('timeout');
306 $timeout = 600 unless $timeout;
309 if ( $type eq 'opac' ) {
310 $template_name = "opac-auth.tmpl";
313 $template_name = "auth.tmpl";
319 my ( $userid, $cookie, $sessionID, $flags, $envcookie );
320 my $logout = $query->param('logout.x');
321 if ( $userid = $ENV{'REMOTE_USER'} ) {
323 # Using Basic Authentication, no cookies required
324 $cookie = $query->cookie(
325 -name => 'sessionID',
331 elsif ( $sessionID = $query->cookie('sessionID') ) {
332 C4::Context->_new_userenv($sessionID);
333 if ( my %hash = $query->cookie('userenv') ) {
334 C4::Context::set_userenv(
335 $hash{number}, $hash{id},
336 $hash{cardnumber}, $hash{firstname},
337 $hash{surname}, $hash{branch},
338 $hash{branchname}, $hash{flags},
339 $hash{emailaddress}, $hash{branchprinter}
342 my ( $ip, $lasttime );
344 ( $userid, $ip, $lasttime ) =
345 $dbh->selectrow_array(
346 "SELECT userid,ip,lasttime FROM sessions WHERE sessionid=?",
350 # voluntary logout the user
351 $dbh->do( "DELETE FROM sessions WHERE sessionID=?",
353 C4::Context->_unset_userenv($sessionID);
356 open L, ">>/tmp/sessionlog";
357 my $time = localtime( time() );
358 printf L "%20s from %16s logged out at %30s (manually).\n", $userid,
363 if ( $lasttime < time() - $timeout ) {
366 $info{'timed_out'} = 1;
367 $dbh->do( "DELETE FROM sessions WHERE sessionID=?",
369 C4::Context->_unset_userenv($sessionID);
372 open L, ">>/tmp/sessionlog";
373 my $time = localtime( time() );
374 printf L "%20s from %16s logged out at %30s (inactivity).\n",
378 elsif ( $ip ne $ENV{'REMOTE_ADDR'} ) {
380 # Different ip than originally logged in from
381 $info{'oldip'} = $ip;
382 $info{'newip'} = $ENV{'REMOTE_ADDR'};
383 $info{'different_ip'} = 1;
384 $dbh->do( "DELETE FROM sessions WHERE sessionID=?",
386 C4::Context->_unset_userenv($sessionID);
389 open L, ">>/tmp/sessionlog";
390 my $time = localtime( time() );
392 "%20s from logged out at %30s (ip changed from %16s to %16s).\n",
393 $userid, $time, $ip, $info{'newip'};
397 $cookie = $query->cookie(
398 -name => 'sessionID',
399 -value => $sessionID,
402 $dbh->do( "UPDATE sessions SET lasttime=? WHERE sessionID=?",
403 undef, ( time(), $sessionID ) );
404 $flags = haspermission( $dbh, $userid, $flagsrequired );
409 $info{'nopermission'} = 1;
415 $sessionID = int( rand() * 100000 ) . '-' . time();
416 $userid = $query->param('userid');
417 C4::Context->_new_userenv($sessionID);
418 my $password = $query->param('password');
419 C4::Context->_new_userenv($sessionID);
420 my ( $return, $cardnumber ) = checkpw( $dbh, $userid, $password );
422 $dbh->do( "DELETE FROM sessions WHERE sessionID=? AND userid=?",
423 undef, ( $sessionID, $userid ) );
425 "INSERT INTO sessions (sessionID, userid, ip,lasttime) VALUES (?, ?, ?, ?)",
427 ( $sessionID, $userid, $ENV{'REMOTE_ADDR'}, time() )
429 open L, ">>/tmp/sessionlog";
430 my $time = localtime( time() );
431 printf L "%20s from %16s logged in at %30s.\n", $userid,
432 $ENV{'REMOTE_ADDR'}, $time;
434 $cookie = $query->cookie(
435 -name => 'sessionID',
436 -value => $sessionID,
439 if ( $flags = haspermission( $dbh, $userid, $flagsrequired ) ) {
443 $info{'nopermission'} = 1;
444 C4::Context->_unset_userenv($sessionID);
446 if ( $return == 1 ) {
447 my ( $bornum, $firstname, $surname, $userflags, $branchcode,
448 $branchname, $branchprinter, $emailaddress );
451 "select borrowernumber, firstname, surname, flags, borrowers.branchcode, branches.branchname as branchname,branches.branchprinter as branchprinter, email from borrowers left join branches on borrowers.branchcode=branches.branchcode where userid=?"
453 $sth->execute($userid);
455 $bornum, $firstname, $surname, $userflags, $branchcode,
456 $branchname, $branchprinter, $emailaddress
461 # warn "$cardnumber,$bornum,$userid,$firstname,$surname,$userflags,$branchcode,$emailaddress";
462 unless ( $sth->rows ) {
465 "select borrowernumber, firstname, surname, flags, borrowers.branchcode, branches.branchname as branchname, branches.branchprinter as branchprinter, email from borrowers left join branches on borrowers.branchcode=branches.branchcode where cardnumber=?"
467 $sth->execute($cardnumber);
469 $bornum, $firstname, $surname, $userflags, $branchcode,
470 $branchcode, $branchprinter, $emailaddress
475 # warn "$cardnumber,$bornum,$userid,$firstname,$surname,$userflags,$branchcode,$emailaddress";
476 unless ( $sth->rows ) {
477 $sth->execute($userid);
479 $bornum, $firstname, $surname, $userflags,
480 $branchcode, $branchprinter, $emailaddress
486 # warn "$cardnumber,$bornum,$userid,$firstname,$surname,$userflags,$branchcode,$emailaddress";
489 # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
491 # launch a sequence to check if we have a ip for the branch, if we have one we replace the branchcode of the userenv by the branch bound in the ip.
492 my $ip = $ENV{'REMOTE_ADDR'};
493 my $branches = getbranches();
496 foreach my $br ( keys %$branches ) {
498 # now we work with the treatment of ip
499 my $domain = $branches->{$br}->{branchip};
500 if ( $domain && $ip =~ /^$domain/ ) {
501 $branchcode = $branches->{$br}->{'branchcode'};
503 # new op dev : add the branchprinter and branchname in the cookie
504 $branchprinter = $branches->{$br}->{'branchprinter'};
505 $branchname = $branches->{$br}->{'branchname'};
509 my $hash = C4::Context::set_userenv(
510 $bornum, $userid, $cardnumber,
511 $firstname, $surname, $branchcode,
512 $branchname, $userflags, $emailaddress,
516 $envcookie = $query->cookie(
522 elsif ( $return == 2 ) {
524 #We suppose the user is the superlibrarian
525 my $hash = C4::Context::set_userenv(
528 C4::Context->config('user'),
529 C4::Context->config('user'),
530 C4::Context->config('user'),
533 C4::Context->preference('KohaAdminEmailAddress')
535 $envcookie = $query->cookie(
544 $info{'invalid_username_or_password'} = 1;
545 C4::Context->_unset_userenv($sessionID);
549 my $insecure = C4::Context->boolean_preference('insecure');
551 # finished authentification, now respond
552 if ( $loggedin || $authnotrequired || ( defined($insecure) && $insecure ) )
557 $cookie = $query->cookie(
558 -name => 'sessionID',
564 return ( $userid, [ $cookie, $envcookie ], $sessionID, $flags );
567 return ( $userid, $cookie, $sessionID, $flags );
571 # else we have a problem...
572 # get the inputs from the incoming query
574 foreach my $name ( param $query) {
575 (next) if ( $name eq 'userid' || $name eq 'password' );
576 my $value = $query->param($name);
577 push @inputs, { name => $name, value => $value };
580 my $template = gettemplate( $template_name, $type, $query );
583 intranetcolorstylesheet =>
584 C4::Context->preference("intranetcolorstylesheet"),
585 intranetstylesheet => C4::Context->preference("intranetstylesheet"),
586 IntranetNav => C4::Context->preference("IntranetNav"),
587 TemplateEncoding => C4::Context->preference("TemplateEncoding"),
590 $template->param( loginprompt => 1 ) unless $info{'nopermission'};
592 my $self_url = $query->url( -absolute => 1 );
595 LibraryName => => C4::Context->preference("LibraryName"),
597 $template->param( \%info );
598 $cookie = $query->cookie(
599 -name => 'sessionID',
600 -value => $sessionID,
603 print $query->header(
604 -type => guesstype( $template->output ),
613 my ( $dbh, $userid, $password ) = @_;
617 $dbh->prepare("select password,cardnumber from borrowers where userid=?");
618 $sth->execute($userid);
620 my ( $md5password, $cardnumber ) = $sth->fetchrow;
621 if ( md5_base64($password) eq $md5password ) {
623 # C4::Context->set_userenv("$bornum",$userid,$cardnumber,$firstname,$surname,$branchcode,$userflags);
624 return 1, $cardnumber;
627 $sth = $dbh->prepare("select password from borrowers where cardnumber=?");
628 $sth->execute($userid);
630 my ($md5password) = $sth->fetchrow;
631 if ( md5_base64($password) eq $md5password ) {
633 # C4::Context->set_userenv($bornum,$userid,$cardnumber,$firstname,$surname,$branchcode,$userflags);
637 if ( $userid eq C4::Context->config('user')
638 && $password eq C4::Context->config('pass') )
641 # Koha superuser account
642 # C4::Context->set_userenv(0,0,C4::Context->config('user'),C4::Context->config('user'),C4::Context->config('user'),"",1);
645 if ( $userid eq 'demo'
646 && $password eq 'demo'
647 && C4::Context->config('demo') )
650 # DEMO => the demo user is allowed to do everything (if demo set to 1 in koha.conf
651 # some features won't be effective : modify systempref, modify MARC structure,
658 my $cardnumber = shift;
661 my $sth = $dbh->prepare("SELECT flags FROM borrowers WHERE cardnumber=?");
662 $sth->execute($cardnumber);
663 my ($flags) = $sth->fetchrow;
664 $flags = 0 unless $flags;
665 $sth = $dbh->prepare("SELECT bit, flag, defaulton FROM userflags");
668 while ( my ( $bit, $flag, $defaulton ) = $sth->fetchrow ) {
669 if ( ( $flags & ( 2**$bit ) ) || $defaulton ) {
670 $userflags->{$flag} = 1;
673 $userflags->{$flag} = 0;
680 my ( $dbh, $userid, $flagsrequired ) = @_;
681 my $sth = $dbh->prepare("SELECT cardnumber FROM borrowers WHERE userid=?");
682 $sth->execute($userid);
683 my ($cardnumber) = $sth->fetchrow;
684 ($cardnumber) || ( $cardnumber = $userid );
685 my $flags = getuserflags( $cardnumber, $dbh );
687 if ( $userid eq C4::Context->config('user') ) {
689 # Super User Account from /etc/koha.conf
690 $flags->{'superlibrarian'} = 1;
692 if ( $userid eq 'demo' && C4::Context->config('demo') ) {
694 # Demo user that can do "anything" (demo=1 in /etc/koha.conf)
695 $flags->{'superlibrarian'} = 1;
697 return $flags if $flags->{superlibrarian};
698 foreach ( keys %$flagsrequired ) {
699 return $flags if $flags->{$_};
704 sub getborrowernumber {
706 my $dbh = C4::Context->dbh;
707 for my $field ( 'userid', 'cardnumber' ) {
709 $dbh->prepare("select borrowernumber from borrowers where $field=?");
710 $sth->execute($userid);
712 my ($bnumber) = $sth->fetchrow;
719 END { } # module clean-up code here (global destructor)