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
31 use C4::Branch; # GetBranches
34 # use Net::LDAP qw(:all);
36 use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
38 # set the version for version checking
39 $VERSION = do { my @v = '$Revision$' =~ /\d+/g;
40 shift(@v) . "." . join( "_", map { sprintf "%03d", $_ } @v );
45 C4::Auth - Authenticates Koha users
54 my ($template, $borrowernumber, $cookie)
55 = get_template_and_user({template_name => "opac-main.tmpl",
59 flagsrequired => {borrow => 1},
70 The main function of this module is to provide
71 authentification. However the get_template_and_user function has
72 been provided so that a users login information is passed along
73 automatically. This gets loaded into the template.
84 &get_template_and_user
87 =item get_template_and_user
89 my ($template, $borrowernumber, $cookie)
90 = get_template_and_user({template_name => "opac-main.tmpl",
94 flagsrequired => {borrow => 1},
97 This call passes the C<query>, C<flagsrequired> and C<authnotrequired>
98 to C<&checkauth> (in this module) to perform authentification.
99 See C<&checkauth> for an explanation of these parameters.
101 The C<template_name> is then used to find the correct template for
102 the page. The authenticated users details are loaded onto the
103 template in the HTML::Template LOOP variable C<USER_INFO>. Also the
104 C<sessionID> is passed to the template. This can be used in templates
105 if cookies are disabled. It needs to be put as and input to every
108 More information on the C<gettemplate> sub can be found in the
113 sub get_template_and_user {
116 gettemplate( $in->{'template_name'}, $in->{'type'}, $in->{'query'} );
117 my ( $user, $cookie, $sessionID, $flags ) = checkauth(
119 $in->{'authnotrequired'},
120 $in->{'flagsrequired'},
125 my $insecure = C4::Context->preference('insecure');
126 if ($user or $insecure) {
127 $template->param( loggedinusername => $user );
128 $template->param( sessionID => $sessionID );
130 $borrowernumber = getborrowernumber($user);
131 my ( $borr, $alternativeflags ) =
132 GetMemberDetails( $borrowernumber );
135 $template->param( "USER_INFO" => \@bordat );
137 # We are going to use the $flags returned by checkauth
138 # to create the template's parameters that will indicate
139 # which menus the user can access.
140 if (( $flags && $flags->{superlibrarian}==1) or $insecure==1) {
141 $template->param( CAN_user_circulate => 1 );
142 $template->param( CAN_user_catalogue => 1 );
143 $template->param( CAN_user_parameters => 1 );
144 $template->param( CAN_user_borrowers => 1 );
145 $template->param( CAN_user_permission => 1 );
146 $template->param( CAN_user_reserveforothers => 1 );
147 $template->param( CAN_user_borrow => 1 );
148 $template->param( CAN_user_editcatalogue => 1 );
149 $template->param( CAN_user_updatecharge => 1 );
150 $template->param( CAN_user_acquisition => 1 );
151 $template->param( CAN_user_management => 1 );
152 $template->param( CAN_user_tools => 1 );
153 $template->param( CAN_user_editauthorities => 1 );
154 $template->param( CAN_user_serials => 1 );
155 $template->param( CAN_user_reports => 1 );
158 if ( $flags && $flags->{circulate} == 1 ) {
159 $template->param( CAN_user_circulate => 1 );
162 if ( $flags && $flags->{catalogue} == 1 ) {
163 $template->param( CAN_user_catalogue => 1 );
166 if ( $flags && $flags->{parameters} == 1 ) {
167 $template->param( CAN_user_parameters => 1 );
168 $template->param( CAN_user_management => 1 );
171 if ( $flags && $flags->{borrowers} == 1 ) {
172 $template->param( CAN_user_borrowers => 1 );
175 if ( $flags && $flags->{permissions} == 1 ) {
176 $template->param( CAN_user_permission => 1 );
179 if ( $flags && $flags->{reserveforothers} == 1 ) {
180 $template->param( CAN_user_reserveforothers => 1 );
183 if ( $flags && $flags->{borrow} == 1 ) {
184 $template->param( CAN_user_borrow => 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->{tools} == 1 ) {
200 $template->param( CAN_user_tools => 1 );
203 if ( $flags && $flags->{editauthorities} == 1 ) {
204 $template->param( CAN_user_editauthorities => 1 );
207 if ( $flags && $flags->{serials} == 1 ) {
208 $template->param( CAN_user_serials => 1 );
211 if ( $flags && $flags->{reports} == 1 ) {
212 $template->param( CAN_user_reports => 1 );
215 if ( $in->{'type'} eq "intranet" ) {
217 intranetcolorstylesheet =>
218 C4::Context->preference("intranetcolorstylesheet"),
219 intranetstylesheet => C4::Context->preference("intranetstylesheet"),
220 IntranetNav => C4::Context->preference("IntranetNav"),
221 intranetuserjs => C4::Context->preference("intranetuserjs"),
222 TemplateEncoding => C4::Context->preference("TemplateEncoding"),
223 AmazonContent => C4::Context->preference("AmazonContent"),
224 LibraryName => C4::Context->preference("LibraryName"),
225 LoginBranchname => (C4::Context->userenv?C4::Context->userenv->{"branchname"}:"insecure"),
226 AutoLocation => C4::Context->preference("AutoLocation"),
227 hide_marc => C4::Context->preference("hide_marc"),
228 patronimages => C4::Context->preference("patronimages"),
229 "BiblioDefaultView".C4::Context->preference("BiblioDefaultView") => 1,
233 warn "template type should be OPAC, here it is=[" . $in->{'type'} . "]"
234 unless ( $in->{'type'} eq 'opac' );
235 my $LibraryNameTitle = C4::Context->preference("LibraryName");
236 $LibraryNameTitle =~ s/<(?:\/?)(?:br|p)\s*(?:\/?)>/ /sgi;
237 $LibraryNameTitle =~ s/<(?:[^<>'"]|'(?:[^']*)'|"(?:[^"]*)")*>//sg;
239 suggestion => "" . C4::Context->preference("suggestion"),
240 virtualshelves => "" . C4::Context->preference("virtualshelves"),
241 OpacNav => "" . C4::Context->preference("OpacNav"),
242 opacheader => "" . C4::Context->preference("opacheader"),
243 opaccredits => "" . C4::Context->preference("opaccredits"),
244 opacsmallimage => "" . C4::Context->preference("opacsmallimage"),
245 opaclargeimage => "" . C4::Context->preference("opaclargeimage"),
246 opaclayoutstylesheet => "". C4::Context->preference("opaclayoutstylesheet"),
247 opaccolorstylesheet => "". C4::Context->preference("opaccolorstylesheet"),
248 opaclanguagesdisplay => "". C4::Context->preference("opaclanguagesdisplay"),
249 opacuserlogin => "" . C4::Context->preference("opacuserlogin"),
250 opacbookbag => "" . C4::Context->preference("opacbookbag"),
251 TemplateEncoding => "". C4::Context->preference("TemplateEncoding"),
252 AmazonContent => "" . C4::Context->preference("AmazonContent"),
253 LibraryName => "" . C4::Context->preference("LibraryName"),
254 LibraryNameTitle => "" . $LibraryNameTitle,
255 LoginBranchname => C4::Context->userenv?C4::Context->userenv->{"branchname"}:"",
256 OpacPasswordChange => C4::Context->preference("OpacPasswordChange"),
257 opacreadinghistory => C4::Context->preference("opacreadinghistory"),
258 opacuserjs => C4::Context->preference("opacuserjs"),
259 OpacCloud => C4::Context->preference("OpacCloud"),
260 OpacTopissue => C4::Context->preference("OpacTopissue"),
261 OpacAuthorities => C4::Context->preference("OpacAuthorities"),
262 OpacBrowser => C4::Context->preference("OpacBrowser"),
263 RequestOnOpac => C4::Context->preference("RequestOnOpac"),
264 reviewson => C4::Context->preference("reviewson"),
265 hide_marc => C4::Context->preference("hide_marc"),
266 patronimages => C4::Context->preference("patronimages"),
267 "BiblioDefaultView".C4::Context->preference("BiblioDefaultView") => 1,
270 return ( $template, $borrowernumber, $cookie );
275 ($userid, $cookie, $sessionID) = &checkauth($query, $noauth, $flagsrequired, $type);
277 Verifies that the user is authorized to run this script. If
278 the user is authorized, a (userid, cookie, session-id, flags)
279 quadruple is returned. If the user is not authorized but does
280 not have the required privilege (see $flagsrequired below), it
281 displays an error page and exits. Otherwise, it displays the
282 login page and exits.
284 Note that C<&checkauth> will return if and only if the user
285 is authorized, so it should be called early on, before any
286 unfinished operations (e.g., if you've opened a file, then
287 C<&checkauth> won't close it for you).
289 C<$query> is the CGI object for the script calling C<&checkauth>.
291 The C<$noauth> argument is optional. If it is set, then no
292 authorization is required for the script.
294 C<&checkauth> fetches user and session information from C<$query> and
295 ensures that the user is authorized to run scripts that require
298 The C<$flagsrequired> argument specifies the required privileges
299 the user must have if the username and password are correct.
300 It should be specified as a reference-to-hash; keys in the hash
301 should be the "flags" for the user, as specified in the Members
302 intranet module. Any key specified must correspond to a "flag"
303 in the userflags table. E.g., { circulate => 1 } would specify
304 that the user must have the "circulate" privilege in order to
305 proceed. To make sure that access control is correct, the
306 C<$flagsrequired> parameter must be specified correctly.
308 The C<$type> argument specifies whether the template should be
309 retrieved from the opac or intranet directory tree. "opac" is
310 assumed if it is not specified; however, if C<$type> is specified,
311 "intranet" is assumed if it is not "opac".
313 If C<$query> does not have a valid session ID associated with it
314 (i.e., the user has not logged in) or if the session has expired,
315 C<&checkauth> presents the user with a login page (from the point of
316 view of the original script, C<&checkauth> does not return). Once the
317 user has authenticated, C<&checkauth> restarts the original script
318 (this time, C<&checkauth> returns).
320 The login page is provided using a HTML::Template, which is set in the
321 systempreferences table or at the top of this file. The variable C<$type>
322 selects which template to use, either the opac or the intranet
323 authentification template.
325 C<&checkauth> returns a user ID, a cookie, and a session ID. The
326 cookie should be sent back to the browser; it verifies that the user
334 # $authnotrequired will be set for scripts which will run without authentication
335 my $authnotrequired = shift;
336 my $flagsrequired = shift;
338 $type = 'opac' unless $type;
340 my $dbh = C4::Context->dbh;
341 unless (C4::Context->preference('Version')){
342 print $query->redirect("/cgi-bin/koha/installer/install.pl?step=3");
345 my $timeout = C4::Context->preference('timeout');
346 $timeout = 600 unless $timeout;
349 if ( $type eq 'opac' ) {
350 $template_name = "opac-auth.tmpl";
353 $template_name = "auth.tmpl";
359 my ( $userid, $cookie, $sessionID, $flags, $envcookie );
360 my $logout = $query->param('logout.x');
361 if ( $userid = $ENV{'REMOTE_USER'} ) {
363 # Using Basic Authentication, no cookies required
364 $cookie = $query->cookie(
365 -name => 'sessionID',
371 elsif ( $sessionID = $query->cookie('sessionID') ) {
372 C4::Context->_new_userenv($sessionID);
373 if ( my %hash = $query->cookie('userenv') ) {
374 C4::Context::set_userenv(
375 $hash{number}, $hash{id},
376 $hash{cardnumber}, $hash{firstname},
377 $hash{surname}, $hash{branch},
378 $hash{branchname}, $hash{flags},
379 $hash{emailaddress}, $hash{branchprinter}
382 my ( $ip, $lasttime );
384 ( $userid, $ip, $lasttime ) =
385 $dbh->selectrow_array(
386 "SELECT userid,ip,lasttime FROM sessions WHERE sessionid=?",
390 # voluntary logout the user
391 $dbh->do( "DELETE FROM sessions WHERE sessionID=?",
393 C4::Context->_unset_userenv($sessionID);
396 open L, ">>/tmp/sessionlog";
397 my $time = localtime( time() );
398 printf L "%20s from %16s logged out at %30s (manually).\n", $userid,
403 if ( $lasttime < time() - $timeout ) {
406 $info{'timed_out'} = 1;
407 $dbh->do( "DELETE FROM sessions WHERE sessionID=?",
409 C4::Context->_unset_userenv($sessionID);
412 open L, ">>/tmp/sessionlog";
413 my $time = localtime( time() );
414 printf L "%20s from %16s logged out at %30s (inactivity).\n",
418 elsif ( $ip ne $ENV{'REMOTE_ADDR'} ) {
420 # Different ip than originally logged in from
421 $info{'oldip'} = $ip;
422 $info{'newip'} = $ENV{'REMOTE_ADDR'};
423 $info{'different_ip'} = 1;
424 $dbh->do( "DELETE FROM sessions WHERE sessionID=?",
426 C4::Context->_unset_userenv($sessionID);
429 open L, ">>/tmp/sessionlog";
430 my $time = localtime( time() );
432 "%20s from logged out at %30s (ip changed from %16s to %16s).\n",
433 $userid, $time, $ip, $info{'newip'};
437 $cookie = $query->cookie(
438 -name => 'sessionID',
439 -value => $sessionID,
442 $dbh->do( "UPDATE sessions SET lasttime=? WHERE sessionID=?",
443 undef, ( time(), $sessionID ) );
444 $flags = haspermission( $dbh, $userid, $flagsrequired );
449 $info{'nopermission'} = 1;
455 $sessionID = int( rand() * 100000 ) . '-' . time();
456 $userid = $query->param('userid');
457 C4::Context->_new_userenv($sessionID);
458 my $password = $query->param('password');
459 C4::Context->_new_userenv($sessionID);
460 my ( $return, $cardnumber ) = checkpw( $dbh, $userid, $password );
462 $dbh->do( "DELETE FROM sessions WHERE sessionID=? AND userid=?",
463 undef, ( $sessionID, $userid ) );
465 "INSERT INTO sessions (sessionID, userid, ip,lasttime) VALUES (?, ?, ?, ?)",
467 ( $sessionID, $userid, $ENV{'REMOTE_ADDR'}, time() )
469 open L, ">>/tmp/sessionlog";
470 my $time = localtime( time() );
471 printf L "%20s from %16s logged in at %30s.\n", $userid,
472 $ENV{'REMOTE_ADDR'}, $time;
474 $cookie = $query->cookie(
475 -name => 'sessionID',
476 -value => $sessionID,
479 if ( $flags = haspermission( $dbh, $userid, $flagsrequired ) ) {
483 $info{'nopermission'} = 1;
484 C4::Context->_unset_userenv($sessionID);
486 if ( $return == 1 ) {
488 $borrowernumber, $firstname, $surname,
489 $userflags, $branchcode, $branchname,
490 $branchprinter, $emailaddress
494 "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=?"
496 $sth->execute($userid);
498 $borrowernumber, $firstname, $surname,
499 $userflags, $branchcode, $branchname,
500 $branchprinter, $emailaddress
505 # warn "$cardnumber,$borrowernumber,$userid,$firstname,$surname,$userflags,$branchcode,$emailaddress";
506 unless ( $sth->rows ) {
509 "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=?"
511 $sth->execute($cardnumber);
513 $borrowernumber, $firstname, $surname,
514 $userflags, $branchcode, $branchname,
515 $branchprinter, $emailaddress
520 # warn "$cardnumber,$borrowernumber,$userid,$firstname,$surname,$userflags,$branchcode,$emailaddress";
521 unless ( $sth->rows ) {
522 $sth->execute($userid);
524 $borrowernumber, $firstname, $surname, $userflags,
525 $branchcode, $branchname, $branchprinter, $emailaddress
531 # warn "$cardnumber,$borrowernumber,$userid,$firstname,$surname,$userflags,$branchcode,$emailaddress";
534 # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
536 # 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.
537 my $ip = $ENV{'REMOTE_ADDR'};
538 my $branches = GetBranches();
540 foreach my $br ( keys %$branches ) {
542 # now we work with the treatment of ip
543 my $domain = $branches->{$br}->{'branchip'};
544 if ( $domain && $ip =~ /^$domain/ ) {
545 $branchcode = $branches->{$br}->{'branchcode'};
547 # new op dev : add the branchprinter and branchname in the cookie
548 $branchprinter = $branches->{$br}->{'branchprinter'};
549 $branchname = $branches->{$br}->{'branchname'};
552 my $hash = C4::Context::set_userenv(
553 $borrowernumber, $userid, $cardnumber,
554 $firstname, $surname, $branchcode,
555 $branchname, $userflags, $emailaddress,
559 $envcookie = $query->cookie(
565 elsif ( $return == 2 ) {
567 #We suppose the user is the superlibrarian
568 my $hash = C4::Context::set_userenv(
571 C4::Context->config('user'),
572 C4::Context->config('user'),
573 C4::Context->config('user'),
577 C4::Context->preference('KohaAdminEmailAddress')
579 $envcookie = $query->cookie(
588 $info{'invalid_username_or_password'} = 1;
589 C4::Context->_unset_userenv($sessionID);
593 my $insecure = C4::Context->boolean_preference('insecure');
595 # finished authentification, now respond
596 if ( $loggedin || $authnotrequired || ( defined($insecure) && $insecure ) )
601 $cookie = $query->cookie(
602 -name => 'sessionID',
608 return ( $userid, [ $cookie, $envcookie ], $sessionID, $flags );
611 return ( $userid, $cookie, $sessionID, $flags );
615 # else we have a problem...
616 # get the inputs from the incoming query
618 foreach my $name ( param $query) {
619 (next) if ( $name eq 'userid' || $name eq 'password' );
620 my $value = $query->param($name);
621 push @inputs, { name => $name, value => $value };
624 my $template = gettemplate( $template_name, $type, $query );
627 suggestion => C4::Context->preference("suggestion"),
628 virtualshelves => C4::Context->preference("virtualshelves"),
629 opaclargeimage => C4::Context->preference("opaclargeimage"),
630 LibraryName => C4::Context->preference("LibraryName"),
631 OpacNav => C4::Context->preference("OpacNav"),
632 opaccredits => C4::Context->preference("opaccredits"),
633 opacreadinghistory => C4::Context->preference("opacreadinghistory"),
634 opacsmallimage => C4::Context->preference("opacsmallimage"),
635 opaclayoutstylesheet => C4::Context->preference("opaclayoutstylesheet"),
636 opaccolorstylesheet => C4::Context->preference("opaccolorstylesheet"),
637 opaclanguagesdisplay => C4::Context->preference("opaclanguagesdisplay"),
638 opacuserjs => C4::Context->preference("opacuserjs"),
640 intranetcolorstylesheet =>
641 C4::Context->preference("intranetcolorstylesheet"),
642 intranetstylesheet => C4::Context->preference("intranetstylesheet"),
643 IntranetNav => C4::Context->preference("IntranetNav"),
644 intranetuserjs => C4::Context->preference("intranetuserjs"),
645 TemplateEncoding => C4::Context->preference("TemplateEncoding"),
648 $template->param( loginprompt => 1 ) unless $info{'nopermission'};
650 my $self_url = $query->url( -absolute => 1 );
653 LibraryName => => C4::Context->preference("LibraryName"),
655 $template->param( \%info );
656 $cookie = $query->cookie(
657 -name => 'sessionID',
658 -value => $sessionID,
661 print $query->header(
671 my ( $dbh, $userid, $password ) = @_;
676 "select password,cardnumber,borrowernumber,userid,firstname,surname,branchcode,flags from borrowers where userid=?"
678 $sth->execute($userid);
680 my ( $md5password, $cardnumber, $borrowernumber, $userid, $firstname,
681 $surname, $branchcode, $flags )
683 if ( md5_base64($password) eq $md5password ) {
685 C4::Context->set_userenv( "$borrowernumber", $userid, $cardnumber,
686 $firstname, $surname, $branchcode, $flags );
687 return 1, $cardnumber;
692 "select password,cardnumber,borrowernumber,userid, firstname,surname,branchcode,flags from borrowers where cardnumber=?"
694 $sth->execute($userid);
696 my ( $md5password, $cardnumber, $borrowernumber, $userid, $firstname,
697 $surname, $branchcode, $flags )
699 if ( md5_base64($password) eq $md5password ) {
701 C4::Context->set_userenv( $borrowernumber, $userid, $cardnumber,
702 $firstname, $surname, $branchcode, $flags );
706 if ( $userid && $userid eq C4::Context->config('user')
707 && "$password" eq C4::Context->config('pass') )
710 # Koha superuser account
711 # C4::Context->set_userenv(0,0,C4::Context->config('user'),C4::Context->config('user'),C4::Context->config('user'),"",1);
714 if ( $userid && $userid eq 'demo'
715 && "$password" eq 'demo'
716 && C4::Context->config('demo') )
719 # DEMO => the demo user is allowed to do everything (if demo set to 1 in koha.conf
720 # some features won't be effective : modify systempref, modify MARC structure,
727 my $cardnumber = shift;
730 my $sth = $dbh->prepare("SELECT flags FROM borrowers WHERE cardnumber=?");
731 $sth->execute($cardnumber);
732 my ($flags) = $sth->fetchrow;
733 $flags = 0 unless $flags;
734 $sth = $dbh->prepare("SELECT bit, flag, defaulton FROM userflags");
737 while ( my ( $bit, $flag, $defaulton ) = $sth->fetchrow ) {
738 if ( ( $flags & ( 2**$bit ) ) || $defaulton ) {
739 $userflags->{$flag} = 1;
742 $userflags->{$flag} = 0;
749 my ( $dbh, $userid, $flagsrequired ) = @_;
750 my $sth = $dbh->prepare("SELECT cardnumber FROM borrowers WHERE userid=?");
751 $sth->execute($userid);
752 my ($cardnumber) = $sth->fetchrow;
753 ($cardnumber) || ( $cardnumber = $userid );
754 my $flags = getuserflags( $cardnumber, $dbh );
756 if ( $userid eq C4::Context->config('user') ) {
758 # Super User Account from /etc/koha.conf
759 $flags->{'superlibrarian'} = 1;
761 if ( $userid eq 'demo' && C4::Context->config('demo') ) {
763 # Demo user that can do "anything" (demo=1 in /etc/koha.conf)
764 $flags->{'superlibrarian'} = 1;
766 return $flags if $flags->{superlibrarian};
767 foreach ( keys %$flagsrequired ) {
768 return $flags if $flags->{$_};
773 sub getborrowernumber {
775 my $dbh = C4::Context->dbh;
776 for my $field ( 'userid', 'cardnumber' ) {
778 $dbh->prepare("select borrowernumber from borrowers where $field=?");
779 $sth->execute($userid);
781 my ($bnumber) = $sth->fetchrow;
788 END { } # module clean-up code here (global destructor)