3 # NOTE: This file uses 8-character tabs; do not change the tab size!
7 # Copyright 2000-2002 Katipo Communications
9 # This file is part of Koha.
11 # Koha is free software; you can redistribute it and/or modify it under the
12 # terms of the GNU General Public License as published by the Free Software
13 # Foundation; either version 2 of the License, or (at your option) any later
16 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
17 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
18 # A PARTICULAR PURPOSE. See the GNU General Public License for more details.
20 # You should have received a copy of the GNU General Public License along with
21 # Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
22 # Suite 330, Boston, MA 02111-1307 USA
25 use Digest::MD5 qw(md5_base64);
30 use C4::Output; # to get the template
33 use C4::Branch; # GetBranches
37 # use Net::LDAP qw(:all);
39 use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
41 # set the version for version checking
46 C4::Auth - Authenticates Koha users
55 my ($template, $borrowernumber, $cookie)
56 = get_template_and_user(
58 template_name => "opac-main.tmpl",
62 flagsrequired => {borrow => 1},
74 The main function of this module is to provide
75 authentification. However the get_template_and_user function has
76 been provided so that a users login information is passed along
77 automatically. This gets loaded into the template.
88 &get_template_and_user
96 =item get_template_and_user
98 my ($template, $borrowernumber, $cookie)
99 = get_template_and_user(
101 template_name => "opac-main.tmpl",
104 authnotrequired => 1,
105 flagsrequired => {borrow => 1},
109 This call passes the C<query>, C<flagsrequired> and C<authnotrequired>
110 to C<&checkauth> (in this module) to perform authentification.
111 See C<&checkauth> for an explanation of these parameters.
113 The C<template_name> is then used to find the correct template for
114 the page. The authenticated users details are loaded onto the
115 template in the HTML::Template LOOP variable C<USER_INFO>. Also the
116 C<sessionID> is passed to the template. This can be used in templates
117 if cookies are disabled. It needs to be put as and input to every
120 More information on the C<gettemplate> sub can be found in the
125 sub get_template_and_user {
128 gettemplate( $in->{'template_name'}, $in->{'type'}, $in->{'query'} );
129 my ( $user, $cookie, $sessionID, $flags ) = checkauth(
131 $in->{'authnotrequired'},
132 $in->{'flagsrequired'},
134 ) unless ($in->{'template_name'}=~/maintenance/);
137 my $insecure = C4::Context->preference('insecure');
138 if ($user or $insecure) {
140 # load the template variables for stylesheets and JavaScript
141 $template->param( css_libs => $in->{'css_libs'} );
142 $template->param( css_module => $in->{'css_module'} );
143 $template->param( css_page => $in->{'css_page'} );
144 $template->param( css_widgets => $in->{'css_widgets'} );
146 $template->param( js_libs => $in->{'js_libs'} );
147 $template->param( js_module => $in->{'js_module'} );
148 $template->param( js_page => $in->{'js_page'} );
149 $template->param( js_widgets => $in->{'js_widgets'} );
152 $template->param( loggedinusername => $user );
153 $template->param( sessionID => $sessionID );
155 $borrowernumber = getborrowernumber($user);
156 my ( $borr, $alternativeflags ) =
157 GetMemberDetails( $borrowernumber );
160 $template->param( "USER_INFO" => \@bordat );
162 # We are going to use the $flags returned by checkauth
163 # to create the template's parameters that will indicate
164 # which menus the user can access.
165 if (( $flags && $flags->{superlibrarian}==1) or $insecure==1) {
166 $template->param( CAN_user_circulate => 1 );
167 $template->param( CAN_user_catalogue => 1 );
168 $template->param( CAN_user_parameters => 1 );
169 $template->param( CAN_user_borrowers => 1 );
170 $template->param( CAN_user_permission => 1 );
171 $template->param( CAN_user_reserveforothers => 1 );
172 $template->param( CAN_user_borrow => 1 );
173 $template->param( CAN_user_editcatalogue => 1 );
174 $template->param( CAN_user_updatecharge => 1 );
175 $template->param( CAN_user_acquisition => 1 );
176 $template->param( CAN_user_management => 1 );
177 $template->param( CAN_user_tools => 1 );
178 $template->param( CAN_user_editauthorities => 1 );
179 $template->param( CAN_user_serials => 1 );
180 $template->param( CAN_user_reports => 1 );
183 if ( $flags && $flags->{circulate} == 1 ) {
184 $template->param( CAN_user_circulate => 1 );
187 if ( $flags && $flags->{catalogue} == 1 ) {
188 $template->param( CAN_user_catalogue => 1 );
191 if ( $flags && $flags->{parameters} == 1 ) {
192 $template->param( CAN_user_parameters => 1 );
193 $template->param( CAN_user_management => 1 );
196 if ( $flags && $flags->{borrowers} == 1 ) {
197 $template->param( CAN_user_borrowers => 1 );
200 if ( $flags && $flags->{permissions} == 1 ) {
201 $template->param( CAN_user_permission => 1 );
204 if ( $flags && $flags->{reserveforothers} == 1 ) {
205 $template->param( CAN_user_reserveforothers => 1 );
208 if ( $flags && $flags->{borrow} == 1 ) {
209 $template->param( CAN_user_borrow => 1 );
212 if ( $flags && $flags->{editcatalogue} == 1 ) {
213 $template->param( CAN_user_editcatalogue => 1 );
216 if ( $flags && $flags->{updatecharges} == 1 ) {
217 $template->param( CAN_user_updatecharge => 1 );
220 if ( $flags && $flags->{acquisition} == 1 ) {
221 $template->param( CAN_user_acquisition => 1 );
224 if ( $flags && $flags->{tools} == 1 ) {
225 $template->param( CAN_user_tools => 1 );
228 if ( $flags && $flags->{editauthorities} == 1 ) {
229 $template->param( CAN_user_editauthorities => 1 );
232 if ( $flags && $flags->{serials} == 1 ) {
233 $template->param( CAN_user_serials => 1 );
236 if ( $flags && $flags->{reports} == 1 ) {
237 $template->param( CAN_user_reports => 1 );
240 if ( $in->{'type'} eq "intranet" ) {
242 intranetcolorstylesheet => C4::Context->preference("intranetcolorstylesheet"),
243 intranetstylesheet => C4::Context->preference("intranetstylesheet"),
244 IntranetNav => C4::Context->preference("IntranetNav"),
245 intranetuserjs => C4::Context->preference("intranetuserjs"),
246 TemplateEncoding => C4::Context->preference("TemplateEncoding"),
247 AmazonContent => C4::Context->preference("AmazonContent"),
248 LibraryName => C4::Context->preference("LibraryName"),
249 LoginBranchcode => (C4::Context->userenv?C4::Context->userenv->{"branch"}:"insecure"),
250 LoginBranchname => (C4::Context->userenv?C4::Context->userenv->{"branchname"}:"insecure"),
251 LoginFirstname => (C4::Context->userenv?C4::Context->userenv->{"firstname"}:"Bel"),
252 LoginSurname => C4::Context->userenv?C4::Context->userenv->{"surname"}:"Inconnu",
253 AutoLocation => C4::Context->preference("AutoLocation"),
254 hide_marc => C4::Context->preference("hide_marc"),
255 patronimages => C4::Context->preference("patronimages"),
256 "BiblioDefaultView".C4::Context->preference("IntranetBiblioDefaultView") => 1,
257 advancedMARCEditor => C4::Context->preference("advancedMARCEditor"),
258 suggestion => C4::Context->preference("suggestion"),
259 virtualshelves => C4::Context->preference("virtualshelves"),
260 LibraryName => C4::Context->preference("LibraryName"),
261 KohaAdminEmailAddress => "" . C4::Context->preference("KohaAdminEmailAddress"),
262 IntranetmainUserblock => C4::Context->preference("IntranetmainUserblock"),
263 IndependantBranches => C4::Context->preference("IndependantBranches"),
264 CircAutocompl => C4::Context->preference("CircAutocompl"),
265 yuipath => C4::Context->preference("yuipath"),
266 FRBRizeEditions => C4::Context->preference("FRBRizeEditions"),
267 AmazonSimilarItems => C4::Context->preference("AmazonSimilarItems"),
271 warn "template type should be OPAC, here it is=[" . $in->{'type'} . "]" unless ( $in->{'type'} eq 'opac' );
272 my $LibraryNameTitle = C4::Context->preference("LibraryName");
273 $LibraryNameTitle =~ s/<(?:\/?)(?:br|p)\s*(?:\/?)>/ /sgi;
274 $LibraryNameTitle =~ s/<(?:[^<>'"]|'(?:[^']*)'|"(?:[^"]*)")*>//sg;
276 KohaAdminEmailAddress => "" . C4::Context->preference("KohaAdminEmailAddress"),
277 AnonSuggestions => "" . C4::Context->preference("AnonSuggestions"),
278 suggestion => "" . C4::Context->preference("suggestion"),
279 virtualshelves => "" . C4::Context->preference("virtualshelves"),
280 OpacNav => "" . C4::Context->preference("OpacNav"),
281 opacheader => "" . C4::Context->preference("opacheader"),
282 opaccredits => "" . C4::Context->preference("opaccredits"),
283 opacsmallimage => "" . C4::Context->preference("opacsmallimage"),
284 opaclargeimage => "" . C4::Context->preference("opaclargeimage"),
285 opaclayoutstylesheet => "". C4::Context->preference("opaclayoutstylesheet"),
286 opaccolorstylesheet => "". C4::Context->preference("opaccolorstylesheet"),
287 opaclanguagesdisplay => "". C4::Context->preference("opaclanguagesdisplay"),
288 opacuserlogin => "" . C4::Context->preference("opacuserlogin"),
289 opacbookbag => "" . C4::Context->preference("opacbookbag"),
290 TemplateEncoding => "". C4::Context->preference("TemplateEncoding"),
291 AmazonContent => "" . C4::Context->preference("AmazonContent"),
292 LibraryName => "" . C4::Context->preference("LibraryName"),
293 LibraryNameTitle => "" . $LibraryNameTitle,
294 LoginBranchcode => (C4::Context->userenv?C4::Context->userenv->{"branch"}:"insecure"),
295 LoginBranchname => C4::Context->userenv?C4::Context->userenv->{"branchname"}:"",
296 LoginFirstname => (C4::Context->userenv?C4::Context->userenv->{"firstname"}:"Bel"),
297 LoginSurname => C4::Context->userenv?C4::Context->userenv->{"surname"}:"Inconnu",
298 OpacPasswordChange => C4::Context->preference("OpacPasswordChange"),
299 opacreadinghistory => C4::Context->preference("opacreadinghistory"),
300 opacuserjs => C4::Context->preference("opacuserjs"),
301 OpacCloud => C4::Context->preference("OpacCloud"),
302 OpacTopissue => C4::Context->preference("OpacTopissue"),
303 OpacAuthorities => C4::Context->preference("OpacAuthorities"),
304 OpacBrowser => C4::Context->preference("OpacBrowser"),
305 RequestOnOpac => C4::Context->preference("RequestOnOpac"),
306 reviewson => C4::Context->preference("reviewson"),
307 hide_marc => C4::Context->preference("hide_marc"),
308 patronimages => C4::Context->preference("patronimages"),
309 mylibraryfirst => C4::Context->preference("SearchMyLibraryFirst"),
310 "BiblioDefaultView".C4::Context->preference("BiblioDefaultView") => 1,
311 OPACFRBRizeEditions => C4::Context->preference("OPACFRBRizeEditions"),
314 return ( $template, $borrowernumber, $cookie );
319 ($userid, $cookie, $sessionID) = &checkauth($query, $noauth, $flagsrequired, $type);
321 Verifies that the user is authorized to run this script. If
322 the user is authorized, a (userid, cookie, session-id, flags)
323 quadruple is returned. If the user is not authorized but does
324 not have the required privilege (see $flagsrequired below), it
325 displays an error page and exits. Otherwise, it displays the
326 login page and exits.
328 Note that C<&checkauth> will return if and only if the user
329 is authorized, so it should be called early on, before any
330 unfinished operations (e.g., if you've opened a file, then
331 C<&checkauth> won't close it for you).
333 C<$query> is the CGI object for the script calling C<&checkauth>.
335 The C<$noauth> argument is optional. If it is set, then no
336 authorization is required for the script.
338 C<&checkauth> fetches user and session information from C<$query> and
339 ensures that the user is authorized to run scripts that require
342 The C<$flagsrequired> argument specifies the required privileges
343 the user must have if the username and password are correct.
344 It should be specified as a reference-to-hash; keys in the hash
345 should be the "flags" for the user, as specified in the Members
346 intranet module. Any key specified must correspond to a "flag"
347 in the userflags table. E.g., { circulate => 1 } would specify
348 that the user must have the "circulate" privilege in order to
349 proceed. To make sure that access control is correct, the
350 C<$flagsrequired> parameter must be specified correctly.
352 The C<$type> argument specifies whether the template should be
353 retrieved from the opac or intranet directory tree. "opac" is
354 assumed if it is not specified; however, if C<$type> is specified,
355 "intranet" is assumed if it is not "opac".
357 If C<$query> does not have a valid session ID associated with it
358 (i.e., the user has not logged in) or if the session has expired,
359 C<&checkauth> presents the user with a login page (from the point of
360 view of the original script, C<&checkauth> does not return). Once the
361 user has authenticated, C<&checkauth> restarts the original script
362 (this time, C<&checkauth> returns).
364 The login page is provided using a HTML::Template, which is set in the
365 systempreferences table or at the top of this file. The variable C<$type>
366 selects which template to use, either the opac or the intranet
367 authentification template.
369 C<&checkauth> returns a user ID, a cookie, and a session ID. The
370 cookie should be sent back to the browser; it verifies that the user
377 # warn "Checking Auth";
378 # $authnotrequired will be set for scripts which will run without authentication
379 my $authnotrequired = shift;
380 my $flagsrequired = shift;
382 $type = 'opac' unless $type;
384 my $dbh = C4::Context->dbh;
385 my $timeout = C4::Context->preference('timeout');
387 if ($timeout =~ /(\d*)[dD]/) {
388 $timeout = $1 * 86400;
390 $timeout = 600 unless $timeout;
392 # If Version syspref is unavailable, it means Koha is beeing installed,
393 # and so we must redirect to OPAC maintenance page or to the WebInstaller
394 #warn "about to check version";
395 unless (C4::Context->preference('Version')) {
396 if ($type ne 'opac') {
397 warn "Install required, redirecting to Installer";
398 print $query->redirect("/cgi-bin/koha/installer/install.pl");
401 warn "OPAC Install required, redirecting to maintenance";
402 print $query->redirect("/cgi-bin/koha/maintenance.pl");
411 my ( $userid, $cookie, $sessionID, $flags );
412 my $logout = $query->param('logout.x');
413 if ( $userid = $ENV{'REMOTE_USER'} ) {
414 # Using Basic Authentication, no cookies required
415 $cookie = $query->cookie(
416 -name => 'CGISESSID',
422 elsif ( $sessionID = $query->cookie("CGISESSID")) {
423 my $session = get_session($sessionID);
424 C4::Context->_new_userenv($sessionID);
426 C4::Context::set_userenv(
427 $session->param('number'), $session->param('id'),
428 $session->param('cardnumber'), $session->param('firstname'),
429 $session->param('surname'), $session->param('branch'),
430 $session->param('branchname'), $session->param('flags'),
431 $session->param('emailaddress'), $session->param('branchprinter')
433 # warn "".$session->param('cardnumber').", ".$session->param('firstname').",
434 # ".$session->param('surname').", ".$session->param('branch');
439 $ip = $session->param('ip');
440 $lasttime = $session->param('lasttime');
441 $userid = $session->param('id');
447 # voluntary logout the user
451 C4::Context->_unset_userenv($sessionID);
454 open L, ">>/tmp/sessionlog";
455 my $time = localtime( time() );
456 printf L "%20s from %16s logged out at %30s (manually).\n", $userid,
461 if ( $lasttime < time() - $timeout ) {
463 $info{'timed_out'} = 1;
465 C4::Context->_unset_userenv($sessionID);
468 open L, ">>/tmp/sessionlog";
469 my $time = localtime( time() );
470 printf L "%20s from %16s logged out at %30s (inactivity).\n",
474 elsif ( $ip ne $ENV{'REMOTE_ADDR'} ) {
475 # Different ip than originally logged in from
476 $info{'oldip'} = $ip;
477 $info{'newip'} = $ENV{'REMOTE_ADDR'};
478 $info{'different_ip'} = 1;
480 C4::Context->_unset_userenv($sessionID);
483 open L, ">>/tmp/sessionlog";
484 my $time = localtime( time() );
486 "%20s from logged out at %30s (ip changed from %16s to %16s).\n",
487 $userid, $time, $ip, $info{'newip'};
491 $cookie = $query->cookie( CGISESSID => $session->id );
492 $session->param('lasttime',time());
493 $flags = haspermission( $dbh, $userid, $flagsrequired );
498 $info{'nopermission'} = 1;
504 my $session = get_session("");
508 $sessionID = $session->id;
510 $userid = $query->param('userid');
511 C4::Context->_new_userenv($sessionID);
512 my $password = $query->param('password');
513 C4::Context->_new_userenv($sessionID);
514 my ( $return, $cardnumber ) = checkpw( $dbh, $userid, $password );
516 open L, ">>/tmp/sessionlog";
517 my $time = localtime( time() );
518 printf L "%20s from %16s logged in at %30s.\n", $userid,
519 $ENV{'REMOTE_ADDR'}, $time;
521 $cookie = $query->cookie(CGISESSID => $sessionID);
522 if ( $flags = haspermission( $dbh, $userid, $flagsrequired ) ) {
526 $info{'nopermission'} = 1;
527 C4::Context->_unset_userenv($sessionID);
529 if ( $return == 1 ) {
531 $borrowernumber, $firstname, $surname,
532 $userflags, $branchcode, $branchname,
533 $branchprinter, $emailaddress
537 "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=?"
539 $sth->execute($userid);
541 $borrowernumber, $firstname, $surname,
542 $userflags, $branchcode, $branchname,
543 $branchprinter, $emailaddress
548 # warn "$cardnumber,$borrowernumber,$userid,$firstname,$surname,$userflags,$branchcode,$emailaddress";
549 unless ( $sth->rows ) {
552 "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=?"
554 $sth->execute($cardnumber);
556 $borrowernumber, $firstname, $surname,
557 $userflags, $branchcode, $branchname,
558 $branchprinter, $emailaddress
563 # warn "$cardnumber,$borrowernumber,$userid,$firstname,$surname,$userflags,$branchcode,$emailaddress";
564 unless ( $sth->rows ) {
565 $sth->execute($userid);
567 $borrowernumber, $firstname, $surname, $userflags,
568 $branchcode, $branchname, $branchprinter, $emailaddress
575 # 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.
576 my $ip = $ENV{'REMOTE_ADDR'};
577 # if they specify at login, use that
578 if ($query->param('branch')) {
579 $branchcode = $query->param('branch');
580 $branchname = GetBranchName($branchcode);
582 my $branches = GetBranches();
584 foreach my $br ( keys %$branches ) {
585 # now we work with the treatment of ip
586 my $domain = $branches->{$br}->{'branchip'};
587 if ( $domain && $ip =~ /^$domain/ ) {
588 $branchcode = $branches->{$br}->{'branchcode'};
590 # new op dev : add the branchprinter and branchname in the cookie
591 $branchprinter = $branches->{$br}->{'branchprinter'};
592 $branchname = $branches->{$br}->{'branchname'};
595 $session->param('number',$borrowernumber);
596 $session->param('id',$userid);
597 $session->param('cardnumber',$cardnumber);
598 $session->param('firstname',$firstname);
599 $session->param('surname',$surname);
600 $session->param('branch',$branchcode);
601 $session->param('branchname',$branchname);
602 $session->param('flags',$userflags);
603 $session->param('emailaddress',$emailaddress);
604 $session->param('ip',$session->remote_addr());
605 $session->param('lasttime',time());
606 # warn "".$session->param('cardnumber').", ".$session->param('firstname').",
607 # ".$session->param('surname').", ".$session->param('branch');
609 elsif ( $return == 2 ) {
610 #We suppose the user is the superlibrarian
611 $session->param('number',0);
612 $session->param('id',C4::Context->config('user'));
613 $session->param('cardnumber',C4::Context->config('user'));
614 $session->param('firstname',C4::Context->config('user'));
615 $session->param('surname',C4::Context->config('user'));
616 $session->param('branch','NO_LIBRARY_SET');
617 $session->param('branchname','NO_LIBRARY_SET');
618 $session->param('flags',1);
619 $session->param('emailaddress', C4::Context->preference('KohaAdminEmailAddress'));
620 $session->param('ip',$session->remote_addr());
621 $session->param('lasttime',time());
624 C4::Context::set_userenv(
625 $session->param('number'), $session->param('id'),
626 $session->param('cardnumber'), $session->param('firstname'),
627 $session->param('surname'), $session->param('branch'),
628 $session->param('branchname'), $session->param('flags'),
629 $session->param('emailaddress'), $session->param('branchprinter')
636 $info{'invalid_username_or_password'} = 1;
637 C4::Context->_unset_userenv($sessionID);
641 my $insecure = C4::Context->boolean_preference('insecure');
643 # finished authentification, now respond
644 if ( $loggedin || $authnotrequired || ( defined($insecure) && $insecure ) )
648 $cookie = $query->cookie( CGISESSID => ''
651 return ( $userid, $cookie, $sessionID, $flags );
657 # AUTH rejected, show the login/password template, after checking the DB.
661 # get the inputs from the incoming query
663 foreach my $name ( param $query) {
664 (next) if ( $name eq 'userid' || $name eq 'password' );
665 my $value = $query->param($name);
666 push @inputs, { name => $name, value => $value };
668 # get the branchloop, which we need for authentication
669 my $branches = GetBranches();
671 for my $branch_hash (keys %$branches) {
672 push @branch_loop, {branchcode => "$branch_hash", branchname => $branches->{$branch_hash}->{'branchname'}, };
675 # check that database and koha version are the same
676 # there is no DB version, it's a fresh install,
677 # go to web installer
678 # there is a DB version, compare it to the code version
679 my $kohaversion=C4::Context::KOHAVERSION;
680 # remove the 3 last . to have a Perl number
681 $kohaversion =~ s/(.*\..*)\.(.*)\.(.*)/$1$2$3/;
682 # warn "kohaversion : $kohaversion";
683 if (C4::Context->preference('Version') < $kohaversion){
684 if ($type ne 'opac'){
685 warn "Database update needed, redirecting to Installer. Database is ".C4::Context->preference('Version')." and Koha is : ".C4::Context->config("kohaversion");
686 print $query->redirect("/cgi-bin/koha/installer/install.pl?step=3");
688 warn "OPAC :Database update needed, redirecting to maintenance. Database is ".C4::Context->preference('Version')." and Koha is : ".C4::Context->config("kohaversion");
689 print $query->redirect("/cgi-bin/koha/maintenance.pl");
694 if ( $type eq 'opac' ) {
695 $template_name = "opac-auth.tmpl";
698 $template_name = "auth.tmpl";
700 my $template = gettemplate( $template_name, $type, $query );
701 $template->param(branchloop => \@branch_loop,);
705 suggestion => C4::Context->preference("suggestion"),
706 virtualshelves => C4::Context->preference("virtualshelves"),
707 opaclargeimage => C4::Context->preference("opaclargeimage"),
708 LibraryName => C4::Context->preference("LibraryName"),
709 OpacNav => C4::Context->preference("OpacNav"),
710 opaccredits => C4::Context->preference("opaccredits"),
711 opacreadinghistory => C4::Context->preference("opacreadinghistory"),
712 opacsmallimage => C4::Context->preference("opacsmallimage"),
713 opaclayoutstylesheet => C4::Context->preference("opaclayoutstylesheet"),
714 opaccolorstylesheet => C4::Context->preference("opaccolorstylesheet"),
715 opaclanguagesdisplay => C4::Context->preference("opaclanguagesdisplay"),
716 opacuserjs => C4::Context->preference("opacuserjs"),
718 intranetcolorstylesheet =>
719 C4::Context->preference("intranetcolorstylesheet"),
720 intranetstylesheet => C4::Context->preference("intranetstylesheet"),
721 IntranetNav => C4::Context->preference("IntranetNav"),
722 intranetuserjs => C4::Context->preference("intranetuserjs"),
723 TemplateEncoding => C4::Context->preference("TemplateEncoding"),
724 IndependantBranches => C4::Context->preference("IndependantBranches"),
725 AutoLocation => C4::Context->preference("AutoLocation"),
727 $template->param( loginprompt => 1 ) unless $info{'nopermission'};
729 my $self_url = $query->url( -absolute => 1 );
732 LibraryName => => C4::Context->preference("LibraryName"),
734 $template->param( \%info );
735 # $cookie = $query->cookie(CGISESSID => $session->id
737 print $query->header(
738 -type => 'text/html',
748 ($status, $cookie, $sessionId) = check_api_auth($query, $userflags);
750 Given a CGI query containing the parameters 'userid' and 'password' and/or a session
751 cookie, determine if the user has the privileges specified by C<$userflags>.
753 C<check_api_auth> is is meant for authenticating users of web services, and
754 consequently will always return and will not attempt to redirect the user
757 If a valid session cookie is already present, check_api_auth will return a status
758 of "ok", the cookie, and the Koha session ID.
760 If no session cookie is present, check_api_auth will check the 'userid' and 'password
761 parameters and create a session cookie and Koha session if the supplied credentials
764 Possible return values in C<$status> are:
768 =item "ok" -- user authenticated; C<$cookie> and C<$sessionid> have valid values.
770 =item "failed" -- credentials are not correct; C<$cookie> and C<$sessionid> are undef
772 =item "maintenance" -- DB is in maintenance mode; no login possible at the moment
774 =item "expired -- session cookie has expired; API user should resubmit userid and password
782 my $flagsrequired = shift;
784 my $dbh = C4::Context->dbh;
785 my $timeout = C4::Context->preference('timeout');
786 $timeout = 600 unless $timeout;
788 unless (C4::Context->preference('Version')) {
789 # database has not been installed yet
790 return ("maintenance", undef, undef);
792 my $kohaversion=C4::Context::KOHAVERSION;
793 $kohaversion =~ s/(.*\..*)\.(.*)\.(.*)/$1$2$3/;
794 if (C4::Context->preference('Version') < $kohaversion) {
795 # database in need of version update; assume that
796 # no API should be called while databsae is in
798 return ("maintenance", undef, undef);
801 # FIXME -- most of what follows is a copy-and-paste
802 # of code from checkauth. There is an obvious need
803 # for refactoring to separate the various parts of
804 # the authentication code, but as of 2007-11-19 this
805 # is deferred so as to not introduce bugs into the
806 # regular authentication code for Koha 3.0.
808 # see if we have a valid session cookie already
809 # however, if a userid parameter is present (i.e., from
810 # a form submission, assume that any current cookie
812 my $sessionID = undef;
813 unless ($query->param('userid')) {
814 $sessionID = $query->cookie("CGISESSID");
817 my $session = get_session($sessionID);
818 C4::Context->_new_userenv($sessionID);
820 C4::Context::set_userenv(
821 $session->param('number'), $session->param('id'),
822 $session->param('cardnumber'), $session->param('firstname'),
823 $session->param('surname'), $session->param('branch'),
824 $session->param('branchname'), $session->param('flags'),
825 $session->param('emailaddress'), $session->param('branchprinter')
828 my $ip = $session->param('ip');
829 my $lasttime = $session->param('lasttime');
830 my $userid = $session->param('id');
831 if ( $lasttime < time() - $timeout ) {
834 C4::Context->_unset_userenv($sessionID);
837 return ("expired", undef, undef);
838 } elsif ( $ip ne $ENV{'REMOTE_ADDR'} ) {
841 C4::Context->_unset_userenv($sessionID);
844 return ("expired", undef, undef);
846 my $cookie = $query->cookie( CGISESSID => $session->id );
847 $session->param('lasttime',time());
848 my $flags = haspermission( $dbh, $userid, $flagsrequired );
850 return ("ok", $cookie, $sessionID);
853 C4::Context->_unset_userenv($sessionID);
856 return ("failed", undef, undef);
860 return ("expired", undef, undef);
864 my $userid = $query->param('userid');
865 my $password = $query->param('password');
866 unless ($userid and $password) {
867 # caller did something wrong, fail the authenticateion
868 return ("failed", undef, undef);
870 my ( $return, $cardnumber ) = checkpw( $dbh, $userid, $password );
871 if ($return and haspermission( $dbh, $userid, $flagsrequired)) {
872 my $session = get_session("");
873 return ("failed", undef, undef) unless $session;
875 my $sessionID = $session->id;
876 C4::Context->_new_userenv($sessionID);
877 my $cookie = $query->cookie(CGISESSID => $sessionID);
878 if ( $return == 1 ) {
880 $borrowernumber, $firstname, $surname,
881 $userflags, $branchcode, $branchname,
882 $branchprinter, $emailaddress
886 "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=?"
888 $sth->execute($userid);
890 $borrowernumber, $firstname, $surname,
891 $userflags, $branchcode, $branchname,
892 $branchprinter, $emailaddress
893 ) = $sth->fetchrow if ( $sth->rows );
895 unless ($sth->rows ) {
896 my $sth = $dbh->prepare(
897 "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=?"
899 $sth->execute($cardnumber);
901 $borrowernumber, $firstname, $surname,
902 $userflags, $branchcode, $branchname,
903 $branchprinter, $emailaddress
904 ) = $sth->fetchrow if ( $sth->rows );
906 unless ( $sth->rows ) {
907 $sth->execute($userid);
909 $borrowernumber, $firstname, $surname, $userflags,
910 $branchcode, $branchname, $branchprinter, $emailaddress
911 ) = $sth->fetchrow if ( $sth->rows );
915 my $ip = $ENV{'REMOTE_ADDR'};
916 # if they specify at login, use that
917 if ($query->param('branch')) {
918 $branchcode = $query->param('branch');
919 $branchname = GetBranchName($branchcode);
921 my $branches = GetBranches();
923 foreach my $br ( keys %$branches ) {
924 # now we work with the treatment of ip
925 my $domain = $branches->{$br}->{'branchip'};
926 if ( $domain && $ip =~ /^$domain/ ) {
927 $branchcode = $branches->{$br}->{'branchcode'};
929 # new op dev : add the branchprinter and branchname in the cookie
930 $branchprinter = $branches->{$br}->{'branchprinter'};
931 $branchname = $branches->{$br}->{'branchname'};
934 $session->param('number',$borrowernumber);
935 $session->param('id',$userid);
936 $session->param('cardnumber',$cardnumber);
937 $session->param('firstname',$firstname);
938 $session->param('surname',$surname);
939 $session->param('branch',$branchcode);
940 $session->param('branchname',$branchname);
941 $session->param('flags',$userflags);
942 $session->param('emailaddress',$emailaddress);
943 $session->param('ip',$session->remote_addr());
944 $session->param('lasttime',time());
945 } elsif ( $return == 2 ) {
946 #We suppose the user is the superlibrarian
947 $session->param('number',0);
948 $session->param('id',C4::Context->config('user'));
949 $session->param('cardnumber',C4::Context->config('user'));
950 $session->param('firstname',C4::Context->config('user'));
951 $session->param('surname',C4::Context->config('user'));
952 $session->param('branch','NO_LIBRARY_SET');
953 $session->param('branchname','NO_LIBRARY_SET');
954 $session->param('flags',1);
955 $session->param('emailaddress', C4::Context->preference('KohaAdminEmailAddress'));
956 $session->param('ip',$session->remote_addr());
957 $session->param('lasttime',time());
959 C4::Context::set_userenv(
960 $session->param('number'), $session->param('id'),
961 $session->param('cardnumber'), $session->param('firstname'),
962 $session->param('surname'), $session->param('branch'),
963 $session->param('branchname'), $session->param('flags'),
964 $session->param('emailaddress'), $session->param('branchprinter')
966 return ("ok", $cookie, $sessionID);
968 return ("failed", undef, undef);
973 =item check_cookie_auth
975 ($status, $sessionId) = check_api_auth($cookie, $userflags);
977 Given a CGISESSID cookie set during a previous login to Koha, determine
978 if the user has the privileges specified by C<$userflags>.
980 C<check_cookie_auth> is meant for authenticating special services
981 such as tools/upload-file.pl that are invoked by other pages that
982 have been authenticated in the usual way.
984 Possible return values in C<$status> are:
988 =item "ok" -- user authenticated; C<$sessionID> have valid values.
990 =item "failed" -- credentials are not correct; C<$sessionid> are undef
992 =item "maintenance" -- DB is in maintenance mode; no login possible at the moment
994 =item "expired -- session cookie has expired; API user should resubmit userid and password
1000 sub check_cookie_auth {
1002 my $flagsrequired = shift;
1004 my $dbh = C4::Context->dbh;
1005 my $timeout = C4::Context->preference('timeout');
1006 $timeout = 600 unless $timeout;
1008 unless (C4::Context->preference('Version')) {
1009 # database has not been installed yet
1010 return ("maintenance", undef);
1012 my $kohaversion=C4::Context::KOHAVERSION;
1013 $kohaversion =~ s/(.*\..*)\.(.*)\.(.*)/$1$2$3/;
1014 if (C4::Context->preference('Version') < $kohaversion) {
1015 # database in need of version update; assume that
1016 # no API should be called while databsae is in
1018 return ("maintenance", undef);
1021 # FIXME -- most of what follows is a copy-and-paste
1022 # of code from checkauth. There is an obvious need
1023 # for refactoring to separate the various parts of
1024 # the authentication code, but as of 2007-11-23 this
1025 # is deferred so as to not introduce bugs into the
1026 # regular authentication code for Koha 3.0.
1028 # see if we have a valid session cookie already
1029 # however, if a userid parameter is present (i.e., from
1030 # a form submission, assume that any current cookie
1032 unless (defined $cookie and $cookie) {
1033 return ("failed", undef);
1035 my $sessionID = $cookie;
1036 my $session = get_session($sessionID);
1037 C4::Context->_new_userenv($sessionID);
1039 C4::Context::set_userenv(
1040 $session->param('number'), $session->param('id'),
1041 $session->param('cardnumber'), $session->param('firstname'),
1042 $session->param('surname'), $session->param('branch'),
1043 $session->param('branchname'), $session->param('flags'),
1044 $session->param('emailaddress'), $session->param('branchprinter')
1047 my $ip = $session->param('ip');
1048 my $lasttime = $session->param('lasttime');
1049 my $userid = $session->param('id');
1050 if ( $lasttime < time() - $timeout ) {
1053 C4::Context->_unset_userenv($sessionID);
1056 return ("expired", undef);
1057 } elsif ( $ip ne $ENV{'REMOTE_ADDR'} ) {
1058 # IP address changed
1060 C4::Context->_unset_userenv($sessionID);
1063 return ("expired", undef);
1065 $session->param('lasttime',time());
1066 my $flags = haspermission( $dbh, $userid, $flagsrequired );
1068 return ("ok", $sessionID);
1071 C4::Context->_unset_userenv($sessionID);
1074 return ("failed", undef);
1078 return ("expired", undef);
1085 my $session = get_session($sessionID);
1087 Given a session ID, retrieve the CGI::Session object used to store
1088 the session's state. The session object can be used to store
1089 data that needs to be accessed by different scripts during a
1092 If the C<$sessionID> parameter is an empty string, a new session
1098 my $sessionID = shift;
1099 my $storage_method = C4::Context->preference('SessionStorage');
1100 my $dbh = C4::Context->dbh;
1102 if ($storage_method eq 'mysql'){
1103 $session = new CGI::Session("driver:MySQL", $sessionID, {Handle=>$dbh});
1105 elsif ($storage_method eq 'Pg') {
1106 $session = new CGI::Session("driver:PostgreSQL", $sessionID, {Handle=>$dbh});
1109 # catch all defaults to tmp should work on all systems
1110 $session = new CGI::Session("driver:File", $sessionID, {Directory=>'/tmp'});
1117 my ( $dbh, $userid, $password ) = @_;
1122 "select password,cardnumber,borrowernumber,userid,firstname,surname,branchcode,flags from borrowers where userid=?"
1124 $sth->execute($userid);
1126 my ( $md5password, $cardnumber, $borrowernumber, $userid, $firstname,
1127 $surname, $branchcode, $flags )
1129 if ( md5_base64($password) eq $md5password ) {
1131 C4::Context->set_userenv( "$borrowernumber", $userid, $cardnumber,
1132 $firstname, $surname, $branchcode, $flags );
1133 return 1, $cardnumber;
1138 "select password,cardnumber,borrowernumber,userid, firstname,surname,branchcode,flags from borrowers where cardnumber=?"
1140 $sth->execute($userid);
1142 my ( $md5password, $cardnumber, $borrowernumber, $userid, $firstname,
1143 $surname, $branchcode, $flags )
1145 if ( md5_base64($password) eq $md5password ) {
1147 C4::Context->set_userenv( $borrowernumber, $userid, $cardnumber,
1148 $firstname, $surname, $branchcode, $flags );
1152 if ( $userid && $userid eq C4::Context->config('user')
1153 && "$password" eq C4::Context->config('pass') )
1156 # Koha superuser account
1157 # C4::Context->set_userenv(0,0,C4::Context->config('user'),C4::Context->config('user'),C4::Context->config('user'),"",1);
1160 if ( $userid && $userid eq 'demo'
1161 && "$password" eq 'demo'
1162 && C4::Context->config('demo') )
1165 # DEMO => the demo user is allowed to do everything (if demo set to 1 in koha.conf
1166 # some features won't be effective : modify systempref, modify MARC structure,
1173 my $cardnumber = shift;
1176 my $sth = $dbh->prepare("SELECT flags FROM borrowers WHERE cardnumber=?");
1177 $sth->execute($cardnumber);
1178 my ($flags) = $sth->fetchrow;
1179 $flags = 0 unless $flags;
1180 $sth = $dbh->prepare("SELECT bit, flag, defaulton FROM userflags");
1183 while ( my ( $bit, $flag, $defaulton ) = $sth->fetchrow ) {
1184 if ( ( $flags & ( 2**$bit ) ) || $defaulton ) {
1185 $userflags->{$flag} = 1;
1188 $userflags->{$flag} = 0;
1195 my ( $dbh, $userid, $flagsrequired ) = @_;
1196 my $sth = $dbh->prepare("SELECT cardnumber FROM borrowers WHERE userid=?");
1197 $sth->execute($userid);
1198 my ($cardnumber) = $sth->fetchrow;
1199 ($cardnumber) || ( $cardnumber = $userid );
1200 my $flags = getuserflags( $cardnumber, $dbh );
1202 if ( $userid eq C4::Context->config('user') ) {
1204 # Super User Account from /etc/koha.conf
1205 $flags->{'superlibrarian'} = 1;
1207 if ( $userid eq 'demo' && C4::Context->config('demo') ) {
1209 # Demo user that can do "anything" (demo=1 in /etc/koha.conf)
1210 $flags->{'superlibrarian'} = 1;
1212 return $flags if $flags->{superlibrarian};
1213 foreach ( keys %$flagsrequired ) {
1214 return $flags if $flags->{$_};
1219 sub getborrowernumber {
1221 my $dbh = C4::Context->dbh;
1222 for my $field ( 'userid', 'cardnumber' ) {
1224 $dbh->prepare("select borrowernumber from borrowers where $field=?");
1225 $sth->execute($userid);
1227 my ($bnumber) = $sth->fetchrow;
1234 END { } # module clean-up code here (global destructor)