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
94 =item get_template_and_user
96 my ($template, $borrowernumber, $cookie)
97 = get_template_and_user(
99 template_name => "opac-main.tmpl",
102 authnotrequired => 1,
103 flagsrequired => {borrow => 1},
107 This call passes the C<query>, C<flagsrequired> and C<authnotrequired>
108 to C<&checkauth> (in this module) to perform authentification.
109 See C<&checkauth> for an explanation of these parameters.
111 The C<template_name> is then used to find the correct template for
112 the page. The authenticated users details are loaded onto the
113 template in the HTML::Template LOOP variable C<USER_INFO>. Also the
114 C<sessionID> is passed to the template. This can be used in templates
115 if cookies are disabled. It needs to be put as and input to every
118 More information on the C<gettemplate> sub can be found in the
123 sub get_template_and_user {
126 gettemplate( $in->{'template_name'}, $in->{'type'}, $in->{'query'} );
127 my ( $user, $cookie, $sessionID, $flags ) = checkauth(
129 $in->{'authnotrequired'},
130 $in->{'flagsrequired'},
132 ) unless ($in->{'template_name'}=~/maintenance/);
135 my $insecure = C4::Context->preference('insecure');
136 if ($user or $insecure) {
138 # load the template variables for stylesheets and JavaScript
139 $template->param( css_libs => $in->{'css_libs'} );
140 $template->param( css_module => $in->{'css_module'} );
141 $template->param( css_page => $in->{'css_page'} );
142 $template->param( css_widgets => $in->{'css_widgets'} );
144 $template->param( js_libs => $in->{'js_libs'} );
145 $template->param( js_module => $in->{'js_module'} );
146 $template->param( js_page => $in->{'js_page'} );
147 $template->param( js_widgets => $in->{'js_widgets'} );
150 $template->param( loggedinusername => $user );
151 $template->param( sessionID => $sessionID );
153 $borrowernumber = getborrowernumber($user);
154 my ( $borr, $alternativeflags ) =
155 GetMemberDetails( $borrowernumber );
158 $template->param( "USER_INFO" => \@bordat );
160 # We are going to use the $flags returned by checkauth
161 # to create the template's parameters that will indicate
162 # which menus the user can access.
163 if (( $flags && $flags->{superlibrarian}==1) or $insecure==1) {
164 $template->param( CAN_user_circulate => 1 );
165 $template->param( CAN_user_catalogue => 1 );
166 $template->param( CAN_user_parameters => 1 );
167 $template->param( CAN_user_borrowers => 1 );
168 $template->param( CAN_user_permission => 1 );
169 $template->param( CAN_user_reserveforothers => 1 );
170 $template->param( CAN_user_borrow => 1 );
171 $template->param( CAN_user_editcatalogue => 1 );
172 $template->param( CAN_user_updatecharge => 1 );
173 $template->param( CAN_user_acquisition => 1 );
174 $template->param( CAN_user_management => 1 );
175 $template->param( CAN_user_tools => 1 );
176 $template->param( CAN_user_editauthorities => 1 );
177 $template->param( CAN_user_serials => 1 );
178 $template->param( CAN_user_reports => 1 );
181 if ( $flags && $flags->{circulate} == 1 ) {
182 $template->param( CAN_user_circulate => 1 );
185 if ( $flags && $flags->{catalogue} == 1 ) {
186 $template->param( CAN_user_catalogue => 1 );
189 if ( $flags && $flags->{parameters} == 1 ) {
190 $template->param( CAN_user_parameters => 1 );
191 $template->param( CAN_user_management => 1 );
194 if ( $flags && $flags->{borrowers} == 1 ) {
195 $template->param( CAN_user_borrowers => 1 );
198 if ( $flags && $flags->{permissions} == 1 ) {
199 $template->param( CAN_user_permission => 1 );
202 if ( $flags && $flags->{reserveforothers} == 1 ) {
203 $template->param( CAN_user_reserveforothers => 1 );
206 if ( $flags && $flags->{borrow} == 1 ) {
207 $template->param( CAN_user_borrow => 1 );
210 if ( $flags && $flags->{editcatalogue} == 1 ) {
211 $template->param( CAN_user_editcatalogue => 1 );
214 if ( $flags && $flags->{updatecharges} == 1 ) {
215 $template->param( CAN_user_updatecharge => 1 );
218 if ( $flags && $flags->{acquisition} == 1 ) {
219 $template->param( CAN_user_acquisition => 1 );
222 if ( $flags && $flags->{tools} == 1 ) {
223 $template->param( CAN_user_tools => 1 );
226 if ( $flags && $flags->{editauthorities} == 1 ) {
227 $template->param( CAN_user_editauthorities => 1 );
230 if ( $flags && $flags->{serials} == 1 ) {
231 $template->param( CAN_user_serials => 1 );
234 if ( $flags && $flags->{reports} == 1 ) {
235 $template->param( CAN_user_reports => 1 );
238 if ( $in->{'type'} eq "intranet" ) {
240 intranetcolorstylesheet => C4::Context->preference("intranetcolorstylesheet"),
241 intranetstylesheet => C4::Context->preference("intranetstylesheet"),
242 IntranetNav => C4::Context->preference("IntranetNav"),
243 intranetuserjs => C4::Context->preference("intranetuserjs"),
244 TemplateEncoding => C4::Context->preference("TemplateEncoding"),
245 AmazonContent => C4::Context->preference("AmazonContent"),
246 LibraryName => C4::Context->preference("LibraryName"),
247 LoginBranchcode => (C4::Context->userenv?C4::Context->userenv->{"branch"}:"insecure"),
248 LoginBranchname => (C4::Context->userenv?C4::Context->userenv->{"branchname"}:"insecure"),
249 LoginFirstname => (C4::Context->userenv?C4::Context->userenv->{"firstname"}:"Bel"),
250 LoginSurname => C4::Context->userenv?C4::Context->userenv->{"surname"}:"Inconnu",
251 AutoLocation => C4::Context->preference("AutoLocation"),
252 hide_marc => C4::Context->preference("hide_marc"),
253 patronimages => C4::Context->preference("patronimages"),
254 "BiblioDefaultView".C4::Context->preference("IntranetBiblioDefaultView") => 1,
255 advancedMARCEditor => C4::Context->preference("advancedMARCEditor"),
256 suggestion => C4::Context->preference("suggestion"),
257 virtualshelves => C4::Context->preference("virtualshelves"),
258 LibraryName => C4::Context->preference("LibraryName"),
259 KohaAdminEmailAddress => "" . C4::Context->preference("KohaAdminEmailAddress"),
260 IntranetmainUserblock => C4::Context->preference("IntranetmainUserblock"),
261 IndependantBranches => C4::Context->preference("IndependantBranches"),
262 CircAutocompl => C4::Context->preference("CircAutocompl"),
263 yuipath => C4::Context->preference("yuipath"),
267 warn "template type should be OPAC, here it is=[" . $in->{'type'} . "]" unless ( $in->{'type'} eq 'opac' );
268 my $LibraryNameTitle = C4::Context->preference("LibraryName");
269 $LibraryNameTitle =~ s/<(?:\/?)(?:br|p)\s*(?:\/?)>/ /sgi;
270 $LibraryNameTitle =~ s/<(?:[^<>'"]|'(?:[^']*)'|"(?:[^"]*)")*>//sg;
272 KohaAdminEmailAddress => "" . C4::Context->preference("KohaAdminEmailAddress"),
273 AnonSuggestions => "" . C4::Context->preference("AnonSuggestions"),
274 suggestion => "" . C4::Context->preference("suggestion"),
275 virtualshelves => "" . C4::Context->preference("virtualshelves"),
276 OpacNav => "" . C4::Context->preference("OpacNav"),
277 opacheader => "" . C4::Context->preference("opacheader"),
278 opaccredits => "" . C4::Context->preference("opaccredits"),
279 opacsmallimage => "" . C4::Context->preference("opacsmallimage"),
280 opaclargeimage => "" . C4::Context->preference("opaclargeimage"),
281 opaclayoutstylesheet => "". C4::Context->preference("opaclayoutstylesheet"),
282 opaccolorstylesheet => "". C4::Context->preference("opaccolorstylesheet"),
283 opaclanguagesdisplay => "". C4::Context->preference("opaclanguagesdisplay"),
284 opacuserlogin => "" . C4::Context->preference("opacuserlogin"),
285 opacbookbag => "" . C4::Context->preference("opacbookbag"),
286 TemplateEncoding => "". C4::Context->preference("TemplateEncoding"),
287 AmazonContent => "" . C4::Context->preference("AmazonContent"),
288 LibraryName => "" . C4::Context->preference("LibraryName"),
289 LibraryNameTitle => "" . $LibraryNameTitle,
290 LoginBranchcode => (C4::Context->userenv?C4::Context->userenv->{"branch"}:"insecure"),
291 LoginBranchname => C4::Context->userenv?C4::Context->userenv->{"branchname"}:"",
292 LoginFirstname => (C4::Context->userenv?C4::Context->userenv->{"firstname"}:"Bel"),
293 LoginSurname => C4::Context->userenv?C4::Context->userenv->{"surname"}:"Inconnu",
294 OpacPasswordChange => C4::Context->preference("OpacPasswordChange"),
295 opacreadinghistory => C4::Context->preference("opacreadinghistory"),
296 opacuserjs => C4::Context->preference("opacuserjs"),
297 OpacCloud => C4::Context->preference("OpacCloud"),
298 OpacTopissue => C4::Context->preference("OpacTopissue"),
299 OpacAuthorities => C4::Context->preference("OpacAuthorities"),
300 OpacBrowser => C4::Context->preference("OpacBrowser"),
301 RequestOnOpac => C4::Context->preference("RequestOnOpac"),
302 reviewson => C4::Context->preference("reviewson"),
303 hide_marc => C4::Context->preference("hide_marc"),
304 patronimages => C4::Context->preference("patronimages"),
305 mylibraryfirst => C4::Context->preference("SearchMyLibraryFirst"),
306 "BiblioDefaultView".C4::Context->preference("BiblioDefaultView") => 1,
309 return ( $template, $borrowernumber, $cookie );
314 ($userid, $cookie, $sessionID) = &checkauth($query, $noauth, $flagsrequired, $type);
316 Verifies that the user is authorized to run this script. If
317 the user is authorized, a (userid, cookie, session-id, flags)
318 quadruple is returned. If the user is not authorized but does
319 not have the required privilege (see $flagsrequired below), it
320 displays an error page and exits. Otherwise, it displays the
321 login page and exits.
323 Note that C<&checkauth> will return if and only if the user
324 is authorized, so it should be called early on, before any
325 unfinished operations (e.g., if you've opened a file, then
326 C<&checkauth> won't close it for you).
328 C<$query> is the CGI object for the script calling C<&checkauth>.
330 The C<$noauth> argument is optional. If it is set, then no
331 authorization is required for the script.
333 C<&checkauth> fetches user and session information from C<$query> and
334 ensures that the user is authorized to run scripts that require
337 The C<$flagsrequired> argument specifies the required privileges
338 the user must have if the username and password are correct.
339 It should be specified as a reference-to-hash; keys in the hash
340 should be the "flags" for the user, as specified in the Members
341 intranet module. Any key specified must correspond to a "flag"
342 in the userflags table. E.g., { circulate => 1 } would specify
343 that the user must have the "circulate" privilege in order to
344 proceed. To make sure that access control is correct, the
345 C<$flagsrequired> parameter must be specified correctly.
347 The C<$type> argument specifies whether the template should be
348 retrieved from the opac or intranet directory tree. "opac" is
349 assumed if it is not specified; however, if C<$type> is specified,
350 "intranet" is assumed if it is not "opac".
352 If C<$query> does not have a valid session ID associated with it
353 (i.e., the user has not logged in) or if the session has expired,
354 C<&checkauth> presents the user with a login page (from the point of
355 view of the original script, C<&checkauth> does not return). Once the
356 user has authenticated, C<&checkauth> restarts the original script
357 (this time, C<&checkauth> returns).
359 The login page is provided using a HTML::Template, which is set in the
360 systempreferences table or at the top of this file. The variable C<$type>
361 selects which template to use, either the opac or the intranet
362 authentification template.
364 C<&checkauth> returns a user ID, a cookie, and a session ID. The
365 cookie should be sent back to the browser; it verifies that the user
372 # warn "Checking Auth";
373 # $authnotrequired will be set for scripts which will run without authentication
374 my $authnotrequired = shift;
375 my $flagsrequired = shift;
377 $type = 'opac' unless $type;
379 my $dbh = C4::Context->dbh;
380 my $timeout = C4::Context->preference('timeout');
381 $timeout = 600 unless $timeout;
384 # If Version syspref is unavailable, it means Koha is beeing installed,
385 # and so we must redirect to OPAC maintenance page or to the WebInstaller
386 #warn "about to check version";
387 unless (C4::Context->preference('Version')) {
388 if ($type ne 'opac') {
389 warn "Install required, redirecting to Installer";
390 print $query->redirect("/cgi-bin/koha/installer/install.pl");
393 warn "OPAC Install required, redirecting to maintenance";
394 print $query->redirect("/cgi-bin/koha/maintenance.pl");
403 my ( $userid, $cookie, $sessionID, $flags );
404 my $logout = $query->param('logout.x');
405 if ( $userid = $ENV{'REMOTE_USER'} ) {
406 # Using Basic Authentication, no cookies required
407 $cookie = $query->cookie(
408 -name => 'CGISESSID',
414 elsif ( $sessionID = $query->cookie("CGISESSID")) {
415 my $storage_method = C4::Context->preference('SessionStorage');
417 if ($storage_method eq 'mysql'){
418 $session = new CGI::Session("driver:MySQL", $sessionID, {Handle=>$dbh});
420 elsif ($storage_method eq 'Pg') {
421 $session = new CGI::Session("driver:PostgreSQL", $sessionID, {Handle=>$dbh});
424 # catch all defaults to tmp should work on all systems
425 $session = new CGI::Session("driver:File", $sessionID, {Directory=>'/tmp'});
427 C4::Context->_new_userenv($sessionID);
429 C4::Context::set_userenv(
430 $session->param('number'), $session->param('id'),
431 $session->param('cardnumber'), $session->param('firstname'),
432 $session->param('surname'), $session->param('branch'),
433 $session->param('branchname'), $session->param('flags'),
434 $session->param('emailaddress'), $session->param('branchprinter')
436 # warn "".$session->param('cardnumber').", ".$session->param('firstname').",
437 # ".$session->param('surname').", ".$session->param('branch');
442 $ip = $session->param('ip');
443 $lasttime = $session->param('lasttime');
444 $userid = $session->param('id');
450 # voluntary logout the user
454 C4::Context->_unset_userenv($sessionID);
457 open L, ">>/tmp/sessionlog";
458 my $time = localtime( time() );
459 printf L "%20s from %16s logged out at %30s (manually).\n", $userid,
464 if ( $lasttime < time() - $timeout ) {
466 $info{'timed_out'} = 1;
468 C4::Context->_unset_userenv($sessionID);
471 open L, ">>/tmp/sessionlog";
472 my $time = localtime( time() );
473 printf L "%20s from %16s logged out at %30s (inactivity).\n",
477 elsif ( $ip ne $ENV{'REMOTE_ADDR'} ) {
478 # Different ip than originally logged in from
479 $info{'oldip'} = $ip;
480 $info{'newip'} = $ENV{'REMOTE_ADDR'};
481 $info{'different_ip'} = 1;
483 C4::Context->_unset_userenv($sessionID);
486 open L, ">>/tmp/sessionlog";
487 my $time = localtime( time() );
489 "%20s from logged out at %30s (ip changed from %16s to %16s).\n",
490 $userid, $time, $ip, $info{'newip'};
494 $cookie = $query->cookie( CGISESSID => $session->id );
495 $session->param('lasttime',time());
496 $flags = haspermission( $dbh, $userid, $flagsrequired );
501 $info{'nopermission'} = 1;
507 my $storage_method = C4::Context->preference('SessionStorage');
509 if ($storage_method eq 'mysql'){
510 $session = new CGI::Session("driver:MySQL", $sessionID, {Handle=>$dbh});
512 elsif ($storage_method eq 'Pg') {
513 $session = new CGI::Session("driver:PostgreSQL", $sessionID, {Handle=>$dbh});
516 # catch all defaults to tmp should work on all systems
517 $session = new CGI::Session("driver:File", $sessionID, {Directory=>'/tmp'});
522 $sessionID = $session->id;
524 $userid = $query->param('userid');
525 C4::Context->_new_userenv($sessionID);
526 my $password = $query->param('password');
527 C4::Context->_new_userenv($sessionID);
528 my ( $return, $cardnumber ) = checkpw( $dbh, $userid, $password );
530 open L, ">>/tmp/sessionlog";
531 my $time = localtime( time() );
532 printf L "%20s from %16s logged in at %30s.\n", $userid,
533 $ENV{'REMOTE_ADDR'}, $time;
535 $cookie = $query->cookie(CGISESSID => $sessionID);
536 if ( $flags = haspermission( $dbh, $userid, $flagsrequired ) ) {
540 $info{'nopermission'} = 1;
541 C4::Context->_unset_userenv($sessionID);
543 if ( $return == 1 ) {
545 $borrowernumber, $firstname, $surname,
546 $userflags, $branchcode, $branchname,
547 $branchprinter, $emailaddress
551 "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=?"
553 $sth->execute($userid);
555 $borrowernumber, $firstname, $surname,
556 $userflags, $branchcode, $branchname,
557 $branchprinter, $emailaddress
562 # warn "$cardnumber,$borrowernumber,$userid,$firstname,$surname,$userflags,$branchcode,$emailaddress";
563 unless ( $sth->rows ) {
566 "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=?"
568 $sth->execute($cardnumber);
570 $borrowernumber, $firstname, $surname,
571 $userflags, $branchcode, $branchname,
572 $branchprinter, $emailaddress
577 # warn "$cardnumber,$borrowernumber,$userid,$firstname,$surname,$userflags,$branchcode,$emailaddress";
578 unless ( $sth->rows ) {
579 $sth->execute($userid);
581 $borrowernumber, $firstname, $surname, $userflags,
582 $branchcode, $branchname, $branchprinter, $emailaddress
589 # 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.
590 my $ip = $ENV{'REMOTE_ADDR'};
591 # if they specify at login, use that
592 if ($query->param('branch')) {
593 $branchcode = $query->param('branch');
594 $branchname = GetBranchName($branchcode);
596 my $branches = GetBranches();
598 foreach my $br ( keys %$branches ) {
599 # now we work with the treatment of ip
600 my $domain = $branches->{$br}->{'branchip'};
601 if ( $domain && $ip =~ /^$domain/ ) {
602 $branchcode = $branches->{$br}->{'branchcode'};
604 # new op dev : add the branchprinter and branchname in the cookie
605 $branchprinter = $branches->{$br}->{'branchprinter'};
606 $branchname = $branches->{$br}->{'branchname'};
609 $session->param('number',$borrowernumber);
610 $session->param('id',$userid);
611 $session->param('cardnumber',$cardnumber);
612 $session->param('firstname',$firstname);
613 $session->param('surname',$surname);
614 $session->param('branch',$branchcode);
615 $session->param('branchname',$branchname);
616 $session->param('flags',$userflags);
617 $session->param('emailaddress',$emailaddress);
618 $session->param('ip',$session->remote_addr());
619 $session->param('lasttime',time());
620 # warn "".$session->param('cardnumber').", ".$session->param('firstname').",
621 # ".$session->param('surname').", ".$session->param('branch');
623 elsif ( $return == 2 ) {
624 #We suppose the user is the superlibrarian
625 $session->param('number',0);
626 $session->param('id',C4::Context->config('user'));
627 $session->param('cardnumber',C4::Context->config('user'));
628 $session->param('firstname',C4::Context->config('user'));
629 $session->param('surname',C4::Context->config('user'));
630 $session->param('branch','NO_LIBRARY_SET');
631 $session->param('branchname','NO_LIBRARY_SET');
632 $session->param('flags',1);
633 $session->param('emailaddress', C4::Context->preference('KohaAdminEmailAddress'));
634 $session->param('ip',$session->remote_addr());
635 $session->param('lasttime',time());
638 C4::Context::set_userenv(
639 $session->param('number'), $session->param('id'),
640 $session->param('cardnumber'), $session->param('firstname'),
641 $session->param('surname'), $session->param('branch'),
642 $session->param('branchname'), $session->param('flags'),
643 $session->param('emailaddress'), $session->param('branchprinter')
650 $info{'invalid_username_or_password'} = 1;
651 C4::Context->_unset_userenv($sessionID);
655 my $insecure = C4::Context->boolean_preference('insecure');
657 # finished authentification, now respond
658 if ( $loggedin || $authnotrequired || ( defined($insecure) && $insecure ) )
662 $cookie = $query->cookie( CGISESSID => ''
665 return ( $userid, $cookie, $sessionID, $flags );
671 # AUTH rejected, show the login/password template, after checking the DB.
675 # get the inputs from the incoming query
677 foreach my $name ( param $query) {
678 (next) if ( $name eq 'userid' || $name eq 'password' );
679 my $value = $query->param($name);
680 push @inputs, { name => $name, value => $value };
682 # get the branchloop, which we need for authentication
683 my $branches = GetBranches();
685 for my $branch_hash (keys %$branches) {
686 push @branch_loop, {branchcode => "$branch_hash", branchname => $branches->{$branch_hash}->{'branchname'}, };
689 # check that database and koha version are the same
690 # there is no DB version, it's a fresh install,
691 # go to web installer
692 # there is a DB version, compare it to the code version
693 my $kohaversion=C4::Context::KOHAVERSION;
694 # remove the 3 last . to have a Perl number
695 $kohaversion =~ s/(.*\..*)\.(.*)\.(.*)/$1$2$3/;
696 # warn "kohaversion : $kohaversion";
697 if (C4::Context->preference('Version') < $kohaversion){
698 if ($type ne 'opac'){
699 warn "Database update needed, redirecting to Installer. Database is ".C4::Context->preference('Version')." and Koha is : ".C4::Context->config("kohaversion");
700 print $query->redirect("/cgi-bin/koha/installer/install.pl?step=3");
702 warn "OPAC :Database update needed, redirecting to maintenance. Database is ".C4::Context->preference('Version')." and Koha is : ".C4::Context->config("kohaversion");
703 print $query->redirect("/cgi-bin/koha/maintenance.pl");
708 if ( $type eq 'opac' ) {
709 $template_name = "opac-auth.tmpl";
712 $template_name = "auth.tmpl";
714 my $template = gettemplate( $template_name, $type, $query );
715 $template->param(branchloop => \@branch_loop,);
719 suggestion => C4::Context->preference("suggestion"),
720 virtualshelves => C4::Context->preference("virtualshelves"),
721 opaclargeimage => C4::Context->preference("opaclargeimage"),
722 LibraryName => C4::Context->preference("LibraryName"),
723 OpacNav => C4::Context->preference("OpacNav"),
724 opaccredits => C4::Context->preference("opaccredits"),
725 opacreadinghistory => C4::Context->preference("opacreadinghistory"),
726 opacsmallimage => C4::Context->preference("opacsmallimage"),
727 opaclayoutstylesheet => C4::Context->preference("opaclayoutstylesheet"),
728 opaccolorstylesheet => C4::Context->preference("opaccolorstylesheet"),
729 opaclanguagesdisplay => C4::Context->preference("opaclanguagesdisplay"),
730 opacuserjs => C4::Context->preference("opacuserjs"),
732 intranetcolorstylesheet =>
733 C4::Context->preference("intranetcolorstylesheet"),
734 intranetstylesheet => C4::Context->preference("intranetstylesheet"),
735 IntranetNav => C4::Context->preference("IntranetNav"),
736 intranetuserjs => C4::Context->preference("intranetuserjs"),
737 TemplateEncoding => C4::Context->preference("TemplateEncoding"),
738 IndependantBranches => C4::Context->preference("IndependantBranches"),
739 AutoLocation => C4::Context->preference("AutoLocation"),
741 $template->param( loginprompt => 1 ) unless $info{'nopermission'};
743 my $self_url = $query->url( -absolute => 1 );
746 LibraryName => => C4::Context->preference("LibraryName"),
748 $template->param( \%info );
749 # $cookie = $query->cookie(CGISESSID => $session->id
751 print $query->header(
752 -type => 'text/html',
762 ($status, $cookie, $sessionId) = check_api_auth($query, $userflags);
764 Given a CGI query containing the parameters 'userid' and 'password' and/or a session
765 cookie, determine if the user has the privileges specified by C<$userflags>.
767 C<check_api_auth> is is meant for authenticating users of web services, and
768 consequently will always return and will not attempt to redirect the user
771 If a valid session cookie is already present, check_api_auth will return a status
772 of "ok", the cookie, and the Koha session ID.
774 If no session cookie is present, check_api_auth will check the 'userid' and 'password
775 parameters and create a session cookie and Koha session if the supplied credentials
778 Possible return values in C<$status> are:
782 =item "ok" -- user authenticated; C<$cookie> and C<$sessionid> have valid values.
784 =item "failed" -- credentials are not correct; C<$cookie> and C<$sessionid> are undef
786 =item "maintenance" -- DB is in maintenance mode; no login possible at the moment
788 =item "expired -- session cookie has expired; API user should resubmit userid and password
796 my $flagsrequired = shift;
798 my $dbh = C4::Context->dbh;
799 my $timeout = C4::Context->preference('timeout');
800 $timeout = 600 unless $timeout;
802 unless (C4::Context->preference('Version')) {
803 # database has not been installed yet
804 return ("maintenance", undef, undef);
806 my $kohaversion=C4::Context::KOHAVERSION;
807 $kohaversion =~ s/(.*\..*)\.(.*)\.(.*)/$1$2$3/;
808 if (C4::Context->preference('Version') < $kohaversion) {
809 # database in need of version update; assume that
810 # no API should be called while databsae is in
812 return ("maintenance", undef, undef);
815 # FIXME -- most of what follows is a copy-and-paste
816 # of code from checkauth. There is an obvious need
817 # for refactoring to separate the various parts of
818 # the authentication code, but as of 2007-11-19 this
819 # is deferred so as to not introduce bugs into the
820 # regular authentication code for Koha 3.0.
822 # see if we have a valid session cookie already
823 # however, if a userid parameter is present (i.e., from
824 # a form submission, assume that any current cookie
826 my $sessionID = undef;
827 unless ($query->param('userid')) {
828 $sessionID = $query->cookie("CGISESSID");
831 my $storage_method = C4::Context->preference('SessionStorage');
833 if ($storage_method eq 'mysql'){
834 $session = new CGI::Session("driver:MySQL", $sessionID, {Handle=>$dbh});
836 elsif ($storage_method eq 'Pg') {
837 $session = new CGI::Session("driver:PostgreSQL", $sessionID, {Handle=>$dbh});
840 # catch all defaults to tmp should work on all systems
841 $session = new CGI::Session("driver:File", $sessionID, {Directory=>'/tmp'});
843 C4::Context->_new_userenv($sessionID);
845 C4::Context::set_userenv(
846 $session->param('number'), $session->param('id'),
847 $session->param('cardnumber'), $session->param('firstname'),
848 $session->param('surname'), $session->param('branch'),
849 $session->param('branchname'), $session->param('flags'),
850 $session->param('emailaddress'), $session->param('branchprinter')
853 my $ip = $session->param('ip');
854 my $lasttime = $session->param('lasttime');
855 my $userid = $session->param('id');
856 if ( $lasttime < time() - $timeout ) {
859 C4::Context->_unset_userenv($sessionID);
862 return ("expired", undef, undef);
863 } elsif ( $ip ne $ENV{'REMOTE_ADDR'} ) {
866 C4::Context->_unset_userenv($sessionID);
869 return ("expired", undef, undef);
871 my $cookie = $query->cookie( CGISESSID => $session->id );
872 $session->param('lasttime',time());
873 my $flags = haspermission( $dbh, $userid, $flagsrequired );
875 return ("ok", $cookie, $sessionID);
878 C4::Context->_unset_userenv($sessionID);
881 return ("failed", undef, undef);
885 return ("expired", undef, undef);
889 my $userid = $query->param('userid');
890 my $password = $query->param('password');
891 unless ($userid and $password) {
892 # caller did something wrong, fail the authenticateion
893 return ("failed", undef, undef);
895 my ( $return, $cardnumber ) = checkpw( $dbh, $userid, $password );
896 if ($return and haspermission( $dbh, $userid, $flagsrequired)) {
897 my $storage_method = C4::Context->preference('SessionStorage');
899 if ($storage_method eq 'mysql'){
900 $session = new CGI::Session("driver:MySQL", $sessionID, {Handle=>$dbh});
901 } elsif ($storage_method eq 'Pg') {
902 $session = new CGI::Session("driver:PostgreSQL", $sessionID, {Handle=>$dbh});
904 # catch all defaults to tmp should work on all systems
905 $session = new CGI::Session("driver:File", $sessionID, {Directory=>'/tmp'});
907 return ("failed", undef, undef) unless $session;
909 my $sessionID = $session->id;
910 C4::Context->_new_userenv($sessionID);
911 my $cookie = $query->cookie(CGISESSID => $sessionID);
912 if ( $return == 1 ) {
914 $borrowernumber, $firstname, $surname,
915 $userflags, $branchcode, $branchname,
916 $branchprinter, $emailaddress
920 "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=?"
922 $sth->execute($userid);
924 $borrowernumber, $firstname, $surname,
925 $userflags, $branchcode, $branchname,
926 $branchprinter, $emailaddress
927 ) = $sth->fetchrow if ( $sth->rows );
929 unless ($sth->rows ) {
930 my $sth = $dbh->prepare(
931 "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=?"
933 $sth->execute($cardnumber);
935 $borrowernumber, $firstname, $surname,
936 $userflags, $branchcode, $branchname,
937 $branchprinter, $emailaddress
938 ) = $sth->fetchrow if ( $sth->rows );
940 unless ( $sth->rows ) {
941 $sth->execute($userid);
943 $borrowernumber, $firstname, $surname, $userflags,
944 $branchcode, $branchname, $branchprinter, $emailaddress
945 ) = $sth->fetchrow if ( $sth->rows );
949 my $ip = $ENV{'REMOTE_ADDR'};
950 # if they specify at login, use that
951 if ($query->param('branch')) {
952 $branchcode = $query->param('branch');
953 $branchname = GetBranchName($branchcode);
955 my $branches = GetBranches();
957 foreach my $br ( keys %$branches ) {
958 # now we work with the treatment of ip
959 my $domain = $branches->{$br}->{'branchip'};
960 if ( $domain && $ip =~ /^$domain/ ) {
961 $branchcode = $branches->{$br}->{'branchcode'};
963 # new op dev : add the branchprinter and branchname in the cookie
964 $branchprinter = $branches->{$br}->{'branchprinter'};
965 $branchname = $branches->{$br}->{'branchname'};
968 $session->param('number',$borrowernumber);
969 $session->param('id',$userid);
970 $session->param('cardnumber',$cardnumber);
971 $session->param('firstname',$firstname);
972 $session->param('surname',$surname);
973 $session->param('branch',$branchcode);
974 $session->param('branchname',$branchname);
975 $session->param('flags',$userflags);
976 $session->param('emailaddress',$emailaddress);
977 $session->param('ip',$session->remote_addr());
978 $session->param('lasttime',time());
979 } elsif ( $return == 2 ) {
980 #We suppose the user is the superlibrarian
981 $session->param('number',0);
982 $session->param('id',C4::Context->config('user'));
983 $session->param('cardnumber',C4::Context->config('user'));
984 $session->param('firstname',C4::Context->config('user'));
985 $session->param('surname',C4::Context->config('user'));
986 $session->param('branch','NO_LIBRARY_SET');
987 $session->param('branchname','NO_LIBRARY_SET');
988 $session->param('flags',1);
989 $session->param('emailaddress', C4::Context->preference('KohaAdminEmailAddress'));
990 $session->param('ip',$session->remote_addr());
991 $session->param('lasttime',time());
993 C4::Context::set_userenv(
994 $session->param('number'), $session->param('id'),
995 $session->param('cardnumber'), $session->param('firstname'),
996 $session->param('surname'), $session->param('branch'),
997 $session->param('branchname'), $session->param('flags'),
998 $session->param('emailaddress'), $session->param('branchprinter')
1000 return ("ok", $cookie, $sessionID);
1002 return ("failed", undef, undef);
1009 my ( $dbh, $userid, $password ) = @_;
1014 "select password,cardnumber,borrowernumber,userid,firstname,surname,branchcode,flags from borrowers where userid=?"
1016 $sth->execute($userid);
1018 my ( $md5password, $cardnumber, $borrowernumber, $userid, $firstname,
1019 $surname, $branchcode, $flags )
1021 if ( md5_base64($password) eq $md5password ) {
1023 C4::Context->set_userenv( "$borrowernumber", $userid, $cardnumber,
1024 $firstname, $surname, $branchcode, $flags );
1025 return 1, $cardnumber;
1030 "select password,cardnumber,borrowernumber,userid, firstname,surname,branchcode,flags from borrowers where cardnumber=?"
1032 $sth->execute($userid);
1034 my ( $md5password, $cardnumber, $borrowernumber, $userid, $firstname,
1035 $surname, $branchcode, $flags )
1037 if ( md5_base64($password) eq $md5password ) {
1039 C4::Context->set_userenv( $borrowernumber, $userid, $cardnumber,
1040 $firstname, $surname, $branchcode, $flags );
1044 if ( $userid && $userid eq C4::Context->config('user')
1045 && "$password" eq C4::Context->config('pass') )
1048 # Koha superuser account
1049 # C4::Context->set_userenv(0,0,C4::Context->config('user'),C4::Context->config('user'),C4::Context->config('user'),"",1);
1052 if ( $userid && $userid eq 'demo'
1053 && "$password" eq 'demo'
1054 && C4::Context->config('demo') )
1057 # DEMO => the demo user is allowed to do everything (if demo set to 1 in koha.conf
1058 # some features won't be effective : modify systempref, modify MARC structure,
1065 my $cardnumber = shift;
1068 my $sth = $dbh->prepare("SELECT flags FROM borrowers WHERE cardnumber=?");
1069 $sth->execute($cardnumber);
1070 my ($flags) = $sth->fetchrow;
1071 $flags = 0 unless $flags;
1072 $sth = $dbh->prepare("SELECT bit, flag, defaulton FROM userflags");
1075 while ( my ( $bit, $flag, $defaulton ) = $sth->fetchrow ) {
1076 if ( ( $flags & ( 2**$bit ) ) || $defaulton ) {
1077 $userflags->{$flag} = 1;
1080 $userflags->{$flag} = 0;
1087 my ( $dbh, $userid, $flagsrequired ) = @_;
1088 my $sth = $dbh->prepare("SELECT cardnumber FROM borrowers WHERE userid=?");
1089 $sth->execute($userid);
1090 my ($cardnumber) = $sth->fetchrow;
1091 ($cardnumber) || ( $cardnumber = $userid );
1092 my $flags = getuserflags( $cardnumber, $dbh );
1094 if ( $userid eq C4::Context->config('user') ) {
1096 # Super User Account from /etc/koha.conf
1097 $flags->{'superlibrarian'} = 1;
1099 if ( $userid eq 'demo' && C4::Context->config('demo') ) {
1101 # Demo user that can do "anything" (demo=1 in /etc/koha.conf)
1102 $flags->{'superlibrarian'} = 1;
1104 return $flags if $flags->{superlibrarian};
1105 foreach ( keys %$flagsrequired ) {
1106 return $flags if $flags->{$_};
1111 sub getborrowernumber {
1113 my $dbh = C4::Context->dbh;
1114 for my $field ( 'userid', 'cardnumber' ) {
1116 $dbh->prepare("select borrowernumber from borrowers where $field=?");
1117 $sth->execute($userid);
1119 my ($bnumber) = $sth->fetchrow;
1126 END { } # module clean-up code here (global destructor)