3 # Copyright 2000-2002 Katipo Communications
5 # This file is part of Koha.
7 # Koha is free software; you can redistribute it and/or modify it under the
8 # terms of the GNU General Public License as published by the Free Software
9 # Foundation; either version 2 of the License, or (at your option) any later
12 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
13 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14 # A PARTICULAR PURPOSE. See the GNU General Public License for more details.
16 # You should have received a copy of the GNU General Public License along
17 # with Koha; if not, write to the Free Software Foundation, Inc.,
18 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
22 use Digest::MD5 qw(md5_base64);
23 use JSON qw/encode_json decode_json/;
29 use C4::Templates; # to get the template
30 use C4::Branch; # GetBranches
31 use C4::VirtualShelves;
32 use Koha::AuthUtils qw(hash_password);
33 use POSIX qw/strftime/;
34 use List::MoreUtils qw/ any /;
37 use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS $debug $ldap $cas $caslogout);
40 sub psgi_env { any { /^psgi\./ } keys %ENV }
42 if ( psgi_env ) { die 'psgi:exit' }
45 $VERSION = 3.07.00.049; # set version for version checking
49 @EXPORT = qw(&checkauth &get_template_and_user &haspermission &get_user_subpermissions);
50 @EXPORT_OK = qw(&check_api_auth &get_session &check_cookie_auth &checkpw &checkpw_internal &checkpw_hash
51 &get_all_subpermissions &get_user_subpermissions
52 ParseSearchHistoryCookie
54 %EXPORT_TAGS = ( EditPermissions => [qw(get_all_subpermissions get_user_subpermissions)] );
55 $ldap = C4::Context->config('useldapserver') || 0;
56 $cas = C4::Context->preference('casAuthentication');
57 $caslogout = C4::Context->preference('casLogout');
58 require C4::Auth_with_cas; # no import
60 require C4::Auth_with_ldap;
61 import C4::Auth_with_ldap qw(checkpw_ldap);
64 import C4::Auth_with_cas qw(check_api_auth_cas checkpw_cas login_cas logout_cas login_cas_url);
71 C4::Auth - Authenticates Koha users
81 my ($template, $borrowernumber, $cookie)
82 = get_template_and_user(
84 template_name => "opac-main.tmpl",
88 flagsrequired => {borrow => 1, catalogue => '*', tools => 'import_patrons' },
92 output_html_with_http_headers $query, $cookie, $template->output;
96 The main function of this module is to provide
97 authentification. However the get_template_and_user function has
98 been provided so that a users login information is passed along
99 automatically. This gets loaded into the template.
103 =head2 get_template_and_user
105 my ($template, $borrowernumber, $cookie)
106 = get_template_and_user(
108 template_name => "opac-main.tmpl",
111 authnotrequired => 1,
112 flagsrequired => {borrow => 1, catalogue => '*', tools => 'import_patrons' },
116 This call passes the C<query>, C<flagsrequired> and C<authnotrequired>
117 to C<&checkauth> (in this module) to perform authentification.
118 See C<&checkauth> for an explanation of these parameters.
120 The C<template_name> is then used to find the correct template for
121 the page. The authenticated users details are loaded onto the
122 template in the HTML::Template LOOP variable C<USER_INFO>. Also the
123 C<sessionID> is passed to the template. This can be used in templates
124 if cookies are disabled. It needs to be put as and input to every
127 More information on the C<gettemplate> sub can be found in the
132 my $SEARCH_HISTORY_INSERT_SQL =<<EOQ;
133 INSERT INTO search_history(userid, sessionid, query_desc, query_cgi, total, time )
134 VALUES ( ?, ?, ?, ?, ?, FROM_UNIXTIME(?))
137 sub get_template_and_user {
140 my ( $user, $cookie, $sessionID, $flags );
142 my $template = C4::Templates::gettemplate(
143 $in->{'template_name'},
149 if ( $in->{'template_name'} !~m/maintenance/ ) {
150 ( $user, $cookie, $sessionID, $flags ) = checkauth(
152 $in->{'authnotrequired'},
153 $in->{'flagsrequired'},
161 # It's possible for $user to be the borrowernumber if they don't have a
162 # userid defined (and are logging in through some other method, such
163 # as SSL certs against an email address)
164 $borrowernumber = getborrowernumber($user) if defined($user);
165 if (!defined($borrowernumber) && defined($user)) {
166 my $borrower = C4::Members::GetMember(borrowernumber => $user);
168 $borrowernumber = $user;
169 # A bit of a hack, but I don't know there's a nicer way
171 $user = $borrower->{firstname} . ' ' . $borrower->{surname};
176 $template->param( loggedinusername => $user );
177 $template->param( sessionID => $sessionID );
179 my ($total, $pubshelves, $barshelves) = C4::VirtualShelves::GetSomeShelfNames($borrowernumber, 'MASTHEAD');
181 pubshelves => $total->{pubtotal},
182 pubshelvesloop => $pubshelves,
183 barshelves => $total->{bartotal},
184 barshelvesloop => $barshelves,
187 my ( $borr ) = C4::Members::GetMemberDetails( $borrowernumber );
190 $template->param( "USER_INFO" => \@bordat );
192 my $all_perms = get_all_subpermissions();
194 my @flagroots = qw(circulate catalogue parameters borrowers permissions reserveforothers borrow
195 editcatalogue updatecharges management tools editauthorities serials reports acquisition);
196 # We are going to use the $flags returned by checkauth
197 # to create the template's parameters that will indicate
198 # which menus the user can access.
199 if ( $flags && $flags->{superlibrarian}==1 ) {
200 $template->param( CAN_user_circulate => 1 );
201 $template->param( CAN_user_catalogue => 1 );
202 $template->param( CAN_user_parameters => 1 );
203 $template->param( CAN_user_borrowers => 1 );
204 $template->param( CAN_user_permissions => 1 );
205 $template->param( CAN_user_reserveforothers => 1 );
206 $template->param( CAN_user_borrow => 1 );
207 $template->param( CAN_user_editcatalogue => 1 );
208 $template->param( CAN_user_updatecharges => 1 );
209 $template->param( CAN_user_acquisition => 1 );
210 $template->param( CAN_user_management => 1 );
211 $template->param( CAN_user_tools => 1 );
212 $template->param( CAN_user_editauthorities => 1 );
213 $template->param( CAN_user_serials => 1 );
214 $template->param( CAN_user_reports => 1 );
215 $template->param( CAN_user_staffaccess => 1 );
216 $template->param( CAN_user_plugins => 1 );
217 $template->param( CAN_user_coursereserves => 1 );
218 foreach my $module (keys %$all_perms) {
219 foreach my $subperm (keys %{ $all_perms->{$module} }) {
220 $template->param( "CAN_user_${module}_${subperm}" => 1 );
226 foreach my $module (keys %$all_perms) {
227 if ( $flags->{$module} == 1) {
228 foreach my $subperm (keys %{ $all_perms->{$module} }) {
229 $template->param( "CAN_user_${module}_${subperm}" => 1 );
231 } elsif ( ref($flags->{$module}) ) {
232 foreach my $subperm (keys %{ $flags->{$module} } ) {
233 $template->param( "CAN_user_${module}_${subperm}" => 1 );
240 foreach my $module (keys %$flags) {
241 if ( $flags->{$module} == 1 or ref($flags->{$module}) ) {
242 $template->param( "CAN_user_$module" => 1 );
243 if ($module eq "parameters") {
244 $template->param( CAN_user_management => 1 );
249 # Logged-in opac search history
250 # If the requested template is an opac one and opac search history is enabled
251 if ($in->{type} eq 'opac' && C4::Context->preference('EnableOpacSearchHistory')) {
252 my $dbh = C4::Context->dbh;
253 my $query = "SELECT COUNT(*) FROM search_history WHERE userid=?";
254 my $sth = $dbh->prepare($query);
255 $sth->execute($borrowernumber);
257 # If at least one search has already been performed
258 if ($sth->fetchrow_array > 0) {
259 # We show the link in opac
260 $template->param(ShowOpacRecentSearchLink => 1);
263 # And if there's a cookie with searches performed when the user was not logged in,
264 # we add them to the logged-in search history
265 my @recentSearches = ParseSearchHistoryCookie($in->{'query'});
266 if (@recentSearches) {
267 my $sth = $dbh->prepare($SEARCH_HISTORY_INSERT_SQL);
268 $sth->execute( $borrowernumber,
269 $in->{'query'}->cookie("CGISESSID"),
274 ) foreach @recentSearches;
276 # And then, delete the cookie's content
277 my $newsearchcookie = $in->{'query'}->cookie(
278 -name => 'KohaOpacRecentSearches',
279 -value => encode_json([]),
283 $cookie = [$cookie, $newsearchcookie];
287 else { # if this is an anonymous session, setup to display public lists...
289 $template->param( sessionID => $sessionID );
291 my ($total, $pubshelves) = C4::VirtualShelves::GetSomeShelfNames(undef, 'MASTHEAD');
293 pubshelves => $total->{pubtotal},
294 pubshelvesloop => $pubshelves,
297 # Anonymous opac search history
298 # If opac search history is enabled and at least one search has already been performed
299 if (C4::Context->preference('EnableOpacSearchHistory')) {
300 my @recentSearches = ParseSearchHistoryCookie($in->{'query'});
301 if (@recentSearches) {
302 $template->param(ShowOpacRecentSearchLink => 1);
306 if(C4::Context->preference('dateformat')){
307 $template->param(dateformat => C4::Context->preference('dateformat'))
310 # these template parameters are set the same regardless of $in->{'type'}
312 "BiblioDefaultView".C4::Context->preference("BiblioDefaultView") => 1,
313 EnhancedMessagingPreferences => C4::Context->preference('EnhancedMessagingPreferences'),
314 GoogleJackets => C4::Context->preference("GoogleJackets"),
315 OpenLibraryCovers => C4::Context->preference("OpenLibraryCovers"),
316 KohaAdminEmailAddress => "" . C4::Context->preference("KohaAdminEmailAddress"),
317 LoginBranchcode => (C4::Context->userenv?C4::Context->userenv->{"branch"}:undef),
318 LoginFirstname => (C4::Context->userenv?C4::Context->userenv->{"firstname"}:"Bel"),
319 LoginSurname => C4::Context->userenv?C4::Context->userenv->{"surname"}:"Inconnu",
320 emailaddress => C4::Context->userenv?C4::Context->userenv->{"emailaddress"}:undef,
321 loggedinpersona => C4::Context->userenv?C4::Context->userenv->{"persona"}:undef,
322 TagsEnabled => C4::Context->preference("TagsEnabled"),
323 hide_marc => C4::Context->preference("hide_marc"),
324 item_level_itypes => C4::Context->preference('item-level_itypes'),
325 patronimages => C4::Context->preference("patronimages"),
326 singleBranchMode => C4::Context->preference("singleBranchMode"),
327 XSLTDetailsDisplay => C4::Context->preference("XSLTDetailsDisplay"),
328 XSLTResultsDisplay => C4::Context->preference("XSLTResultsDisplay"),
329 using_https => $in->{'query'}->https() ? 1 : 0,
330 noItemTypeImages => C4::Context->preference("noItemTypeImages"),
331 marcflavour => C4::Context->preference("marcflavour"),
332 persona => C4::Context->preference("persona"),
334 if ( $in->{'type'} eq "intranet" ) {
336 AmazonCoverImages => C4::Context->preference("AmazonCoverImages"),
337 AutoLocation => C4::Context->preference("AutoLocation"),
338 "BiblioDefaultView".C4::Context->preference("IntranetBiblioDefaultView") => 1,
339 CalendarFirstDayOfWeek => (C4::Context->preference("CalendarFirstDayOfWeek") eq "Sunday")?0:1,
340 CircAutocompl => C4::Context->preference("CircAutocompl"),
341 FRBRizeEditions => C4::Context->preference("FRBRizeEditions"),
342 IndependentBranches => C4::Context->preference("IndependentBranches"),
343 IntranetNav => C4::Context->preference("IntranetNav"),
344 IntranetmainUserblock => C4::Context->preference("IntranetmainUserblock"),
345 LibraryName => C4::Context->preference("LibraryName"),
346 LoginBranchname => (C4::Context->userenv?C4::Context->userenv->{"branchname"}:undef),
347 advancedMARCEditor => C4::Context->preference("advancedMARCEditor"),
348 canreservefromotherbranches => C4::Context->preference('canreservefromotherbranches'),
349 intranetcolorstylesheet => C4::Context->preference("intranetcolorstylesheet"),
350 IntranetFavicon => C4::Context->preference("IntranetFavicon"),
351 intranetreadinghistory => C4::Context->preference("intranetreadinghistory"),
352 intranetstylesheet => C4::Context->preference("intranetstylesheet"),
353 IntranetUserCSS => C4::Context->preference("IntranetUserCSS"),
354 intranetuserjs => C4::Context->preference("intranetuserjs"),
355 intranetbookbag => C4::Context->preference("intranetbookbag"),
356 suggestion => C4::Context->preference("suggestion"),
357 virtualshelves => C4::Context->preference("virtualshelves"),
358 StaffSerialIssueDisplayCount => C4::Context->preference("StaffSerialIssueDisplayCount"),
359 EasyAnalyticalRecords => C4::Context->preference('EasyAnalyticalRecords'),
360 LocalCoverImages => C4::Context->preference('LocalCoverImages'),
361 OPACLocalCoverImages => C4::Context->preference('OPACLocalCoverImages'),
362 AllowMultipleCovers => C4::Context->preference('AllowMultipleCovers'),
363 EnableBorrowerFiles => C4::Context->preference('EnableBorrowerFiles'),
364 UseKohaPlugins => C4::Context->preference('UseKohaPlugins'),
365 UseCourseReserves => C4::Context->preference("UseCourseReserves"),
369 warn "template type should be OPAC, here it is=[" . $in->{'type'} . "]" unless ( $in->{'type'} eq 'opac' );
370 #TODO : replace LibraryName syspref with 'system name', and remove this html processing
371 my $LibraryNameTitle = C4::Context->preference("LibraryName");
372 $LibraryNameTitle =~ s/<(?:\/?)(?:br|p)\s*(?:\/?)>/ /sgi;
373 $LibraryNameTitle =~ s/<(?:[^<>'"]|'(?:[^']*)'|"(?:[^"]*)")*>//sg;
374 # clean up the busc param in the session if the page is not opac-detail and not the "add to list" page
375 if ( C4::Context->preference("OpacBrowseResults")
376 && $in->{'template_name'} =~ /opac-(.+)\.(?:tt|tmpl)$/ ) {
378 unless ( $pagename =~ /^(?:MARC|ISBD)?detail$/
379 or $pagename =~ /^addbybiblionumber$/ ) {
380 my $sessionSearch = get_session($sessionID || $in->{'query'}->cookie("CGISESSID"));
381 $sessionSearch->clear(["busc"]) if ($sessionSearch->param("busc"));
384 # variables passed from CGI: opac_css_override and opac_search_limits.
385 my $opac_search_limit = $ENV{'OPAC_SEARCH_LIMIT'};
386 my $opac_limit_override = $ENV{'OPAC_LIMIT_OVERRIDE'};
388 if (($opac_search_limit && $opac_search_limit =~ /branch:(\w+)/ && $opac_limit_override) || ($in->{'query'}->param('limit') && $in->{'query'}->param('limit') =~ /branch:(\w+)/)){
389 $opac_name = $1; # opac_search_limit is a branch, so we use it.
390 } elsif ( $in->{'query'}->param('multibranchlimit') ) {
391 $opac_name = $in->{'query'}->param('multibranchlimit');
392 } elsif (C4::Context->preference("SearchMyLibraryFirst") && C4::Context->userenv && C4::Context->userenv->{'branch'}) {
393 $opac_name = C4::Context->userenv->{'branch'};
396 opaccolorstylesheet => C4::Context->preference("opaccolorstylesheet"),
397 AnonSuggestions => "" . C4::Context->preference("AnonSuggestions"),
398 AuthorisedValueImages => C4::Context->preference("AuthorisedValueImages"),
399 BranchesLoop => GetBranchesLoop($opac_name),
400 BranchCategoriesLoop => GetBranchCategories( 'searchdomain', 1, $opac_name ),
401 CalendarFirstDayOfWeek => (C4::Context->preference("CalendarFirstDayOfWeek") eq "Sunday")?0:1,
402 LibraryName => "" . C4::Context->preference("LibraryName"),
403 LibraryNameTitle => "" . $LibraryNameTitle,
404 LoginBranchname => C4::Context->userenv?C4::Context->userenv->{"branchname"}:"",
405 OPACAmazonCoverImages => C4::Context->preference("OPACAmazonCoverImages"),
406 OPACFRBRizeEditions => C4::Context->preference("OPACFRBRizeEditions"),
407 OpacHighlightedWords => C4::Context->preference("OpacHighlightedWords"),
408 OPACItemHolds => C4::Context->preference("OPACItemHolds"),
409 OPACShelfBrowser => "". C4::Context->preference("OPACShelfBrowser"),
410 OPACURLOpenInNewWindow => "" . C4::Context->preference("OPACURLOpenInNewWindow"),
411 OPACUserCSS => "". C4::Context->preference("OPACUserCSS"),
412 OPACMobileUserCSS => "". C4::Context->preference("OPACMobileUserCSS"),
413 OPACViewOthersSuggestions => "" . C4::Context->preference("OPACViewOthersSuggestions"),
414 OpacAuthorities => C4::Context->preference("OpacAuthorities"),
415 OPACBaseURL => ($in->{'query'}->https() ? "https://" : "http://") . $ENV{'SERVER_NAME'} .
416 ($ENV{'SERVER_PORT'} eq ($in->{'query'}->https() ? "443" : "80") ? '' : ":$ENV{'SERVER_PORT'}"),
417 opac_css_override => $ENV{'OPAC_CSS_OVERRIDE'},
418 opac_search_limit => $opac_search_limit,
419 opac_limit_override => $opac_limit_override,
420 OpacBrowser => C4::Context->preference("OpacBrowser"),
421 OpacCloud => C4::Context->preference("OpacCloud"),
422 OpacKohaUrl => C4::Context->preference("OpacKohaUrl"),
423 OpacMainUserBlock => "" . C4::Context->preference("OpacMainUserBlock"),
424 OpacMainUserBlockMobile => "" . C4::Context->preference("OpacMainUserBlockMobile"),
425 OpacShowFiltersPulldownMobile => C4::Context->preference("OpacShowFiltersPulldownMobile"),
426 OpacShowLibrariesPulldownMobile => C4::Context->preference("OpacShowLibrariesPulldownMobile"),
427 OpacNav => "" . C4::Context->preference("OpacNav"),
428 OpacNavRight => "" . C4::Context->preference("OpacNavRight"),
429 OpacNavBottom => "" . C4::Context->preference("OpacNavBottom"),
430 OpacPasswordChange => C4::Context->preference("OpacPasswordChange"),
431 OPACPatronDetails => C4::Context->preference("OPACPatronDetails"),
432 OPACPrivacy => C4::Context->preference("OPACPrivacy"),
433 OPACFinesTab => C4::Context->preference("OPACFinesTab"),
434 OpacTopissue => C4::Context->preference("OpacTopissue"),
435 RequestOnOpac => C4::Context->preference("RequestOnOpac"),
436 'Version' => C4::Context->preference('Version'),
437 hidelostitems => C4::Context->preference("hidelostitems"),
438 mylibraryfirst => (C4::Context->preference("SearchMyLibraryFirst") && C4::Context->userenv) ? C4::Context->userenv->{'branch'} : '',
439 opaclayoutstylesheet => "" . C4::Context->preference("opaclayoutstylesheet"),
440 opacbookbag => "" . C4::Context->preference("opacbookbag"),
441 opaccredits => "" . C4::Context->preference("opaccredits"),
442 OpacFavicon => C4::Context->preference("OpacFavicon"),
443 opacheader => "" . C4::Context->preference("opacheader"),
444 opaclanguagesdisplay => "" . C4::Context->preference("opaclanguagesdisplay"),
445 opacreadinghistory => C4::Context->preference("opacreadinghistory"),
446 opacsmallimage => "" . C4::Context->preference("opacsmallimage"),
447 opacuserjs => C4::Context->preference("opacuserjs"),
448 opacuserlogin => "" . C4::Context->preference("opacuserlogin"),
449 ShowReviewer => C4::Context->preference("ShowReviewer"),
450 ShowReviewerPhoto => C4::Context->preference("ShowReviewerPhoto"),
451 suggestion => "" . C4::Context->preference("suggestion"),
452 virtualshelves => "" . C4::Context->preference("virtualshelves"),
453 OPACSerialIssueDisplayCount => C4::Context->preference("OPACSerialIssueDisplayCount"),
454 OPACXSLTDetailsDisplay => C4::Context->preference("OPACXSLTDetailsDisplay"),
455 OPACXSLTResultsDisplay => C4::Context->preference("OPACXSLTResultsDisplay"),
456 SyndeticsClientCode => C4::Context->preference("SyndeticsClientCode"),
457 SyndeticsEnabled => C4::Context->preference("SyndeticsEnabled"),
458 SyndeticsCoverImages => C4::Context->preference("SyndeticsCoverImages"),
459 SyndeticsTOC => C4::Context->preference("SyndeticsTOC"),
460 SyndeticsSummary => C4::Context->preference("SyndeticsSummary"),
461 SyndeticsEditions => C4::Context->preference("SyndeticsEditions"),
462 SyndeticsExcerpt => C4::Context->preference("SyndeticsExcerpt"),
463 SyndeticsReviews => C4::Context->preference("SyndeticsReviews"),
464 SyndeticsAuthorNotes => C4::Context->preference("SyndeticsAuthorNotes"),
465 SyndeticsAwards => C4::Context->preference("SyndeticsAwards"),
466 SyndeticsSeries => C4::Context->preference("SyndeticsSeries"),
467 SyndeticsCoverImageSize => C4::Context->preference("SyndeticsCoverImageSize"),
468 OPACLocalCoverImages => C4::Context->preference("OPACLocalCoverImages"),
469 PatronSelfRegistration => C4::Context->preference("PatronSelfRegistration"),
470 PatronSelfRegistrationDefaultCategory => C4::Context->preference("PatronSelfRegistrationDefaultCategory"),
473 $template->param(OpacPublic => '1') if ($user || C4::Context->preference("OpacPublic"));
476 # Check if we were asked using parameters to force a specific language
477 if ( defined $in->{'query'}->param('language') ) {
478 # Extract the language, let C4::Templates::getlanguage choose
480 my $language = C4::Templates::getlanguage($in->{'query'},$in->{'type'});
481 my $languagecookie = C4::Templates::getlanguagecookie($in->{'query'},$language);
482 if ( ref $cookie eq 'ARRAY' ) {
483 push @{ $cookie }, $languagecookie;
485 $cookie = [$cookie, $languagecookie];
489 return ( $template, $borrowernumber, $cookie, $flags);
494 ($userid, $cookie, $sessionID) = &checkauth($query, $noauth, $flagsrequired, $type);
496 Verifies that the user is authorized to run this script. If
497 the user is authorized, a (userid, cookie, session-id, flags)
498 quadruple is returned. If the user is not authorized but does
499 not have the required privilege (see $flagsrequired below), it
500 displays an error page and exits. Otherwise, it displays the
501 login page and exits.
503 Note that C<&checkauth> will return if and only if the user
504 is authorized, so it should be called early on, before any
505 unfinished operations (e.g., if you've opened a file, then
506 C<&checkauth> won't close it for you).
508 C<$query> is the CGI object for the script calling C<&checkauth>.
510 The C<$noauth> argument is optional. If it is set, then no
511 authorization is required for the script.
513 C<&checkauth> fetches user and session information from C<$query> and
514 ensures that the user is authorized to run scripts that require
517 The C<$flagsrequired> argument specifies the required privileges
518 the user must have if the username and password are correct.
519 It should be specified as a reference-to-hash; keys in the hash
520 should be the "flags" for the user, as specified in the Members
521 intranet module. Any key specified must correspond to a "flag"
522 in the userflags table. E.g., { circulate => 1 } would specify
523 that the user must have the "circulate" privilege in order to
524 proceed. To make sure that access control is correct, the
525 C<$flagsrequired> parameter must be specified correctly.
527 Koha also has a concept of sub-permissions, also known as
528 granular permissions. This makes the value of each key
529 in the C<flagsrequired> hash take on an additional
534 The user must have access to all subfunctions of the module
535 specified by the hash key.
539 The user must have access to at least one subfunction of the module
540 specified by the hash key.
542 specific permission, e.g., 'export_catalog'
544 The user must have access to the specific subfunction list, which
545 must correspond to a row in the permissions table.
547 The C<$type> argument specifies whether the template should be
548 retrieved from the opac or intranet directory tree. "opac" is
549 assumed if it is not specified; however, if C<$type> is specified,
550 "intranet" is assumed if it is not "opac".
552 If C<$query> does not have a valid session ID associated with it
553 (i.e., the user has not logged in) or if the session has expired,
554 C<&checkauth> presents the user with a login page (from the point of
555 view of the original script, C<&checkauth> does not return). Once the
556 user has authenticated, C<&checkauth> restarts the original script
557 (this time, C<&checkauth> returns).
559 The login page is provided using a HTML::Template, which is set in the
560 systempreferences table or at the top of this file. The variable C<$type>
561 selects which template to use, either the opac or the intranet
562 authentification template.
564 C<&checkauth> returns a user ID, a cookie, and a session ID. The
565 cookie should be sent back to the browser; it verifies that the user
574 # If Version syspref is unavailable, it means Koha is beeing installed,
575 # and so we must redirect to OPAC maintenance page or to the WebInstaller
576 # also, if OpacMaintenance is ON, OPAC should redirect to maintenance
577 if (C4::Context->preference('OpacMaintenance') && $type eq 'opac') {
578 warn "OPAC Install required, redirecting to maintenance";
579 print $query->redirect("/cgi-bin/koha/maintenance.pl");
582 unless ( $version = C4::Context->preference('Version') ) { # assignment, not comparison
583 if ( $type ne 'opac' ) {
584 warn "Install required, redirecting to Installer";
585 print $query->redirect("/cgi-bin/koha/installer/install.pl");
587 warn "OPAC Install required, redirecting to maintenance";
588 print $query->redirect("/cgi-bin/koha/maintenance.pl");
593 # check that database and koha version are the same
594 # there is no DB version, it's a fresh install,
595 # go to web installer
596 # there is a DB version, compare it to the code version
597 my $kohaversion=C4::Context::KOHAVERSION;
598 # remove the 3 last . to have a Perl number
599 $kohaversion =~ s/(.*\..*)\.(.*)\.(.*)/$1$2$3/;
600 $debug and print STDERR "kohaversion : $kohaversion\n";
601 if ($version < $kohaversion){
602 my $warning = "Database update needed, redirecting to %s. Database is $version and Koha is $kohaversion";
603 if ($type ne 'opac'){
604 warn sprintf($warning, 'Installer');
605 print $query->redirect("/cgi-bin/koha/installer/install.pl?step=3");
607 warn sprintf("OPAC: " . $warning, 'maintenance');
608 print $query->redirect("/cgi-bin/koha/maintenance.pl");
616 open my $fh, '>>', "/tmp/sessionlog" or warn "ERROR: Cannot append to /tmp/sessionlog";
617 printf $fh join("\n",@_);
621 sub _timeout_syspref {
622 my $timeout = C4::Context->preference('timeout') || 600;
623 # value in days, convert in seconds
624 if ($timeout =~ /(\d+)[dD]/) {
625 $timeout = $1 * 86400;
632 $debug and warn "Checking Auth";
633 # $authnotrequired will be set for scripts which will run without authentication
634 my $authnotrequired = shift;
635 my $flagsrequired = shift;
638 $type = 'opac' unless $type;
640 my $dbh = C4::Context->dbh;
641 my $timeout = _timeout_syspref();
643 _version_check($type,$query);
647 my ( $userid, $cookie, $sessionID, $flags, $barshelves, $pubshelves );
648 my $logout = $query->param('logout.x');
650 # This parameter is the name of the CAS server we want to authenticate against,
651 # when using authentication against multiple CAS servers, as configured in Auth_cas_servers.yaml
652 my $casparam = $query->param('cas');
654 if ( $userid = $ENV{'REMOTE_USER'} ) {
655 # Using Basic Authentication, no cookies required
656 $cookie = $query->cookie(
657 -name => 'CGISESSID',
665 # we dont want to set a session because we are being called by a persona callback
667 elsif ( $sessionID = $query->cookie("CGISESSID") )
668 { # assignment, not comparison
669 my $session = get_session($sessionID);
670 C4::Context->_new_userenv($sessionID);
671 my ($ip, $lasttime, $sessiontype);
673 C4::Context::set_userenv(
674 $session->param('number'), $session->param('id'),
675 $session->param('cardnumber'), $session->param('firstname'),
676 $session->param('surname'), $session->param('branch'),
677 $session->param('branchname'), $session->param('flags'),
678 $session->param('emailaddress'), $session->param('branchprinter'),
679 $session->param('persona')
681 C4::Context::set_shelves_userenv('bar',$session->param('barshelves'));
682 C4::Context::set_shelves_userenv('pub',$session->param('pubshelves'));
683 C4::Context::set_shelves_userenv('tot',$session->param('totshelves'));
684 $debug and printf STDERR "AUTH_SESSION: (%s)\t%s %s - %s\n", map {$session->param($_)} qw(cardnumber firstname surname branch) ;
685 $ip = $session->param('ip');
686 $lasttime = $session->param('lasttime');
687 $userid = $session->param('id');
688 $sessiontype = $session->param('sessiontype') || '';
690 if ( ( ($query->param('koha_login_context')) && ($query->param('userid') ne ($session->param('id') // '')) )
691 || ( $cas && $query->param('ticket') ) ) {
692 #if a user enters an id ne to the id in the current session, we need to log them in...
693 #first we need to clear the anonymous session...
694 $debug and warn "query id = " . $query->param('userid') . " but session id = " . $session->param('id');
697 C4::Context->_unset_userenv($sessionID);
702 # voluntary logout the user
705 C4::Context->_unset_userenv($sessionID);
706 #_session_log(sprintf "%20s from %16s logged out at %30s (manually).\n", $userid,$ip,(strftime "%c",localtime));
710 if ($cas and $caslogout) {
714 elsif ( $lasttime < time() - $timeout ) {
716 $info{'timed_out'} = 1;
717 $session->delete() if $session;
718 C4::Context->_unset_userenv($sessionID);
719 #_session_log(sprintf "%20s from %16s logged out at %30s (inactivity).\n", $userid,$ip,(strftime "%c",localtime));
723 elsif ( $ip ne $ENV{'REMOTE_ADDR'} ) {
724 # Different ip than originally logged in from
725 $info{'oldip'} = $ip;
726 $info{'newip'} = $ENV{'REMOTE_ADDR'};
727 $info{'different_ip'} = 1;
729 C4::Context->_unset_userenv($sessionID);
730 #_session_log(sprintf "%20s from %16s logged out at %30s (ip changed to %16s).\n", $userid,$ip,(strftime "%c",localtime), $info{'newip'});
735 $cookie = $query->cookie(
736 -name => 'CGISESSID',
737 -value => $session->id,
740 $session->param( 'lasttime', time() );
741 unless ( $sessiontype && $sessiontype eq 'anon' ) { #if this is an anonymous session, we want to update the session, but not behave as if they are logged in...
742 $flags = haspermission($userid, $flagsrequired);
746 $info{'nopermission'} = 1;
751 unless ($userid || $sessionID) {
753 #we initiate a session prior to checking for a username to allow for anonymous sessions...
754 my $session = get_session("") or die "Auth ERROR: Cannot get_session()";
755 my $sessionID = $session->id;
756 C4::Context->_new_userenv($sessionID);
757 $cookie = $query->cookie(
758 -name => 'CGISESSID',
759 -value => $session->id,
762 $userid = $query->param('userid');
763 my $pki_field = C4::Context->preference('AllowPKIAuth') // 'None';
764 if ( ( $cas && $query->param('ticket') )
766 || $pki_field ne 'None'
769 my $password = $query->param('password');
771 my ( $return, $cardnumber );
772 if ( $cas && $query->param('ticket') ) {
774 ( $return, $cardnumber, $retuserid ) =
775 checkpw( $dbh, $userid, $password, $query );
776 $userid = $retuserid;
777 $info{'invalidCasLogin'} = 1 unless ($return);
781 my $value = $persona;
783 # If we're looking up the email, there's a chance that the person
784 # doesn't have a userid. So if there is none, we pass along the
785 # borrower number, and the bits of code that need to know the user
786 # ID will have to be smart enough to handle that.
788 my @users_info = C4::Members::GetBorrowersWithEmail($value);
791 # First the userid, then the borrowernum
792 $value = $users_info[0][1] || $users_info[0][0];
797 $return = $value ? 1 : 0;
802 ( $pki_field eq 'Common Name' && $ENV{'SSL_CLIENT_S_DN_CN'} )
803 || ( $pki_field eq 'emailAddress'
804 && $ENV{'SSL_CLIENT_S_DN_Email'} )
808 if ( $pki_field eq 'Common Name' ) {
809 $value = $ENV{'SSL_CLIENT_S_DN_CN'};
811 elsif ( $pki_field eq 'emailAddress' ) {
812 $value = $ENV{'SSL_CLIENT_S_DN_Email'};
814 # If we're looking up the email, there's a chance that the person
815 # doesn't have a userid. So if there is none, we pass along the
816 # borrower number, and the bits of code that need to know the user
817 # ID will have to be smart enough to handle that.
819 my @users_info = C4::Members::GetBorrowersWithEmail($value);
822 # First the userid, then the borrowernum
823 $value = $users_info[0][1] || $users_info[0][0];
830 $return = $value ? 1 : 0;
836 ( $return, $cardnumber, $retuserid ) =
837 checkpw( $dbh, $userid, $password, $query );
838 $userid = $retuserid if ( $retuserid ne '' );
841 #_session_log(sprintf "%20s from %16s logged in at %30s.\n", $userid,$ENV{'REMOTE_ADDR'},(strftime '%c', localtime));
842 if ( $flags = haspermission( $userid, $flagsrequired ) ) {
846 $info{'nopermission'} = 1;
847 C4::Context->_unset_userenv($sessionID);
849 my ($borrowernumber, $firstname, $surname, $userflags,
850 $branchcode, $branchname, $branchprinter, $emailaddress);
852 if ( $return == 1 ) {
854 SELECT borrowernumber, firstname, surname, flags, borrowers.branchcode,
855 branches.branchname as branchname,
856 branches.branchprinter as branchprinter,
859 LEFT JOIN branches on borrowers.branchcode=branches.branchcode
861 my $sth = $dbh->prepare("$select where userid=?");
862 $sth->execute($userid);
863 unless ($sth->rows) {
864 $debug and print STDERR "AUTH_1: no rows for userid='$userid'\n";
865 $sth = $dbh->prepare("$select where cardnumber=?");
866 $sth->execute($cardnumber);
868 unless ($sth->rows) {
869 $debug and print STDERR "AUTH_2a: no rows for cardnumber='$cardnumber'\n";
870 $sth->execute($userid);
871 unless ($sth->rows) {
872 $debug and print STDERR "AUTH_2b: no rows for userid='$userid' AS cardnumber\n";
877 ($borrowernumber, $firstname, $surname, $userflags,
878 $branchcode, $branchname, $branchprinter, $emailaddress) = $sth->fetchrow;
879 $debug and print STDERR "AUTH_3 results: " .
880 "$cardnumber,$borrowernumber,$userid,$firstname,$surname,$userflags,$branchcode,$emailaddress\n";
882 print STDERR "AUTH_3: no results for userid='$userid', cardnumber='$cardnumber'.\n";
885 # launch a sequence to check if we have a ip for the branch, i
886 # if we have one we replace the branchcode of the userenv by the branch bound in the ip.
888 my $ip = $ENV{'REMOTE_ADDR'};
889 # if they specify at login, use that
890 if ($query->param('branch')) {
891 $branchcode = $query->param('branch');
892 $branchname = GetBranchName($branchcode);
894 my $branches = GetBranches();
895 if (C4::Context->boolean_preference('IndependentBranches') && C4::Context->boolean_preference('Autolocation')){
896 # we have to check they are coming from the right ip range
897 my $domain = $branches->{$branchcode}->{'branchip'};
898 if ($ip !~ /^$domain/){
900 $info{'wrongip'} = 1;
905 foreach my $br ( keys %$branches ) {
906 # now we work with the treatment of ip
907 my $domain = $branches->{$br}->{'branchip'};
908 if ( $domain && $ip =~ /^$domain/ ) {
909 $branchcode = $branches->{$br}->{'branchcode'};
911 # new op dev : add the branchprinter and branchname in the cookie
912 $branchprinter = $branches->{$br}->{'branchprinter'};
913 $branchname = $branches->{$br}->{'branchname'};
916 $session->param('number',$borrowernumber);
917 $session->param('id',$userid);
918 $session->param('cardnumber',$cardnumber);
919 $session->param('firstname',$firstname);
920 $session->param('surname',$surname);
921 $session->param('branch',$branchcode);
922 $session->param('branchname',$branchname);
923 $session->param('flags',$userflags);
924 $session->param('emailaddress',$emailaddress);
925 $session->param('ip',$session->remote_addr());
926 $session->param('lasttime',time());
927 $debug and printf STDERR "AUTH_4: (%s)\t%s %s - %s\n", map {$session->param($_)} qw(cardnumber firstname surname branch) ;
929 elsif ( $return == 2 ) {
930 #We suppose the user is the superlibrarian
932 $session->param('number',0);
933 $session->param('id',C4::Context->config('user'));
934 $session->param('cardnumber',C4::Context->config('user'));
935 $session->param('firstname',C4::Context->config('user'));
936 $session->param('surname',C4::Context->config('user'));
937 $session->param('branch','NO_LIBRARY_SET');
938 $session->param('branchname','NO_LIBRARY_SET');
939 $session->param('flags',1);
940 $session->param('emailaddress', C4::Context->preference('KohaAdminEmailAddress'));
941 $session->param('ip',$session->remote_addr());
942 $session->param('lasttime',time());
945 $session->param('persona',1);
947 C4::Context::set_userenv(
948 $session->param('number'), $session->param('id'),
949 $session->param('cardnumber'), $session->param('firstname'),
950 $session->param('surname'), $session->param('branch'),
951 $session->param('branchname'), $session->param('flags'),
952 $session->param('emailaddress'), $session->param('branchprinter'),
953 $session->param('persona')
959 $info{'invalid_username_or_password'} = 1;
960 C4::Context->_unset_userenv($sessionID);
963 } # END if ( $userid = $query->param('userid') )
964 elsif ($type eq "opac") {
965 # if we are here this is an anonymous session; add public lists to it and a few other items...
966 # anonymous sessions are created only for the OPAC
967 $debug and warn "Initiating an anonymous session...";
969 # setting a couple of other session vars...
970 $session->param('ip',$session->remote_addr());
971 $session->param('lasttime',time());
972 $session->param('sessiontype','anon');
974 } # END unless ($userid)
976 # finished authentification, now respond
977 if ( $loggedin || $authnotrequired )
981 $cookie = $query->cookie(
982 -name => 'CGISESSID',
987 return ( $userid, $cookie, $sessionID, $flags );
992 # AUTH rejected, show the login/password template, after checking the DB.
996 # get the inputs from the incoming query
998 foreach my $name ( param $query) {
999 (next) if ( $name eq 'userid' || $name eq 'password' || $name eq 'ticket' );
1000 my $value = $query->param($name);
1001 push @inputs, { name => $name, value => $value };
1004 my $LibraryNameTitle = C4::Context->preference("LibraryName");
1005 $LibraryNameTitle =~ s/<(?:\/?)(?:br|p)\s*(?:\/?)>/ /sgi;
1006 $LibraryNameTitle =~ s/<(?:[^<>'"]|'(?:[^']*)'|"(?:[^"]*)")*>//sg;
1008 my $template_name = ( $type eq 'opac' ) ? 'opac-auth.tmpl' : 'auth.tmpl';
1009 my $template = C4::Templates::gettemplate($template_name, $type, $query );
1011 branchloop => GetBranchesLoop(),
1012 opaccolorstylesheet => C4::Context->preference("opaccolorstylesheet"),
1013 opaclayoutstylesheet => C4::Context->preference("opaclayoutstylesheet"),
1016 casAuthentication => C4::Context->preference("casAuthentication"),
1017 suggestion => C4::Context->preference("suggestion"),
1018 virtualshelves => C4::Context->preference("virtualshelves"),
1019 LibraryName => "" . C4::Context->preference("LibraryName"),
1020 LibraryNameTitle => "" . $LibraryNameTitle,
1021 opacuserlogin => C4::Context->preference("opacuserlogin"),
1022 OpacNav => C4::Context->preference("OpacNav"),
1023 OpacNavRight => C4::Context->preference("OpacNavRight"),
1024 OpacNavBottom => C4::Context->preference("OpacNavBottom"),
1025 opaccredits => C4::Context->preference("opaccredits"),
1026 OpacFavicon => C4::Context->preference("OpacFavicon"),
1027 opacreadinghistory => C4::Context->preference("opacreadinghistory"),
1028 opacsmallimage => C4::Context->preference("opacsmallimage"),
1029 opaclanguagesdisplay => C4::Context->preference("opaclanguagesdisplay"),
1030 opacuserjs => C4::Context->preference("opacuserjs"),
1031 opacbookbag => "" . C4::Context->preference("opacbookbag"),
1032 OpacCloud => C4::Context->preference("OpacCloud"),
1033 OpacTopissue => C4::Context->preference("OpacTopissue"),
1034 OpacAuthorities => C4::Context->preference("OpacAuthorities"),
1035 OpacBrowser => C4::Context->preference("OpacBrowser"),
1036 opacheader => C4::Context->preference("opacheader"),
1037 TagsEnabled => C4::Context->preference("TagsEnabled"),
1038 OPACUserCSS => C4::Context->preference("OPACUserCSS"),
1039 intranetcolorstylesheet => C4::Context->preference("intranetcolorstylesheet"),
1040 intranetstylesheet => C4::Context->preference("intranetstylesheet"),
1041 intranetbookbag => C4::Context->preference("intranetbookbag"),
1042 IntranetNav => C4::Context->preference("IntranetNav"),
1043 IntranetFavicon => C4::Context->preference("IntranetFavicon"),
1044 intranetuserjs => C4::Context->preference("intranetuserjs"),
1045 IndependentBranches=> C4::Context->preference("IndependentBranches"),
1046 AutoLocation => C4::Context->preference("AutoLocation"),
1047 wrongip => $info{'wrongip'},
1048 PatronSelfRegistration => C4::Context->preference("PatronSelfRegistration"),
1049 PatronSelfRegistrationDefaultCategory => C4::Context->preference("PatronSelfRegistrationDefaultCategory"),
1050 persona => C4::Context->preference("Persona"),
1051 opac_css_override => $ENV{'OPAC_CSS_OVERRIDE'},
1054 $template->param( OpacPublic => C4::Context->preference("OpacPublic"));
1055 $template->param( loginprompt => 1 ) unless $info{'nopermission'};
1057 if($type eq 'opac'){
1058 my ($total, $pubshelves) = C4::VirtualShelves::GetSomeShelfNames(undef, 'MASTHEAD');
1060 pubshelves => $total->{pubtotal},
1061 pubshelvesloop => $pubshelves,
1067 # Is authentication against multiple CAS servers enabled?
1068 if (C4::Auth_with_cas::multipleAuth && !$casparam) {
1069 my $casservers = C4::Auth_with_cas::getMultipleAuth();
1071 foreach my $key (keys %$casservers) {
1072 push @tmplservers, {name => $key, value => login_cas_url($query, $key) . "?cas=$key" };
1075 casServersLoop => \@tmplservers
1079 casServerUrl => login_cas_url($query),
1084 invalidCasLogin => $info{'invalidCasLogin'}
1088 my $self_url = $query->url( -absolute => 1 );
1091 LibraryName => C4::Context->preference("LibraryName"),
1093 $template->param( %info );
1094 # $cookie = $query->cookie(CGISESSID => $session->id
1096 print $query->header(
1097 -type => 'text/html',
1098 -charset => 'utf-8',
1105 =head2 check_api_auth
1107 ($status, $cookie, $sessionId) = check_api_auth($query, $userflags);
1109 Given a CGI query containing the parameters 'userid' and 'password' and/or a session
1110 cookie, determine if the user has the privileges specified by C<$userflags>.
1112 C<check_api_auth> is is meant for authenticating users of web services, and
1113 consequently will always return and will not attempt to redirect the user
1116 If a valid session cookie is already present, check_api_auth will return a status
1117 of "ok", the cookie, and the Koha session ID.
1119 If no session cookie is present, check_api_auth will check the 'userid' and 'password
1120 parameters and create a session cookie and Koha session if the supplied credentials
1123 Possible return values in C<$status> are:
1127 =item "ok" -- user authenticated; C<$cookie> and C<$sessionid> have valid values.
1129 =item "failed" -- credentials are not correct; C<$cookie> and C<$sessionid> are undef
1131 =item "maintenance" -- DB is in maintenance mode; no login possible at the moment
1133 =item "expired -- session cookie has expired; API user should resubmit userid and password
1139 sub check_api_auth {
1141 my $flagsrequired = shift;
1143 my $dbh = C4::Context->dbh;
1144 my $timeout = _timeout_syspref();
1146 unless (C4::Context->preference('Version')) {
1147 # database has not been installed yet
1148 return ("maintenance", undef, undef);
1150 my $kohaversion=C4::Context::KOHAVERSION;
1151 $kohaversion =~ s/(.*\..*)\.(.*)\.(.*)/$1$2$3/;
1152 if (C4::Context->preference('Version') < $kohaversion) {
1153 # database in need of version update; assume that
1154 # no API should be called while databsae is in
1156 return ("maintenance", undef, undef);
1159 # FIXME -- most of what follows is a copy-and-paste
1160 # of code from checkauth. There is an obvious need
1161 # for refactoring to separate the various parts of
1162 # the authentication code, but as of 2007-11-19 this
1163 # is deferred so as to not introduce bugs into the
1164 # regular authentication code for Koha 3.0.
1166 # see if we have a valid session cookie already
1167 # however, if a userid parameter is present (i.e., from
1168 # a form submission, assume that any current cookie
1170 my $sessionID = undef;
1171 unless ($query->param('userid')) {
1172 $sessionID = $query->cookie("CGISESSID");
1174 if ($sessionID && not ($cas && $query->param('PT')) ) {
1175 my $session = get_session($sessionID);
1176 C4::Context->_new_userenv($sessionID);
1178 C4::Context::set_userenv(
1179 $session->param('number'), $session->param('id'),
1180 $session->param('cardnumber'), $session->param('firstname'),
1181 $session->param('surname'), $session->param('branch'),
1182 $session->param('branchname'), $session->param('flags'),
1183 $session->param('emailaddress'), $session->param('branchprinter')
1186 my $ip = $session->param('ip');
1187 my $lasttime = $session->param('lasttime');
1188 my $userid = $session->param('id');
1189 if ( $lasttime < time() - $timeout ) {
1192 C4::Context->_unset_userenv($sessionID);
1195 return ("expired", undef, undef);
1196 } elsif ( $ip ne $ENV{'REMOTE_ADDR'} ) {
1197 # IP address changed
1199 C4::Context->_unset_userenv($sessionID);
1202 return ("expired", undef, undef);
1204 my $cookie = $query->cookie(
1205 -name => 'CGISESSID',
1206 -value => $session->id,
1209 $session->param('lasttime',time());
1210 my $flags = haspermission($userid, $flagsrequired);
1212 return ("ok", $cookie, $sessionID);
1215 C4::Context->_unset_userenv($sessionID);
1218 return ("failed", undef, undef);
1222 return ("expired", undef, undef);
1226 my $userid = $query->param('userid');
1227 my $password = $query->param('password');
1228 my ($return, $cardnumber);
1231 if ($cas && $query->param('PT')) {
1233 $debug and print STDERR "## check_api_auth - checking CAS\n";
1234 # In case of a CAS authentication, we use the ticket instead of the password
1235 my $PT = $query->param('PT');
1236 ($return,$cardnumber,$userid) = check_api_auth_cas($dbh, $PT, $query); # EXTERNAL AUTH
1238 # User / password auth
1239 unless ($userid and $password) {
1240 # caller did something wrong, fail the authenticateion
1241 return ("failed", undef, undef);
1243 ( $return, $cardnumber ) = checkpw( $dbh, $userid, $password, $query );
1246 if ($return and haspermission( $userid, $flagsrequired)) {
1247 my $session = get_session("");
1248 return ("failed", undef, undef) unless $session;
1250 my $sessionID = $session->id;
1251 C4::Context->_new_userenv($sessionID);
1252 my $cookie = $query->cookie(
1253 -name => 'CGISESSID',
1254 -value => $sessionID,
1257 if ( $return == 1 ) {
1259 $borrowernumber, $firstname, $surname,
1260 $userflags, $branchcode, $branchname,
1261 $branchprinter, $emailaddress
1265 "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=?"
1267 $sth->execute($userid);
1269 $borrowernumber, $firstname, $surname,
1270 $userflags, $branchcode, $branchname,
1271 $branchprinter, $emailaddress
1272 ) = $sth->fetchrow if ( $sth->rows );
1274 unless ($sth->rows ) {
1275 my $sth = $dbh->prepare(
1276 "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=?"
1278 $sth->execute($cardnumber);
1280 $borrowernumber, $firstname, $surname,
1281 $userflags, $branchcode, $branchname,
1282 $branchprinter, $emailaddress
1283 ) = $sth->fetchrow if ( $sth->rows );
1285 unless ( $sth->rows ) {
1286 $sth->execute($userid);
1288 $borrowernumber, $firstname, $surname, $userflags,
1289 $branchcode, $branchname, $branchprinter, $emailaddress
1290 ) = $sth->fetchrow if ( $sth->rows );
1294 my $ip = $ENV{'REMOTE_ADDR'};
1295 # if they specify at login, use that
1296 if ($query->param('branch')) {
1297 $branchcode = $query->param('branch');
1298 $branchname = GetBranchName($branchcode);
1300 my $branches = GetBranches();
1302 foreach my $br ( keys %$branches ) {
1303 # now we work with the treatment of ip
1304 my $domain = $branches->{$br}->{'branchip'};
1305 if ( $domain && $ip =~ /^$domain/ ) {
1306 $branchcode = $branches->{$br}->{'branchcode'};
1308 # new op dev : add the branchprinter and branchname in the cookie
1309 $branchprinter = $branches->{$br}->{'branchprinter'};
1310 $branchname = $branches->{$br}->{'branchname'};
1313 $session->param('number',$borrowernumber);
1314 $session->param('id',$userid);
1315 $session->param('cardnumber',$cardnumber);
1316 $session->param('firstname',$firstname);
1317 $session->param('surname',$surname);
1318 $session->param('branch',$branchcode);
1319 $session->param('branchname',$branchname);
1320 $session->param('flags',$userflags);
1321 $session->param('emailaddress',$emailaddress);
1322 $session->param('ip',$session->remote_addr());
1323 $session->param('lasttime',time());
1324 } elsif ( $return == 2 ) {
1325 #We suppose the user is the superlibrarian
1326 $session->param('number',0);
1327 $session->param('id',C4::Context->config('user'));
1328 $session->param('cardnumber',C4::Context->config('user'));
1329 $session->param('firstname',C4::Context->config('user'));
1330 $session->param('surname',C4::Context->config('user'));
1331 $session->param('branch','NO_LIBRARY_SET');
1332 $session->param('branchname','NO_LIBRARY_SET');
1333 $session->param('flags',1);
1334 $session->param('emailaddress', C4::Context->preference('KohaAdminEmailAddress'));
1335 $session->param('ip',$session->remote_addr());
1336 $session->param('lasttime',time());
1338 C4::Context::set_userenv(
1339 $session->param('number'), $session->param('id'),
1340 $session->param('cardnumber'), $session->param('firstname'),
1341 $session->param('surname'), $session->param('branch'),
1342 $session->param('branchname'), $session->param('flags'),
1343 $session->param('emailaddress'), $session->param('branchprinter')
1345 return ("ok", $cookie, $sessionID);
1347 return ("failed", undef, undef);
1352 =head2 check_cookie_auth
1354 ($status, $sessionId) = check_api_auth($cookie, $userflags);
1356 Given a CGISESSID cookie set during a previous login to Koha, determine
1357 if the user has the privileges specified by C<$userflags>.
1359 C<check_cookie_auth> is meant for authenticating special services
1360 such as tools/upload-file.pl that are invoked by other pages that
1361 have been authenticated in the usual way.
1363 Possible return values in C<$status> are:
1367 =item "ok" -- user authenticated; C<$sessionID> have valid values.
1369 =item "failed" -- credentials are not correct; C<$sessionid> are undef
1371 =item "maintenance" -- DB is in maintenance mode; no login possible at the moment
1373 =item "expired -- session cookie has expired; API user should resubmit userid and password
1379 sub check_cookie_auth {
1381 my $flagsrequired = shift;
1383 my $dbh = C4::Context->dbh;
1384 my $timeout = _timeout_syspref();
1386 unless (C4::Context->preference('Version')) {
1387 # database has not been installed yet
1388 return ("maintenance", undef);
1390 my $kohaversion=C4::Context::KOHAVERSION;
1391 $kohaversion =~ s/(.*\..*)\.(.*)\.(.*)/$1$2$3/;
1392 if (C4::Context->preference('Version') < $kohaversion) {
1393 # database in need of version update; assume that
1394 # no API should be called while databsae is in
1396 return ("maintenance", undef);
1399 # FIXME -- most of what follows is a copy-and-paste
1400 # of code from checkauth. There is an obvious need
1401 # for refactoring to separate the various parts of
1402 # the authentication code, but as of 2007-11-23 this
1403 # is deferred so as to not introduce bugs into the
1404 # regular authentication code for Koha 3.0.
1406 # see if we have a valid session cookie already
1407 # however, if a userid parameter is present (i.e., from
1408 # a form submission, assume that any current cookie
1410 unless (defined $cookie and $cookie) {
1411 return ("failed", undef);
1413 my $sessionID = $cookie;
1414 my $session = get_session($sessionID);
1415 C4::Context->_new_userenv($sessionID);
1417 C4::Context::set_userenv(
1418 $session->param('number'), $session->param('id'),
1419 $session->param('cardnumber'), $session->param('firstname'),
1420 $session->param('surname'), $session->param('branch'),
1421 $session->param('branchname'), $session->param('flags'),
1422 $session->param('emailaddress'), $session->param('branchprinter')
1425 my $ip = $session->param('ip');
1426 my $lasttime = $session->param('lasttime');
1427 my $userid = $session->param('id');
1428 if ( $lasttime < time() - $timeout ) {
1431 C4::Context->_unset_userenv($sessionID);
1434 return ("expired", undef);
1435 } elsif ( $ip ne $ENV{'REMOTE_ADDR'} ) {
1436 # IP address changed
1438 C4::Context->_unset_userenv($sessionID);
1441 return ("expired", undef);
1443 $session->param('lasttime',time());
1444 my $flags = haspermission($userid, $flagsrequired);
1446 return ("ok", $sessionID);
1449 C4::Context->_unset_userenv($sessionID);
1452 return ("failed", undef);
1456 return ("expired", undef);
1463 my $session = get_session($sessionID);
1465 Given a session ID, retrieve the CGI::Session object used to store
1466 the session's state. The session object can be used to store
1467 data that needs to be accessed by different scripts during a
1470 If the C<$sessionID> parameter is an empty string, a new session
1476 my $sessionID = shift;
1477 my $storage_method = C4::Context->preference('SessionStorage');
1478 my $dbh = C4::Context->dbh;
1480 if ($storage_method eq 'mysql'){
1481 $session = new CGI::Session("driver:MySQL;serializer:yaml;id:md5", $sessionID, {Handle=>$dbh});
1483 elsif ($storage_method eq 'Pg') {
1484 $session = new CGI::Session("driver:PostgreSQL;serializer:yaml;id:md5", $sessionID, {Handle=>$dbh});
1486 elsif ($storage_method eq 'memcached' && C4::Context->ismemcached){
1487 $session = new CGI::Session("driver:memcached;serializer:yaml;id:md5", $sessionID, { Memcached => C4::Context->memcached } );
1490 # catch all defaults to tmp should work on all systems
1491 $session = new CGI::Session("driver:File;serializer:yaml;id:md5", $sessionID, {Directory=>'/tmp'});
1497 my ( $dbh, $userid, $password, $query ) = @_;
1500 $debug and print STDERR "## checkpw - checking LDAP\n";
1501 my ($retval,$retcard,$retuserid) = checkpw_ldap(@_); # EXTERNAL AUTH
1502 ($retval) and return ($retval,$retcard,$retuserid);
1505 if ($cas && $query && $query->param('ticket')) {
1506 $debug and print STDERR "## checkpw - checking CAS\n";
1507 # In case of a CAS authentication, we use the ticket instead of the password
1508 my $ticket = $query->param('ticket');
1509 my ($retval,$retcard,$retuserid) = checkpw_cas($dbh, $ticket, $query); # EXTERNAL AUTH
1510 ($retval) and return ($retval,$retcard,$retuserid);
1514 return checkpw_internal(@_)
1517 sub checkpw_internal {
1518 my ( $dbh, $userid, $password ) = @_;
1522 "select password,cardnumber,borrowernumber,userid,firstname,surname,branchcode,flags from borrowers where userid=?"
1524 $sth->execute($userid);
1526 my ( $stored_hash, $cardnumber, $borrowernumber, $userid, $firstname,
1527 $surname, $branchcode, $flags )
1530 if ( checkpw_hash($password, $stored_hash) ) {
1532 C4::Context->set_userenv( "$borrowernumber", $userid, $cardnumber,
1533 $firstname, $surname, $branchcode, $flags );
1534 return 1, $cardnumber, $userid;
1539 "select password,cardnumber,borrowernumber,userid, firstname,surname,branchcode,flags from borrowers where cardnumber=?"
1541 $sth->execute($userid);
1543 my ( $stored_hash, $cardnumber, $borrowernumber, $userid, $firstname,
1544 $surname, $branchcode, $flags )
1547 if ( checkpw_hash($password, $stored_hash) ) {
1549 C4::Context->set_userenv( $borrowernumber, $userid, $cardnumber,
1550 $firstname, $surname, $branchcode, $flags );
1551 return 1, $cardnumber, $userid;
1554 if ( $userid && $userid eq C4::Context->config('user')
1555 && "$password" eq C4::Context->config('pass') )
1558 # Koha superuser account
1559 # C4::Context->set_userenv(0,0,C4::Context->config('user'),C4::Context->config('user'),C4::Context->config('user'),"",1);
1562 if ( $userid && $userid eq 'demo'
1563 && "$password" eq 'demo'
1564 && C4::Context->config('demo') )
1567 # DEMO => the demo user is allowed to do everything (if demo set to 1 in koha.conf
1568 # some features won't be effective : modify systempref, modify MARC structure,
1575 my ( $password, $stored_hash ) = @_;
1577 return if $stored_hash eq '!';
1579 # check what encryption algorithm was implemented: Bcrypt - if the hash starts with '$2' it is Bcrypt else md5
1581 if ( substr($stored_hash,0,2) eq '$2') {
1582 $hash = hash_password($password, $stored_hash);
1584 $hash = md5_base64($password);
1586 return $hash eq $stored_hash;
1591 my $authflags = getuserflags($flags, $userid, [$dbh]);
1593 Translates integer flags into permissions strings hash.
1595 C<$flags> is the integer userflags value ( borrowers.userflags )
1596 C<$userid> is the members.userid, used for building subpermissions
1597 C<$authflags> is a hashref of permissions
1604 my $dbh = @_ ? shift : C4::Context->dbh;
1607 # I don't want to do this, but if someone logs in as the database
1608 # user, it would be preferable not to spam them to death with
1609 # numeric warnings. So, we make $flags numeric.
1610 no warnings 'numeric';
1613 my $sth = $dbh->prepare("SELECT bit, flag, defaulton FROM userflags");
1616 while ( my ( $bit, $flag, $defaulton ) = $sth->fetchrow ) {
1617 if ( ( $flags & ( 2**$bit ) ) || $defaulton ) {
1618 $userflags->{$flag} = 1;
1621 $userflags->{$flag} = 0;
1624 # get subpermissions and merge with top-level permissions
1625 my $user_subperms = get_user_subpermissions($userid);
1626 foreach my $module (keys %$user_subperms) {
1627 next if $userflags->{$module} == 1; # user already has permission for everything in this module
1628 $userflags->{$module} = $user_subperms->{$module};
1634 =head2 get_user_subpermissions
1636 $user_perm_hashref = get_user_subpermissions($userid);
1638 Given the userid (note, not the borrowernumber) of a staff user,
1639 return a hashref of hashrefs of the specific subpermissions
1640 accorded to the user. An example return is
1644 export_catalog => 1,
1645 import_patrons => 1,
1649 The top-level hash-key is a module or function code from
1650 userflags.flag, while the second-level key is a code
1653 The results of this function do not give a complete picture
1654 of the functions that a staff user can access; it is also
1655 necessary to check borrowers.flags.
1659 sub get_user_subpermissions {
1662 my $dbh = C4::Context->dbh;
1663 my $sth = $dbh->prepare("SELECT flag, user_permissions.code
1664 FROM user_permissions
1665 JOIN permissions USING (module_bit, code)
1666 JOIN userflags ON (module_bit = bit)
1667 JOIN borrowers USING (borrowernumber)
1669 $sth->execute($userid);
1671 my $user_perms = {};
1672 while (my $perm = $sth->fetchrow_hashref) {
1673 $user_perms->{$perm->{'flag'}}->{$perm->{'code'}} = 1;
1678 =head2 get_all_subpermissions
1680 my $perm_hashref = get_all_subpermissions();
1682 Returns a hashref of hashrefs defining all specific
1683 permissions currently defined. The return value
1684 has the same structure as that of C<get_user_subpermissions>,
1685 except that the innermost hash value is the description
1686 of the subpermission.
1690 sub get_all_subpermissions {
1691 my $dbh = C4::Context->dbh;
1692 my $sth = $dbh->prepare("SELECT flag, code, description
1694 JOIN userflags ON (module_bit = bit)");
1698 while (my $perm = $sth->fetchrow_hashref) {
1699 $all_perms->{$perm->{'flag'}}->{$perm->{'code'}} = $perm->{'description'};
1704 =head2 haspermission
1706 $flags = ($userid, $flagsrequired);
1708 C<$userid> the userid of the member
1709 C<$flags> is a hashref of required flags like C<$borrower-<{authflags}>
1711 Returns member's flags or 0 if a permission is not met.
1716 my ($userid, $flagsrequired) = @_;
1717 my $sth = C4::Context->dbh->prepare("SELECT flags FROM borrowers WHERE userid=?");
1718 $sth->execute($userid);
1719 my $row = $sth->fetchrow();
1720 my $flags = getuserflags($row, $userid);
1721 if ( $userid eq C4::Context->config('user') ) {
1722 # Super User Account from /etc/koha.conf
1723 $flags->{'superlibrarian'} = 1;
1725 elsif ( $userid eq 'demo' && C4::Context->config('demo') ) {
1726 # Demo user that can do "anything" (demo=1 in /etc/koha.conf)
1727 $flags->{'superlibrarian'} = 1;
1730 return $flags if $flags->{superlibrarian};
1732 foreach my $module ( keys %$flagsrequired ) {
1733 my $subperm = $flagsrequired->{$module};
1734 if ($subperm eq '*') {
1735 return 0 unless ( $flags->{$module} == 1 or ref($flags->{$module}) );
1737 return 0 unless ( $flags->{$module} == 1 or
1738 ( ref($flags->{$module}) and
1739 exists $flags->{$module}->{$subperm} and
1740 $flags->{$module}->{$subperm} == 1
1746 #FIXME - This fcn should return the failed permission so a suitable error msg can be delivered.
1750 sub getborrowernumber {
1752 my $userenv = C4::Context->userenv;
1753 if ( defined( $userenv ) && ref( $userenv ) eq 'HASH' && $userenv->{number} ) {
1754 return $userenv->{number};
1756 my $dbh = C4::Context->dbh;
1757 for my $field ( 'userid', 'cardnumber' ) {
1759 $dbh->prepare("select borrowernumber from borrowers where $field=?");
1760 $sth->execute($userid);
1762 my ($bnumber) = $sth->fetchrow;
1769 sub ParseSearchHistoryCookie {
1771 my $search_cookie = $input->cookie('KohaOpacRecentSearches');
1772 return () unless $search_cookie;
1773 my $obj = eval { decode_json(uri_unescape($search_cookie)) };
1774 return () unless defined $obj;
1775 return () unless ref $obj eq 'ARRAY';
1779 END { } # module clean-up code here (global destructor)
1789 Crypt::Eksblowfish::Bcrypt(3)