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
8 # under the terms of the GNU General Public License as published by
9 # the Free Software Foundation; either version 3 of the License, or
10 # (at your option) any later version.
12 # Koha is distributed in the hope that it will be useful, but
13 # WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU General Public License for more details.
17 # You should have received a copy of the GNU General Public License
18 # along with Koha; if not, see <http://www.gnu.org/licenses>.
22 use Digest::MD5 qw(md5_base64);
23 use JSON qw/encode_json/;
29 use C4::Templates; # to get the template
31 use C4::Search::History;
33 use Koha::UploadedFile;
35 use Koha::AuthUtils qw(get_script_name hash_password);
36 use Koha::DateUtils qw(dt_from_string);
37 use Koha::Library::Groups;
40 use POSIX qw/strftime/;
41 use List::MoreUtils qw/ any /;
42 use Encode qw( encode is_utf8);
45 use vars qw(@ISA @EXPORT @EXPORT_OK %EXPORT_TAGS $debug $ldap $cas $caslogout $shib $shib_login);
48 sub psgi_env { any { /^psgi\./ } keys %ENV }
51 if (psgi_env) { die 'psgi:exit' }
57 @EXPORT = qw(&checkauth &get_template_and_user &haspermission &get_user_subpermissions);
58 @EXPORT_OK = qw(&check_api_auth &get_session &check_cookie_auth &checkpw &checkpw_internal &checkpw_hash
59 &get_all_subpermissions &get_user_subpermissions track_login_daily
61 %EXPORT_TAGS = ( EditPermissions => [qw(get_all_subpermissions get_user_subpermissions)] );
62 $ldap = C4::Context->config('useldapserver') || 0;
63 $cas = C4::Context->preference('casAuthentication');
64 $shib = C4::Context->config('useshibboleth') || 0;
65 $caslogout = C4::Context->preference('casLogout');
66 require C4::Auth_with_cas; # no import
69 require C4::Auth_with_ldap;
70 import C4::Auth_with_ldap qw(checkpw_ldap);
73 require C4::Auth_with_shibboleth;
74 import C4::Auth_with_shibboleth
75 qw(shib_ok checkpw_shib logout_shib login_shib_url get_login_shib);
77 # Check for good config
80 # Get shibboleth login attribute
81 $shib_login = get_login_shib();
84 # Bad config, disable shibboleth
90 import C4::Auth_with_cas qw(check_api_auth_cas checkpw_cas login_cas logout_cas login_cas_url logout_if_required);
97 C4::Auth - Authenticates Koha users
101 use CGI qw ( -utf8 );
107 my ($template, $borrowernumber, $cookie)
108 = get_template_and_user(
110 template_name => "opac-main.tt",
113 authnotrequired => 0,
114 flagsrequired => { catalogue => '*', tools => 'import_patrons' },
118 output_html_with_http_headers $query, $cookie, $template->output;
122 The main function of this module is to provide
123 authentification. However the get_template_and_user function has
124 been provided so that a users login information is passed along
125 automatically. This gets loaded into the template.
129 =head2 get_template_and_user
131 my ($template, $borrowernumber, $cookie)
132 = get_template_and_user(
134 template_name => "opac-main.tt",
137 authnotrequired => 0,
138 flagsrequired => { catalogue => '*', tools => 'import_patrons' },
142 This call passes the C<query>, C<flagsrequired> and C<authnotrequired>
143 to C<&checkauth> (in this module) to perform authentification.
144 See C<&checkauth> for an explanation of these parameters.
146 The C<template_name> is then used to find the correct template for
147 the page. The authenticated users details are loaded onto the
148 template in the HTML::Template LOOP variable C<USER_INFO>. Also the
149 C<sessionID> is passed to the template. This can be used in templates
150 if cookies are disabled. It needs to be put as and input to every
153 More information on the C<gettemplate> sub can be found in the
158 sub get_template_and_user {
161 my ( $user, $cookie, $sessionID, $flags );
163 C4::Context->interface( $in->{type} );
165 $in->{'authnotrequired'} ||= 0;
167 # the following call includes a bad template check; might croak
168 my $template = C4::Templates::gettemplate(
169 $in->{'template_name'},
174 if ( $in->{'template_name'} !~ m/maintenance/ ) {
175 ( $user, $cookie, $sessionID, $flags ) = checkauth(
177 $in->{'authnotrequired'},
178 $in->{'flagsrequired'},
183 if ( $in->{type} eq 'opac' && $user ) {
187 # If the user logged in is the SCO user and they try to go out of the SCO module,
188 # log the user out removing the CGISESSID cookie
189 $in->{template_name} !~ m|sco/|
190 && C4::Context->preference('AutoSelfCheckID')
191 && $user eq C4::Context->preference('AutoSelfCheckID')
197 # If the user logged in is the SCI user and they try to go out of the SCI module,
198 # kick them out unless it is SCO with a valid permission
199 # or they are a superlibrarian
200 $in->{template_name} !~ m|sci/|
201 && haspermission( $user, { self_check => 'self_checkin_module' } )
203 $in->{template_name} =~ m|sco/| && haspermission(
204 $user, { self_check => 'self_checkout_module' }
207 && $flags && $flags->{superlibrarian} != 1
214 $template = C4::Templates::gettemplate( 'opac-auth.tt', 'opac',
216 $cookie = $in->{query}->cookie(
217 -name => 'CGISESSID',
225 script_name => get_script_name(),
228 print $in->{query}->header(
233 'X-Frame-Options' => 'SAMEORIGIN'
244 # It's possible for $user to be the borrowernumber if they don't have a
245 # userid defined (and are logging in through some other method, such
246 # as SSL certs against an email address)
248 $borrowernumber = getborrowernumber($user) if defined($user);
249 if ( !defined($borrowernumber) && defined($user) ) {
250 $patron = Koha::Patrons->find( $user );
252 $borrowernumber = $user;
254 # A bit of a hack, but I don't know there's a nicer way
256 $user = $patron->firstname . ' ' . $patron->surname;
259 $patron = Koha::Patrons->find( $borrowernumber );
260 # FIXME What to do if $patron does not exist?
264 $template->param( loggedinusername => $user ); # FIXME Should be replaced with something like patron-title.inc
265 $template->param( loggedinusernumber => $borrowernumber ); # FIXME Should be replaced with logged_in_user.borrowernumber
266 $template->param( logged_in_user => $patron );
267 $template->param( sessionID => $sessionID );
269 if ( $in->{'type'} eq 'opac' ) {
270 require Koha::Virtualshelves;
271 my $some_private_shelves = Koha::Virtualshelves->get_some_shelves(
273 borrowernumber => $borrowernumber,
277 my $some_public_shelves = Koha::Virtualshelves->get_some_shelves(
283 some_private_shelves => $some_private_shelves,
284 some_public_shelves => $some_public_shelves,
288 $template->param( "USER_INFO" => $patron->unblessed ) if $borrowernumber != 0;
290 my $all_perms = get_all_subpermissions();
292 my @flagroots = qw(circulate catalogue parameters borrowers permissions reserveforothers borrow
293 editcatalogue updatecharges tools editauthorities serials reports acquisition clubs);
295 # We are going to use the $flags returned by checkauth
296 # to create the template's parameters that will indicate
297 # which menus the user can access.
298 if ( $flags && $flags->{superlibrarian} == 1 ) {
299 $template->param( CAN_user_circulate => 1 );
300 $template->param( CAN_user_catalogue => 1 );
301 $template->param( CAN_user_parameters => 1 );
302 $template->param( CAN_user_borrowers => 1 );
303 $template->param( CAN_user_permissions => 1 );
304 $template->param( CAN_user_reserveforothers => 1 );
305 $template->param( CAN_user_editcatalogue => 1 );
306 $template->param( CAN_user_updatecharges => 1 );
307 $template->param( CAN_user_acquisition => 1 );
308 $template->param( CAN_user_tools => 1 );
309 $template->param( CAN_user_editauthorities => 1 );
310 $template->param( CAN_user_serials => 1 );
311 $template->param( CAN_user_reports => 1 );
312 $template->param( CAN_user_staffaccess => 1 );
313 $template->param( CAN_user_plugins => 1 );
314 $template->param( CAN_user_coursereserves => 1 );
315 $template->param( CAN_user_clubs => 1 );
316 $template->param( CAN_user_ill => 1 );
318 foreach my $module ( keys %$all_perms ) {
319 foreach my $subperm ( keys %{ $all_perms->{$module} } ) {
320 $template->param( "CAN_user_${module}_${subperm}" => 1 );
326 foreach my $module ( keys %$all_perms ) {
327 if ( defined($flags->{$module}) && $flags->{$module} == 1 ) {
328 foreach my $subperm ( keys %{ $all_perms->{$module} } ) {
329 $template->param( "CAN_user_${module}_${subperm}" => 1 );
331 } elsif ( ref( $flags->{$module} ) ) {
332 foreach my $subperm ( keys %{ $flags->{$module} } ) {
333 $template->param( "CAN_user_${module}_${subperm}" => 1 );
340 foreach my $module ( keys %$flags ) {
341 if ( $flags->{$module} == 1 or ref( $flags->{$module} ) ) {
342 $template->param( "CAN_user_$module" => 1 );
347 # Logged-in opac search history
348 # If the requested template is an opac one and opac search history is enabled
349 if ( $in->{type} eq 'opac' && C4::Context->preference('EnableOpacSearchHistory') ) {
350 my $dbh = C4::Context->dbh;
351 my $query = "SELECT COUNT(*) FROM search_history WHERE userid=?";
352 my $sth = $dbh->prepare($query);
353 $sth->execute($borrowernumber);
355 # If at least one search has already been performed
356 if ( $sth->fetchrow_array > 0 ) {
358 # We show the link in opac
359 $template->param( EnableOpacSearchHistory => 1 );
361 if (C4::Context->preference('LoadSearchHistoryToTheFirstLoggedUser'))
363 # And if there are searches performed when the user was not logged in,
364 # we add them to the logged-in search history
365 my @recentSearches = C4::Search::History::get_from_session( { cgi => $in->{'query'} } );
366 if (@recentSearches) {
367 my $dbh = C4::Context->dbh;
369 INSERT INTO search_history(userid, sessionid, query_desc, query_cgi, type, total, time )
370 VALUES (?, ?, ?, ?, ?, ?, ?)
372 my $sth = $dbh->prepare($query);
373 $sth->execute( $borrowernumber,
374 $in->{query}->cookie("CGISESSID"),
377 $_->{type} || 'biblio',
380 ) foreach @recentSearches;
382 # clear out the search history from the session now that
383 # we've saved it to the database
386 C4::Search::History::set_to_session( { cgi => $in->{'query'}, search_history => [] } );
388 } elsif ( $in->{type} eq 'intranet' and C4::Context->preference('EnableSearchHistory') ) {
389 $template->param( EnableSearchHistory => 1 );
392 else { # if this is an anonymous session, setup to display public lists...
394 # If shibboleth is enabled, and we're in an anonymous session, we should allow
395 # the user to attempt login via shibboleth.
397 $template->param( shibbolethAuthentication => $shib,
398 shibbolethLoginUrl => login_shib_url( $in->{'query'} ),
401 # If shibboleth is enabled and we have a shibboleth login attribute,
402 # but we are in an anonymous session, then we clearly have an invalid
403 # shibboleth koha account.
405 $template->param( invalidShibLogin => '1' );
409 $template->param( sessionID => $sessionID );
411 if ( $in->{'type'} eq 'opac' ){
412 require Koha::Virtualshelves;
413 my $some_public_shelves = Koha::Virtualshelves->get_some_shelves(
419 some_public_shelves => $some_public_shelves,
424 # Anonymous opac search history
425 # If opac search history is enabled and at least one search has already been performed
426 if ( C4::Context->preference('EnableOpacSearchHistory') ) {
427 my @recentSearches = C4::Search::History::get_from_session( { cgi => $in->{'query'} } );
428 if (@recentSearches) {
429 $template->param( EnableOpacSearchHistory => 1 );
433 if ( C4::Context->preference('dateformat') ) {
434 $template->param( dateformat => C4::Context->preference('dateformat') );
437 $template->param(auth_forwarded_hash => scalar $in->{'query'}->param('auth_forwarded_hash'));
439 # these template parameters are set the same regardless of $in->{'type'}
441 # Set the using_https variable for templates
442 # FIXME Under Plack the CGI->https method always returns 'OFF'
443 my $https = $in->{query}->https();
444 my $using_https = ( defined $https and $https ne 'OFF' ) ? 1 : 0;
446 my $minPasswordLength = C4::Context->preference('minPasswordLength');
447 $minPasswordLength = 3 if not $minPasswordLength or $minPasswordLength < 3;
449 "BiblioDefaultView" . C4::Context->preference("BiblioDefaultView") => 1,
450 EnhancedMessagingPreferences => C4::Context->preference('EnhancedMessagingPreferences'),
451 GoogleJackets => C4::Context->preference("GoogleJackets"),
452 OpenLibraryCovers => C4::Context->preference("OpenLibraryCovers"),
453 KohaAdminEmailAddress => "" . C4::Context->preference("KohaAdminEmailAddress"),
454 LoginBranchcode => ( C4::Context->userenv ? C4::Context->userenv->{"branch"} : undef ),
455 LoginFirstname => ( C4::Context->userenv ? C4::Context->userenv->{"firstname"} : "Bel" ),
456 LoginSurname => C4::Context->userenv ? C4::Context->userenv->{"surname"} : "Inconnu",
457 emailaddress => C4::Context->userenv ? C4::Context->userenv->{"emailaddress"} : undef,
458 TagsEnabled => C4::Context->preference("TagsEnabled"),
459 hide_marc => C4::Context->preference("hide_marc"),
460 item_level_itypes => C4::Context->preference('item-level_itypes'),
461 patronimages => C4::Context->preference("patronimages"),
462 singleBranchMode => ( Koha::Libraries->search->count == 1 ),
463 XSLTDetailsDisplay => C4::Context->preference("XSLTDetailsDisplay"),
464 XSLTResultsDisplay => C4::Context->preference("XSLTResultsDisplay"),
465 using_https => $using_https,
466 noItemTypeImages => C4::Context->preference("noItemTypeImages"),
467 marcflavour => C4::Context->preference("marcflavour"),
468 OPACBaseURL => C4::Context->preference('OPACBaseURL'),
469 minPasswordLength => $minPasswordLength,
471 if ( $in->{'type'} eq "intranet" ) {
473 AmazonCoverImages => C4::Context->preference("AmazonCoverImages"),
474 AutoLocation => C4::Context->preference("AutoLocation"),
475 "BiblioDefaultView" . C4::Context->preference("IntranetBiblioDefaultView") => 1,
476 CircAutocompl => C4::Context->preference("CircAutocompl"),
477 FRBRizeEditions => C4::Context->preference("FRBRizeEditions"),
478 IndependentBranches => C4::Context->preference("IndependentBranches"),
479 IntranetNav => C4::Context->preference("IntranetNav"),
480 IntranetmainUserblock => C4::Context->preference("IntranetmainUserblock"),
481 LibraryName => C4::Context->preference("LibraryName"),
482 LoginBranchname => ( C4::Context->userenv ? C4::Context->userenv->{"branchname"} : undef ),
483 advancedMARCEditor => C4::Context->preference("advancedMARCEditor"),
484 canreservefromotherbranches => C4::Context->preference('canreservefromotherbranches'),
485 intranetcolorstylesheet => C4::Context->preference("intranetcolorstylesheet"),
486 IntranetFavicon => C4::Context->preference("IntranetFavicon"),
487 intranetreadinghistory => C4::Context->preference("intranetreadinghistory"),
488 intranetstylesheet => C4::Context->preference("intranetstylesheet"),
489 IntranetUserCSS => C4::Context->preference("IntranetUserCSS"),
490 IntranetUserJS => C4::Context->preference("IntranetUserJS"),
491 intranetbookbag => C4::Context->preference("intranetbookbag"),
492 suggestion => C4::Context->preference("suggestion"),
493 virtualshelves => C4::Context->preference("virtualshelves"),
494 StaffSerialIssueDisplayCount => C4::Context->preference("StaffSerialIssueDisplayCount"),
495 EasyAnalyticalRecords => C4::Context->preference('EasyAnalyticalRecords'),
496 LocalCoverImages => C4::Context->preference('LocalCoverImages'),
497 OPACLocalCoverImages => C4::Context->preference('OPACLocalCoverImages'),
498 AllowMultipleCovers => C4::Context->preference('AllowMultipleCovers'),
499 EnableBorrowerFiles => C4::Context->preference('EnableBorrowerFiles'),
500 UseKohaPlugins => C4::Context->preference('UseKohaPlugins'),
501 UseCourseReserves => C4::Context->preference("UseCourseReserves"),
502 useDischarge => C4::Context->preference('useDischarge')
506 warn "template type should be OPAC, here it is=[" . $in->{'type'} . "]" unless ( $in->{'type'} eq 'opac' );
508 #TODO : replace LibraryName syspref with 'system name', and remove this html processing
509 my $LibraryNameTitle = C4::Context->preference("LibraryName");
510 $LibraryNameTitle =~ s/<(?:\/?)(?:br|p)\s*(?:\/?)>/ /sgi;
511 $LibraryNameTitle =~ s/<(?:[^<>'"]|'(?:[^']*)'|"(?:[^"]*)")*>//sg;
513 # clean up the busc param in the session
514 # if the page is not opac-detail and not the "add to list" page
515 # and not the "edit comments" page
516 if ( C4::Context->preference("OpacBrowseResults")
517 && $in->{'template_name'} =~ /opac-(.+)\.(?:tt|tmpl)$/ ) {
519 unless ( $pagename =~ /^(?:MARC|ISBD)?detail$/
520 or $pagename =~ /^addbybiblionumber$/
521 or $pagename =~ /^review$/ ) {
522 my $sessionSearch = get_session( $sessionID || $in->{'query'}->cookie("CGISESSID") );
523 $sessionSearch->clear( ["busc"] ) if ( $sessionSearch->param("busc") );
527 # variables passed from CGI: opac_css_override and opac_search_limits.
528 my $opac_search_limit = $ENV{'OPAC_SEARCH_LIMIT'};
529 my $opac_limit_override = $ENV{'OPAC_LIMIT_OVERRIDE'};
532 ( $opac_limit_override && $opac_search_limit && $opac_search_limit =~ /branch:(\w+)/ ) ||
533 ( $in->{'query'}->param('limit') && $in->{'query'}->param('limit') =~ /branch:(\w+)/ ) ||
534 ( $in->{'query'}->param('multibranchlimit') && $in->{'query'}->param('multibranchlimit') =~ /multibranchlimit-(\w+)/ )
536 $opac_name = $1; # opac_search_limit is a branch, so we use it.
537 } elsif ( $in->{'query'}->param('multibranchlimit') ) {
538 $opac_name = $in->{'query'}->param('multibranchlimit');
539 } elsif ( C4::Context->preference("SearchMyLibraryFirst") && C4::Context->userenv && C4::Context->userenv->{'branch'} ) {
540 $opac_name = C4::Context->userenv->{'branch'};
543 my @search_groups = Koha::Library::Groups->get_search_groups({ interface => 'opac' });
545 OpacAdditionalStylesheet => C4::Context->preference("OpacAdditionalStylesheet"),
546 AnonSuggestions => "" . C4::Context->preference("AnonSuggestions"),
547 LibrarySearchGroups => \@search_groups,
548 opac_name => $opac_name,
549 LibraryName => "" . C4::Context->preference("LibraryName"),
550 LibraryNameTitle => "" . $LibraryNameTitle,
551 LoginBranchname => C4::Context->userenv ? C4::Context->userenv->{"branchname"} : "",
552 OPACAmazonCoverImages => C4::Context->preference("OPACAmazonCoverImages"),
553 OPACFRBRizeEditions => C4::Context->preference("OPACFRBRizeEditions"),
554 OpacHighlightedWords => C4::Context->preference("OpacHighlightedWords"),
555 OPACShelfBrowser => "" . C4::Context->preference("OPACShelfBrowser"),
556 OPACURLOpenInNewWindow => "" . C4::Context->preference("OPACURLOpenInNewWindow"),
557 OPACUserCSS => "" . C4::Context->preference("OPACUserCSS"),
558 OpacAuthorities => C4::Context->preference("OpacAuthorities"),
559 opac_css_override => $ENV{'OPAC_CSS_OVERRIDE'},
560 opac_search_limit => $opac_search_limit,
561 opac_limit_override => $opac_limit_override,
562 OpacBrowser => C4::Context->preference("OpacBrowser"),
563 OpacCloud => C4::Context->preference("OpacCloud"),
564 OpacKohaUrl => C4::Context->preference("OpacKohaUrl"),
565 OpacMainUserBlock => "" . C4::Context->preference("OpacMainUserBlock"),
566 OpacNav => "" . C4::Context->preference("OpacNav"),
567 OpacNavRight => "" . C4::Context->preference("OpacNavRight"),
568 OpacNavBottom => "" . C4::Context->preference("OpacNavBottom"),
569 OpacPasswordChange => C4::Context->preference("OpacPasswordChange"),
570 OPACPatronDetails => C4::Context->preference("OPACPatronDetails"),
571 OPACPrivacy => C4::Context->preference("OPACPrivacy"),
572 OPACFinesTab => C4::Context->preference("OPACFinesTab"),
573 OpacTopissue => C4::Context->preference("OpacTopissue"),
574 RequestOnOpac => C4::Context->preference("RequestOnOpac"),
575 'Version' => C4::Context->preference('Version'),
576 hidelostitems => C4::Context->preference("hidelostitems"),
577 mylibraryfirst => ( C4::Context->preference("SearchMyLibraryFirst") && C4::Context->userenv ) ? C4::Context->userenv->{'branch'} : '',
578 opaclayoutstylesheet => "" . C4::Context->preference("opaclayoutstylesheet"),
579 opacbookbag => "" . C4::Context->preference("opacbookbag"),
580 opaccredits => "" . C4::Context->preference("opaccredits"),
581 OpacFavicon => C4::Context->preference("OpacFavicon"),
582 opacheader => "" . C4::Context->preference("opacheader"),
583 opaclanguagesdisplay => "" . C4::Context->preference("opaclanguagesdisplay"),
584 opacreadinghistory => C4::Context->preference("opacreadinghistory"),
585 OPACUserJS => C4::Context->preference("OPACUserJS"),
586 opacuserlogin => "" . C4::Context->preference("opacuserlogin"),
587 OpenLibrarySearch => C4::Context->preference("OpenLibrarySearch"),
588 ShowReviewer => C4::Context->preference("ShowReviewer"),
589 ShowReviewerPhoto => C4::Context->preference("ShowReviewerPhoto"),
590 suggestion => "" . C4::Context->preference("suggestion"),
591 virtualshelves => "" . C4::Context->preference("virtualshelves"),
592 OPACSerialIssueDisplayCount => C4::Context->preference("OPACSerialIssueDisplayCount"),
593 OPACXSLTDetailsDisplay => C4::Context->preference("OPACXSLTDetailsDisplay"),
594 OPACXSLTResultsDisplay => C4::Context->preference("OPACXSLTResultsDisplay"),
595 SyndeticsClientCode => C4::Context->preference("SyndeticsClientCode"),
596 SyndeticsEnabled => C4::Context->preference("SyndeticsEnabled"),
597 SyndeticsCoverImages => C4::Context->preference("SyndeticsCoverImages"),
598 SyndeticsTOC => C4::Context->preference("SyndeticsTOC"),
599 SyndeticsSummary => C4::Context->preference("SyndeticsSummary"),
600 SyndeticsEditions => C4::Context->preference("SyndeticsEditions"),
601 SyndeticsExcerpt => C4::Context->preference("SyndeticsExcerpt"),
602 SyndeticsReviews => C4::Context->preference("SyndeticsReviews"),
603 SyndeticsAuthorNotes => C4::Context->preference("SyndeticsAuthorNotes"),
604 SyndeticsAwards => C4::Context->preference("SyndeticsAwards"),
605 SyndeticsSeries => C4::Context->preference("SyndeticsSeries"),
606 SyndeticsCoverImageSize => C4::Context->preference("SyndeticsCoverImageSize"),
607 OPACLocalCoverImages => C4::Context->preference("OPACLocalCoverImages"),
608 PatronSelfRegistration => C4::Context->preference("PatronSelfRegistration"),
609 PatronSelfRegistrationDefaultCategory => C4::Context->preference("PatronSelfRegistrationDefaultCategory"),
610 useDischarge => C4::Context->preference('useDischarge'),
613 $template->param( OpacPublic => '1' ) if ( $user || C4::Context->preference("OpacPublic") );
616 # Check if we were asked using parameters to force a specific language
617 if ( defined $in->{'query'}->param('language') ) {
619 # Extract the language, let C4::Languages::getlanguage choose
621 my $language = C4::Languages::getlanguage( $in->{'query'} );
622 my $languagecookie = C4::Templates::getlanguagecookie( $in->{'query'}, $language );
623 if ( ref $cookie eq 'ARRAY' ) {
624 push @{$cookie}, $languagecookie;
626 $cookie = [ $cookie, $languagecookie ];
630 return ( $template, $borrowernumber, $cookie, $flags );
635 ($userid, $cookie, $sessionID) = &checkauth($query, $noauth, $flagsrequired, $type);
637 Verifies that the user is authorized to run this script. If
638 the user is authorized, a (userid, cookie, session-id, flags)
639 quadruple is returned. If the user is not authorized but does
640 not have the required privilege (see $flagsrequired below), it
641 displays an error page and exits. Otherwise, it displays the
642 login page and exits.
644 Note that C<&checkauth> will return if and only if the user
645 is authorized, so it should be called early on, before any
646 unfinished operations (e.g., if you've opened a file, then
647 C<&checkauth> won't close it for you).
649 C<$query> is the CGI object for the script calling C<&checkauth>.
651 The C<$noauth> argument is optional. If it is set, then no
652 authorization is required for the script.
654 C<&checkauth> fetches user and session information from C<$query> and
655 ensures that the user is authorized to run scripts that require
658 The C<$flagsrequired> argument specifies the required privileges
659 the user must have if the username and password are correct.
660 It should be specified as a reference-to-hash; keys in the hash
661 should be the "flags" for the user, as specified in the Members
662 intranet module. Any key specified must correspond to a "flag"
663 in the userflags table. E.g., { circulate => 1 } would specify
664 that the user must have the "circulate" privilege in order to
665 proceed. To make sure that access control is correct, the
666 C<$flagsrequired> parameter must be specified correctly.
668 Koha also has a concept of sub-permissions, also known as
669 granular permissions. This makes the value of each key
670 in the C<flagsrequired> hash take on an additional
675 The user must have access to all subfunctions of the module
676 specified by the hash key.
680 The user must have access to at least one subfunction of the module
681 specified by the hash key.
683 specific permission, e.g., 'export_catalog'
685 The user must have access to the specific subfunction list, which
686 must correspond to a row in the permissions table.
688 The C<$type> argument specifies whether the template should be
689 retrieved from the opac or intranet directory tree. "opac" is
690 assumed if it is not specified; however, if C<$type> is specified,
691 "intranet" is assumed if it is not "opac".
693 If C<$query> does not have a valid session ID associated with it
694 (i.e., the user has not logged in) or if the session has expired,
695 C<&checkauth> presents the user with a login page (from the point of
696 view of the original script, C<&checkauth> does not return). Once the
697 user has authenticated, C<&checkauth> restarts the original script
698 (this time, C<&checkauth> returns).
700 The login page is provided using a HTML::Template, which is set in the
701 systempreferences table or at the top of this file. The variable C<$type>
702 selects which template to use, either the opac or the intranet
703 authentification template.
705 C<&checkauth> returns a user ID, a cookie, and a session ID. The
706 cookie should be sent back to the browser; it verifies that the user
716 # If version syspref is unavailable, it means Koha is being installed,
717 # and so we must redirect to OPAC maintenance page or to the WebInstaller
718 # also, if OpacMaintenance is ON, OPAC should redirect to maintenance
719 if ( C4::Context->preference('OpacMaintenance') && $type eq 'opac' ) {
720 warn "OPAC Install required, redirecting to maintenance";
721 print $query->redirect("/cgi-bin/koha/maintenance.pl");
724 unless ( $version = C4::Context->preference('Version') ) { # assignment, not comparison
725 if ( $type ne 'opac' ) {
726 warn "Install required, redirecting to Installer";
727 print $query->redirect("/cgi-bin/koha/installer/install.pl");
729 warn "OPAC Install required, redirecting to maintenance";
730 print $query->redirect("/cgi-bin/koha/maintenance.pl");
735 # check that database and koha version are the same
736 # there is no DB version, it's a fresh install,
737 # go to web installer
738 # there is a DB version, compare it to the code version
739 my $kohaversion = Koha::version();
741 # remove the 3 last . to have a Perl number
742 $kohaversion =~ s/(.*\..*)\.(.*)\.(.*)/$1$2$3/;
743 $debug and print STDERR "kohaversion : $kohaversion\n";
744 if ( $version < $kohaversion ) {
745 my $warning = "Database update needed, redirecting to %s. Database is $version and Koha is $kohaversion";
746 if ( $type ne 'opac' ) {
747 warn sprintf( $warning, 'Installer' );
748 print $query->redirect("/cgi-bin/koha/installer/install.pl?step=1&op=updatestructure");
750 warn sprintf( "OPAC: " . $warning, 'maintenance' );
751 print $query->redirect("/cgi-bin/koha/maintenance.pl");
759 open my $fh, '>>', "/tmp/sessionlog" or warn "ERROR: Cannot append to /tmp/sessionlog";
760 printf $fh join( "\n", @_ );
764 sub _timeout_syspref {
765 my $timeout = C4::Context->preference('timeout') || 600;
767 # value in days, convert in seconds
768 if ( $timeout =~ /(\d+)[dD]/ ) {
769 $timeout = $1 * 86400;
776 $debug and warn "Checking Auth";
777 # $authnotrequired will be set for scripts which will run without authentication
778 my $authnotrequired = shift;
779 my $flagsrequired = shift;
781 my $emailaddress = shift;
782 $type = 'opac' unless $type;
784 my $dbh = C4::Context->dbh;
785 my $timeout = _timeout_syspref();
787 _version_check( $type, $query );
792 my ( $userid, $cookie, $sessionID, $flags );
793 my $logout = $query->param('logout.x');
795 my $anon_search_history;
797 # This parameter is the name of the CAS server we want to authenticate against,
798 # when using authentication against multiple CAS servers, as configured in Auth_cas_servers.yaml
799 my $casparam = $query->param('cas');
800 my $q_userid = $query->param('userid') // '';
804 # Basic authentication is incompatible with the use of Shibboleth,
805 # as Shibboleth may return REMOTE_USER as a Shibboleth attribute,
806 # and it may not be the attribute we want to use to match the koha login.
808 # Also, do not consider an empty REMOTE_USER.
810 # Finally, after those tests, we can assume (although if it would be better with
811 # a syspref) that if we get a REMOTE_USER, that's from basic authentication,
812 # and we can affect it to $userid.
813 if ( !$shib and defined( $ENV{'REMOTE_USER'} ) and $ENV{'REMOTE_USER'} ne '' and $userid = $ENV{'REMOTE_USER'} ) {
815 # Using Basic Authentication, no cookies required
816 $cookie = $query->cookie(
817 -name => 'CGISESSID',
824 elsif ( $emailaddress) {
825 # the Google OpenID Connect passes an email address
827 elsif ( $sessionID = $query->cookie("CGISESSID") )
828 { # assignment, not comparison
829 $session = get_session($sessionID);
830 C4::Context->_new_userenv($sessionID);
831 my ( $ip, $lasttime, $sessiontype );
834 $s_userid = $session->param('id') // '';
835 C4::Context->set_userenv(
836 $session->param('number'), $s_userid,
837 $session->param('cardnumber'), $session->param('firstname'),
838 $session->param('surname'), $session->param('branch'),
839 $session->param('branchname'), $session->param('flags'),
840 $session->param('emailaddress'), $session->param('branchprinter'),
841 $session->param('shibboleth')
843 C4::Context::set_shelves_userenv( 'bar', $session->param('barshelves') );
844 C4::Context::set_shelves_userenv( 'pub', $session->param('pubshelves') );
845 C4::Context::set_shelves_userenv( 'tot', $session->param('totshelves') );
846 $debug and printf STDERR "AUTH_SESSION: (%s)\t%s %s - %s\n", map { $session->param($_) } qw(cardnumber firstname surname branch);
847 $ip = $session->param('ip');
848 $lasttime = $session->param('lasttime');
850 $sessiontype = $session->param('sessiontype') || '';
852 if ( ( $query->param('koha_login_context') && ( $q_userid ne $s_userid ) )
853 || ( $cas && $query->param('ticket') && !C4::Context->userenv->{'id'} )
854 || ( $shib && $shib_login && !$logout && !C4::Context->userenv->{'id'} )
857 #if a user enters an id ne to the id in the current session, we need to log them in...
858 #first we need to clear the anonymous session...
859 $debug and warn "query id = $q_userid but session id = $s_userid";
860 $anon_search_history = $session->param('search_history');
863 C4::Context->_unset_userenv($sessionID);
869 # voluntary logout the user
870 # check wether the user was using their shibboleth session or a local one
871 my $shibSuccess = C4::Context->userenv->{'shibboleth'};
874 C4::Context->_unset_userenv($sessionID);
876 #_session_log(sprintf "%20s from %16s logged out at %30s (manually).\n", $userid,$ip,(strftime "%c",localtime));
880 if ($cas and $caslogout) {
881 logout_cas($query, $type);
884 # If we are in a shibboleth session (shibboleth is enabled, a shibboleth match attribute is set and matches koha matchpoint)
885 if ( $shib and $shib_login and $shibSuccess and $type eq 'opac' ) {
887 # (Note: $type eq 'opac' condition should be removed when shibboleth authentication for intranet will be implemented)
891 elsif ( !$lasttime || ( $lasttime < time() - $timeout ) ) {
894 $info{'timed_out'} = 1;
899 C4::Context->_unset_userenv($sessionID);
901 #_session_log(sprintf "%20s from %16s logged out at %30s (inactivity).\n", $userid,$ip,(strftime "%c",localtime));
905 elsif ( C4::Context->preference('SessionRestrictionByIP') && $ip ne $ENV{'REMOTE_ADDR'} ) {
907 # Different ip than originally logged in from
908 $info{'oldip'} = $ip;
909 $info{'newip'} = $ENV{'REMOTE_ADDR'};
910 $info{'different_ip'} = 1;
913 C4::Context->_unset_userenv($sessionID);
915 #_session_log(sprintf "%20s from %16s logged out at %30s (ip changed to %16s).\n", $userid,$ip,(strftime "%c",localtime), $info{'newip'});
920 $cookie = $query->cookie(
921 -name => 'CGISESSID',
922 -value => $session->id,
925 $session->param( 'lasttime', time() );
926 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...
927 $flags = haspermission( $userid, $flagsrequired );
931 $info{'nopermission'} = 1;
936 unless ( $userid || $sessionID ) {
937 #we initiate a session prior to checking for a username to allow for anonymous sessions...
938 my $session = get_session("") or die "Auth ERROR: Cannot get_session()";
940 # Save anonymous search history in new session so it can be retrieved
941 # by get_template_and_user to store it in user's search history after
942 # a successful login.
943 if ($anon_search_history) {
944 $session->param( 'search_history', $anon_search_history );
947 my $sessionID = $session->id;
948 C4::Context->_new_userenv($sessionID);
949 $cookie = $query->cookie(
950 -name => 'CGISESSID',
951 -value => $session->id,
954 my $pki_field = C4::Context->preference('AllowPKIAuth');
955 if ( !defined($pki_field) ) {
956 print STDERR "ERROR: Missing system preference AllowPKIAuth.\n";
959 if ( ( $cas && $query->param('ticket') )
961 || ( $shib && $shib_login )
962 || $pki_field ne 'None'
965 my $password = $query->param('password');
967 my ( $return, $cardnumber );
969 # If shib is enabled and we have a shib login, does the login match a valid koha user
970 if ( $shib && $shib_login && $type eq 'opac' ) {
973 # Do not pass password here, else shib will not be checked in checkpw.
974 ( $return, $cardnumber, $retuserid ) = checkpw( $dbh, $q_userid, undef, $query );
975 $userid = $retuserid;
976 $shibSuccess = $return;
977 $info{'invalidShibLogin'} = 1 unless ($return);
980 # If shib login and match were successful, skip further login methods
981 unless ($shibSuccess) {
982 if ( $cas && $query->param('ticket') ) {
984 ( $return, $cardnumber, $retuserid, $cas_ticket ) =
985 checkpw( $dbh, $userid, $password, $query, $type );
986 $userid = $retuserid;
987 $info{'invalidCasLogin'} = 1 unless ($return);
990 elsif ( $emailaddress ) {
991 my $value = $emailaddress;
993 # If we're looking up the email, there's a chance that the person
994 # doesn't have a userid. So if there is none, we pass along the
995 # borrower number, and the bits of code that need to know the user
996 # ID will have to be smart enough to handle that.
997 my $patrons = Koha::Patrons->search({ email => $value });
998 if ($patrons->count) {
1000 # First the userid, then the borrowernum
1001 my $patron = $patrons->next;
1002 $value = $patron->userid || $patron->borrowernumber;
1006 $return = $value ? 1 : 0;
1011 ( $pki_field eq 'Common Name' && $ENV{'SSL_CLIENT_S_DN_CN'} )
1012 || ( $pki_field eq 'emailAddress'
1013 && $ENV{'SSL_CLIENT_S_DN_Email'} )
1017 if ( $pki_field eq 'Common Name' ) {
1018 $value = $ENV{'SSL_CLIENT_S_DN_CN'};
1020 elsif ( $pki_field eq 'emailAddress' ) {
1021 $value = $ENV{'SSL_CLIENT_S_DN_Email'};
1023 # If we're looking up the email, there's a chance that the person
1024 # doesn't have a userid. So if there is none, we pass along the
1025 # borrower number, and the bits of code that need to know the user
1026 # ID will have to be smart enough to handle that.
1027 my $patrons = Koha::Patrons->search({ email => $value });
1028 if ($patrons->count) {
1030 # First the userid, then the borrowernum
1031 my $patron = $patrons->next;
1032 $value = $patron->userid || $patron->borrowernumber;
1038 $return = $value ? 1 : 0;
1044 ( $return, $cardnumber, $retuserid, $cas_ticket ) =
1045 checkpw( $dbh, $q_userid, $password, $query, $type );
1046 $userid = $retuserid if ($retuserid);
1047 $info{'invalid_username_or_password'} = 1 unless ($return);
1051 # $return: 1 = valid user
1054 #_session_log(sprintf "%20s from %16s logged in at %30s.\n", $userid,$ENV{'REMOTE_ADDR'},(strftime '%c', localtime));
1055 if ( $flags = haspermission( $userid, $flagsrequired ) ) {
1059 $info{'nopermission'} = 1;
1060 C4::Context->_unset_userenv($sessionID);
1062 my ( $borrowernumber, $firstname, $surname, $userflags,
1063 $branchcode, $branchname, $branchprinter, $emailaddress );
1065 if ( $return == 1 ) {
1067 SELECT borrowernumber, firstname, surname, flags, borrowers.branchcode,
1068 branches.branchname as branchname,
1069 branches.branchprinter as branchprinter,
1072 LEFT JOIN branches on borrowers.branchcode=branches.branchcode
1074 my $sth = $dbh->prepare("$select where userid=?");
1075 $sth->execute($userid);
1076 unless ( $sth->rows ) {
1077 $debug and print STDERR "AUTH_1: no rows for userid='$userid'\n";
1078 $sth = $dbh->prepare("$select where cardnumber=?");
1079 $sth->execute($cardnumber);
1081 unless ( $sth->rows ) {
1082 $debug and print STDERR "AUTH_2a: no rows for cardnumber='$cardnumber'\n";
1083 $sth->execute($userid);
1084 unless ( $sth->rows ) {
1085 $debug and print STDERR "AUTH_2b: no rows for userid='$userid' AS cardnumber\n";
1090 ( $borrowernumber, $firstname, $surname, $userflags,
1091 $branchcode, $branchname, $branchprinter, $emailaddress ) = $sth->fetchrow;
1092 $debug and print STDERR "AUTH_3 results: " .
1093 "$cardnumber,$borrowernumber,$userid,$firstname,$surname,$userflags,$branchcode,$emailaddress\n";
1095 print STDERR "AUTH_3: no results for userid='$userid', cardnumber='$cardnumber'.\n";
1098 # launch a sequence to check if we have a ip for the branch, i
1099 # if we have one we replace the branchcode of the userenv by the branch bound in the ip.
1101 my $ip = $ENV{'REMOTE_ADDR'};
1103 # if they specify at login, use that
1104 if ( $query->param('branch') ) {
1105 $branchcode = $query->param('branch');
1106 my $library = Koha::Libraries->find($branchcode);
1107 $branchname = $library? $library->branchname: '';
1109 my $branches = { map { $_->branchcode => $_->unblessed } Koha::Libraries->search };
1110 if ( $type ne 'opac' and C4::Context->boolean_preference('AutoLocation') ) {
1112 # we have to check they are coming from the right ip range
1113 my $domain = $branches->{$branchcode}->{'branchip'};
1114 $domain =~ s|\.\*||g;
1115 if ( $ip !~ /^$domain/ ) {
1117 $cookie = $query->cookie(
1118 -name => 'CGISESSID',
1122 $info{'wrongip'} = 1;
1126 foreach my $br ( keys %$branches ) {
1128 # now we work with the treatment of ip
1129 my $domain = $branches->{$br}->{'branchip'};
1130 if ( $domain && $ip =~ /^$domain/ ) {
1131 $branchcode = $branches->{$br}->{'branchcode'};
1133 # new op dev : add the branchprinter and branchname in the cookie
1134 $branchprinter = $branches->{$br}->{'branchprinter'};
1135 $branchname = $branches->{$br}->{'branchname'};
1138 $session->param( 'number', $borrowernumber );
1139 $session->param( 'id', $userid );
1140 $session->param( 'cardnumber', $cardnumber );
1141 $session->param( 'firstname', $firstname );
1142 $session->param( 'surname', $surname );
1143 $session->param( 'branch', $branchcode );
1144 $session->param( 'branchname', $branchname );
1145 $session->param( 'flags', $userflags );
1146 $session->param( 'emailaddress', $emailaddress );
1147 $session->param( 'ip', $session->remote_addr() );
1148 $session->param( 'lasttime', time() );
1149 $session->param( 'shibboleth', $shibSuccess );
1150 $debug and printf STDERR "AUTH_4: (%s)\t%s %s - %s\n", map { $session->param($_) } qw(cardnumber firstname surname branch);
1152 $session->param('cas_ticket', $cas_ticket) if $cas_ticket;
1153 C4::Context->set_userenv(
1154 $session->param('number'), $session->param('id'),
1155 $session->param('cardnumber'), $session->param('firstname'),
1156 $session->param('surname'), $session->param('branch'),
1157 $session->param('branchname'), $session->param('flags'),
1158 $session->param('emailaddress'), $session->param('branchprinter'),
1159 $session->param('shibboleth')
1163 # $return: 0 = invalid user
1164 # reset to anonymous session
1166 $debug and warn "Login failed, resetting anonymous session...";
1168 $info{'invalid_username_or_password'} = 1;
1169 C4::Context->_unset_userenv($sessionID);
1171 $session->param( 'lasttime', time() );
1172 $session->param( 'ip', $session->remote_addr() );
1173 $session->param( 'sessiontype', 'anon' );
1175 } # END if ( $q_userid
1176 elsif ( $type eq "opac" ) {
1178 # if we are here this is an anonymous session; add public lists to it and a few other items...
1179 # anonymous sessions are created only for the OPAC
1180 $debug and warn "Initiating an anonymous session...";
1182 # setting a couple of other session vars...
1183 $session->param( 'ip', $session->remote_addr() );
1184 $session->param( 'lasttime', time() );
1185 $session->param( 'sessiontype', 'anon' );
1187 } # END unless ($userid)
1189 # finished authentification, now respond
1190 if ( $loggedin || $authnotrequired )
1194 $cookie = $query->cookie(
1195 -name => 'CGISESSID',
1201 track_login_daily( $userid );
1203 return ( $userid, $cookie, $sessionID, $flags );
1208 # AUTH rejected, show the login/password template, after checking the DB.
1212 # get the inputs from the incoming query
1214 foreach my $name ( param $query) {
1215 (next) if ( $name eq 'userid' || $name eq 'password' || $name eq 'ticket' );
1216 my $value = $query->param($name);
1217 push @inputs, { name => $name, value => $value };
1220 my $patron = Koha::Patrons->find({ userid => $q_userid }); # Not necessary logged in!
1222 my $LibraryNameTitle = C4::Context->preference("LibraryName");
1223 $LibraryNameTitle =~ s/<(?:\/?)(?:br|p)\s*(?:\/?)>/ /sgi;
1224 $LibraryNameTitle =~ s/<(?:[^<>'"]|'(?:[^']*)'|"(?:[^"]*)")*>//sg;
1226 my $template_name = ( $type eq 'opac' ) ? 'opac-auth.tt' : 'auth.tt';
1227 my $template = C4::Templates::gettemplate( $template_name, $type, $query );
1229 OpacAdditionalStylesheet => C4::Context->preference("OpacAdditionalStylesheet"),
1230 opaclayoutstylesheet => C4::Context->preference("opaclayoutstylesheet"),
1233 script_name => get_script_name(),
1234 casAuthentication => C4::Context->preference("casAuthentication"),
1235 shibbolethAuthentication => $shib,
1236 SessionRestrictionByIP => C4::Context->preference("SessionRestrictionByIP"),
1237 suggestion => C4::Context->preference("suggestion"),
1238 virtualshelves => C4::Context->preference("virtualshelves"),
1239 LibraryName => "" . C4::Context->preference("LibraryName"),
1240 LibraryNameTitle => "" . $LibraryNameTitle,
1241 opacuserlogin => C4::Context->preference("opacuserlogin"),
1242 OpacNav => C4::Context->preference("OpacNav"),
1243 OpacNavRight => C4::Context->preference("OpacNavRight"),
1244 OpacNavBottom => C4::Context->preference("OpacNavBottom"),
1245 opaccredits => C4::Context->preference("opaccredits"),
1246 OpacFavicon => C4::Context->preference("OpacFavicon"),
1247 opacreadinghistory => C4::Context->preference("opacreadinghistory"),
1248 opaclanguagesdisplay => C4::Context->preference("opaclanguagesdisplay"),
1249 OPACUserJS => C4::Context->preference("OPACUserJS"),
1250 opacbookbag => "" . C4::Context->preference("opacbookbag"),
1251 OpacCloud => C4::Context->preference("OpacCloud"),
1252 OpacTopissue => C4::Context->preference("OpacTopissue"),
1253 OpacAuthorities => C4::Context->preference("OpacAuthorities"),
1254 OpacBrowser => C4::Context->preference("OpacBrowser"),
1255 opacheader => C4::Context->preference("opacheader"),
1256 TagsEnabled => C4::Context->preference("TagsEnabled"),
1257 OPACUserCSS => C4::Context->preference("OPACUserCSS"),
1258 intranetcolorstylesheet => C4::Context->preference("intranetcolorstylesheet"),
1259 intranetstylesheet => C4::Context->preference("intranetstylesheet"),
1260 intranetbookbag => C4::Context->preference("intranetbookbag"),
1261 IntranetNav => C4::Context->preference("IntranetNav"),
1262 IntranetFavicon => C4::Context->preference("IntranetFavicon"),
1263 IntranetUserCSS => C4::Context->preference("IntranetUserCSS"),
1264 IntranetUserJS => C4::Context->preference("IntranetUserJS"),
1265 IndependentBranches => C4::Context->preference("IndependentBranches"),
1266 AutoLocation => C4::Context->preference("AutoLocation"),
1267 wrongip => $info{'wrongip'},
1268 PatronSelfRegistration => C4::Context->preference("PatronSelfRegistration"),
1269 PatronSelfRegistrationDefaultCategory => C4::Context->preference("PatronSelfRegistrationDefaultCategory"),
1270 opac_css_override => $ENV{'OPAC_CSS_OVERRIDE'},
1271 too_many_login_attempts => ( $patron and $patron->account_locked )
1274 $template->param( SCO_login => 1 ) if ( $query->param('sco_user_login') );
1275 $template->param( SCI_login => 1 ) if ( $query->param('sci_user_login') );
1276 $template->param( OpacPublic => C4::Context->preference("OpacPublic") );
1277 $template->param( loginprompt => 1 ) unless $info{'nopermission'};
1279 if ( $type eq 'opac' ) {
1280 require Koha::Virtualshelves;
1281 my $some_public_shelves = Koha::Virtualshelves->get_some_shelves(
1287 some_public_shelves => $some_public_shelves,
1293 # Is authentication against multiple CAS servers enabled?
1294 if ( C4::Auth_with_cas::multipleAuth && !$casparam ) {
1295 my $casservers = C4::Auth_with_cas::getMultipleAuth();
1297 foreach my $key ( keys %$casservers ) {
1298 push @tmplservers, { name => $key, value => login_cas_url( $query, $key, $type ) . "?cas=$key" };
1301 casServersLoop => \@tmplservers
1305 casServerUrl => login_cas_url($query, undef, $type),
1310 invalidCasLogin => $info{'invalidCasLogin'}
1316 shibbolethAuthentication => $shib,
1317 shibbolethLoginUrl => login_shib_url($query),
1321 if (C4::Context->preference('GoogleOpenIDConnect')) {
1322 if ($query->param("OpenIDConnectFailed")) {
1323 my $reason = $query->param('OpenIDConnectFailed');
1324 $template->param(invalidGoogleOpenIDConnectLogin => $reason);
1329 LibraryName => C4::Context->preference("LibraryName"),
1331 $template->param(%info);
1333 # $cookie = $query->cookie(CGISESSID => $session->id
1335 print $query->header(
1336 { type => 'text/html',
1339 'X-Frame-Options' => 'SAMEORIGIN'
1346 =head2 check_api_auth
1348 ($status, $cookie, $sessionId) = check_api_auth($query, $userflags);
1350 Given a CGI query containing the parameters 'userid' and 'password' and/or a session
1351 cookie, determine if the user has the privileges specified by C<$userflags>.
1353 C<check_api_auth> is is meant for authenticating users of web services, and
1354 consequently will always return and will not attempt to redirect the user
1357 If a valid session cookie is already present, check_api_auth will return a status
1358 of "ok", the cookie, and the Koha session ID.
1360 If no session cookie is present, check_api_auth will check the 'userid' and 'password
1361 parameters and create a session cookie and Koha session if the supplied credentials
1364 Possible return values in C<$status> are:
1368 =item "ok" -- user authenticated; C<$cookie> and C<$sessionid> have valid values.
1370 =item "failed" -- credentials are not correct; C<$cookie> and C<$sessionid> are undef
1372 =item "maintenance" -- DB is in maintenance mode; no login possible at the moment
1374 =item "expired -- session cookie has expired; API user should resubmit userid and password
1380 sub check_api_auth {
1383 my $flagsrequired = shift;
1384 my $dbh = C4::Context->dbh;
1385 my $timeout = _timeout_syspref();
1387 unless ( C4::Context->preference('Version') ) {
1389 # database has not been installed yet
1390 return ( "maintenance", undef, undef );
1392 my $kohaversion = Koha::version();
1393 $kohaversion =~ s/(.*\..*)\.(.*)\.(.*)/$1$2$3/;
1394 if ( C4::Context->preference('Version') < $kohaversion ) {
1396 # database in need of version update; assume that
1397 # no API should be called while databsae is in
1399 return ( "maintenance", undef, undef );
1402 # FIXME -- most of what follows is a copy-and-paste
1403 # of code from checkauth. There is an obvious need
1404 # for refactoring to separate the various parts of
1405 # the authentication code, but as of 2007-11-19 this
1406 # is deferred so as to not introduce bugs into the
1407 # regular authentication code for Koha 3.0.
1409 # see if we have a valid session cookie already
1410 # however, if a userid parameter is present (i.e., from
1411 # a form submission, assume that any current cookie
1413 my $sessionID = undef;
1414 unless ( $query->param('userid') ) {
1415 $sessionID = $query->cookie("CGISESSID");
1417 if ( $sessionID && not( $cas && $query->param('PT') ) ) {
1418 my $session = get_session($sessionID);
1419 C4::Context->_new_userenv($sessionID);
1421 C4::Context->set_userenv(
1422 $session->param('number'), $session->param('id'),
1423 $session->param('cardnumber'), $session->param('firstname'),
1424 $session->param('surname'), $session->param('branch'),
1425 $session->param('branchname'), $session->param('flags'),
1426 $session->param('emailaddress'), $session->param('branchprinter')
1429 my $ip = $session->param('ip');
1430 my $lasttime = $session->param('lasttime');
1431 my $userid = $session->param('id');
1432 if ( $lasttime < time() - $timeout ) {
1437 C4::Context->_unset_userenv($sessionID);
1440 return ( "expired", undef, undef );
1441 } elsif ( C4::Context->preference('SessionRestrictionByIP') && $ip ne $ENV{'REMOTE_ADDR'} ) {
1443 # IP address changed
1446 C4::Context->_unset_userenv($sessionID);
1449 return ( "expired", undef, undef );
1451 my $cookie = $query->cookie(
1452 -name => 'CGISESSID',
1453 -value => $session->id,
1456 $session->param( 'lasttime', time() );
1457 my $flags = haspermission( $userid, $flagsrequired );
1459 return ( "ok", $cookie, $sessionID );
1463 C4::Context->_unset_userenv($sessionID);
1466 return ( "failed", undef, undef );
1470 return ( "expired", undef, undef );
1475 my $userid = $query->param('userid');
1476 my $password = $query->param('password');
1477 my ( $return, $cardnumber, $cas_ticket );
1480 if ( $cas && $query->param('PT') ) {
1482 $debug and print STDERR "## check_api_auth - checking CAS\n";
1484 # In case of a CAS authentication, we use the ticket instead of the password
1485 my $PT = $query->param('PT');
1486 ( $return, $cardnumber, $userid, $cas_ticket ) = check_api_auth_cas( $dbh, $PT, $query ); # EXTERNAL AUTH
1489 # User / password auth
1490 unless ( $userid and $password ) {
1492 # caller did something wrong, fail the authenticateion
1493 return ( "failed", undef, undef );
1496 ( $return, $cardnumber, $newuserid, $cas_ticket ) = checkpw( $dbh, $userid, $password, $query );
1499 if ( $return and haspermission( $userid, $flagsrequired ) ) {
1500 my $session = get_session("");
1501 return ( "failed", undef, undef ) unless $session;
1503 my $sessionID = $session->id;
1504 C4::Context->_new_userenv($sessionID);
1505 my $cookie = $query->cookie(
1506 -name => 'CGISESSID',
1507 -value => $sessionID,
1510 if ( $return == 1 ) {
1512 $borrowernumber, $firstname, $surname,
1513 $userflags, $branchcode, $branchname,
1514 $branchprinter, $emailaddress
1518 "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=?"
1520 $sth->execute($userid);
1522 $borrowernumber, $firstname, $surname,
1523 $userflags, $branchcode, $branchname,
1524 $branchprinter, $emailaddress
1525 ) = $sth->fetchrow if ( $sth->rows );
1527 unless ( $sth->rows ) {
1528 my $sth = $dbh->prepare(
1529 "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=?"
1531 $sth->execute($cardnumber);
1533 $borrowernumber, $firstname, $surname,
1534 $userflags, $branchcode, $branchname,
1535 $branchprinter, $emailaddress
1536 ) = $sth->fetchrow if ( $sth->rows );
1538 unless ( $sth->rows ) {
1539 $sth->execute($userid);
1541 $borrowernumber, $firstname, $surname, $userflags,
1542 $branchcode, $branchname, $branchprinter, $emailaddress
1543 ) = $sth->fetchrow if ( $sth->rows );
1547 my $ip = $ENV{'REMOTE_ADDR'};
1549 # if they specify at login, use that
1550 if ( $query->param('branch') ) {
1551 $branchcode = $query->param('branch');
1552 my $library = Koha::Libraries->find($branchcode);
1553 $branchname = $library? $library->branchname: '';
1555 my $branches = { map { $_->branchcode => $_->unblessed } Koha::Libraries->search };
1556 foreach my $br ( keys %$branches ) {
1558 # now we work with the treatment of ip
1559 my $domain = $branches->{$br}->{'branchip'};
1560 if ( $domain && $ip =~ /^$domain/ ) {
1561 $branchcode = $branches->{$br}->{'branchcode'};
1563 # new op dev : add the branchprinter and branchname in the cookie
1564 $branchprinter = $branches->{$br}->{'branchprinter'};
1565 $branchname = $branches->{$br}->{'branchname'};
1568 $session->param( 'number', $borrowernumber );
1569 $session->param( 'id', $userid );
1570 $session->param( 'cardnumber', $cardnumber );
1571 $session->param( 'firstname', $firstname );
1572 $session->param( 'surname', $surname );
1573 $session->param( 'branch', $branchcode );
1574 $session->param( 'branchname', $branchname );
1575 $session->param( 'flags', $userflags );
1576 $session->param( 'emailaddress', $emailaddress );
1577 $session->param( 'ip', $session->remote_addr() );
1578 $session->param( 'lasttime', time() );
1580 $session->param( 'cas_ticket', $cas_ticket);
1581 C4::Context->set_userenv(
1582 $session->param('number'), $session->param('id'),
1583 $session->param('cardnumber'), $session->param('firstname'),
1584 $session->param('surname'), $session->param('branch'),
1585 $session->param('branchname'), $session->param('flags'),
1586 $session->param('emailaddress'), $session->param('branchprinter')
1588 return ( "ok", $cookie, $sessionID );
1590 return ( "failed", undef, undef );
1595 =head2 check_cookie_auth
1597 ($status, $sessionId) = check_api_auth($cookie, $userflags);
1599 Given a CGISESSID cookie set during a previous login to Koha, determine
1600 if the user has the privileges specified by C<$userflags>.
1602 C<check_cookie_auth> is meant for authenticating special services
1603 such as tools/upload-file.pl that are invoked by other pages that
1604 have been authenticated in the usual way.
1606 Possible return values in C<$status> are:
1610 =item "ok" -- user authenticated; C<$sessionID> have valid values.
1612 =item "failed" -- credentials are not correct; C<$sessionid> are undef
1614 =item "maintenance" -- DB is in maintenance mode; no login possible at the moment
1616 =item "expired -- session cookie has expired; API user should resubmit userid and password
1622 sub check_cookie_auth {
1624 my $flagsrequired = shift;
1627 my $remote_addr = $params->{remote_addr} || $ENV{REMOTE_ADDR};
1628 my $dbh = C4::Context->dbh;
1629 my $timeout = _timeout_syspref();
1631 unless ( C4::Context->preference('Version') ) {
1633 # database has not been installed yet
1634 return ( "maintenance", undef );
1636 my $kohaversion = Koha::version();
1637 $kohaversion =~ s/(.*\..*)\.(.*)\.(.*)/$1$2$3/;
1638 if ( C4::Context->preference('Version') < $kohaversion ) {
1640 # database in need of version update; assume that
1641 # no API should be called while databsae is in
1643 return ( "maintenance", undef );
1646 # FIXME -- most of what follows is a copy-and-paste
1647 # of code from checkauth. There is an obvious need
1648 # for refactoring to separate the various parts of
1649 # the authentication code, but as of 2007-11-23 this
1650 # is deferred so as to not introduce bugs into the
1651 # regular authentication code for Koha 3.0.
1653 # see if we have a valid session cookie already
1654 # however, if a userid parameter is present (i.e., from
1655 # a form submission, assume that any current cookie
1657 unless ( defined $cookie and $cookie ) {
1658 return ( "failed", undef );
1660 my $sessionID = $cookie;
1661 my $session = get_session($sessionID);
1662 C4::Context->_new_userenv($sessionID);
1664 C4::Context->set_userenv(
1665 $session->param('number'), $session->param('id'),
1666 $session->param('cardnumber'), $session->param('firstname'),
1667 $session->param('surname'), $session->param('branch'),
1668 $session->param('branchname'), $session->param('flags'),
1669 $session->param('emailaddress'), $session->param('branchprinter')
1672 my $ip = $session->param('ip');
1673 my $lasttime = $session->param('lasttime');
1674 my $userid = $session->param('id');
1675 if ( $lasttime < time() - $timeout ) {
1680 C4::Context->_unset_userenv($sessionID);
1683 return ("expired", undef);
1684 } elsif ( C4::Context->preference('SessionRestrictionByIP') && $ip ne $remote_addr ) {
1686 # IP address changed
1689 C4::Context->_unset_userenv($sessionID);
1692 return ( "expired", undef );
1694 $session->param( 'lasttime', time() );
1695 my $flags = haspermission( $userid, $flagsrequired );
1697 return ( "ok", $sessionID );
1701 C4::Context->_unset_userenv($sessionID);
1704 return ( "failed", undef );
1708 return ( "expired", undef );
1715 my $session = get_session($sessionID);
1717 Given a session ID, retrieve the CGI::Session object used to store
1718 the session's state. The session object can be used to store
1719 data that needs to be accessed by different scripts during a
1722 If the C<$sessionID> parameter is an empty string, a new session
1727 sub _get_session_params {
1728 my $storage_method = C4::Context->preference('SessionStorage');
1729 if ( $storage_method eq 'mysql' ) {
1730 my $dbh = C4::Context->dbh;
1731 return { dsn => "driver:MySQL;serializer:yaml;id:md5", dsn_args => { Handle => $dbh } };
1733 elsif ( $storage_method eq 'Pg' ) {
1734 my $dbh = C4::Context->dbh;
1735 return { dsn => "driver:PostgreSQL;serializer:yaml;id:md5", dsn_args => { Handle => $dbh } };
1737 elsif ( $storage_method eq 'memcached' && Koha::Caches->get_instance->memcached_cache ) {
1738 my $memcached = Koha::Caches->get_instance()->memcached_cache;
1739 return { dsn => "driver:memcached;serializer:yaml;id:md5", dsn_args => { Memcached => $memcached } };
1742 # catch all defaults to tmp should work on all systems
1743 my $dir = C4::Context::temporary_directory;
1744 my $instance = C4::Context->config( 'database' ); #actually for packages not exactly the instance name, but generally safer to leave it as it is
1745 return { dsn => "driver:File;serializer:yaml;id:md5", dsn_args => { Directory => "$dir/cgisess_$instance" } };
1750 my $sessionID = shift;
1751 my $params = _get_session_params();
1752 return new CGI::Session( $params->{dsn}, $sessionID, $params->{dsn_args} );
1756 # FIXME no_set_userenv may be replaced with force_branchcode_for_userenv
1757 # (or something similar)
1758 # Currently it's only passed from C4::SIP::ILS::Patron::check_password, but
1759 # not having a userenv defined could cause a crash.
1761 my ( $dbh, $userid, $password, $query, $type, $no_set_userenv ) = @_;
1762 $type = 'opac' unless $type;
1765 my $patron = Koha::Patrons->find({ userid => $userid });
1766 my $check_internal_as_fallback = 0;
1768 # Note: checkpw_* routines returns:
1771 # -1 if user bind failed (LDAP only)
1773 if ( $patron and $patron->account_locked ) {
1774 # Nothing to check, account is locked
1776 $debug and print STDERR "## checkpw - checking LDAP\n";
1777 my ( $retval, $retcard, $retuserid ) = checkpw_ldap(@_); # EXTERNAL AUTH
1778 if ( $retval == 1 ) {
1779 @return = ( $retval, $retcard, $retuserid );
1782 $check_internal_as_fallback = 1 if $retval == 0;
1784 } elsif ( $cas && $query && $query->param('ticket') ) {
1785 $debug and print STDERR "## checkpw - checking CAS\n";
1787 # In case of a CAS authentication, we use the ticket instead of the password
1788 my $ticket = $query->param('ticket');
1789 $query->delete('ticket'); # remove ticket to come back to original URL
1790 my ( $retval, $retcard, $retuserid, $cas_ticket ) = checkpw_cas( $dbh, $ticket, $query, $type ); # EXTERNAL AUTH
1792 @return = ( $retval, $retcard, $retuserid, $cas_ticket );
1796 $passwd_ok = $retval;
1799 # If we are in a shibboleth session (shibboleth is enabled, and a shibboleth match attribute is present)
1800 # Check for password to asertain whether we want to be testing against shibboleth or another method this
1802 elsif ( $shib && $shib_login && !$password ) {
1804 $debug and print STDERR "## checkpw - checking Shibboleth\n";
1806 # In case of a Shibboleth authentication, we expect a shibboleth user attribute
1807 # (defined under shibboleth mapping in koha-conf.xml) to contain the login of the
1808 # shibboleth-authenticated user
1810 # Then, we check if it matches a valid koha user
1812 my ( $retval, $retcard, $retuserid ) = C4::Auth_with_shibboleth::checkpw_shib($shib_login); # EXTERNAL AUTH
1814 @return = ( $retval, $retcard, $retuserid );
1816 $passwd_ok = $retval;
1819 $check_internal_as_fallback = 1;
1823 if ( $check_internal_as_fallback ) {
1824 @return = checkpw_internal( $dbh, $userid, $password, $no_set_userenv);
1825 $passwd_ok = 1 if $return[0] > 0; # 1 or 2
1830 $patron->update({ login_attempts => 0 });
1832 $patron->update({ login_attempts => $patron->login_attempts + 1 });
1838 sub checkpw_internal {
1839 my ( $dbh, $userid, $password, $no_set_userenv ) = @_;
1841 $password = Encode::encode( 'UTF-8', $password )
1842 if Encode::is_utf8($password);
1846 "select password,cardnumber,borrowernumber,userid,firstname,surname,borrowers.branchcode,branches.branchname,flags from borrowers join branches on borrowers.branchcode=branches.branchcode where userid=?"
1848 $sth->execute($userid);
1850 my ( $stored_hash, $cardnumber, $borrowernumber, $userid, $firstname,
1851 $surname, $branchcode, $branchname, $flags )
1854 if ( checkpw_hash( $password, $stored_hash ) ) {
1856 C4::Context->set_userenv( "$borrowernumber", $userid, $cardnumber,
1857 $firstname, $surname, $branchcode, $branchname, $flags ) unless $no_set_userenv;
1858 return 1, $cardnumber, $userid;
1863 "select password,cardnumber,borrowernumber,userid,firstname,surname,borrowers.branchcode,branches.branchname,flags from borrowers join branches on borrowers.branchcode=branches.branchcode where cardnumber=?"
1865 $sth->execute($userid);
1867 my ( $stored_hash, $cardnumber, $borrowernumber, $userid, $firstname,
1868 $surname, $branchcode, $branchname, $flags )
1871 if ( checkpw_hash( $password, $stored_hash ) ) {
1873 C4::Context->set_userenv( $borrowernumber, $userid, $cardnumber,
1874 $firstname, $surname, $branchcode, $branchname, $flags ) unless $no_set_userenv;
1875 return 1, $cardnumber, $userid;
1882 my ( $password, $stored_hash ) = @_;
1884 return if $stored_hash eq '!';
1886 # check what encryption algorithm was implemented: Bcrypt - if the hash starts with '$2' it is Bcrypt else md5
1888 if ( substr( $stored_hash, 0, 2 ) eq '$2' ) {
1889 $hash = hash_password( $password, $stored_hash );
1891 $hash = md5_base64($password);
1893 return $hash eq $stored_hash;
1898 my $authflags = getuserflags($flags, $userid, [$dbh]);
1900 Translates integer flags into permissions strings hash.
1902 C<$flags> is the integer userflags value ( borrowers.userflags )
1903 C<$userid> is the members.userid, used for building subpermissions
1904 C<$authflags> is a hashref of permissions
1911 my $dbh = @_ ? shift : C4::Context->dbh;
1914 # I don't want to do this, but if someone logs in as the database
1915 # user, it would be preferable not to spam them to death with
1916 # numeric warnings. So, we make $flags numeric.
1917 no warnings 'numeric';
1920 my $sth = $dbh->prepare("SELECT bit, flag, defaulton FROM userflags");
1923 while ( my ( $bit, $flag, $defaulton ) = $sth->fetchrow ) {
1924 if ( ( $flags & ( 2**$bit ) ) || $defaulton ) {
1925 $userflags->{$flag} = 1;
1928 $userflags->{$flag} = 0;
1932 # get subpermissions and merge with top-level permissions
1933 my $user_subperms = get_user_subpermissions($userid);
1934 foreach my $module ( keys %$user_subperms ) {
1935 next if $userflags->{$module} == 1; # user already has permission for everything in this module
1936 $userflags->{$module} = $user_subperms->{$module};
1942 =head2 get_user_subpermissions
1944 $user_perm_hashref = get_user_subpermissions($userid);
1946 Given the userid (note, not the borrowernumber) of a staff user,
1947 return a hashref of hashrefs of the specific subpermissions
1948 accorded to the user. An example return is
1952 export_catalog => 1,
1953 import_patrons => 1,
1957 The top-level hash-key is a module or function code from
1958 userflags.flag, while the second-level key is a code
1961 The results of this function do not give a complete picture
1962 of the functions that a staff user can access; it is also
1963 necessary to check borrowers.flags.
1967 sub get_user_subpermissions {
1970 my $dbh = C4::Context->dbh;
1971 my $sth = $dbh->prepare( "SELECT flag, user_permissions.code
1972 FROM user_permissions
1973 JOIN permissions USING (module_bit, code)
1974 JOIN userflags ON (module_bit = bit)
1975 JOIN borrowers USING (borrowernumber)
1976 WHERE userid = ?" );
1977 $sth->execute($userid);
1979 my $user_perms = {};
1980 while ( my $perm = $sth->fetchrow_hashref ) {
1981 $user_perms->{ $perm->{'flag'} }->{ $perm->{'code'} } = 1;
1986 =head2 get_all_subpermissions
1988 my $perm_hashref = get_all_subpermissions();
1990 Returns a hashref of hashrefs defining all specific
1991 permissions currently defined. The return value
1992 has the same structure as that of C<get_user_subpermissions>,
1993 except that the innermost hash value is the description
1994 of the subpermission.
1998 sub get_all_subpermissions {
1999 my $dbh = C4::Context->dbh;
2000 my $sth = $dbh->prepare( "SELECT flag, code
2002 JOIN userflags ON (module_bit = bit)" );
2006 while ( my $perm = $sth->fetchrow_hashref ) {
2007 $all_perms->{ $perm->{'flag'} }->{ $perm->{'code'} } = 1;
2012 =head2 haspermission
2014 $flags = ($userid, $flagsrequired);
2016 C<$userid> the userid of the member
2017 C<$flags> is a hashref of required flags like C<$borrower-<{authflags}>
2019 Returns member's flags or 0 if a permission is not met.
2024 my ( $userid, $flagsrequired ) = @_;
2025 my $sth = C4::Context->dbh->prepare("SELECT flags FROM borrowers WHERE userid=?");
2026 $sth->execute($userid);
2027 my $row = $sth->fetchrow();
2028 my $flags = getuserflags( $row, $userid );
2030 return $flags if $flags->{superlibrarian};
2032 foreach my $module ( keys %$flagsrequired ) {
2033 my $subperm = $flagsrequired->{$module};
2034 if ( $subperm eq '*' ) {
2035 return 0 unless ( $flags->{$module} == 1 or ref( $flags->{$module} ) );
2038 ( defined $flags->{$module} and
2039 $flags->{$module} == 1 )
2041 ( ref( $flags->{$module} ) and
2042 exists $flags->{$module}->{$subperm} and
2043 $flags->{$module}->{$subperm} == 1 )
2049 #FIXME - This fcn should return the failed permission so a suitable error msg can be delivered.
2052 sub getborrowernumber {
2054 my $userenv = C4::Context->userenv;
2055 if ( defined($userenv) && ref($userenv) eq 'HASH' && $userenv->{number} ) {
2056 return $userenv->{number};
2058 my $dbh = C4::Context->dbh;
2059 for my $field ( 'userid', 'cardnumber' ) {
2061 $dbh->prepare("select borrowernumber from borrowers where $field=?");
2062 $sth->execute($userid);
2064 my ($bnumber) = $sth->fetchrow;
2071 =head2 track_login_daily
2073 track_login_daily( $userid );
2075 Wraps the call to $patron->track_login, the method used to update borrowers.lastseen. We only call track_login once a day.
2079 sub track_login_daily {
2081 return if !$userid || !C4::Context->preference('TrackLastPatronActivity');
2083 my $cache = Koha::Caches->get_instance();
2084 my $cache_key = "track_login_" . $userid;
2085 my $cached = $cache->get_from_cache($cache_key);
2086 my $today = dt_from_string()->ymd;
2087 return if $cached && $cached eq $today;
2089 my $patron = Koha::Patrons->find({ userid => $userid });
2090 return unless $patron;
2091 $patron->track_login;
2092 $cache->set_in_cache( $cache_key, $today );
2095 END { } # module clean-up code here (global destructor)
2105 Crypt::Eksblowfish::Bcrypt(3)