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;
32 use C4::Branch; # GetBranches
35 # use Net::LDAP qw(:all);
37 use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
39 # set the version for version checking
40 $VERSION = do { my @v = '$Revision$' =~ /\d+/g;
41 shift(@v) . "." . join( "_", map { sprintf "%03d", $_ } @v );
46 C4::Auth - Authenticates Koha users
55 my ($template, $borrowernumber, $cookie)
56 = get_template_and_user({template_name => "opac-main.tmpl",
60 flagsrequired => {borrow => 1},
64 -type => guesstype($template->output),
71 The main function of this module is to provide
72 authentification. However the get_template_and_user function has
73 been provided so that a users login information is passed along
74 automatically. This gets loaded into the template.
85 &get_template_and_user
88 =item get_template_and_user
90 my ($template, $borrowernumber, $cookie)
91 = get_template_and_user({template_name => "opac-main.tmpl",
95 flagsrequired => {borrow => 1},
98 This call passes the C<query>, C<flagsrequired> and C<authnotrequired>
99 to C<&checkauth> (in this module) to perform authentification.
100 See C<&checkauth> for an explanation of these parameters.
102 The C<template_name> is then used to find the correct template for
103 the page. The authenticated users details are loaded onto the
104 template in the HTML::Template LOOP variable C<USER_INFO>. Also the
105 C<sessionID> is passed to the template. This can be used in templates
106 if cookies are disabled. It needs to be put as and input to every
109 More information on the C<gettemplate> sub can be found in the
114 sub get_template_and_user {
117 gettemplate( $in->{'template_name'}, $in->{'type'}, $in->{'query'} );
118 my ( $user, $cookie, $sessionID, $flags ) = checkauth(
120 $in->{'authnotrequired'},
121 $in->{'flagsrequired'},
126 my $insecure = C4::Context->preference('insecure');
127 if ($user or $insecure) {
128 $template->param( loggedinusername => $user );
129 $template->param( sessionID => $sessionID );
131 $borrowernumber = getborrowernumber($user);
132 my ( $borr, $alternativeflags ) =
133 GetMemberDetails( $borrowernumber );
136 $template->param( "USER_INFO" => \@bordat );
138 # We are going to use the $flags returned by checkauth
139 # to create the template's parameters that will indicate
140 # which menus the user can access.
141 if (( $flags && $flags->{superlibrarian}==1) or $insecure==1) {
142 $template->param( CAN_user_circulate => 1 );
143 $template->param( CAN_user_catalogue => 1 );
144 $template->param( CAN_user_parameters => 1 );
145 $template->param( CAN_user_borrowers => 1 );
146 $template->param( CAN_user_permission => 1 );
147 $template->param( CAN_user_reserveforothers => 1 );
148 $template->param( CAN_user_borrow => 1 );
149 $template->param( CAN_user_editcatalogue => 1 );
150 $template->param( CAN_user_updatecharge => 1 );
151 $template->param( CAN_user_acquisition => 1 );
152 $template->param( CAN_user_management => 1 );
153 $template->param( CAN_user_tools => 1 );
154 $template->param( CAN_user_editauthorities => 1 );
155 $template->param( CAN_user_serials => 1 );
156 $template->param( CAN_user_reports => 1 );
159 if ( $flags && $flags->{circulate} == 1 ) {
160 $template->param( CAN_user_circulate => 1 );
163 if ( $flags && $flags->{catalogue} == 1 ) {
164 $template->param( CAN_user_catalogue => 1 );
167 if ( $flags && $flags->{parameters} == 1 ) {
168 $template->param( CAN_user_parameters => 1 );
169 $template->param( CAN_user_management => 1 );
172 if ( $flags && $flags->{borrowers} == 1 ) {
173 $template->param( CAN_user_borrowers => 1 );
176 if ( $flags && $flags->{permissions} == 1 ) {
177 $template->param( CAN_user_permission => 1 );
180 if ( $flags && $flags->{reserveforothers} == 1 ) {
181 $template->param( CAN_user_reserveforothers => 1 );
184 if ( $flags && $flags->{borrow} == 1 ) {
185 $template->param( CAN_user_borrow => 1 );
188 if ( $flags && $flags->{editcatalogue} == 1 ) {
189 $template->param( CAN_user_editcatalogue => 1 );
192 if ( $flags && $flags->{updatecharges} == 1 ) {
193 $template->param( CAN_user_updatecharge => 1 );
196 if ( $flags && $flags->{acquisition} == 1 ) {
197 $template->param( CAN_user_acquisition => 1 );
200 if ( $flags && $flags->{tools} == 1 ) {
201 $template->param( CAN_user_tools => 1 );
204 if ( $flags && $flags->{editauthorities} == 1 ) {
205 $template->param( CAN_user_editauthorities => 1 );
208 if ( $flags && $flags->{serials} == 1 ) {
209 $template->param( CAN_user_serials => 1 );
212 if ( $flags && $flags->{reports} == 1 ) {
213 $template->param( CAN_user_reports => 1 );
216 if ( $in->{'type'} eq "intranet" ) {
218 intranetcolorstylesheet =>
219 C4::Context->preference("intranetcolorstylesheet"),
220 intranetstylesheet => C4::Context->preference("intranetstylesheet"),
221 IntranetNav => C4::Context->preference("IntranetNav"),
222 intranetuserjs => C4::Context->preference("intranetuserjs"),
223 TemplateEncoding => C4::Context->preference("TemplateEncoding"),
224 AmazonContent => C4::Context->preference("AmazonContent"),
225 LibraryName => C4::Context->preference("LibraryName"),
226 LoginBranchname => (C4::Context->userenv?C4::Context->userenv->{"branchname"}:"insecure"),
227 AutoLocation => C4::Context->preference("AutoLocation"),
228 hide_marc => C4::Context->preference("hide_marc"),
229 patronimages => C4::Context->preference("patronimages"),
230 "BiblioDefaultView".C4::Context->preference("BiblioDefaultView") => 1,
234 warn "template type should be OPAC, here it is=[" . $in->{'type'} . "]"
235 unless ( $in->{'type'} eq 'opac' );
236 my $LibraryNameTitle = C4::Context->preference("LibraryName");
237 $LibraryNameTitle =~ s/<(?:\/?)(?:br|p)\s*(?:\/?)>/ /sgi;
238 $LibraryNameTitle =~ s/<(?:[^<>'"]|'(?:[^']*)'|"(?:[^"]*)")*>//sg;
240 suggestion => "" . C4::Context->preference("suggestion"),
241 virtualshelves => "" . C4::Context->preference("virtualshelves"),
242 OpacNav => "" . C4::Context->preference("OpacNav"),
243 opacheader => "" . C4::Context->preference("opacheader"),
244 opaccredits => "" . C4::Context->preference("opaccredits"),
245 opacsmallimage => "" . C4::Context->preference("opacsmallimage"),
246 opaclargeimage => "" . C4::Context->preference("opaclargeimage"),
247 opaclayoutstylesheet => "". C4::Context->preference("opaclayoutstylesheet"),
248 opaccolorstylesheet => "". C4::Context->preference("opaccolorstylesheet"),
249 opaclanguagesdisplay => "". C4::Context->preference("opaclanguagesdisplay"),
250 opacuserlogin => "" . C4::Context->preference("opacuserlogin"),
251 opacbookbag => "" . C4::Context->preference("opacbookbag"),
252 TemplateEncoding => "". C4::Context->preference("TemplateEncoding"),
253 AmazonContent => "" . C4::Context->preference("AmazonContent"),
254 LibraryName => "" . C4::Context->preference("LibraryName"),
255 LibraryNameTitle => "" . $LibraryNameTitle,
256 LoginBranchname => C4::Context->userenv?C4::Context->userenv->{"branchname"}:"",
257 OpacPasswordChange => C4::Context->preference("OpacPasswordChange"),
258 opacreadinghistory => C4::Context->preference("opacreadinghistory"),
259 opacuserjs => C4::Context->preference("opacuserjs"),
260 OpacCloud => C4::Context->preference("OpacCloud"),
261 OpacTopissue => C4::Context->preference("OpacTopissue"),
262 OpacAuthorities => C4::Context->preference("OpacAuthorities"),
263 OpacBrowser => C4::Context->preference("OpacBrowser"),
264 RequestOnOpac => C4::Context->preference("RequestOnOpac"),
265 reviewson => C4::Context->preference("reviewson"),
266 hide_marc => C4::Context->preference("hide_marc"),
267 patronimages => C4::Context->preference("patronimages"),
268 "BiblioDefaultView".C4::Context->preference("BiblioDefaultView") => 1,
271 return ( $template, $borrowernumber, $cookie );
276 ($userid, $cookie, $sessionID) = &checkauth($query, $noauth, $flagsrequired, $type);
278 Verifies that the user is authorized to run this script. If
279 the user is authorized, a (userid, cookie, session-id, flags)
280 quadruple is returned. If the user is not authorized but does
281 not have the required privilege (see $flagsrequired below), it
282 displays an error page and exits. Otherwise, it displays the
283 login page and exits.
285 Note that C<&checkauth> will return if and only if the user
286 is authorized, so it should be called early on, before any
287 unfinished operations (e.g., if you've opened a file, then
288 C<&checkauth> won't close it for you).
290 C<$query> is the CGI object for the script calling C<&checkauth>.
292 The C<$noauth> argument is optional. If it is set, then no
293 authorization is required for the script.
295 C<&checkauth> fetches user and session information from C<$query> and
296 ensures that the user is authorized to run scripts that require
299 The C<$flagsrequired> argument specifies the required privileges
300 the user must have if the username and password are correct.
301 It should be specified as a reference-to-hash; keys in the hash
302 should be the "flags" for the user, as specified in the Members
303 intranet module. Any key specified must correspond to a "flag"
304 in the userflags table. E.g., { circulate => 1 } would specify
305 that the user must have the "circulate" privilege in order to
306 proceed. To make sure that access control is correct, the
307 C<$flagsrequired> parameter must be specified correctly.
309 The C<$type> argument specifies whether the template should be
310 retrieved from the opac or intranet directory tree. "opac" is
311 assumed if it is not specified; however, if C<$type> is specified,
312 "intranet" is assumed if it is not "opac".
314 If C<$query> does not have a valid session ID associated with it
315 (i.e., the user has not logged in) or if the session has expired,
316 C<&checkauth> presents the user with a login page (from the point of
317 view of the original script, C<&checkauth> does not return). Once the
318 user has authenticated, C<&checkauth> restarts the original script
319 (this time, C<&checkauth> returns).
321 The login page is provided using a HTML::Template, which is set in the
322 systempreferences table or at the top of this file. The variable C<$type>
323 selects which template to use, either the opac or the intranet
324 authentification template.
326 C<&checkauth> returns a user ID, a cookie, and a session ID. The
327 cookie should be sent back to the browser; it verifies that the user
335 # $authnotrequired will be set for scripts which will run without authentication
336 my $authnotrequired = shift;
337 my $flagsrequired = shift;
339 $type = 'opac' unless $type;
341 my $dbh = C4::Context->dbh;
342 unless (C4::Context->preference('Version')){
343 print $query->redirect("/cgi-bin/koha/installer/install.pl?step=3");
346 my $timeout = C4::Context->preference('timeout');
347 $timeout = 600 unless $timeout;
350 if ( $type eq 'opac' ) {
351 $template_name = "opac-auth.tmpl";
354 $template_name = "auth.tmpl";
360 my ( $userid, $cookie, $sessionID, $flags, $envcookie );
361 my $logout = $query->param('logout.x');
362 if ( $userid = $ENV{'REMOTE_USER'} ) {
364 # Using Basic Authentication, no cookies required
365 $cookie = $query->cookie(
366 -name => 'sessionID',
372 elsif ( $sessionID = $query->cookie('sessionID') ) {
373 C4::Context->_new_userenv($sessionID);
374 if ( my %hash = $query->cookie('userenv') ) {
375 C4::Context::set_userenv(
376 $hash{number}, $hash{id},
377 $hash{cardnumber}, $hash{firstname},
378 $hash{surname}, $hash{branch},
379 $hash{branchname}, $hash{flags},
380 $hash{emailaddress}, $hash{branchprinter}
383 my ( $ip, $lasttime );
385 ( $userid, $ip, $lasttime ) =
386 $dbh->selectrow_array(
387 "SELECT userid,ip,lasttime FROM sessions WHERE sessionid=?",
391 # voluntary logout the user
392 $dbh->do( "DELETE FROM sessions WHERE sessionID=?",
394 C4::Context->_unset_userenv($sessionID);
397 open L, ">>/tmp/sessionlog";
398 my $time = localtime( time() );
399 printf L "%20s from %16s logged out at %30s (manually).\n", $userid,
404 if ( $lasttime < time() - $timeout ) {
407 $info{'timed_out'} = 1;
408 $dbh->do( "DELETE FROM sessions WHERE sessionID=?",
410 C4::Context->_unset_userenv($sessionID);
413 open L, ">>/tmp/sessionlog";
414 my $time = localtime( time() );
415 printf L "%20s from %16s logged out at %30s (inactivity).\n",
419 elsif ( $ip ne $ENV{'REMOTE_ADDR'} ) {
421 # Different ip than originally logged in from
422 $info{'oldip'} = $ip;
423 $info{'newip'} = $ENV{'REMOTE_ADDR'};
424 $info{'different_ip'} = 1;
425 $dbh->do( "DELETE FROM sessions WHERE sessionID=?",
427 C4::Context->_unset_userenv($sessionID);
430 open L, ">>/tmp/sessionlog";
431 my $time = localtime( time() );
433 "%20s from logged out at %30s (ip changed from %16s to %16s).\n",
434 $userid, $time, $ip, $info{'newip'};
438 $cookie = $query->cookie(
439 -name => 'sessionID',
440 -value => $sessionID,
443 $dbh->do( "UPDATE sessions SET lasttime=? WHERE sessionID=?",
444 undef, ( time(), $sessionID ) );
445 $flags = haspermission( $dbh, $userid, $flagsrequired );
450 $info{'nopermission'} = 1;
456 $sessionID = int( rand() * 100000 ) . '-' . time();
457 $userid = $query->param('userid');
458 C4::Context->_new_userenv($sessionID);
459 my $password = $query->param('password');
460 C4::Context->_new_userenv($sessionID);
461 my ( $return, $cardnumber ) = checkpw( $dbh, $userid, $password );
463 $dbh->do( "DELETE FROM sessions WHERE sessionID=? AND userid=?",
464 undef, ( $sessionID, $userid ) );
466 "INSERT INTO sessions (sessionID, userid, ip,lasttime) VALUES (?, ?, ?, ?)",
468 ( $sessionID, $userid, $ENV{'REMOTE_ADDR'}, time() )
470 open L, ">>/tmp/sessionlog";
471 my $time = localtime( time() );
472 printf L "%20s from %16s logged in at %30s.\n", $userid,
473 $ENV{'REMOTE_ADDR'}, $time;
475 $cookie = $query->cookie(
476 -name => 'sessionID',
477 -value => $sessionID,
480 if ( $flags = haspermission( $dbh, $userid, $flagsrequired ) ) {
484 $info{'nopermission'} = 1;
485 C4::Context->_unset_userenv($sessionID);
487 if ( $return == 1 ) {
489 $borrowernumber, $firstname, $surname,
490 $userflags, $branchcode, $branchname,
491 $branchprinter, $emailaddress
495 "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=?"
497 $sth->execute($userid);
499 $borrowernumber, $firstname, $surname,
500 $userflags, $branchcode, $branchname,
501 $branchprinter, $emailaddress
506 # warn "$cardnumber,$borrowernumber,$userid,$firstname,$surname,$userflags,$branchcode,$emailaddress";
507 unless ( $sth->rows ) {
510 "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=?"
512 $sth->execute($cardnumber);
514 $borrowernumber, $firstname, $surname,
515 $userflags, $branchcode, $branchname,
516 $branchprinter, $emailaddress
521 # warn "$cardnumber,$borrowernumber,$userid,$firstname,$surname,$userflags,$branchcode,$emailaddress";
522 unless ( $sth->rows ) {
523 $sth->execute($userid);
525 $borrowernumber, $firstname, $surname, $userflags,
526 $branchcode, $branchname, $branchprinter, $emailaddress
532 # warn "$cardnumber,$borrowernumber,$userid,$firstname,$surname,$userflags,$branchcode,$emailaddress";
535 # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
537 # 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.
538 my $ip = $ENV{'REMOTE_ADDR'};
539 my $branches = GetBranches();
541 foreach my $br ( keys %$branches ) {
543 # now we work with the treatment of ip
544 my $domain = $branches->{$br}->{'branchip'};
545 if ( $domain && $ip =~ /^$domain/ ) {
546 $branchcode = $branches->{$br}->{'branchcode'};
548 # new op dev : add the branchprinter and branchname in the cookie
549 $branchprinter = $branches->{$br}->{'branchprinter'};
550 $branchname = $branches->{$br}->{'branchname'};
553 my $hash = C4::Context::set_userenv(
554 $borrowernumber, $userid, $cardnumber,
555 $firstname, $surname, $branchcode,
556 $branchname, $userflags, $emailaddress,
560 $envcookie = $query->cookie(
566 elsif ( $return == 2 ) {
568 #We suppose the user is the superlibrarian
569 my $hash = C4::Context::set_userenv(
572 C4::Context->config('user'),
573 C4::Context->config('user'),
574 C4::Context->config('user'),
578 C4::Context->preference('KohaAdminEmailAddress')
580 $envcookie = $query->cookie(
589 $info{'invalid_username_or_password'} = 1;
590 C4::Context->_unset_userenv($sessionID);
594 my $insecure = C4::Context->boolean_preference('insecure');
596 # finished authentification, now respond
597 if ( $loggedin || $authnotrequired || ( defined($insecure) && $insecure ) )
602 $cookie = $query->cookie(
603 -name => 'sessionID',
609 return ( $userid, [ $cookie, $envcookie ], $sessionID, $flags );
612 return ( $userid, $cookie, $sessionID, $flags );
616 # else we have a problem...
617 # get the inputs from the incoming query
619 foreach my $name ( param $query) {
620 (next) if ( $name eq 'userid' || $name eq 'password' );
621 my $value = $query->param($name);
622 push @inputs, { name => $name, value => $value };
625 my $template = gettemplate( $template_name, $type, $query );
628 suggestion => C4::Context->preference("suggestion"),
629 virtualshelves => C4::Context->preference("virtualshelves"),
630 opaclargeimage => C4::Context->preference("opaclargeimage"),
631 LibraryName => C4::Context->preference("LibraryName"),
632 OpacNav => C4::Context->preference("OpacNav"),
633 opaccredits => C4::Context->preference("opaccredits"),
634 opacreadinghistory => C4::Context->preference("opacreadinghistory"),
635 opacsmallimage => C4::Context->preference("opacsmallimage"),
636 opaclayoutstylesheet => C4::Context->preference("opaclayoutstylesheet"),
637 opaccolorstylesheet => C4::Context->preference("opaccolorstylesheet"),
638 opaclanguagesdisplay => C4::Context->preference("opaclanguagesdisplay"),
639 opacuserjs => C4::Context->preference("opacuserjs"),
641 intranetcolorstylesheet =>
642 C4::Context->preference("intranetcolorstylesheet"),
643 intranetstylesheet => C4::Context->preference("intranetstylesheet"),
644 IntranetNav => C4::Context->preference("IntranetNav"),
645 intranetuserjs => C4::Context->preference("intranetuserjs"),
646 TemplateEncoding => C4::Context->preference("TemplateEncoding"),
649 $template->param( loginprompt => 1 ) unless $info{'nopermission'};
651 my $self_url = $query->url( -absolute => 1 );
654 LibraryName => => C4::Context->preference("LibraryName"),
656 $template->param( \%info );
657 $cookie = $query->cookie(
658 -name => 'sessionID',
659 -value => $sessionID,
662 print $query->header(
663 -type => guesstype( $template->output ),
672 my ( $dbh, $userid, $password ) = @_;
677 "select password,cardnumber,borrowernumber,userid,firstname,surname,branchcode,flags from borrowers where userid=?"
679 $sth->execute($userid);
681 my ( $md5password, $cardnumber, $borrowernumber, $userid, $firstname,
682 $surname, $branchcode, $flags )
684 if ( md5_base64($password) eq $md5password ) {
686 C4::Context->set_userenv( "$borrowernumber", $userid, $cardnumber,
687 $firstname, $surname, $branchcode, $flags );
688 return 1, $cardnumber;
693 "select password,cardnumber,borrowernumber,userid, firstname,surname,branchcode,flags from borrowers where cardnumber=?"
695 $sth->execute($userid);
697 my ( $md5password, $cardnumber, $borrowernumber, $userid, $firstname,
698 $surname, $branchcode, $flags )
700 if ( md5_base64($password) eq $md5password ) {
702 C4::Context->set_userenv( $borrowernumber, $userid, $cardnumber,
703 $firstname, $surname, $branchcode, $flags );
707 if ( $userid && $userid eq C4::Context->config('user')
708 && "$password" eq C4::Context->config('pass') )
711 # Koha superuser account
712 # C4::Context->set_userenv(0,0,C4::Context->config('user'),C4::Context->config('user'),C4::Context->config('user'),"",1);
715 if ( $userid && $userid eq 'demo'
716 && "$password" eq 'demo'
717 && C4::Context->config('demo') )
720 # DEMO => the demo user is allowed to do everything (if demo set to 1 in koha.conf
721 # some features won't be effective : modify systempref, modify MARC structure,
728 my $cardnumber = shift;
731 my $sth = $dbh->prepare("SELECT flags FROM borrowers WHERE cardnumber=?");
732 $sth->execute($cardnumber);
733 my ($flags) = $sth->fetchrow;
734 $flags = 0 unless $flags;
735 $sth = $dbh->prepare("SELECT bit, flag, defaulton FROM userflags");
738 while ( my ( $bit, $flag, $defaulton ) = $sth->fetchrow ) {
739 if ( ( $flags & ( 2**$bit ) ) || $defaulton ) {
740 $userflags->{$flag} = 1;
743 $userflags->{$flag} = 0;
750 my ( $dbh, $userid, $flagsrequired ) = @_;
751 my $sth = $dbh->prepare("SELECT cardnumber FROM borrowers WHERE userid=?");
752 $sth->execute($userid);
753 my ($cardnumber) = $sth->fetchrow;
754 ($cardnumber) || ( $cardnumber = $userid );
755 my $flags = getuserflags( $cardnumber, $dbh );
757 if ( $userid eq C4::Context->config('user') ) {
759 # Super User Account from /etc/koha.conf
760 $flags->{'superlibrarian'} = 1;
762 if ( $userid eq 'demo' && C4::Context->config('demo') ) {
764 # Demo user that can do "anything" (demo=1 in /etc/koha.conf)
765 $flags->{'superlibrarian'} = 1;
767 return $flags if $flags->{superlibrarian};
768 foreach ( keys %$flagsrequired ) {
769 return $flags if $flags->{$_};
774 sub getborrowernumber {
776 my $dbh = C4::Context->dbh;
777 for my $field ( 'userid', 'cardnumber' ) {
779 $dbh->prepare("select borrowernumber from borrowers where $field=?");
780 $sth->execute($userid);
782 my ($bnumber) = $sth->fetchrow;
789 END { } # module clean-up code here (global destructor)