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
34 use C4::VirtualShelves 3.02 qw(GetShelvesSummary);
37 use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS $debug $ldap);
40 $VERSION = 3.02; # set version for version checking
41 $debug = $ENV{DEBUG} || 0 ;
43 @EXPORT = qw(&checkauth &get_template_and_user);
44 @EXPORT_OK = qw(&check_api_auth &get_session &check_cookie_auth &checkpw);
45 $ldap = C4::Context->config('useldapserver') || 0;
47 require C4::Auth_with_ldap; # no import
48 import C4::Auth_with_ldap qw(checkpw_ldap);
54 C4::Auth - Authenticates Koha users
63 my ($template, $borrowernumber, $cookie)
64 = get_template_and_user(
66 template_name => "opac-main.tmpl",
70 flagsrequired => {borrow => 1},
82 The main function of this module is to provide
83 authentification. However the get_template_and_user function has
84 been provided so that a users login information is passed along
85 automatically. This gets loaded into the template.
91 =item get_template_and_user
93 my ($template, $borrowernumber, $cookie)
94 = get_template_and_user(
96 template_name => "opac-main.tmpl",
100 flagsrequired => {borrow => 1},
104 This call passes the C<query>, C<flagsrequired> and C<authnotrequired>
105 to C<&checkauth> (in this module) to perform authentification.
106 See C<&checkauth> for an explanation of these parameters.
108 The C<template_name> is then used to find the correct template for
109 the page. The authenticated users details are loaded onto the
110 template in the HTML::Template LOOP variable C<USER_INFO>. Also the
111 C<sessionID> is passed to the template. This can be used in templates
112 if cookies are disabled. It needs to be put as and input to every
115 More information on the C<gettemplate> sub can be found in the
120 sub get_template_and_user {
123 gettemplate( $in->{'template_name'}, $in->{'type'}, $in->{'query'} );
124 my ( $user, $cookie, $sessionID, $flags ) = checkauth(
126 $in->{'authnotrequired'},
127 $in->{'flagsrequired'},
129 ) unless ($in->{'template_name'}=~/maintenance/);
132 my $insecure = C4::Context->preference('insecure');
133 if ($user or $insecure) {
135 # load the template variables for stylesheets and JavaScript
136 $template->param( css_libs => $in->{'css_libs'} );
137 $template->param( css_module => $in->{'css_module'} );
138 $template->param( css_page => $in->{'css_page'} );
139 $template->param( css_widgets => $in->{'css_widgets'} );
141 $template->param( js_libs => $in->{'js_libs'} );
142 $template->param( js_module => $in->{'js_module'} );
143 $template->param( js_page => $in->{'js_page'} );
144 $template->param( js_widgets => $in->{'js_widgets'} );
147 $template->param( loggedinusername => $user );
148 $template->param( sessionID => $sessionID );
150 if ($shelves = C4::Context->get_shelves_userenv()) {
151 $template->param( barshelves => scalar (@$shelves));
152 $template->param( barshelvesloop => $shelves);
155 $borrowernumber = getborrowernumber($user);
156 my ( $borr, $alternativeflags ) =
157 GetMemberDetails( $borrowernumber );
160 $template->param( "USER_INFO" => \@bordat );
162 my @flagroots = qw(circulate catalogue parameters borrowers permissions reserveforothers borrow
163 editcatalogue updatecharges management tools editauthorities serials reports);
164 # We are going to use the $flags returned by checkauth
165 # to create the template's parameters that will indicate
166 # which menus the user can access.
167 if (( $flags && $flags->{superlibrarian}==1) or $insecure==1) {
168 $template->param( CAN_user_circulate => 1 );
169 $template->param( CAN_user_catalogue => 1 );
170 $template->param( CAN_user_parameters => 1 );
171 $template->param( CAN_user_borrowers => 1 );
172 $template->param( CAN_user_permission => 1 );
173 $template->param( CAN_user_reserveforothers => 1 );
174 $template->param( CAN_user_borrow => 1 );
175 $template->param( CAN_user_editcatalogue => 1 );
176 $template->param( CAN_user_updatecharges => 1 );
177 $template->param( CAN_user_acquisition => 1 );
178 $template->param( CAN_user_management => 1 );
179 $template->param( CAN_user_tools => 1 );
180 $template->param( CAN_user_editauthorities => 1 );
181 $template->param( CAN_user_serials => 1 );
182 $template->param( CAN_user_reports => 1 );
183 $template->param( CAN_user_staffaccess => 1 );
186 if ( $flags && $flags->{circulate} == 1 ) {
187 $template->param( CAN_user_circulate => 1 );
190 if ( $flags && $flags->{catalogue} == 1 ) {
191 $template->param( CAN_user_catalogue => 1 );
194 if ( $flags && $flags->{parameters} == 1 ) {
195 $template->param( CAN_user_parameters => 1 );
196 $template->param( CAN_user_management => 1 );
199 if ( $flags && $flags->{borrowers} == 1 ) {
200 $template->param( CAN_user_borrowers => 1 );
203 if ( $flags && $flags->{permissions} == 1 ) {
204 $template->param( CAN_user_permission => 1 );
207 if ( $flags && $flags->{reserveforothers} == 1 ) {
208 $template->param( CAN_user_reserveforothers => 1 );
211 if ( $flags && $flags->{borrow} == 1 ) {
212 $template->param( CAN_user_borrow => 1 );
215 if ( $flags && $flags->{editcatalogue} == 1 ) {
216 $template->param( CAN_user_editcatalogue => 1 );
219 if ( $flags && $flags->{updatecharges} == 1 ) {
220 $template->param( CAN_user_updatecharges => 1 );
223 if ( $flags && $flags->{acquisition} == 1 ) {
224 $template->param( CAN_user_acquisition => 1 );
227 if ( $flags && $flags->{tools} == 1 ) {
228 $template->param( CAN_user_tools => 1 );
231 if ( $flags && $flags->{editauthorities} == 1 ) {
232 $template->param( CAN_user_editauthorities => 1 );
235 if ( $flags && $flags->{serials} == 1 ) {
236 $template->param( CAN_user_serials => 1 );
239 if ( $flags && $flags->{reports} == 1 ) {
240 $template->param( CAN_user_reports => 1 );
242 if ( $flags && $flags->{staffaccess} == 1 ) {
243 $template->param( CAN_user_staffaccess => 1 );
246 if ( $in->{'type'} eq "intranet" ) {
248 intranetcolorstylesheet => C4::Context->preference("intranetcolorstylesheet"),
249 intranetstylesheet => C4::Context->preference("intranetstylesheet"),
250 IntranetNav => C4::Context->preference("IntranetNav"),
251 intranetuserjs => C4::Context->preference("intranetuserjs"),
252 TemplateEncoding => C4::Context->preference("TemplateEncoding"),
253 AmazonContent => C4::Context->preference("AmazonContent"),
254 LibraryName => C4::Context->preference("LibraryName"),
255 LoginBranchcode => (C4::Context->userenv?C4::Context->userenv->{"branch"}:"insecure"),
256 LoginBranchname => (C4::Context->userenv?C4::Context->userenv->{"branchname"}:"insecure"),
257 LoginFirstname => (C4::Context->userenv?C4::Context->userenv->{"firstname"}:"Bel"),
258 LoginSurname => C4::Context->userenv?C4::Context->userenv->{"surname"}:"Inconnu",
259 AutoLocation => C4::Context->preference("AutoLocation"),
260 hide_marc => C4::Context->preference("hide_marc"),
261 patronimages => C4::Context->preference("patronimages"),
262 "BiblioDefaultView".C4::Context->preference("IntranetBiblioDefaultView") => 1,
263 advancedMARCEditor => C4::Context->preference("advancedMARCEditor"),
264 suggestion => C4::Context->preference("suggestion"),
265 virtualshelves => C4::Context->preference("virtualshelves"),
266 LibraryName => C4::Context->preference("LibraryName"),
267 KohaAdminEmailAddress => "" . C4::Context->preference("KohaAdminEmailAddress"),
268 IntranetmainUserblock => C4::Context->preference("IntranetmainUserblock"),
269 IndependantBranches => C4::Context->preference("IndependantBranches"),
270 CircAutocompl => C4::Context->preference("CircAutocompl"),
271 yuipath => C4::Context->preference("yuipath"),
272 FRBRizeEditions => C4::Context->preference("FRBRizeEditions"),
273 AmazonSimilarItems => C4::Context->preference("AmazonSimilarItems"),
274 'item-level_itypes' => C4::Context->preference('item-level_itypes'),
275 canreservefromotherbranches => C4::Context->preference('canreservefromotherbranches'),
276 intranetreadinghistory => C4::Context->preference("intranetreadinghistory"),
277 noItemTypeImages => C4::Context->preference("noItemTypeImages"),
281 warn "template type should be OPAC, here it is=[" . $in->{'type'} . "]" unless ( $in->{'type'} eq 'opac' );
282 my $LibraryNameTitle = C4::Context->preference("LibraryName");
283 $LibraryNameTitle =~ s/<(?:\/?)(?:br|p)\s*(?:\/?)>/ /sgi;
284 $LibraryNameTitle =~ s/<(?:[^<>'"]|'(?:[^']*)'|"(?:[^"]*)")*>//sg;
286 KohaAdminEmailAddress => "" . C4::Context->preference("KohaAdminEmailAddress"),
287 AnonSuggestions => "" . C4::Context->preference("AnonSuggestions"),
288 suggestion => "" . C4::Context->preference("suggestion"),
289 virtualshelves => "" . C4::Context->preference("virtualshelves"),
290 OpacNav => "" . C4::Context->preference("OpacNav"),
291 opacheader => "" . C4::Context->preference("opacheader"),
292 opaccredits => "" . C4::Context->preference("opaccredits"),
293 opacsmallimage => "" . C4::Context->preference("opacsmallimage"),
294 opaclargeimage => "" . C4::Context->preference("opaclargeimage"),
295 opaclayoutstylesheet => "". C4::Context->preference("opaclayoutstylesheet"),
296 opaccolorstylesheet => "". C4::Context->preference("opaccolorstylesheet"),
297 opaclanguagesdisplay => "". C4::Context->preference("opaclanguagesdisplay"),
298 opacuserlogin => "" . C4::Context->preference("opacuserlogin"),
299 OpacMainUserBlock => "" . C4::Context->preference("OpacMainUserBlock"),
300 OPACURLOpenInNewWindow => "" . C4::Context->preference("OPACURLOpenInNewWindow"),
301 opacbookbag => "" . C4::Context->preference("opacbookbag"),
302 TemplateEncoding => "". C4::Context->preference("TemplateEncoding"),
303 AmazonContent => "" . C4::Context->preference("AmazonContent"),
304 OPACShelfBrowser => "". C4::Context->preference("OPACShelfBrowser"),
305 OPACAmazonSimilarItems => "" . C4::Context->preference("OPACAmazonSimilarItems"),
306 LibraryName => "" . C4::Context->preference("LibraryName"),
307 LibraryNameTitle => "" . $LibraryNameTitle,
308 LoginBranchcode => (C4::Context->userenv?C4::Context->userenv->{"branch"}:"insecure"),
309 LoginBranchname => C4::Context->userenv?C4::Context->userenv->{"branchname"}:"",
310 LoginFirstname => (C4::Context->userenv?C4::Context->userenv->{"firstname"}:"Bel"),
311 LoginSurname => C4::Context->userenv?C4::Context->userenv->{"surname"}:"Inconnu",
312 OpacPasswordChange => C4::Context->preference("OpacPasswordChange"),
313 opacreadinghistory => C4::Context->preference("opacreadinghistory"),
314 opacuserjs => C4::Context->preference("opacuserjs"),
315 OpacCloud => C4::Context->preference("OpacCloud"),
316 OpacTopissue => C4::Context->preference("OpacTopissue"),
317 OpacAuthorities => C4::Context->preference("OpacAuthorities"),
318 OpacBrowser => C4::Context->preference("OpacBrowser"),
319 RequestOnOpac => C4::Context->preference("RequestOnOpac"),
320 reviewson => C4::Context->preference("reviewson"),
321 hide_marc => C4::Context->preference("hide_marc"),
322 patronimages => C4::Context->preference("patronimages"),
323 hidelostitems => C4::Context->preference("hidelostitems"),
324 mylibraryfirst => C4::Context->preference("SearchMyLibraryFirst"),
325 "BiblioDefaultView".C4::Context->preference("BiblioDefaultView") => 1,
326 OPACFRBRizeEditions => C4::Context->preference("OPACFRBRizeEditions"),
327 'item-level_itypes' => C4::Context->preference('item-level_itypes'),
328 'Version' => C4::Context->preference('Version'),
329 yuipath => C4::Context->preference("yuipath"),
332 $template->param(listloop=>[{shelfname=>"Freelist", shelfnumber=>110}]);
333 return ( $template, $borrowernumber, $cookie, $flags);
338 ($userid, $cookie, $sessionID) = &checkauth($query, $noauth, $flagsrequired, $type);
340 Verifies that the user is authorized to run this script. If
341 the user is authorized, a (userid, cookie, session-id, flags)
342 quadruple is returned. If the user is not authorized but does
343 not have the required privilege (see $flagsrequired below), it
344 displays an error page and exits. Otherwise, it displays the
345 login page and exits.
347 Note that C<&checkauth> will return if and only if the user
348 is authorized, so it should be called early on, before any
349 unfinished operations (e.g., if you've opened a file, then
350 C<&checkauth> won't close it for you).
352 C<$query> is the CGI object for the script calling C<&checkauth>.
354 The C<$noauth> argument is optional. If it is set, then no
355 authorization is required for the script.
357 C<&checkauth> fetches user and session information from C<$query> and
358 ensures that the user is authorized to run scripts that require
361 The C<$flagsrequired> argument specifies the required privileges
362 the user must have if the username and password are correct.
363 It should be specified as a reference-to-hash; keys in the hash
364 should be the "flags" for the user, as specified in the Members
365 intranet module. Any key specified must correspond to a "flag"
366 in the userflags table. E.g., { circulate => 1 } would specify
367 that the user must have the "circulate" privilege in order to
368 proceed. To make sure that access control is correct, the
369 C<$flagsrequired> parameter must be specified correctly.
371 The C<$type> argument specifies whether the template should be
372 retrieved from the opac or intranet directory tree. "opac" is
373 assumed if it is not specified; however, if C<$type> is specified,
374 "intranet" is assumed if it is not "opac".
376 If C<$query> does not have a valid session ID associated with it
377 (i.e., the user has not logged in) or if the session has expired,
378 C<&checkauth> presents the user with a login page (from the point of
379 view of the original script, C<&checkauth> does not return). Once the
380 user has authenticated, C<&checkauth> restarts the original script
381 (this time, C<&checkauth> returns).
383 The login page is provided using a HTML::Template, which is set in the
384 systempreferences table or at the top of this file. The variable C<$type>
385 selects which template to use, either the opac or the intranet
386 authentification template.
388 C<&checkauth> returns a user ID, a cookie, and a session ID. The
389 cookie should be sent back to the browser; it verifies that the user
394 sub _version_check ($$) {
398 # If Version syspref is unavailable, it means Koha is beeing installed,
399 # and so we must redirect to OPAC maintenance page or to the WebInstaller
400 #warn "about to check version";
401 unless ($version = C4::Context->preference('Version')) { # assignment, not comparison
402 if ($type ne 'opac') {
403 warn "Install required, redirecting to Installer";
404 print $query->redirect("/cgi-bin/koha/installer/install.pl");
407 warn "OPAC Install required, redirecting to maintenance";
408 print $query->redirect("/cgi-bin/koha/maintenance.pl");
413 # check that database and koha version are the same
414 # there is no DB version, it's a fresh install,
415 # go to web installer
416 # there is a DB version, compare it to the code version
417 my $kohaversion=C4::Context::KOHAVERSION;
418 # remove the 3 last . to have a Perl number
419 $kohaversion =~ s/(.*\..*)\.(.*)\.(.*)/$1$2$3/;
420 $debug and print STDERR "kohaversion : $kohaversion\n";
421 if ($version < $kohaversion){
422 my $warning = "Database update needed, redirecting to %s. Database is $version and Koha is "
423 . C4::Context->config("kohaversion");
424 if ($type ne 'opac'){
425 warn sprintf($warning, 'Installer');
426 print $query->redirect("/cgi-bin/koha/installer/install.pl?step=3");
428 warn sprintf("OPAC: " . $warning, 'maintenance');
429 print $query->redirect("/cgi-bin/koha/maintenance.pl");
437 open L, ">>/tmp/sessionlog" or warn "ERROR: Cannot append to /tmp/sessionlog";
438 printf L join("\n",@_);
444 $debug and warn "Checking Auth";
445 # $authnotrequired will be set for scripts which will run without authentication
446 my $authnotrequired = shift;
447 my $flagsrequired = shift;
449 $type = 'opac' unless $type;
451 my $dbh = C4::Context->dbh;
452 my $timeout = C4::Context->preference('timeout');
454 if ($timeout =~ /(\d+)[dD]/) {
455 $timeout = $1 * 86400;
457 $timeout = 600 unless $timeout;
459 _version_check($type,$query);
463 my ( $userid, $cookie, $sessionID, $flags, $shelves );
464 my $logout = $query->param('logout.x');
465 if ( $userid = $ENV{'REMOTE_USER'} ) {
466 # Using Basic Authentication, no cookies required
467 $cookie = $query->cookie(
468 -name => 'CGISESSID',
474 elsif ( $sessionID = $query->cookie("CGISESSID")) { # assignment, not comparison
475 my $session = get_session($sessionID);
476 C4::Context->_new_userenv($sessionID);
479 C4::Context::set_userenv(
480 $session->param('number'), $session->param('id'),
481 $session->param('cardnumber'), $session->param('firstname'),
482 $session->param('surname'), $session->param('branch'),
483 $session->param('branchname'), $session->param('flags'),
484 $session->param('emailaddress'), $session->param('branchprinter')
486 C4::Context::set_shelves_userenv($session->param('shelves'));
487 $debug and printf STDERR "AUTH_SESSION: (%s)\t%s %s - %s\n", map {$session->param($_)} qw(cardnumber firstname surname branch) ;
488 $ip = $session->param('ip');
489 $lasttime = $session->param('lasttime');
490 $userid = $session->param('id');
494 # voluntary logout the user
497 C4::Context->_unset_userenv($sessionID);
498 _session_log(sprintf "%20s from %16s logged out at %30s (manually).\n", $userid,$ip,localtime);
502 elsif ( $lasttime < time() - $timeout ) {
504 $info{'timed_out'} = 1;
506 C4::Context->_unset_userenv($sessionID);
507 _session_log(sprintf "%20s from %16s logged out at %30s (inactivity).\n", $userid,$ip,localtime);
511 elsif ( $ip ne $ENV{'REMOTE_ADDR'} ) {
512 # Different ip than originally logged in from
513 $info{'oldip'} = $ip;
514 $info{'newip'} = $ENV{'REMOTE_ADDR'};
515 $info{'different_ip'} = 1;
517 C4::Context->_unset_userenv($sessionID);
518 _session_log(sprintf "%20s from %16s logged out at %30s (ip changed to %16s).\n", $userid,$ip,localtime, $info{'newip'});
523 $cookie = $query->cookie( CGISESSID => $session->id );
524 $session->param('lasttime',time());
525 $flags = haspermission( $dbh, $userid, $flagsrequired );
529 $info{'nopermission'} = 1;
534 my $session = get_session("") or die "Auth ERROR: Cannot get_session()";
535 my $sessionID = $session->id;
536 $userid = $query->param('userid');
537 my $password = $query->param('password');
538 C4::Context->_new_userenv($sessionID);
539 my ( $return, $cardnumber ) = checkpw( $dbh, $userid, $password );
541 _session_log(sprintf "%20s from %16s logged in at %30s.\n", $userid,$ENV{'REMOTE_ADDR'},localtime);
542 $cookie = $query->cookie(CGISESSID => $sessionID);
543 if ( $flags = haspermission( $dbh, $userid, $flagsrequired ) ) {
547 $info{'nopermission'} = 1;
548 C4::Context->_unset_userenv($sessionID);
551 my ($borrowernumber, $firstname, $surname, $userflags,
552 $branchcode, $branchname, $branchprinter, $emailaddress);
554 if ( $return == 1 ) {
556 SELECT borrowernumber, firstname, surname, flags, borrowers.branchcode,
557 branches.branchname as branchname,
558 branches.branchprinter as branchprinter,
561 LEFT JOIN branches on borrowers.branchcode=branches.branchcode
563 my $sth = $dbh->prepare("$select where userid=?");
564 $sth->execute($userid);
565 unless ($sth->rows) {
566 $debug and print STDERR "AUTH_1: no rows for userid='$userid'\n";
567 $sth = $dbh->prepare("$select where cardnumber=?");
568 $sth->execute($cardnumber);
569 unless ($sth->rows) {
570 $debug and print STDERR "AUTH_2a: no rows for cardnumber='$cardnumber'\n";
571 $sth->execute($userid);
572 unless ($sth->rows) {
573 $debug and print STDERR "AUTH_2b: no rows for userid='$userid' AS cardnumber\n";
578 ($borrowernumber, $firstname, $surname, $userflags,
579 $branchcode, $branchname, $branchprinter, $emailaddress) = $sth->fetchrow;
580 $debug and print STDERR "AUTH_3 results: " .
581 "$cardnumber,$borrowernumber,$userid,$firstname,$surname,$userflags,$branchcode,$emailaddress\n";
583 print STDERR "AUTH_3: no results for userid='$userid', cardnumber='$cardnumber'.\n";
586 # launch a sequence to check if we have a ip for the branch, i
587 # if we have one we replace the branchcode of the userenv by the branch bound in the ip.
589 my $ip = $ENV{'REMOTE_ADDR'};
590 # if they specify at login, use that
591 if ($query->param('branch')) {
592 $branchcode = $query->param('branch');
593 $branchname = GetBranchName($branchcode);
595 my $branches = GetBranches();
596 if (C4::Context->boolean_preference('IndependantBranches') && C4::Context->boolean_preference('Autolocation')){
597 # we have to check they are coming from the right ip range
598 my $domain = $branches->{$branchcode}->{'branchip'};
599 if ($ip !~ /^$domain/){
601 $info{'wrongip'} = 1;
606 foreach my $br ( keys %$branches ) {
607 # now we work with the treatment of ip
608 my $domain = $branches->{$br}->{'branchip'};
609 if ( $domain && $ip =~ /^$domain/ ) {
610 $branchcode = $branches->{$br}->{'branchcode'};
612 # new op dev : add the branchprinter and branchname in the cookie
613 $branchprinter = $branches->{$br}->{'branchprinter'};
614 $branchname = $branches->{$br}->{'branchname'};
617 $session->param('number',$borrowernumber);
618 $session->param('id',$userid);
619 $session->param('cardnumber',$cardnumber);
620 $session->param('firstname',$firstname);
621 $session->param('surname',$surname);
622 $session->param('branch',$branchcode);
623 $session->param('branchname',$branchname);
624 $session->param('flags',$userflags);
625 $session->param('emailaddress',$emailaddress);
626 $session->param('ip',$session->remote_addr());
627 $session->param('lasttime',time());
628 $debug and printf STDERR "AUTH_4: (%s)\t%s %s - %s\n", map {$session->param($_)} qw(cardnumber firstname surname branch) ;
630 elsif ( $return == 2 ) {
631 #We suppose the user is the superlibrarian
633 $session->param('number',0);
634 $session->param('id',C4::Context->config('user'));
635 $session->param('cardnumber',C4::Context->config('user'));
636 $session->param('firstname',C4::Context->config('user'));
637 $session->param('surname',C4::Context->config('user'));
638 $session->param('branch','NO_LIBRARY_SET');
639 $session->param('branchname','NO_LIBRARY_SET');
640 $session->param('flags',1);
641 $session->param('emailaddress', C4::Context->preference('KohaAdminEmailAddress'));
642 $session->param('ip',$session->remote_addr());
643 $session->param('lasttime',time());
645 C4::Context::set_userenv(
646 $session->param('number'), $session->param('id'),
647 $session->param('cardnumber'), $session->param('firstname'),
648 $session->param('surname'), $session->param('branch'),
649 $session->param('branchname'), $session->param('flags'),
650 $session->param('emailaddress'), $session->param('branchprinter')
652 $shelves = GetShelvesSummary($borrowernumber,2,10);
653 $session->param('shelves', $shelves);
654 C4::Context::set_shelves_userenv($shelves);
658 $info{'invalid_username_or_password'} = 1;
659 C4::Context->_unset_userenv($sessionID);
663 } # END unless ($userid)
664 my $insecure = C4::Context->boolean_preference('insecure');
666 # finished authentification, now respond
667 if ( $loggedin || $authnotrequired || ( defined($insecure) && $insecure ) )
671 $cookie = $query->cookie( CGISESSID => '' );
673 return ( $userid, $cookie, $sessionID, $flags );
678 # AUTH rejected, show the login/password template, after checking the DB.
682 # get the inputs from the incoming query
684 foreach my $name ( param $query) {
685 (next) if ( $name eq 'userid' || $name eq 'password' );
686 my $value = $query->param($name);
687 push @inputs, { name => $name, value => $value };
689 # get the branchloop, which we need for authentication
690 my $branches = GetBranches();
692 for my $branch_hash (sort keys %$branches) {
693 push @branch_loop, {branchcode => "$branch_hash", branchname => $branches->{$branch_hash}->{'branchname'}, };
696 my $template_name = ( $type eq 'opac' ) ? 'opac-auth.tmpl' : 'auth.tmpl';
697 my $template = gettemplate( $template_name, $type, $query );
698 $template->param(branchloop => \@branch_loop,);
702 suggestion => C4::Context->preference("suggestion"),
703 virtualshelves => C4::Context->preference("virtualshelves"),
704 opaclargeimage => C4::Context->preference("opaclargeimage"),
705 LibraryName => C4::Context->preference("LibraryName"),
706 opacuserlogin => C4::Context->preference("opacuserlogin"),
707 OpacNav => C4::Context->preference("OpacNav"),
708 opaccredits => C4::Context->preference("opaccredits"),
709 opacreadinghistory => C4::Context->preference("opacreadinghistory"),
710 opacsmallimage => C4::Context->preference("opacsmallimage"),
711 opaclayoutstylesheet => C4::Context->preference("opaclayoutstylesheet"),
712 opaccolorstylesheet => C4::Context->preference("opaccolorstylesheet"),
713 opaclanguagesdisplay => C4::Context->preference("opaclanguagesdisplay"),
714 opacuserjs => C4::Context->preference("opacuserjs"),
715 opacbookbag => "" . C4::Context->preference("opacbookbag"),
716 OpacCloud => C4::Context->preference("OpacCloud"),
717 OpacTopissue => C4::Context->preference("OpacTopissue"),
718 OpacAuthorities => C4::Context->preference("OpacAuthorities"),
719 OpacBrowser => C4::Context->preference("OpacBrowser"),
720 intranetcolorstylesheet =>
721 C4::Context->preference("intranetcolorstylesheet"),
722 intranetstylesheet => C4::Context->preference("intranetstylesheet"),
723 IntranetNav => C4::Context->preference("IntranetNav"),
724 intranetuserjs => C4::Context->preference("intranetuserjs"),
725 TemplateEncoding => C4::Context->preference("TemplateEncoding"),
726 IndependantBranches=> C4::Context->preference("IndependantBranches"),
727 AutoLocation => C4::Context->preference("AutoLocation"),
728 yuipath => C4::Context->preference("yuipath"),
729 wrongip => $info{'wrongip'}
732 $template->param( loginprompt => 1 ) unless $info{'nopermission'};
734 my $self_url = $query->url( -absolute => 1 );
737 LibraryName => C4::Context->preference("LibraryName"),
739 $template->param( \%info );
740 # $cookie = $query->cookie(CGISESSID => $session->id
742 print $query->header(
743 -type => 'text/html',
753 ($status, $cookie, $sessionId) = check_api_auth($query, $userflags);
755 Given a CGI query containing the parameters 'userid' and 'password' and/or a session
756 cookie, determine if the user has the privileges specified by C<$userflags>.
758 C<check_api_auth> is is meant for authenticating users of web services, and
759 consequently will always return and will not attempt to redirect the user
762 If a valid session cookie is already present, check_api_auth will return a status
763 of "ok", the cookie, and the Koha session ID.
765 If no session cookie is present, check_api_auth will check the 'userid' and 'password
766 parameters and create a session cookie and Koha session if the supplied credentials
769 Possible return values in C<$status> are:
773 =item "ok" -- user authenticated; C<$cookie> and C<$sessionid> have valid values.
775 =item "failed" -- credentials are not correct; C<$cookie> and C<$sessionid> are undef
777 =item "maintenance" -- DB is in maintenance mode; no login possible at the moment
779 =item "expired -- session cookie has expired; API user should resubmit userid and password
787 my $flagsrequired = shift;
789 my $dbh = C4::Context->dbh;
790 my $timeout = C4::Context->preference('timeout');
791 $timeout = 600 unless $timeout;
793 unless (C4::Context->preference('Version')) {
794 # database has not been installed yet
795 return ("maintenance", undef, undef);
797 my $kohaversion=C4::Context::KOHAVERSION;
798 $kohaversion =~ s/(.*\..*)\.(.*)\.(.*)/$1$2$3/;
799 if (C4::Context->preference('Version') < $kohaversion) {
800 # database in need of version update; assume that
801 # no API should be called while databsae is in
803 return ("maintenance", undef, undef);
806 # FIXME -- most of what follows is a copy-and-paste
807 # of code from checkauth. There is an obvious need
808 # for refactoring to separate the various parts of
809 # the authentication code, but as of 2007-11-19 this
810 # is deferred so as to not introduce bugs into the
811 # regular authentication code for Koha 3.0.
813 # see if we have a valid session cookie already
814 # however, if a userid parameter is present (i.e., from
815 # a form submission, assume that any current cookie
817 my $sessionID = undef;
818 unless ($query->param('userid')) {
819 $sessionID = $query->cookie("CGISESSID");
822 my $session = get_session($sessionID);
823 C4::Context->_new_userenv($sessionID);
825 C4::Context::set_userenv(
826 $session->param('number'), $session->param('id'),
827 $session->param('cardnumber'), $session->param('firstname'),
828 $session->param('surname'), $session->param('branch'),
829 $session->param('branchname'), $session->param('flags'),
830 $session->param('emailaddress'), $session->param('branchprinter')
833 my $ip = $session->param('ip');
834 my $lasttime = $session->param('lasttime');
835 my $userid = $session->param('id');
836 if ( $lasttime < time() - $timeout ) {
839 C4::Context->_unset_userenv($sessionID);
842 return ("expired", undef, undef);
843 } elsif ( $ip ne $ENV{'REMOTE_ADDR'} ) {
846 C4::Context->_unset_userenv($sessionID);
849 return ("expired", undef, undef);
851 my $cookie = $query->cookie( CGISESSID => $session->id );
852 $session->param('lasttime',time());
853 my $flags = haspermission( $dbh, $userid, $flagsrequired );
855 return ("ok", $cookie, $sessionID);
858 C4::Context->_unset_userenv($sessionID);
861 return ("failed", undef, undef);
865 return ("expired", undef, undef);
869 my $userid = $query->param('userid');
870 my $password = $query->param('password');
871 unless ($userid and $password) {
872 # caller did something wrong, fail the authenticateion
873 return ("failed", undef, undef);
875 my ( $return, $cardnumber ) = checkpw( $dbh, $userid, $password );
876 if ($return and haspermission( $dbh, $userid, $flagsrequired)) {
877 my $session = get_session("");
878 return ("failed", undef, undef) unless $session;
880 my $sessionID = $session->id;
881 C4::Context->_new_userenv($sessionID);
882 my $cookie = $query->cookie(CGISESSID => $sessionID);
883 if ( $return == 1 ) {
885 $borrowernumber, $firstname, $surname,
886 $userflags, $branchcode, $branchname,
887 $branchprinter, $emailaddress
891 "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=?"
893 $sth->execute($userid);
895 $borrowernumber, $firstname, $surname,
896 $userflags, $branchcode, $branchname,
897 $branchprinter, $emailaddress
898 ) = $sth->fetchrow if ( $sth->rows );
900 unless ($sth->rows ) {
901 my $sth = $dbh->prepare(
902 "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=?"
904 $sth->execute($cardnumber);
906 $borrowernumber, $firstname, $surname,
907 $userflags, $branchcode, $branchname,
908 $branchprinter, $emailaddress
909 ) = $sth->fetchrow if ( $sth->rows );
911 unless ( $sth->rows ) {
912 $sth->execute($userid);
914 $borrowernumber, $firstname, $surname, $userflags,
915 $branchcode, $branchname, $branchprinter, $emailaddress
916 ) = $sth->fetchrow if ( $sth->rows );
920 my $ip = $ENV{'REMOTE_ADDR'};
921 # if they specify at login, use that
922 if ($query->param('branch')) {
923 $branchcode = $query->param('branch');
924 $branchname = GetBranchName($branchcode);
926 my $branches = GetBranches();
928 foreach my $br ( keys %$branches ) {
929 # now we work with the treatment of ip
930 my $domain = $branches->{$br}->{'branchip'};
931 if ( $domain && $ip =~ /^$domain/ ) {
932 $branchcode = $branches->{$br}->{'branchcode'};
934 # new op dev : add the branchprinter and branchname in the cookie
935 $branchprinter = $branches->{$br}->{'branchprinter'};
936 $branchname = $branches->{$br}->{'branchname'};
939 $session->param('number',$borrowernumber);
940 $session->param('id',$userid);
941 $session->param('cardnumber',$cardnumber);
942 $session->param('firstname',$firstname);
943 $session->param('surname',$surname);
944 $session->param('branch',$branchcode);
945 $session->param('branchname',$branchname);
946 $session->param('flags',$userflags);
947 $session->param('emailaddress',$emailaddress);
948 $session->param('ip',$session->remote_addr());
949 $session->param('lasttime',time());
950 } elsif ( $return == 2 ) {
951 #We suppose the user is the superlibrarian
952 $session->param('number',0);
953 $session->param('id',C4::Context->config('user'));
954 $session->param('cardnumber',C4::Context->config('user'));
955 $session->param('firstname',C4::Context->config('user'));
956 $session->param('surname',C4::Context->config('user'));
957 $session->param('branch','NO_LIBRARY_SET');
958 $session->param('branchname','NO_LIBRARY_SET');
959 $session->param('flags',1);
960 $session->param('emailaddress', C4::Context->preference('KohaAdminEmailAddress'));
961 $session->param('ip',$session->remote_addr());
962 $session->param('lasttime',time());
964 C4::Context::set_userenv(
965 $session->param('number'), $session->param('id'),
966 $session->param('cardnumber'), $session->param('firstname'),
967 $session->param('surname'), $session->param('branch'),
968 $session->param('branchname'), $session->param('flags'),
969 $session->param('emailaddress'), $session->param('branchprinter')
971 return ("ok", $cookie, $sessionID);
973 return ("failed", undef, undef);
978 =item check_cookie_auth
980 ($status, $sessionId) = check_api_auth($cookie, $userflags);
982 Given a CGISESSID cookie set during a previous login to Koha, determine
983 if the user has the privileges specified by C<$userflags>.
985 C<check_cookie_auth> is meant for authenticating special services
986 such as tools/upload-file.pl that are invoked by other pages that
987 have been authenticated in the usual way.
989 Possible return values in C<$status> are:
993 =item "ok" -- user authenticated; C<$sessionID> have valid values.
995 =item "failed" -- credentials are not correct; C<$sessionid> are undef
997 =item "maintenance" -- DB is in maintenance mode; no login possible at the moment
999 =item "expired -- session cookie has expired; API user should resubmit userid and password
1005 sub check_cookie_auth {
1007 my $flagsrequired = shift;
1009 my $dbh = C4::Context->dbh;
1010 my $timeout = C4::Context->preference('timeout');
1011 $timeout = 600 unless $timeout;
1013 unless (C4::Context->preference('Version')) {
1014 # database has not been installed yet
1015 return ("maintenance", undef);
1017 my $kohaversion=C4::Context::KOHAVERSION;
1018 $kohaversion =~ s/(.*\..*)\.(.*)\.(.*)/$1$2$3/;
1019 if (C4::Context->preference('Version') < $kohaversion) {
1020 # database in need of version update; assume that
1021 # no API should be called while databsae is in
1023 return ("maintenance", undef);
1026 # FIXME -- most of what follows is a copy-and-paste
1027 # of code from checkauth. There is an obvious need
1028 # for refactoring to separate the various parts of
1029 # the authentication code, but as of 2007-11-23 this
1030 # is deferred so as to not introduce bugs into the
1031 # regular authentication code for Koha 3.0.
1033 # see if we have a valid session cookie already
1034 # however, if a userid parameter is present (i.e., from
1035 # a form submission, assume that any current cookie
1037 unless (defined $cookie and $cookie) {
1038 return ("failed", undef);
1040 my $sessionID = $cookie;
1041 my $session = get_session($sessionID);
1042 C4::Context->_new_userenv($sessionID);
1044 C4::Context::set_userenv(
1045 $session->param('number'), $session->param('id'),
1046 $session->param('cardnumber'), $session->param('firstname'),
1047 $session->param('surname'), $session->param('branch'),
1048 $session->param('branchname'), $session->param('flags'),
1049 $session->param('emailaddress'), $session->param('branchprinter')
1052 my $ip = $session->param('ip');
1053 my $lasttime = $session->param('lasttime');
1054 my $userid = $session->param('id');
1055 if ( $lasttime < time() - $timeout ) {
1058 C4::Context->_unset_userenv($sessionID);
1061 return ("expired", undef);
1062 } elsif ( $ip ne $ENV{'REMOTE_ADDR'} ) {
1063 # IP address changed
1065 C4::Context->_unset_userenv($sessionID);
1068 return ("expired", undef);
1070 $session->param('lasttime',time());
1071 my $flags = haspermission( $dbh, $userid, $flagsrequired );
1073 return ("ok", $sessionID);
1076 C4::Context->_unset_userenv($sessionID);
1079 return ("failed", undef);
1083 return ("expired", undef);
1090 my $session = get_session($sessionID);
1092 Given a session ID, retrieve the CGI::Session object used to store
1093 the session's state. The session object can be used to store
1094 data that needs to be accessed by different scripts during a
1097 If the C<$sessionID> parameter is an empty string, a new session
1103 my $sessionID = shift;
1104 my $storage_method = C4::Context->preference('SessionStorage');
1105 my $dbh = C4::Context->dbh;
1107 if ($storage_method eq 'mysql'){
1108 $session = new CGI::Session("driver:MySQL;serializer:yaml", $sessionID, {Handle=>$dbh});
1110 elsif ($storage_method eq 'Pg') {
1111 $session = new CGI::Session("driver:PostgreSQL;serializer:yaml", $sessionID, {Handle=>$dbh});
1114 # catch all defaults to tmp should work on all systems
1115 $session = new CGI::Session("driver:File;serializer:yaml", $sessionID, {Directory=>'/tmp'});
1122 my ( $dbh, $userid, $password ) = @_;
1124 $debug and print "## checkpw - checking LDAP\n";
1125 my ($retval,$retcard) = checkpw_ldap(@_); # EXTERNAL AUTH
1126 ($retval) and return ($retval,$retcard);
1132 "select password,cardnumber,borrowernumber,userid,firstname,surname,branchcode,flags from borrowers where userid=?"
1134 $sth->execute($userid);
1136 my ( $md5password, $cardnumber, $borrowernumber, $userid, $firstname,
1137 $surname, $branchcode, $flags )
1139 if ( md5_base64($password) eq $md5password ) {
1141 C4::Context->set_userenv( "$borrowernumber", $userid, $cardnumber,
1142 $firstname, $surname, $branchcode, $flags );
1143 return 1, $cardnumber;
1148 "select password,cardnumber,borrowernumber,userid, firstname,surname,branchcode,flags from borrowers where cardnumber=?"
1150 $sth->execute($userid);
1152 my ( $md5password, $cardnumber, $borrowernumber, $userid, $firstname,
1153 $surname, $branchcode, $flags )
1155 if ( md5_base64($password) eq $md5password ) {
1157 C4::Context->set_userenv( $borrowernumber, $userid, $cardnumber,
1158 $firstname, $surname, $branchcode, $flags );
1162 if ( $userid && $userid eq C4::Context->config('user')
1163 && "$password" eq C4::Context->config('pass') )
1166 # Koha superuser account
1167 # C4::Context->set_userenv(0,0,C4::Context->config('user'),C4::Context->config('user'),C4::Context->config('user'),"",1);
1170 if ( $userid && $userid eq 'demo'
1171 && "$password" eq 'demo'
1172 && C4::Context->config('demo') )
1175 # DEMO => the demo user is allowed to do everything (if demo set to 1 in koha.conf
1176 # some features won't be effective : modify systempref, modify MARC structure,
1184 $authflags = getuserflags($flags,$dbh);
1185 Translates integer flags into permissions strings hash.
1187 C<$flags> is the integer userflags value ( borrowers.userflags )
1188 C<$authflags> is a hashref of permissions
1196 $flags = 0 unless $flags;
1197 my $sth = $dbh->prepare("SELECT bit, flag, defaulton FROM userflags");
1200 while ( my ( $bit, $flag, $defaulton ) = $sth->fetchrow ) {
1201 if ( ( $flags & ( 2**$bit ) ) || $defaulton ) {
1202 $userflags->{$flag} = 1;
1205 $userflags->{$flag} = 0;
1213 $flags = ($dbh,$member,$flagsrequired);
1215 C<$member> may be either userid or overloaded with $borrower hashref from GetMemberDetails.
1216 C<$flags> is a hashref of required flags lik C<$borrower-<{authflags}>
1218 Returns member's flags or 0 if a permission is not met.
1223 my ( $dbh, $userid, $flagsrequired ) = @_;
1224 my ($flags,$intflags);
1225 $dbh=C4::Context->dbh unless($dbh);
1227 $intflags = $userid->{'flags'};
1229 my $sth = $dbh->prepare("SELECT flags FROM borrowers WHERE userid=?");
1230 $sth->execute($userid);
1231 my ($intflags) = $sth->fetchrow;
1232 $flags = getuserflags( $intflags, $dbh );
1234 if ( $userid eq C4::Context->config('user') ) {
1235 # Super User Account from /etc/koha.conf
1236 $flags->{'superlibrarian'} = 1;
1238 if ( $userid eq 'demo' && C4::Context->config('demo') ) {
1239 # Demo user that can do "anything" (demo=1 in /etc/koha.conf)
1240 $flags->{'superlibrarian'} = 1;
1242 return $flags if $flags->{superlibrarian};
1243 foreach ( keys %$flagsrequired ) {
1244 return 0 unless( $flags->{$_} );
1247 #FIXME - This fcn should return the failed permission so a suitable error msg can be delivered.
1251 sub getborrowernumber {
1253 my $dbh = C4::Context->dbh;
1254 for my $field ( 'userid', 'cardnumber' ) {
1256 $dbh->prepare("select borrowernumber from borrowers where $field=?");
1257 $sth->execute($userid);
1259 my ($bnumber) = $sth->fetchrow;
1266 END { } # module clean-up code here (global destructor)