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 &get_all_subpermissions &get_user_subpermissions);
45 %EXPORT_TAGS = (EditPermissions => [qw(get_all_subpermissions get_user_subpermissions)]);
46 $ldap = C4::Context->config('useldapserver') || 0;
48 require C4::Auth_with_ldap; # no import
49 import C4::Auth_with_ldap qw(checkpw_ldap);
55 C4::Auth - Authenticates Koha users
64 my ($template, $borrowernumber, $cookie)
65 = get_template_and_user(
67 template_name => "opac-main.tmpl",
71 flagsrequired => {borrow => 1, catalogue => '*', tools => 'import_patrons' },
83 The main function of this module is to provide
84 authentification. However the get_template_and_user function has
85 been provided so that a users login information is passed along
86 automatically. This gets loaded into the template.
92 =item get_template_and_user
94 my ($template, $borrowernumber, $cookie)
95 = get_template_and_user(
97 template_name => "opac-main.tmpl",
100 authnotrequired => 1,
101 flagsrequired => {borrow => 1, catalogue => '*', tools => 'import_patrons' },
105 This call passes the C<query>, C<flagsrequired> and C<authnotrequired>
106 to C<&checkauth> (in this module) to perform authentification.
107 See C<&checkauth> for an explanation of these parameters.
109 The C<template_name> is then used to find the correct template for
110 the page. The authenticated users details are loaded onto the
111 template in the HTML::Template LOOP variable C<USER_INFO>. Also the
112 C<sessionID> is passed to the template. This can be used in templates
113 if cookies are disabled. It needs to be put as and input to every
116 More information on the C<gettemplate> sub can be found in the
121 sub get_template_and_user {
124 gettemplate( $in->{'template_name'}, $in->{'type'}, $in->{'query'} );
125 my ( $user, $cookie, $sessionID, $flags ) = checkauth(
127 $in->{'authnotrequired'},
128 $in->{'flagsrequired'},
130 ) unless ($in->{'template_name'}=~/maintenance/);
133 my $insecure = C4::Context->preference('insecure');
134 if ($user or $insecure) {
136 # load the template variables for stylesheets and JavaScript
137 $template->param( css_libs => $in->{'css_libs'} );
138 $template->param( css_module => $in->{'css_module'} );
139 $template->param( css_page => $in->{'css_page'} );
140 $template->param( css_widgets => $in->{'css_widgets'} );
142 $template->param( js_libs => $in->{'js_libs'} );
143 $template->param( js_module => $in->{'js_module'} );
144 $template->param( js_page => $in->{'js_page'} );
145 $template->param( js_widgets => $in->{'js_widgets'} );
148 $template->param( loggedinusername => $user );
149 $template->param( sessionID => $sessionID );
151 if ($shelves = C4::Context->get_shelves_userenv()) {
152 $template->param( barshelves => scalar (@$shelves));
153 $template->param( barshelvesloop => $shelves);
156 $borrowernumber = getborrowernumber($user);
157 my ( $borr, $alternativeflags ) =
158 GetMemberDetails( $borrowernumber );
161 $template->param( "USER_INFO" => \@bordat );
163 my $all_perms = get_all_subpermissions();
165 my @flagroots = qw(circulate catalogue parameters borrowers permissions reserveforothers borrow
166 editcatalogue updatecharges management tools editauthorities serials reports);
167 # We are going to use the $flags returned by checkauth
168 # to create the template's parameters that will indicate
169 # which menus the user can access.
170 if (( $flags && $flags->{superlibrarian}==1) or $insecure==1) {
171 $template->param( CAN_user_circulate => 1 );
172 $template->param( CAN_user_catalogue => 1 );
173 $template->param( CAN_user_parameters => 1 );
174 $template->param( CAN_user_borrowers => 1 );
175 $template->param( CAN_user_permissions => 1 );
176 $template->param( CAN_user_reserveforothers => 1 );
177 $template->param( CAN_user_borrow => 1 );
178 $template->param( CAN_user_editcatalogue => 1 );
179 $template->param( CAN_user_updatecharges => 1 );
180 $template->param( CAN_user_acquisition => 1 );
181 $template->param( CAN_user_management => 1 );
182 $template->param( CAN_user_tools => 1 );
183 $template->param( CAN_user_editauthorities => 1 );
184 $template->param( CAN_user_serials => 1 );
185 $template->param( CAN_user_reports => 1 );
186 $template->param( CAN_user_staffaccess => 1 );
187 foreach my $module (keys %$all_perms) {
188 foreach my $subperm (keys %{ $all_perms->{$module} }) {
189 $template->param( "CAN_user_${module}_${subperm}" => 1 );
194 if (C4::Context->preference('GranularPermissions')) {
196 foreach my $module (keys %$all_perms) {
197 if ( $flags->{$module} == 1) {
198 foreach my $subperm (keys %{ $all_perms->{$module} }) {
199 $template->param( "CAN_user_${module}_${subperm}" => 1 );
201 } elsif ( ref($flags->{$module}) ) {
202 foreach my $subperm (keys %{ $flags->{$module} } ) {
203 $template->param( "CAN_user_${module}_${subperm}" => 1 );
209 foreach my $module (keys %$all_perms) {
210 foreach my $subperm (keys %{ $all_perms->{$module} }) {
211 $template->param( "CAN_user_${module}_${subperm}" => 1 );
217 foreach my $module (keys %$flags) {
218 if ( $flags->{$module} == 1 or ref($flags->{$module}) ) {
219 $template->param( "CAN_user_$module" => 1 );
220 if ($module eq "parameters") {
221 $template->param( CAN_user_management => 1 );
228 if ( $in->{'type'} eq "intranet" ) {
230 intranetcolorstylesheet => C4::Context->preference("intranetcolorstylesheet"),
231 intranetstylesheet => C4::Context->preference("intranetstylesheet"),
232 IntranetNav => C4::Context->preference("IntranetNav"),
233 intranetuserjs => C4::Context->preference("intranetuserjs"),
234 TemplateEncoding => C4::Context->preference("TemplateEncoding"),
235 AmazonContent => C4::Context->preference("AmazonContent"),
236 LibraryName => C4::Context->preference("LibraryName"),
237 LoginBranchcode => (C4::Context->userenv?C4::Context->userenv->{"branch"}:"insecure"),
238 LoginBranchname => (C4::Context->userenv?C4::Context->userenv->{"branchname"}:"insecure"),
239 LoginFirstname => (C4::Context->userenv?C4::Context->userenv->{"firstname"}:"Bel"),
240 LoginSurname => C4::Context->userenv?C4::Context->userenv->{"surname"}:"Inconnu",
241 AutoLocation => C4::Context->preference("AutoLocation"),
242 hide_marc => C4::Context->preference("hide_marc"),
243 patronimages => C4::Context->preference("patronimages"),
244 "BiblioDefaultView".C4::Context->preference("IntranetBiblioDefaultView") => 1,
245 advancedMARCEditor => C4::Context->preference("advancedMARCEditor"),
246 suggestion => C4::Context->preference("suggestion"),
247 virtualshelves => C4::Context->preference("virtualshelves"),
248 LibraryName => C4::Context->preference("LibraryName"),
249 KohaAdminEmailAddress => "" . C4::Context->preference("KohaAdminEmailAddress"),
250 IntranetmainUserblock => C4::Context->preference("IntranetmainUserblock"),
251 IndependantBranches => C4::Context->preference("IndependantBranches"),
252 CircAutocompl => C4::Context->preference("CircAutocompl"),
253 yuipath => C4::Context->preference("yuipath"),
254 FRBRizeEditions => C4::Context->preference("FRBRizeEditions"),
255 AmazonSimilarItems => C4::Context->preference("AmazonSimilarItems"),
256 'item-level_itypes' => C4::Context->preference('item-level_itypes'),
257 canreservefromotherbranches => C4::Context->preference('canreservefromotherbranches'),
258 intranetreadinghistory => C4::Context->preference("intranetreadinghistory"),
259 noItemTypeImages => C4::Context->preference("noItemTypeImages"),
260 singleBranchMode => C4::Context->preference("singleBranchMode"),
264 warn "template type should be OPAC, here it is=[" . $in->{'type'} . "]" unless ( $in->{'type'} eq 'opac' );
265 my $LibraryNameTitle = C4::Context->preference("LibraryName");
266 $LibraryNameTitle =~ s/<(?:\/?)(?:br|p)\s*(?:\/?)>/ /sgi;
267 $LibraryNameTitle =~ s/<(?:[^<>'"]|'(?:[^']*)'|"(?:[^"]*)")*>//sg;
269 KohaAdminEmailAddress => "" . C4::Context->preference("KohaAdminEmailAddress"),
270 AnonSuggestions => "" . C4::Context->preference("AnonSuggestions"),
271 suggestion => "" . C4::Context->preference("suggestion"),
272 OPACViewOthersSuggestions => "" . C4::Context->preference("OPACViewOthersSuggestions"),
273 virtualshelves => "" . C4::Context->preference("virtualshelves"),
274 OpacNav => "" . C4::Context->preference("OpacNav"),
275 opacheader => "" . C4::Context->preference("opacheader"),
276 opaccredits => "" . C4::Context->preference("opaccredits"),
277 opacsmallimage => "" . C4::Context->preference("opacsmallimage"),
278 opaclargeimage => "" . C4::Context->preference("opaclargeimage"),
279 opaclayoutstylesheet => "". C4::Context->preference("opaclayoutstylesheet"),
280 opaccolorstylesheet => "". C4::Context->preference("opaccolorstylesheet"),
281 OPACUserCSS => "". C4::Context->preference("OPACUserCSS"),
282 opaclanguagesdisplay => "". C4::Context->preference("opaclanguagesdisplay"),
283 opacuserlogin => "" . C4::Context->preference("opacuserlogin"),
284 OpacMainUserBlock => "" . C4::Context->preference("OpacMainUserBlock"),
285 OPACURLOpenInNewWindow => "" . C4::Context->preference("OPACURLOpenInNewWindow"),
286 opacbookbag => "" . C4::Context->preference("opacbookbag"),
287 TemplateEncoding => "". C4::Context->preference("TemplateEncoding"),
288 AmazonContent => "" . C4::Context->preference("AmazonContent"),
289 OPACShelfBrowser => "". C4::Context->preference("OPACShelfBrowser"),
290 OPACAmazonSimilarItems => "" . C4::Context->preference("OPACAmazonSimilarItems"),
291 LibraryName => "" . C4::Context->preference("LibraryName"),
292 LibraryNameTitle => "" . $LibraryNameTitle,
293 LoginBranchcode => (C4::Context->userenv?C4::Context->userenv->{"branch"}:"insecure"),
294 LoginBranchname => C4::Context->userenv?C4::Context->userenv->{"branchname"}:"",
295 LoginFirstname => (C4::Context->userenv?C4::Context->userenv->{"firstname"}:"Bel"),
296 LoginSurname => C4::Context->userenv?C4::Context->userenv->{"surname"}:"Inconnu",
297 OpacPasswordChange => C4::Context->preference("OpacPasswordChange"),
298 opacreadinghistory => C4::Context->preference("opacreadinghistory"),
299 opacuserjs => C4::Context->preference("opacuserjs"),
300 OpacCloud => C4::Context->preference("OpacCloud"),
301 OpacTopissue => C4::Context->preference("OpacTopissue"),
302 OpacAuthorities => C4::Context->preference("OpacAuthorities"),
303 OpacBrowser => C4::Context->preference("OpacBrowser"),
304 RequestOnOpac => C4::Context->preference("RequestOnOpac"),
305 OPACItemHolds => C4::Context->preference("OPACItemHolds"),
306 reviewson => C4::Context->preference("reviewson"),
307 hide_marc => C4::Context->preference("hide_marc"),
308 patronimages => C4::Context->preference("patronimages"),
309 hidelostitems => C4::Context->preference("hidelostitems"),
310 mylibraryfirst => C4::Context->preference("SearchMyLibraryFirst"),
311 "BiblioDefaultView".C4::Context->preference("BiblioDefaultView") => 1,
312 OPACFRBRizeEditions => C4::Context->preference("OPACFRBRizeEditions"),
313 'item-level_itypes' => C4::Context->preference('item-level_itypes'),
314 'Version' => C4::Context->preference('Version'),
315 yuipath => C4::Context->preference("yuipath"),
316 singleBranchMode => C4::Context->preference("singleBranchMode"),
317 XSLTResultsDisplay => C4::Context->preference("XSLTResultsDisplay"),
318 XSLTDetailsDisplay => C4::Context->preference("XSLTDetailsDisplay"),
321 $template->param(listloop=>[{shelfname=>"Freelist", shelfnumber=>110}]);
322 return ( $template, $borrowernumber, $cookie, $flags);
327 ($userid, $cookie, $sessionID) = &checkauth($query, $noauth, $flagsrequired, $type);
329 Verifies that the user is authorized to run this script. If
330 the user is authorized, a (userid, cookie, session-id, flags)
331 quadruple is returned. If the user is not authorized but does
332 not have the required privilege (see $flagsrequired below), it
333 displays an error page and exits. Otherwise, it displays the
334 login page and exits.
336 Note that C<&checkauth> will return if and only if the user
337 is authorized, so it should be called early on, before any
338 unfinished operations (e.g., if you've opened a file, then
339 C<&checkauth> won't close it for you).
341 C<$query> is the CGI object for the script calling C<&checkauth>.
343 The C<$noauth> argument is optional. If it is set, then no
344 authorization is required for the script.
346 C<&checkauth> fetches user and session information from C<$query> and
347 ensures that the user is authorized to run scripts that require
350 The C<$flagsrequired> argument specifies the required privileges
351 the user must have if the username and password are correct.
352 It should be specified as a reference-to-hash; keys in the hash
353 should be the "flags" for the user, as specified in the Members
354 intranet module. Any key specified must correspond to a "flag"
355 in the userflags table. E.g., { circulate => 1 } would specify
356 that the user must have the "circulate" privilege in order to
357 proceed. To make sure that access control is correct, the
358 C<$flagsrequired> parameter must be specified correctly.
360 If the GranularPermissions system preference is ON, the
361 value of each key in the C<flagsrequired> hash takes on an additional
366 The user must have access to all subfunctions of the module
367 specified by the hash key.
371 The user must have access to at least one subfunction of the module
372 specified by the hash key.
374 =item specific permission, e.g., 'export_catalog'
376 The user must have access to the specific subfunction list, which
377 must correspond to a row in the permissions table.
379 The C<$type> argument specifies whether the template should be
380 retrieved from the opac or intranet directory tree. "opac" is
381 assumed if it is not specified; however, if C<$type> is specified,
382 "intranet" is assumed if it is not "opac".
384 If C<$query> does not have a valid session ID associated with it
385 (i.e., the user has not logged in) or if the session has expired,
386 C<&checkauth> presents the user with a login page (from the point of
387 view of the original script, C<&checkauth> does not return). Once the
388 user has authenticated, C<&checkauth> restarts the original script
389 (this time, C<&checkauth> returns).
391 The login page is provided using a HTML::Template, which is set in the
392 systempreferences table or at the top of this file. The variable C<$type>
393 selects which template to use, either the opac or the intranet
394 authentification template.
396 C<&checkauth> returns a user ID, a cookie, and a session ID. The
397 cookie should be sent back to the browser; it verifies that the user
402 sub _version_check ($$) {
406 # If Version syspref is unavailable, it means Koha is beeing installed,
407 # and so we must redirect to OPAC maintenance page or to the WebInstaller
408 #warn "about to check version";
409 unless ($version = C4::Context->preference('Version')) { # assignment, not comparison
410 if ($type ne 'opac') {
411 warn "Install required, redirecting to Installer";
412 print $query->redirect("/cgi-bin/koha/installer/install.pl");
415 warn "OPAC Install required, redirecting to maintenance";
416 print $query->redirect("/cgi-bin/koha/maintenance.pl");
421 # check that database and koha version are the same
422 # there is no DB version, it's a fresh install,
423 # go to web installer
424 # there is a DB version, compare it to the code version
425 my $kohaversion=C4::Context::KOHAVERSION;
426 # remove the 3 last . to have a Perl number
427 $kohaversion =~ s/(.*\..*)\.(.*)\.(.*)/$1$2$3/;
428 $debug and print STDERR "kohaversion : $kohaversion\n";
429 if ($version < $kohaversion){
430 my $warning = "Database update needed, redirecting to %s. Database is $version and Koha is $kohaversion";
431 if ($type ne 'opac'){
432 warn sprintf($warning, 'Installer');
433 print $query->redirect("/cgi-bin/koha/installer/install.pl?step=3");
435 warn sprintf("OPAC: " . $warning, 'maintenance');
436 print $query->redirect("/cgi-bin/koha/maintenance.pl");
444 open L, ">>/tmp/sessionlog" or warn "ERROR: Cannot append to /tmp/sessionlog";
445 printf L join("\n",@_);
451 $debug and warn "Checking Auth";
452 # $authnotrequired will be set for scripts which will run without authentication
453 my $authnotrequired = shift;
454 my $flagsrequired = shift;
456 $type = 'opac' unless $type;
458 my $dbh = C4::Context->dbh;
459 my $timeout = C4::Context->preference('timeout');
461 if ($timeout =~ /(\d+)[dD]/) {
462 $timeout = $1 * 86400;
464 $timeout = 600 unless $timeout;
466 _version_check($type,$query);
470 my ( $userid, $cookie, $sessionID, $flags, $shelves );
471 my $logout = $query->param('logout.x');
472 if ( $userid = $ENV{'REMOTE_USER'} ) {
473 # Using Basic Authentication, no cookies required
474 $cookie = $query->cookie(
475 -name => 'CGISESSID',
481 elsif ( $sessionID = $query->cookie("CGISESSID")) { # assignment, not comparison
482 my $session = get_session($sessionID);
483 C4::Context->_new_userenv($sessionID);
486 C4::Context::set_userenv(
487 $session->param('number'), $session->param('id'),
488 $session->param('cardnumber'), $session->param('firstname'),
489 $session->param('surname'), $session->param('branch'),
490 $session->param('branchname'), $session->param('flags'),
491 $session->param('emailaddress'), $session->param('branchprinter')
493 C4::Context::set_shelves_userenv($session->param('shelves'));
494 $debug and printf STDERR "AUTH_SESSION: (%s)\t%s %s - %s\n", map {$session->param($_)} qw(cardnumber firstname surname branch) ;
495 $ip = $session->param('ip');
496 $lasttime = $session->param('lasttime');
497 $userid = $session->param('id');
501 # voluntary logout the user
504 C4::Context->_unset_userenv($sessionID);
505 _session_log(sprintf "%20s from %16s logged out at %30s (manually).\n", $userid,$ip,localtime);
509 elsif ( $lasttime < time() - $timeout ) {
511 $info{'timed_out'} = 1;
513 C4::Context->_unset_userenv($sessionID);
514 _session_log(sprintf "%20s from %16s logged out at %30s (inactivity).\n", $userid,$ip,localtime);
518 elsif ( $ip ne $ENV{'REMOTE_ADDR'} ) {
519 # Different ip than originally logged in from
520 $info{'oldip'} = $ip;
521 $info{'newip'} = $ENV{'REMOTE_ADDR'};
522 $info{'different_ip'} = 1;
524 C4::Context->_unset_userenv($sessionID);
525 _session_log(sprintf "%20s from %16s logged out at %30s (ip changed to %16s).\n", $userid,$ip,localtime, $info{'newip'});
530 $cookie = $query->cookie( CGISESSID => $session->id );
531 $session->param('lasttime',time());
532 $flags = haspermission( $dbh, $userid, $flagsrequired );
536 $info{'nopermission'} = 1;
541 my $session = get_session("") or die "Auth ERROR: Cannot get_session()";
542 my $sessionID = $session->id;
543 $userid = $query->param('userid');
544 my $password = $query->param('password');
545 C4::Context->_new_userenv($sessionID);
546 my ( $return, $cardnumber ) = checkpw( $dbh, $userid, $password );
548 _session_log(sprintf "%20s from %16s logged in at %30s.\n", $userid,$ENV{'REMOTE_ADDR'},localtime);
549 $cookie = $query->cookie(CGISESSID => $sessionID);
550 if ( $flags = haspermission( $dbh, $userid, $flagsrequired ) ) {
554 $info{'nopermission'} = 1;
555 C4::Context->_unset_userenv($sessionID);
558 my ($borrowernumber, $firstname, $surname, $userflags,
559 $branchcode, $branchname, $branchprinter, $emailaddress);
561 if ( $return == 1 ) {
563 SELECT borrowernumber, firstname, surname, flags, borrowers.branchcode,
564 branches.branchname as branchname,
565 branches.branchprinter as branchprinter,
568 LEFT JOIN branches on borrowers.branchcode=branches.branchcode
570 my $sth = $dbh->prepare("$select where userid=?");
571 $sth->execute($userid);
572 unless ($sth->rows) {
573 $debug and print STDERR "AUTH_1: no rows for userid='$userid'\n";
574 $sth = $dbh->prepare("$select where cardnumber=?");
575 $sth->execute($cardnumber);
576 unless ($sth->rows) {
577 $debug and print STDERR "AUTH_2a: no rows for cardnumber='$cardnumber'\n";
578 $sth->execute($userid);
579 unless ($sth->rows) {
580 $debug and print STDERR "AUTH_2b: no rows for userid='$userid' AS cardnumber\n";
585 ($borrowernumber, $firstname, $surname, $userflags,
586 $branchcode, $branchname, $branchprinter, $emailaddress) = $sth->fetchrow;
587 $debug and print STDERR "AUTH_3 results: " .
588 "$cardnumber,$borrowernumber,$userid,$firstname,$surname,$userflags,$branchcode,$emailaddress\n";
590 print STDERR "AUTH_3: no results for userid='$userid', cardnumber='$cardnumber'.\n";
593 # launch a sequence to check if we have a ip for the branch, i
594 # if we have one we replace the branchcode of the userenv by the branch bound in the ip.
596 my $ip = $ENV{'REMOTE_ADDR'};
597 # if they specify at login, use that
598 if ($query->param('branch')) {
599 $branchcode = $query->param('branch');
600 $branchname = GetBranchName($branchcode);
602 my $branches = GetBranches();
603 if (C4::Context->boolean_preference('IndependantBranches') && C4::Context->boolean_preference('Autolocation')){
604 # we have to check they are coming from the right ip range
605 my $domain = $branches->{$branchcode}->{'branchip'};
606 if ($ip !~ /^$domain/){
608 $info{'wrongip'} = 1;
613 foreach my $br ( keys %$branches ) {
614 # now we work with the treatment of ip
615 my $domain = $branches->{$br}->{'branchip'};
616 if ( $domain && $ip =~ /^$domain/ ) {
617 $branchcode = $branches->{$br}->{'branchcode'};
619 # new op dev : add the branchprinter and branchname in the cookie
620 $branchprinter = $branches->{$br}->{'branchprinter'};
621 $branchname = $branches->{$br}->{'branchname'};
624 $session->param('number',$borrowernumber);
625 $session->param('id',$userid);
626 $session->param('cardnumber',$cardnumber);
627 $session->param('firstname',$firstname);
628 $session->param('surname',$surname);
629 $session->param('branch',$branchcode);
630 $session->param('branchname',$branchname);
631 $session->param('flags',$userflags);
632 $session->param('emailaddress',$emailaddress);
633 $session->param('ip',$session->remote_addr());
634 $session->param('lasttime',time());
635 $debug and printf STDERR "AUTH_4: (%s)\t%s %s - %s\n", map {$session->param($_)} qw(cardnumber firstname surname branch) ;
637 elsif ( $return == 2 ) {
638 #We suppose the user is the superlibrarian
640 $session->param('number',0);
641 $session->param('id',C4::Context->config('user'));
642 $session->param('cardnumber',C4::Context->config('user'));
643 $session->param('firstname',C4::Context->config('user'));
644 $session->param('surname',C4::Context->config('user'));
645 $session->param('branch','NO_LIBRARY_SET');
646 $session->param('branchname','NO_LIBRARY_SET');
647 $session->param('flags',1);
648 $session->param('emailaddress', C4::Context->preference('KohaAdminEmailAddress'));
649 $session->param('ip',$session->remote_addr());
650 $session->param('lasttime',time());
652 C4::Context::set_userenv(
653 $session->param('number'), $session->param('id'),
654 $session->param('cardnumber'), $session->param('firstname'),
655 $session->param('surname'), $session->param('branch'),
656 $session->param('branchname'), $session->param('flags'),
657 $session->param('emailaddress'), $session->param('branchprinter')
659 $shelves = GetShelvesSummary($borrowernumber,2,10);
660 $session->param('shelves', $shelves);
661 C4::Context::set_shelves_userenv($shelves);
665 $info{'invalid_username_or_password'} = 1;
666 C4::Context->_unset_userenv($sessionID);
670 } # END unless ($userid)
671 my $insecure = C4::Context->boolean_preference('insecure');
673 # finished authentification, now respond
674 if ( $loggedin || $authnotrequired || ( defined($insecure) && $insecure ) )
678 $cookie = $query->cookie( CGISESSID => '' );
680 return ( $userid, $cookie, $sessionID, $flags );
685 # AUTH rejected, show the login/password template, after checking the DB.
689 # get the inputs from the incoming query
691 foreach my $name ( param $query) {
692 (next) if ( $name eq 'userid' || $name eq 'password' );
693 my $value = $query->param($name);
694 push @inputs, { name => $name, value => $value };
696 # get the branchloop, which we need for authentication
697 my $branches = GetBranches();
699 for my $branch_hash (sort keys %$branches) {
700 push @branch_loop, {branchcode => "$branch_hash", branchname => $branches->{$branch_hash}->{'branchname'}, };
703 my $template_name = ( $type eq 'opac' ) ? 'opac-auth.tmpl' : 'auth.tmpl';
704 my $template = gettemplate( $template_name, $type, $query );
705 $template->param(branchloop => \@branch_loop,);
709 suggestion => C4::Context->preference("suggestion"),
710 virtualshelves => C4::Context->preference("virtualshelves"),
711 opaclargeimage => C4::Context->preference("opaclargeimage"),
712 LibraryName => C4::Context->preference("LibraryName"),
713 opacuserlogin => C4::Context->preference("opacuserlogin"),
714 OpacNav => C4::Context->preference("OpacNav"),
715 opaccredits => C4::Context->preference("opaccredits"),
716 opacreadinghistory => C4::Context->preference("opacreadinghistory"),
717 opacsmallimage => C4::Context->preference("opacsmallimage"),
718 opaclayoutstylesheet => C4::Context->preference("opaclayoutstylesheet"),
719 opaccolorstylesheet => C4::Context->preference("opaccolorstylesheet"),
720 opaclanguagesdisplay => C4::Context->preference("opaclanguagesdisplay"),
721 opacuserjs => C4::Context->preference("opacuserjs"),
722 opacbookbag => "" . C4::Context->preference("opacbookbag"),
723 OpacCloud => C4::Context->preference("OpacCloud"),
724 OpacTopissue => C4::Context->preference("OpacTopissue"),
725 OpacAuthorities => C4::Context->preference("OpacAuthorities"),
726 OpacBrowser => C4::Context->preference("OpacBrowser"),
727 intranetcolorstylesheet =>
728 C4::Context->preference("intranetcolorstylesheet"),
729 intranetstylesheet => C4::Context->preference("intranetstylesheet"),
730 IntranetNav => C4::Context->preference("IntranetNav"),
731 intranetuserjs => C4::Context->preference("intranetuserjs"),
732 TemplateEncoding => C4::Context->preference("TemplateEncoding"),
733 IndependantBranches=> C4::Context->preference("IndependantBranches"),
734 AutoLocation => C4::Context->preference("AutoLocation"),
735 yuipath => C4::Context->preference("yuipath"),
736 wrongip => $info{'wrongip'}
739 $template->param( loginprompt => 1 ) unless $info{'nopermission'};
741 my $self_url = $query->url( -absolute => 1 );
744 LibraryName => C4::Context->preference("LibraryName"),
746 $template->param( \%info );
747 # $cookie = $query->cookie(CGISESSID => $session->id
749 print $query->header(
750 -type => 'text/html',
760 ($status, $cookie, $sessionId) = check_api_auth($query, $userflags);
762 Given a CGI query containing the parameters 'userid' and 'password' and/or a session
763 cookie, determine if the user has the privileges specified by C<$userflags>.
765 C<check_api_auth> is is meant for authenticating users of web services, and
766 consequently will always return and will not attempt to redirect the user
769 If a valid session cookie is already present, check_api_auth will return a status
770 of "ok", the cookie, and the Koha session ID.
772 If no session cookie is present, check_api_auth will check the 'userid' and 'password
773 parameters and create a session cookie and Koha session if the supplied credentials
776 Possible return values in C<$status> are:
780 =item "ok" -- user authenticated; C<$cookie> and C<$sessionid> have valid values.
782 =item "failed" -- credentials are not correct; C<$cookie> and C<$sessionid> are undef
784 =item "maintenance" -- DB is in maintenance mode; no login possible at the moment
786 =item "expired -- session cookie has expired; API user should resubmit userid and password
794 my $flagsrequired = shift;
796 my $dbh = C4::Context->dbh;
797 my $timeout = C4::Context->preference('timeout');
798 $timeout = 600 unless $timeout;
800 unless (C4::Context->preference('Version')) {
801 # database has not been installed yet
802 return ("maintenance", undef, undef);
804 my $kohaversion=C4::Context::KOHAVERSION;
805 $kohaversion =~ s/(.*\..*)\.(.*)\.(.*)/$1$2$3/;
806 if (C4::Context->preference('Version') < $kohaversion) {
807 # database in need of version update; assume that
808 # no API should be called while databsae is in
810 return ("maintenance", undef, undef);
813 # FIXME -- most of what follows is a copy-and-paste
814 # of code from checkauth. There is an obvious need
815 # for refactoring to separate the various parts of
816 # the authentication code, but as of 2007-11-19 this
817 # is deferred so as to not introduce bugs into the
818 # regular authentication code for Koha 3.0.
820 # see if we have a valid session cookie already
821 # however, if a userid parameter is present (i.e., from
822 # a form submission, assume that any current cookie
824 my $sessionID = undef;
825 unless ($query->param('userid')) {
826 $sessionID = $query->cookie("CGISESSID");
829 my $session = get_session($sessionID);
830 C4::Context->_new_userenv($sessionID);
832 C4::Context::set_userenv(
833 $session->param('number'), $session->param('id'),
834 $session->param('cardnumber'), $session->param('firstname'),
835 $session->param('surname'), $session->param('branch'),
836 $session->param('branchname'), $session->param('flags'),
837 $session->param('emailaddress'), $session->param('branchprinter')
840 my $ip = $session->param('ip');
841 my $lasttime = $session->param('lasttime');
842 my $userid = $session->param('id');
843 if ( $lasttime < time() - $timeout ) {
846 C4::Context->_unset_userenv($sessionID);
849 return ("expired", undef, undef);
850 } elsif ( $ip ne $ENV{'REMOTE_ADDR'} ) {
853 C4::Context->_unset_userenv($sessionID);
856 return ("expired", undef, undef);
858 my $cookie = $query->cookie( CGISESSID => $session->id );
859 $session->param('lasttime',time());
860 my $flags = haspermission( $dbh, $userid, $flagsrequired );
862 return ("ok", $cookie, $sessionID);
865 C4::Context->_unset_userenv($sessionID);
868 return ("failed", undef, undef);
872 return ("expired", undef, undef);
876 my $userid = $query->param('userid');
877 my $password = $query->param('password');
878 unless ($userid and $password) {
879 # caller did something wrong, fail the authenticateion
880 return ("failed", undef, undef);
882 my ( $return, $cardnumber ) = checkpw( $dbh, $userid, $password );
883 if ($return and haspermission( $dbh, $userid, $flagsrequired)) {
884 my $session = get_session("");
885 return ("failed", undef, undef) unless $session;
887 my $sessionID = $session->id;
888 C4::Context->_new_userenv($sessionID);
889 my $cookie = $query->cookie(CGISESSID => $sessionID);
890 if ( $return == 1 ) {
892 $borrowernumber, $firstname, $surname,
893 $userflags, $branchcode, $branchname,
894 $branchprinter, $emailaddress
898 "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=?"
900 $sth->execute($userid);
902 $borrowernumber, $firstname, $surname,
903 $userflags, $branchcode, $branchname,
904 $branchprinter, $emailaddress
905 ) = $sth->fetchrow if ( $sth->rows );
907 unless ($sth->rows ) {
908 my $sth = $dbh->prepare(
909 "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=?"
911 $sth->execute($cardnumber);
913 $borrowernumber, $firstname, $surname,
914 $userflags, $branchcode, $branchname,
915 $branchprinter, $emailaddress
916 ) = $sth->fetchrow if ( $sth->rows );
918 unless ( $sth->rows ) {
919 $sth->execute($userid);
921 $borrowernumber, $firstname, $surname, $userflags,
922 $branchcode, $branchname, $branchprinter, $emailaddress
923 ) = $sth->fetchrow if ( $sth->rows );
927 my $ip = $ENV{'REMOTE_ADDR'};
928 # if they specify at login, use that
929 if ($query->param('branch')) {
930 $branchcode = $query->param('branch');
931 $branchname = GetBranchName($branchcode);
933 my $branches = GetBranches();
935 foreach my $br ( keys %$branches ) {
936 # now we work with the treatment of ip
937 my $domain = $branches->{$br}->{'branchip'};
938 if ( $domain && $ip =~ /^$domain/ ) {
939 $branchcode = $branches->{$br}->{'branchcode'};
941 # new op dev : add the branchprinter and branchname in the cookie
942 $branchprinter = $branches->{$br}->{'branchprinter'};
943 $branchname = $branches->{$br}->{'branchname'};
946 $session->param('number',$borrowernumber);
947 $session->param('id',$userid);
948 $session->param('cardnumber',$cardnumber);
949 $session->param('firstname',$firstname);
950 $session->param('surname',$surname);
951 $session->param('branch',$branchcode);
952 $session->param('branchname',$branchname);
953 $session->param('flags',$userflags);
954 $session->param('emailaddress',$emailaddress);
955 $session->param('ip',$session->remote_addr());
956 $session->param('lasttime',time());
957 } elsif ( $return == 2 ) {
958 #We suppose the user is the superlibrarian
959 $session->param('number',0);
960 $session->param('id',C4::Context->config('user'));
961 $session->param('cardnumber',C4::Context->config('user'));
962 $session->param('firstname',C4::Context->config('user'));
963 $session->param('surname',C4::Context->config('user'));
964 $session->param('branch','NO_LIBRARY_SET');
965 $session->param('branchname','NO_LIBRARY_SET');
966 $session->param('flags',1);
967 $session->param('emailaddress', C4::Context->preference('KohaAdminEmailAddress'));
968 $session->param('ip',$session->remote_addr());
969 $session->param('lasttime',time());
971 C4::Context::set_userenv(
972 $session->param('number'), $session->param('id'),
973 $session->param('cardnumber'), $session->param('firstname'),
974 $session->param('surname'), $session->param('branch'),
975 $session->param('branchname'), $session->param('flags'),
976 $session->param('emailaddress'), $session->param('branchprinter')
978 return ("ok", $cookie, $sessionID);
980 return ("failed", undef, undef);
985 =item check_cookie_auth
987 ($status, $sessionId) = check_api_auth($cookie, $userflags);
989 Given a CGISESSID cookie set during a previous login to Koha, determine
990 if the user has the privileges specified by C<$userflags>.
992 C<check_cookie_auth> is meant for authenticating special services
993 such as tools/upload-file.pl that are invoked by other pages that
994 have been authenticated in the usual way.
996 Possible return values in C<$status> are:
1000 =item "ok" -- user authenticated; C<$sessionID> have valid values.
1002 =item "failed" -- credentials are not correct; C<$sessionid> are undef
1004 =item "maintenance" -- DB is in maintenance mode; no login possible at the moment
1006 =item "expired -- session cookie has expired; API user should resubmit userid and password
1012 sub check_cookie_auth {
1014 my $flagsrequired = shift;
1016 my $dbh = C4::Context->dbh;
1017 my $timeout = C4::Context->preference('timeout');
1018 $timeout = 600 unless $timeout;
1020 unless (C4::Context->preference('Version')) {
1021 # database has not been installed yet
1022 return ("maintenance", undef);
1024 my $kohaversion=C4::Context::KOHAVERSION;
1025 $kohaversion =~ s/(.*\..*)\.(.*)\.(.*)/$1$2$3/;
1026 if (C4::Context->preference('Version') < $kohaversion) {
1027 # database in need of version update; assume that
1028 # no API should be called while databsae is in
1030 return ("maintenance", undef);
1033 # FIXME -- most of what follows is a copy-and-paste
1034 # of code from checkauth. There is an obvious need
1035 # for refactoring to separate the various parts of
1036 # the authentication code, but as of 2007-11-23 this
1037 # is deferred so as to not introduce bugs into the
1038 # regular authentication code for Koha 3.0.
1040 # see if we have a valid session cookie already
1041 # however, if a userid parameter is present (i.e., from
1042 # a form submission, assume that any current cookie
1044 unless (defined $cookie and $cookie) {
1045 return ("failed", undef);
1047 my $sessionID = $cookie;
1048 my $session = get_session($sessionID);
1049 C4::Context->_new_userenv($sessionID);
1051 C4::Context::set_userenv(
1052 $session->param('number'), $session->param('id'),
1053 $session->param('cardnumber'), $session->param('firstname'),
1054 $session->param('surname'), $session->param('branch'),
1055 $session->param('branchname'), $session->param('flags'),
1056 $session->param('emailaddress'), $session->param('branchprinter')
1059 my $ip = $session->param('ip');
1060 my $lasttime = $session->param('lasttime');
1061 my $userid = $session->param('id');
1062 if ( $lasttime < time() - $timeout ) {
1065 C4::Context->_unset_userenv($sessionID);
1068 return ("expired", undef);
1069 } elsif ( $ip ne $ENV{'REMOTE_ADDR'} ) {
1070 # IP address changed
1072 C4::Context->_unset_userenv($sessionID);
1075 return ("expired", undef);
1077 $session->param('lasttime',time());
1078 my $flags = haspermission( $dbh, $userid, $flagsrequired );
1080 return ("ok", $sessionID);
1083 C4::Context->_unset_userenv($sessionID);
1086 return ("failed", undef);
1090 return ("expired", undef);
1097 my $session = get_session($sessionID);
1099 Given a session ID, retrieve the CGI::Session object used to store
1100 the session's state. The session object can be used to store
1101 data that needs to be accessed by different scripts during a
1104 If the C<$sessionID> parameter is an empty string, a new session
1110 my $sessionID = shift;
1111 my $storage_method = C4::Context->preference('SessionStorage');
1112 my $dbh = C4::Context->dbh;
1114 if ($storage_method eq 'mysql'){
1115 $session = new CGI::Session("driver:MySQL;serializer:yaml", $sessionID, {Handle=>$dbh});
1117 elsif ($storage_method eq 'Pg') {
1118 $session = new CGI::Session("driver:PostgreSQL;serializer:yaml", $sessionID, {Handle=>$dbh});
1121 # catch all defaults to tmp should work on all systems
1122 $session = new CGI::Session("driver:File;serializer:yaml", $sessionID, {Directory=>'/tmp'});
1129 my ( $dbh, $userid, $password ) = @_;
1131 $debug and print "## checkpw - checking LDAP\n";
1132 my ($retval,$retcard) = checkpw_ldap(@_); # EXTERNAL AUTH
1133 ($retval) and return ($retval,$retcard);
1139 "select password,cardnumber,borrowernumber,userid,firstname,surname,branchcode,flags from borrowers where userid=?"
1141 $sth->execute($userid);
1143 my ( $md5password, $cardnumber, $borrowernumber, $userid, $firstname,
1144 $surname, $branchcode, $flags )
1146 if ( md5_base64($password) eq $md5password ) {
1148 C4::Context->set_userenv( "$borrowernumber", $userid, $cardnumber,
1149 $firstname, $surname, $branchcode, $flags );
1150 return 1, $cardnumber;
1155 "select password,cardnumber,borrowernumber,userid, firstname,surname,branchcode,flags from borrowers where cardnumber=?"
1157 $sth->execute($userid);
1159 my ( $md5password, $cardnumber, $borrowernumber, $userid, $firstname,
1160 $surname, $branchcode, $flags )
1162 if ( md5_base64($password) eq $md5password ) {
1164 C4::Context->set_userenv( $borrowernumber, $userid, $cardnumber,
1165 $firstname, $surname, $branchcode, $flags );
1169 if ( $userid && $userid eq C4::Context->config('user')
1170 && "$password" eq C4::Context->config('pass') )
1173 # Koha superuser account
1174 # C4::Context->set_userenv(0,0,C4::Context->config('user'),C4::Context->config('user'),C4::Context->config('user'),"",1);
1177 if ( $userid && $userid eq 'demo'
1178 && "$password" eq 'demo'
1179 && C4::Context->config('demo') )
1182 # DEMO => the demo user is allowed to do everything (if demo set to 1 in koha.conf
1183 # some features won't be effective : modify systempref, modify MARC structure,
1191 $authflags = getuserflags($flags,$dbh);
1192 Translates integer flags into permissions strings hash.
1194 C<$flags> is the integer userflags value ( borrowers.userflags )
1195 C<$authflags> is a hashref of permissions
1204 $flags = 0 unless $flags;
1205 my $sth = $dbh->prepare("SELECT bit, flag, defaulton FROM userflags");
1208 while ( my ( $bit, $flag, $defaulton ) = $sth->fetchrow ) {
1209 if ( ( $flags & ( 2**$bit ) ) || $defaulton ) {
1210 $userflags->{$flag} = 1;
1213 $userflags->{$flag} = 0;
1217 # get subpermissions and merge with top-level permissions
1218 my $user_subperms = get_user_subpermissions($userid);
1219 foreach my $module (keys %$user_subperms) {
1220 next if $userflags->{$module} == 1; # user already has permission for everything in this module
1221 $userflags->{$module} = $user_subperms->{$module};
1227 =item get_user_subpermissions
1231 my $user_perm_hashref = get_user_subpermissions($userid);
1235 Given the userid (note, not the borrowernumber) of a staff user,
1236 return a hashref of hashrefs of the specific subpermissions
1237 accorded to the user. An example return is
1241 export_catalog => 1,
1242 import_patrons => 1,
1246 The top-level hash-key is a module or function code from
1247 userflags.flag, while the second-level key is a code
1250 The results of this function do not give a complete picture
1251 of the functions that a staff user can access; it is also
1252 necessary to check borrowers.flags.
1256 sub get_user_subpermissions {
1259 my $dbh = C4::Context->dbh;
1260 my $sth = $dbh->prepare("SELECT flag, code
1261 FROM user_permissions
1262 JOIN permissions USING (module_bit, code)
1263 JOIN userflags ON (module_bit = bit)
1264 JOIN borrowers USING (borrowernumber)
1266 $sth->execute($userid);
1268 my $user_perms = {};
1269 while (my $perm = $sth->fetchrow_hashref) {
1270 $user_perms->{$perm->{'flag'}}->{$perm->{'code'}} = 1;
1275 =item get_all_subpermissions
1279 my $perm_hashref = get_all_subpermissions();
1283 Returns a hashref of hashrefs defining all specific
1284 permissions currently defined. The return value
1285 has the same structure as that of C<get_user_subpermissions>,
1286 except that the innermost hash value is the description
1287 of the subpermission.
1291 sub get_all_subpermissions {
1292 my $dbh = C4::Context->dbh;
1293 my $sth = $dbh->prepare("SELECT flag, code, description
1295 JOIN userflags ON (module_bit = bit)");
1299 while (my $perm = $sth->fetchrow_hashref) {
1300 $all_perms->{$perm->{'flag'}}->{$perm->{'code'}} = $perm->{'description'};
1307 $flags = ($dbh,$member,$flagsrequired);
1309 C<$member> may be either userid or overloaded with $borrower hashref from GetMemberDetails.
1310 C<$flags> is a hashref of required flags like C<$borrower-<{authflags}>
1312 Returns member's flags or 0 if a permission is not met.
1317 my ( $dbh, $userid, $flagsrequired ) = @_;
1318 my ($flags,$intflags);
1319 $dbh=C4::Context->dbh unless($dbh);
1321 $intflags = $userid->{'flags'};
1323 my $sth = $dbh->prepare("SELECT flags FROM borrowers WHERE userid=?");
1324 $sth->execute($userid);
1325 my ($intflags) = $sth->fetchrow;
1326 $flags = getuserflags( $intflags, $userid, $dbh );
1328 if ( $userid eq C4::Context->config('user') ) {
1329 # Super User Account from /etc/koha.conf
1330 $flags->{'superlibrarian'} = 1;
1332 if ( $userid eq 'demo' && C4::Context->config('demo') ) {
1333 # Demo user that can do "anything" (demo=1 in /etc/koha.conf)
1334 $flags->{'superlibrarian'} = 1;
1336 return $flags if $flags->{superlibrarian};
1337 foreach my $module ( keys %$flagsrequired ) {
1338 if (C4::Context->preference('GranularPermissions')) {
1339 my $subperm = $flagsrequired->{$module};
1340 if ($subperm eq '*') {
1341 return 0 unless ( $flags->{$module} == 1 or ref($flags->{$module}) );
1343 return 0 unless ( $flags->{$module} == 1 or
1344 ( ref($flags->{$module}) and
1345 exists $flags->{$module}->{$subperm} and
1346 $flags->{$module}->{$subperm} == 1
1351 return 0 unless ( $flags->{$module} );
1355 #FIXME - This fcn should return the failed permission so a suitable error msg can be delivered.
1359 sub getborrowernumber {
1361 my $dbh = C4::Context->dbh;
1362 for my $field ( 'userid', 'cardnumber' ) {
1364 $dbh->prepare("select borrowernumber from borrowers where $field=?");
1365 $sth->execute($userid);
1367 my ($bnumber) = $sth->fetchrow;
1374 END { } # module clean-up code here (global destructor)