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>.
24 use Digest::MD5 qw(md5_base64);
25 use JSON qw/encode_json/;
31 use C4::Templates; # to get the template
33 use C4::Search::History;
36 use Koha::AuthUtils qw(get_script_name hash_password);
38 use Koha::DateUtils qw(dt_from_string);
39 use Koha::Library::Groups;
41 use Koha::Cash::Registers;
44 use Koha::Patron::Consents;
45 use POSIX qw/strftime/;
46 use List::MoreUtils qw/ any /;
47 use Encode qw( encode is_utf8);
48 use C4::Auth_with_shibboleth;
50 use C4::Log qw/logaction/;
53 use vars qw(@ISA @EXPORT @EXPORT_OK %EXPORT_TAGS $debug $ldap $cas $caslogout);
56 sub psgi_env { any { /^psgi\./ } keys %ENV }
59 if (psgi_env) { die 'psgi:exit' }
63 C4::Context->set_remote_address;
67 @EXPORT = qw(&checkauth &get_template_and_user &haspermission &get_user_subpermissions);
68 @EXPORT_OK = qw(&check_api_auth &get_session &check_cookie_auth &checkpw &checkpw_internal &checkpw_hash
69 &get_all_subpermissions &get_user_subpermissions track_login_daily &in_iprange
71 %EXPORT_TAGS = ( EditPermissions => [qw(get_all_subpermissions get_user_subpermissions)] );
72 $ldap = C4::Context->config('useldapserver') || 0;
73 $cas = C4::Context->preference('casAuthentication');
74 $caslogout = C4::Context->preference('casLogout');
75 require C4::Auth_with_cas; # no import
78 require C4::Auth_with_ldap;
79 import C4::Auth_with_ldap qw(checkpw_ldap);
82 import C4::Auth_with_cas qw(check_api_auth_cas checkpw_cas login_cas logout_cas login_cas_url logout_if_required);
89 C4::Auth - Authenticates Koha users
99 my ($template, $borrowernumber, $cookie)
100 = get_template_and_user(
102 template_name => "opac-main.tt",
105 authnotrequired => 0,
106 flagsrequired => { catalogue => '*', tools => 'import_patrons' },
110 output_html_with_http_headers $query, $cookie, $template->output;
114 The main function of this module is to provide
115 authentification. However the get_template_and_user function has
116 been provided so that a users login information is passed along
117 automatically. This gets loaded into the template.
121 =head2 get_template_and_user
123 my ($template, $borrowernumber, $cookie)
124 = get_template_and_user(
126 template_name => "opac-main.tt",
129 authnotrequired => 0,
130 flagsrequired => { catalogue => '*', tools => 'import_patrons' },
134 This call passes the C<query>, C<flagsrequired> and C<authnotrequired>
135 to C<&checkauth> (in this module) to perform authentification.
136 See C<&checkauth> for an explanation of these parameters.
138 The C<template_name> is then used to find the correct template for
139 the page. The authenticated users details are loaded onto the
140 template in the logged_in_user variable (which is a Koha::Patron object). Also the
141 C<sessionID> is passed to the template. This can be used in templates
142 if cookies are disabled. It needs to be put as and input to every
145 More information on the C<gettemplate> sub can be found in the
150 sub get_template_and_user {
153 my ( $user, $cookie, $sessionID, $flags );
155 # Get shibboleth login attribute
156 my $shib = C4::Context->config('useshibboleth') && shib_ok();
157 my $shib_login = $shib ? get_login_shib() : undef;
159 C4::Context->interface( $in->{type} );
161 $in->{'authnotrequired'} ||= 0;
163 # the following call includes a bad template check; might croak
164 my $template = C4::Templates::gettemplate(
165 $in->{'template_name'},
170 if ( $in->{'template_name'} !~ m/maintenance/ ) {
171 ( $user, $cookie, $sessionID, $flags ) = checkauth(
173 $in->{'authnotrequired'},
174 $in->{'flagsrequired'},
177 $in->{template_name},
181 # If we enforce GDPR and the user did not consent, redirect
182 # Exceptions for consent page itself and SCI/SCO system
183 if( $in->{type} eq 'opac' && $user &&
184 $in->{'template_name'} !~ /^(opac-patron-consent|sc[io]\/)/ &&
185 C4::Context->preference('GDPR_Policy') eq 'Enforced' )
187 my $consent = Koha::Patron::Consents->search({
188 borrowernumber => getborrowernumber($user),
189 type => 'GDPR_PROCESSING',
190 given_on => { '!=', undef },
193 print $in->{query}->redirect(-uri => '/cgi-bin/koha/opac-patron-consent.pl', -cookie => $cookie);
198 if ( $in->{type} eq 'opac' && $user ) {
201 my $session = get_session($sessionID);
203 $is_sco_user = $session->param('sco_user');
209 # If the user logged in is the SCO user and they try to go out of the SCO module,
210 # log the user out removing the CGISESSID cookie
211 $in->{template_name} !~ m|sco/| && $in->{template_name} !~ m|errors/errorpage.tt|
215 C4::Context->preference('AutoSelfCheckID')
216 && $user eq C4::Context->preference('AutoSelfCheckID')
224 # If the user logged in is the SCI user and they try to go out of the SCI module,
225 # kick them out unless it is SCO with a valid permission
226 # or they are a superlibrarian
227 $in->{template_name} !~ m|sci/|
228 && haspermission( $user, { self_check => 'self_checkin_module' } )
230 $in->{template_name} =~ m|sco/| && haspermission(
231 $user, { self_check => 'self_checkout_module' }
234 && $flags && $flags->{superlibrarian} != 1
241 $template = C4::Templates::gettemplate( 'opac-auth.tt', 'opac',
243 $cookie = $in->{query}->cookie(
244 -name => 'CGISESSID',
248 -secure => ( C4::Context->https_enabled() ? 1 : 0 ),
253 script_name => get_script_name(),
256 print $in->{query}->header(
261 'X-Frame-Options' => 'SAMEORIGIN'
272 # It's possible for $user to be the borrowernumber if they don't have a
273 # userid defined (and are logging in through some other method, such
274 # as SSL certs against an email address)
276 $borrowernumber = getborrowernumber($user) if defined($user);
277 if ( !defined($borrowernumber) && defined($user) ) {
278 $patron = Koha::Patrons->find( $user );
280 $borrowernumber = $user;
282 # A bit of a hack, but I don't know there's a nicer way
284 $user = $patron->firstname . ' ' . $patron->surname;
287 $patron = Koha::Patrons->find( $borrowernumber );
288 # FIXME What to do if $patron does not exist?
292 $template->param( loggedinusername => $user ); # OBSOLETE - Do not reuse this in template, use logged_in_user.userid instead
293 $template->param( loggedinusernumber => $borrowernumber ); # FIXME Should be replaced with logged_in_user.borrowernumber
294 $template->param( logged_in_user => $patron );
295 $template->param( sessionID => $sessionID );
297 if ( $in->{'type'} eq 'opac' ) {
298 require Koha::Virtualshelves;
299 my $some_private_shelves = Koha::Virtualshelves->get_some_shelves(
301 borrowernumber => $borrowernumber,
305 my $some_public_shelves = Koha::Virtualshelves->get_some_shelves(
311 some_private_shelves => $some_private_shelves,
312 some_public_shelves => $some_public_shelves,
316 my $all_perms = get_all_subpermissions();
318 my @flagroots = qw(circulate catalogue parameters borrowers permissions reserveforothers borrow
319 editcatalogue updatecharges tools editauthorities serials reports acquisition clubs problem_reports);
321 # We are going to use the $flags returned by checkauth
322 # to create the template's parameters that will indicate
323 # which menus the user can access.
324 if ( $flags && $flags->{superlibrarian} == 1 ) {
325 $template->param( CAN_user_circulate => 1 );
326 $template->param( CAN_user_catalogue => 1 );
327 $template->param( CAN_user_parameters => 1 );
328 $template->param( CAN_user_borrowers => 1 );
329 $template->param( CAN_user_permissions => 1 );
330 $template->param( CAN_user_reserveforothers => 1 );
331 $template->param( CAN_user_editcatalogue => 1 );
332 $template->param( CAN_user_updatecharges => 1 );
333 $template->param( CAN_user_acquisition => 1 );
334 $template->param( CAN_user_suggestions => 1 );
335 $template->param( CAN_user_tools => 1 );
336 $template->param( CAN_user_editauthorities => 1 );
337 $template->param( CAN_user_serials => 1 );
338 $template->param( CAN_user_reports => 1 );
339 $template->param( CAN_user_staffaccess => 1 );
340 $template->param( CAN_user_coursereserves => 1 );
341 $template->param( CAN_user_plugins => 1 );
342 $template->param( CAN_user_lists => 1 );
343 $template->param( CAN_user_clubs => 1 );
344 $template->param( CAN_user_ill => 1 );
345 $template->param( CAN_user_stockrotation => 1 );
346 $template->param( CAN_user_cash_management => 1 );
347 $template->param( CAN_user_problem_reports => 1 );
349 foreach my $module ( keys %$all_perms ) {
350 foreach my $subperm ( keys %{ $all_perms->{$module} } ) {
351 $template->param( "CAN_user_${module}_${subperm}" => 1 );
357 foreach my $module ( keys %$all_perms ) {
358 if ( defined($flags->{$module}) && $flags->{$module} == 1 ) {
359 foreach my $subperm ( keys %{ $all_perms->{$module} } ) {
360 $template->param( "CAN_user_${module}_${subperm}" => 1 );
362 } elsif ( ref( $flags->{$module} ) ) {
363 foreach my $subperm ( keys %{ $flags->{$module} } ) {
364 $template->param( "CAN_user_${module}_${subperm}" => 1 );
371 foreach my $module ( keys %$flags ) {
372 if ( $flags->{$module} == 1 or ref( $flags->{$module} ) ) {
373 $template->param( "CAN_user_$module" => 1 );
378 # Logged-in opac search history
379 # If the requested template is an opac one and opac search history is enabled
380 if ( $in->{type} eq 'opac' && C4::Context->preference('EnableOpacSearchHistory') ) {
381 my $dbh = C4::Context->dbh;
382 my $query = "SELECT COUNT(*) FROM search_history WHERE userid=?";
383 my $sth = $dbh->prepare($query);
384 $sth->execute($borrowernumber);
386 # If at least one search has already been performed
387 if ( $sth->fetchrow_array > 0 ) {
389 # We show the link in opac
390 $template->param( EnableOpacSearchHistory => 1 );
392 if (C4::Context->preference('LoadSearchHistoryToTheFirstLoggedUser'))
394 # And if there are searches performed when the user was not logged in,
395 # we add them to the logged-in search history
396 my @recentSearches = C4::Search::History::get_from_session( { cgi => $in->{'query'} } );
397 if (@recentSearches) {
398 my $dbh = C4::Context->dbh;
400 INSERT INTO search_history(userid, sessionid, query_desc, query_cgi, type, total, time )
401 VALUES (?, ?, ?, ?, ?, ?, ?)
403 my $sth = $dbh->prepare($query);
404 $sth->execute( $borrowernumber,
405 $in->{query}->cookie("CGISESSID"),
408 $_->{type} || 'biblio',
411 ) foreach @recentSearches;
413 # clear out the search history from the session now that
414 # we've saved it to the database
417 C4::Search::History::set_to_session( { cgi => $in->{'query'}, search_history => [] } );
419 } elsif ( $in->{type} eq 'intranet' and C4::Context->preference('EnableSearchHistory') ) {
420 $template->param( EnableSearchHistory => 1 );
423 else { # if this is an anonymous session, setup to display public lists...
425 # If shibboleth is enabled, and we're in an anonymous session, we should allow
426 # the user to attempt login via shibboleth.
428 $template->param( shibbolethAuthentication => $shib,
429 shibbolethLoginUrl => login_shib_url( $in->{'query'} ),
432 # If shibboleth is enabled and we have a shibboleth login attribute,
433 # but we are in an anonymous session, then we clearly have an invalid
434 # shibboleth koha account.
436 $template->param( invalidShibLogin => '1' );
440 $template->param( sessionID => $sessionID );
442 if ( $in->{'type'} eq 'opac' ){
443 require Koha::Virtualshelves;
444 my $some_public_shelves = Koha::Virtualshelves->get_some_shelves(
450 some_public_shelves => $some_public_shelves,
455 # Sysprefs disabled via URL param
456 # Note that value must be defined in order to override via ENV
457 foreach my $syspref (
463 OpacAdditionalStylesheet
465 intranetcolorstylesheet
470 $ENV{"OVERRIDE_SYSPREF_$syspref"} = q{}
471 if $in->{'query'}->param("DISABLE_SYSPREF_$syspref");
474 # Anonymous opac search history
475 # If opac search history is enabled and at least one search has already been performed
476 if ( C4::Context->preference('EnableOpacSearchHistory') ) {
477 my @recentSearches = C4::Search::History::get_from_session( { cgi => $in->{'query'} } );
478 if (@recentSearches) {
479 $template->param( EnableOpacSearchHistory => 1 );
483 if ( C4::Context->preference('dateformat') ) {
484 $template->param( dateformat => C4::Context->preference('dateformat') );
487 $template->param(auth_forwarded_hash => scalar $in->{'query'}->param('auth_forwarded_hash'));
489 # these template parameters are set the same regardless of $in->{'type'}
491 my $minPasswordLength = C4::Context->preference('minPasswordLength');
492 $minPasswordLength = 3 if not $minPasswordLength or $minPasswordLength < 3;
494 "BiblioDefaultView" . C4::Context->preference("BiblioDefaultView") => 1,
495 EnhancedMessagingPreferences => C4::Context->preference('EnhancedMessagingPreferences'),
496 GoogleJackets => C4::Context->preference("GoogleJackets"),
497 OpenLibraryCovers => C4::Context->preference("OpenLibraryCovers"),
498 KohaAdminEmailAddress => "" . C4::Context->preference("KohaAdminEmailAddress"),
499 LoginFirstname => ( C4::Context->userenv ? C4::Context->userenv->{"firstname"} : "Bel" ),
500 LoginSurname => C4::Context->userenv ? C4::Context->userenv->{"surname"} : "Inconnu",
501 emailaddress => C4::Context->userenv ? C4::Context->userenv->{"emailaddress"} : undef,
502 TagsEnabled => C4::Context->preference("TagsEnabled"),
503 hide_marc => C4::Context->preference("hide_marc"),
504 item_level_itypes => C4::Context->preference('item-level_itypes'),
505 patronimages => C4::Context->preference("patronimages"),
506 singleBranchMode => ( Koha::Libraries->search->count == 1 ),
507 XSLTDetailsDisplay => C4::Context->preference("XSLTDetailsDisplay"),
508 XSLTResultsDisplay => C4::Context->preference("XSLTResultsDisplay"),
509 noItemTypeImages => C4::Context->preference("noItemTypeImages"),
510 marcflavour => C4::Context->preference("marcflavour"),
511 OPACBaseURL => C4::Context->preference('OPACBaseURL'),
512 minPasswordLength => $minPasswordLength,
514 if ( $in->{'type'} eq "intranet" ) {
516 AmazonCoverImages => C4::Context->preference("AmazonCoverImages"),
517 AutoLocation => C4::Context->preference("AutoLocation"),
518 "BiblioDefaultView" . C4::Context->preference("IntranetBiblioDefaultView") => 1,
519 PatronAutoComplete => C4::Context->preference("PatronAutoComplete"),
520 FRBRizeEditions => C4::Context->preference("FRBRizeEditions"),
521 IndependentBranches => C4::Context->preference("IndependentBranches"),
522 IntranetNav => C4::Context->preference("IntranetNav"),
523 IntranetmainUserblock => C4::Context->preference("IntranetmainUserblock"),
524 LibraryName => C4::Context->preference("LibraryName"),
525 advancedMARCEditor => C4::Context->preference("advancedMARCEditor"),
526 canreservefromotherbranches => C4::Context->preference('canreservefromotherbranches'),
527 intranetcolorstylesheet => C4::Context->preference("intranetcolorstylesheet"),
528 IntranetFavicon => C4::Context->preference("IntranetFavicon"),
529 intranetreadinghistory => C4::Context->preference("intranetreadinghistory"),
530 intranetstylesheet => C4::Context->preference("intranetstylesheet"),
531 IntranetUserCSS => C4::Context->preference("IntranetUserCSS"),
532 IntranetUserJS => C4::Context->preference("IntranetUserJS"),
533 suggestion => C4::Context->preference("suggestion"),
534 virtualshelves => C4::Context->preference("virtualshelves"),
535 StaffSerialIssueDisplayCount => C4::Context->preference("StaffSerialIssueDisplayCount"),
536 EasyAnalyticalRecords => C4::Context->preference('EasyAnalyticalRecords'),
537 LocalCoverImages => C4::Context->preference('LocalCoverImages'),
538 OPACLocalCoverImages => C4::Context->preference('OPACLocalCoverImages'),
539 AllowMultipleCovers => C4::Context->preference('AllowMultipleCovers'),
540 EnableBorrowerFiles => C4::Context->preference('EnableBorrowerFiles'),
541 UseCourseReserves => C4::Context->preference("UseCourseReserves"),
542 useDischarge => C4::Context->preference('useDischarge'),
543 pending_checkout_notes => scalar Koha::Checkouts->search({ noteseen => 0 }),
547 warn "template type should be OPAC, here it is=[" . $in->{'type'} . "]" unless ( $in->{'type'} eq 'opac' );
549 #TODO : replace LibraryName syspref with 'system name', and remove this html processing
550 my $LibraryNameTitle = C4::Context->preference("LibraryName");
551 $LibraryNameTitle =~ s/<(?:\/?)(?:br|p)\s*(?:\/?)>/ /sgi;
552 $LibraryNameTitle =~ s/<(?:[^<>'"]|'(?:[^']*)'|"(?:[^"]*)")*>//sg;
554 # clean up the busc param in the session
555 # if the page is not opac-detail and not the "add to list" page
556 # and not the "edit comments" page
557 if ( C4::Context->preference("OpacBrowseResults")
558 && $in->{'template_name'} =~ /opac-(.+)\.(?:tt|tmpl)$/ ) {
560 unless ( $pagename =~ /^(?:MARC|ISBD)?detail$/
561 or $pagename =~ /^showmarc$/
562 or $pagename =~ /^addbybiblionumber$/
563 or $pagename =~ /^review$/ ) {
564 my $sessionSearch = get_session( $sessionID || $in->{'query'}->cookie("CGISESSID") );
565 $sessionSearch->clear( ["busc"] ) if ( $sessionSearch->param("busc") );
569 # variables passed from CGI: opac_css_override and opac_search_limits.
570 my $opac_search_limit = $ENV{'OPAC_SEARCH_LIMIT'};
571 my $opac_limit_override = $ENV{'OPAC_LIMIT_OVERRIDE'};
574 ( $opac_limit_override && $opac_search_limit && $opac_search_limit =~ /branch:([\w-]+)/ ) ||
575 ( $in->{'query'}->param('limit') && $in->{'query'}->param('limit') =~ /branch:([\w-]+)/ ) ||
576 ( $in->{'query'}->param('limit') && $in->{'query'}->param('limit') =~ /multibranchlimit:(\w+)/ )
578 $opac_name = $1; # opac_search_limit is a branch, so we use it.
579 } elsif ( $in->{'query'}->param('multibranchlimit') ) {
580 $opac_name = $in->{'query'}->param('multibranchlimit');
581 } elsif ( C4::Context->preference("SearchMyLibraryFirst") && C4::Context->userenv && C4::Context->userenv->{'branch'} ) {
582 $opac_name = C4::Context->userenv->{'branch'};
585 my @search_groups = Koha::Library::Groups->get_search_groups({ interface => 'opac' });
587 AnonSuggestions => "" . C4::Context->preference("AnonSuggestions"),
588 LibrarySearchGroups => \@search_groups,
589 opac_name => $opac_name,
590 LibraryName => "" . C4::Context->preference("LibraryName"),
591 LibraryNameTitle => "" . $LibraryNameTitle,
592 OPACAmazonCoverImages => C4::Context->preference("OPACAmazonCoverImages"),
593 OPACFRBRizeEditions => C4::Context->preference("OPACFRBRizeEditions"),
594 OpacHighlightedWords => C4::Context->preference("OpacHighlightedWords"),
595 OPACShelfBrowser => "" . C4::Context->preference("OPACShelfBrowser"),
596 OPACURLOpenInNewWindow => "" . C4::Context->preference("OPACURLOpenInNewWindow"),
597 OPACUserCSS => "" . C4::Context->preference("OPACUserCSS"),
598 OpacAuthorities => C4::Context->preference("OpacAuthorities"),
599 opac_css_override => $ENV{'OPAC_CSS_OVERRIDE'},
600 opac_search_limit => $opac_search_limit,
601 opac_limit_override => $opac_limit_override,
602 OpacBrowser => C4::Context->preference("OpacBrowser"),
603 OpacCloud => C4::Context->preference("OpacCloud"),
604 OpacKohaUrl => C4::Context->preference("OpacKohaUrl"),
605 OpacNav => "" . C4::Context->preference("OpacNav"),
606 OpacNavBottom => "" . C4::Context->preference("OpacNavBottom"),
607 OpacPasswordChange => C4::Context->preference("OpacPasswordChange"),
608 OPACPatronDetails => C4::Context->preference("OPACPatronDetails"),
609 OPACPrivacy => C4::Context->preference("OPACPrivacy"),
610 OPACFinesTab => C4::Context->preference("OPACFinesTab"),
611 OpacTopissue => C4::Context->preference("OpacTopissue"),
612 RequestOnOpac => C4::Context->preference("RequestOnOpac"),
613 'Version' => C4::Context->preference('Version'),
614 hidelostitems => C4::Context->preference("hidelostitems"),
615 mylibraryfirst => ( C4::Context->preference("SearchMyLibraryFirst") && C4::Context->userenv ) ? C4::Context->userenv->{'branch'} : '',
616 opacbookbag => "" . C4::Context->preference("opacbookbag"),
617 OpacFavicon => C4::Context->preference("OpacFavicon"),
618 opaclanguagesdisplay => "" . C4::Context->preference("opaclanguagesdisplay"),
619 opacreadinghistory => C4::Context->preference("opacreadinghistory"),
620 OPACUserJS => C4::Context->preference("OPACUserJS"),
621 opacuserlogin => "" . C4::Context->preference("opacuserlogin"),
622 OpenLibrarySearch => C4::Context->preference("OpenLibrarySearch"),
623 ShowReviewer => C4::Context->preference("ShowReviewer"),
624 ShowReviewerPhoto => C4::Context->preference("ShowReviewerPhoto"),
625 suggestion => "" . C4::Context->preference("suggestion"),
626 virtualshelves => "" . C4::Context->preference("virtualshelves"),
627 OPACSerialIssueDisplayCount => C4::Context->preference("OPACSerialIssueDisplayCount"),
628 OPACXSLTDetailsDisplay => C4::Context->preference("OPACXSLTDetailsDisplay"),
629 OPACXSLTResultsDisplay => C4::Context->preference("OPACXSLTResultsDisplay"),
630 SyndeticsClientCode => C4::Context->preference("SyndeticsClientCode"),
631 SyndeticsEnabled => C4::Context->preference("SyndeticsEnabled"),
632 SyndeticsCoverImages => C4::Context->preference("SyndeticsCoverImages"),
633 SyndeticsTOC => C4::Context->preference("SyndeticsTOC"),
634 SyndeticsSummary => C4::Context->preference("SyndeticsSummary"),
635 SyndeticsEditions => C4::Context->preference("SyndeticsEditions"),
636 SyndeticsExcerpt => C4::Context->preference("SyndeticsExcerpt"),
637 SyndeticsReviews => C4::Context->preference("SyndeticsReviews"),
638 SyndeticsAuthorNotes => C4::Context->preference("SyndeticsAuthorNotes"),
639 SyndeticsAwards => C4::Context->preference("SyndeticsAwards"),
640 SyndeticsSeries => C4::Context->preference("SyndeticsSeries"),
641 SyndeticsCoverImageSize => C4::Context->preference("SyndeticsCoverImageSize"),
642 OPACLocalCoverImages => C4::Context->preference("OPACLocalCoverImages"),
643 PatronSelfRegistration => C4::Context->preference("PatronSelfRegistration"),
644 PatronSelfRegistrationDefaultCategory => C4::Context->preference("PatronSelfRegistrationDefaultCategory"),
645 useDischarge => C4::Context->preference('useDischarge'),
648 $template->param( OpacPublic => '1' ) if ( $user || C4::Context->preference("OpacPublic") );
651 # Check if we were asked using parameters to force a specific language
652 if ( defined $in->{'query'}->param('language') ) {
654 # Extract the language, let C4::Languages::getlanguage choose
656 my $language = C4::Languages::getlanguage( $in->{'query'} );
657 my $languagecookie = C4::Templates::getlanguagecookie( $in->{'query'}, $language );
658 if ( ref $cookie eq 'ARRAY' ) {
659 push @{$cookie}, $languagecookie;
661 $cookie = [ $cookie, $languagecookie ];
665 return ( $template, $borrowernumber, $cookie, $flags );
670 ($userid, $cookie, $sessionID) = &checkauth($query, $noauth, $flagsrequired, $type);
672 Verifies that the user is authorized to run this script. If
673 the user is authorized, a (userid, cookie, session-id, flags)
674 quadruple is returned. If the user is not authorized but does
675 not have the required privilege (see $flagsrequired below), it
676 displays an error page and exits. Otherwise, it displays the
677 login page and exits.
679 Note that C<&checkauth> will return if and only if the user
680 is authorized, so it should be called early on, before any
681 unfinished operations (e.g., if you've opened a file, then
682 C<&checkauth> won't close it for you).
684 C<$query> is the CGI object for the script calling C<&checkauth>.
686 The C<$noauth> argument is optional. If it is set, then no
687 authorization is required for the script.
689 C<&checkauth> fetches user and session information from C<$query> and
690 ensures that the user is authorized to run scripts that require
693 The C<$flagsrequired> argument specifies the required privileges
694 the user must have if the username and password are correct.
695 It should be specified as a reference-to-hash; keys in the hash
696 should be the "flags" for the user, as specified in the Members
697 intranet module. Any key specified must correspond to a "flag"
698 in the userflags table. E.g., { circulate => 1 } would specify
699 that the user must have the "circulate" privilege in order to
700 proceed. To make sure that access control is correct, the
701 C<$flagsrequired> parameter must be specified correctly.
703 Koha also has a concept of sub-permissions, also known as
704 granular permissions. This makes the value of each key
705 in the C<flagsrequired> hash take on an additional
710 The user must have access to all subfunctions of the module
711 specified by the hash key.
715 The user must have access to at least one subfunction of the module
716 specified by the hash key.
718 specific permission, e.g., 'export_catalog'
720 The user must have access to the specific subfunction list, which
721 must correspond to a row in the permissions table.
723 The C<$type> argument specifies whether the template should be
724 retrieved from the opac or intranet directory tree. "opac" is
725 assumed if it is not specified; however, if C<$type> is specified,
726 "intranet" is assumed if it is not "opac".
728 If C<$query> does not have a valid session ID associated with it
729 (i.e., the user has not logged in) or if the session has expired,
730 C<&checkauth> presents the user with a login page (from the point of
731 view of the original script, C<&checkauth> does not return). Once the
732 user has authenticated, C<&checkauth> restarts the original script
733 (this time, C<&checkauth> returns).
735 The login page is provided using a HTML::Template, which is set in the
736 systempreferences table or at the top of this file. The variable C<$type>
737 selects which template to use, either the opac or the intranet
738 authentification template.
740 C<&checkauth> returns a user ID, a cookie, and a session ID. The
741 cookie should be sent back to the browser; it verifies that the user
751 # If version syspref is unavailable, it means Koha is being installed,
752 # and so we must redirect to OPAC maintenance page or to the WebInstaller
753 # also, if OpacMaintenance is ON, OPAC should redirect to maintenance
754 if ( C4::Context->preference('OpacMaintenance') && $type eq 'opac' ) {
755 warn "OPAC Install required, redirecting to maintenance";
756 print $query->redirect("/cgi-bin/koha/maintenance.pl");
759 unless ( $version = C4::Context->preference('Version') ) { # assignment, not comparison
760 if ( $type ne 'opac' ) {
761 warn "Install required, redirecting to Installer";
762 print $query->redirect("/cgi-bin/koha/installer/install.pl");
764 warn "OPAC Install required, redirecting to maintenance";
765 print $query->redirect("/cgi-bin/koha/maintenance.pl");
770 # check that database and koha version are the same
771 # there is no DB version, it's a fresh install,
772 # go to web installer
773 # there is a DB version, compare it to the code version
774 my $kohaversion = Koha::version();
776 # remove the 3 last . to have a Perl number
777 $kohaversion =~ s/(.*\..*)\.(.*)\.(.*)/$1$2$3/;
778 $debug and print STDERR "kohaversion : $kohaversion\n";
779 if ( $version < $kohaversion ) {
780 my $warning = "Database update needed, redirecting to %s. Database is $version and Koha is $kohaversion";
781 if ( $type ne 'opac' ) {
782 warn sprintf( $warning, 'Installer' );
783 print $query->redirect("/cgi-bin/koha/installer/install.pl?step=1&op=updatestructure");
785 warn sprintf( "OPAC: " . $warning, 'maintenance' );
786 print $query->redirect("/cgi-bin/koha/maintenance.pl");
792 sub _timeout_syspref {
793 my $default_timeout = 600;
794 my $timeout = C4::Context->preference('timeout') || $default_timeout;
796 # value in days, convert in seconds
797 if ( $timeout =~ /^(\d+)[dD]$/ ) {
798 $timeout = $1 * 86400;
800 # value in hours, convert in seconds
801 elsif ( $timeout =~ /^(\d+)[hH]$/ ) {
802 $timeout = $1 * 3600;
804 elsif ( $timeout !~ m/^\d+$/ ) {
805 warn "The value of the system preference 'timeout' is not correct, defaulting to $default_timeout";
806 $timeout = $default_timeout;
814 $debug and warn "Checking Auth";
816 # Get shibboleth login attribute
817 my $shib = C4::Context->config('useshibboleth') && shib_ok();
818 my $shib_login = $shib ? get_login_shib() : undef;
820 # $authnotrequired will be set for scripts which will run without authentication
821 my $authnotrequired = shift;
822 my $flagsrequired = shift;
824 my $emailaddress = shift;
825 my $template_name = shift;
826 $type = 'opac' unless $type;
828 unless ( C4::Context->preference("OpacPublic") ) {
829 my @allowed_scripts_for_private_opac = qw(
831 opac-registration-email-sent.tt
832 opac-registration-confirmation.tt
833 opac-memberentry-update-submitted.tt
834 opac-password-recovery.tt
836 $authnotrequired = 0 unless grep { $_ eq $template_name }
837 @allowed_scripts_for_private_opac;
840 my $dbh = C4::Context->dbh;
841 my $timeout = _timeout_syspref();
843 _version_check( $type, $query );
848 my ( $userid, $cookie, $sessionID, $flags );
849 my $logout = $query->param('logout.x');
851 my $anon_search_history;
853 # This parameter is the name of the CAS server we want to authenticate against,
854 # when using authentication against multiple CAS servers, as configured in Auth_cas_servers.yaml
855 my $casparam = $query->param('cas');
856 my $q_userid = $query->param('userid') // '';
860 # Basic authentication is incompatible with the use of Shibboleth,
861 # as Shibboleth may return REMOTE_USER as a Shibboleth attribute,
862 # and it may not be the attribute we want to use to match the koha login.
864 # Also, do not consider an empty REMOTE_USER.
866 # Finally, after those tests, we can assume (although if it would be better with
867 # a syspref) that if we get a REMOTE_USER, that's from basic authentication,
868 # and we can affect it to $userid.
869 if ( !$shib and defined( $ENV{'REMOTE_USER'} ) and $ENV{'REMOTE_USER'} ne '' and $userid = $ENV{'REMOTE_USER'} ) {
871 # Using Basic Authentication, no cookies required
872 $cookie = $query->cookie(
873 -name => 'CGISESSID',
877 -secure => ( C4::Context->https_enabled() ? 1 : 0 ),
881 elsif ( $emailaddress) {
882 # the Google OpenID Connect passes an email address
884 elsif ( $sessionID = $query->cookie("CGISESSID") )
885 { # assignment, not comparison
886 $session = get_session($sessionID);
887 C4::Context->_new_userenv($sessionID);
888 my ( $ip, $lasttime, $sessiontype );
891 $s_userid = $session->param('id') // '';
892 C4::Context->set_userenv(
893 $session->param('number'), $s_userid,
894 $session->param('cardnumber'), $session->param('firstname'),
895 $session->param('surname'), $session->param('branch'),
896 $session->param('branchname'), $session->param('flags'),
897 $session->param('emailaddress'), $session->param('shibboleth'),
898 $session->param('desk_id'), $session->param('desk_name'),
899 $session->param('register_id'), $session->param('register_name')
901 C4::Context::set_shelves_userenv( 'bar', $session->param('barshelves') );
902 C4::Context::set_shelves_userenv( 'pub', $session->param('pubshelves') );
903 C4::Context::set_shelves_userenv( 'tot', $session->param('totshelves') );
904 $debug and printf STDERR "AUTH_SESSION: (%s)\t%s %s - %s\n", map { $session->param($_) } qw(cardnumber firstname surname branch);
905 $ip = $session->param('ip');
906 $lasttime = $session->param('lasttime');
908 $sessiontype = $session->param('sessiontype') || '';
910 if ( ( $query->param('koha_login_context') && ( $q_userid ne $s_userid ) )
911 || ( $cas && $query->param('ticket') && !C4::Context->userenv->{'id'} )
912 || ( $shib && $shib_login && !$logout && !C4::Context->userenv->{'id'} )
915 #if a user enters an id ne to the id in the current session, we need to log them in...
916 #first we need to clear the anonymous session...
917 $debug and warn "query id = $q_userid but session id = $s_userid";
918 $anon_search_history = $session->param('search_history');
921 C4::Context->_unset_userenv($sessionID);
927 # voluntary logout the user
928 # check wether the user was using their shibboleth session or a local one
929 my $shibSuccess = C4::Context->userenv->{'shibboleth'};
932 C4::Context->_unset_userenv($sessionID);
937 if ($cas and $caslogout) {
938 logout_cas($query, $type);
941 # If we are in a shibboleth session (shibboleth is enabled, a shibboleth match attribute is set and matches koha matchpoint)
942 if ( $shib and $shib_login and $shibSuccess) {
946 elsif ( !$lasttime || ( $lasttime < time() - $timeout ) ) {
949 $info{'timed_out'} = 1;
954 C4::Context->_unset_userenv($sessionID);
959 elsif ( C4::Context->preference('SessionRestrictionByIP') && $ip ne $ENV{'REMOTE_ADDR'} ) {
961 # Different ip than originally logged in from
962 $info{'oldip'} = $ip;
963 $info{'newip'} = $ENV{'REMOTE_ADDR'};
964 $info{'different_ip'} = 1;
967 C4::Context->_unset_userenv($sessionID);
973 $cookie = $query->cookie(
974 -name => 'CGISESSID',
975 -value => $session->id,
977 -secure => ( C4::Context->https_enabled() ? 1 : 0 ),
979 $session->param( 'lasttime', time() );
980 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...
981 $flags = haspermission( $userid, $flagsrequired );
985 $info{'nopermission'} = 1;
990 unless ( $userid || $sessionID ) {
991 #we initiate a session prior to checking for a username to allow for anonymous sessions...
992 my $session = get_session("") or die "Auth ERROR: Cannot get_session()";
994 # Save anonymous search history in new session so it can be retrieved
995 # by get_template_and_user to store it in user's search history after
996 # a successful login.
997 if ($anon_search_history) {
998 $session->param( 'search_history', $anon_search_history );
1001 $sessionID = $session->id;
1002 C4::Context->_new_userenv($sessionID);
1003 $cookie = $query->cookie(
1004 -name => 'CGISESSID',
1005 -value => $session->id,
1007 -secure => ( C4::Context->https_enabled() ? 1 : 0 ),
1009 my $pki_field = C4::Context->preference('AllowPKIAuth');
1010 if ( !defined($pki_field) ) {
1011 print STDERR "ERROR: Missing system preference AllowPKIAuth.\n";
1012 $pki_field = 'None';
1014 if ( ( $cas && $query->param('ticket') )
1016 || ( $shib && $shib_login )
1017 || $pki_field ne 'None'
1020 my $password = $query->param('password');
1021 my $shibSuccess = 0;
1022 my ( $return, $cardnumber );
1024 # If shib is enabled and we have a shib login, does the login match a valid koha user
1025 if ( $shib && $shib_login ) {
1028 # Do not pass password here, else shib will not be checked in checkpw.
1029 ( $return, $cardnumber, $retuserid ) = checkpw( $dbh, $q_userid, undef, $query );
1030 $userid = $retuserid;
1031 $shibSuccess = $return;
1032 $info{'invalidShibLogin'} = 1 unless ($return);
1035 # If shib login and match were successful, skip further login methods
1036 unless ($shibSuccess) {
1037 if ( $cas && $query->param('ticket') ) {
1039 ( $return, $cardnumber, $retuserid, $cas_ticket ) =
1040 checkpw( $dbh, $userid, $password, $query, $type );
1041 $userid = $retuserid;
1042 $info{'invalidCasLogin'} = 1 unless ($return);
1045 elsif ( $emailaddress ) {
1046 my $value = $emailaddress;
1048 # If we're looking up the email, there's a chance that the person
1049 # doesn't have a userid. So if there is none, we pass along the
1050 # borrower number, and the bits of code that need to know the user
1051 # ID will have to be smart enough to handle that.
1052 my $patrons = Koha::Patrons->search({ email => $value });
1053 if ($patrons->count) {
1055 # First the userid, then the borrowernum
1056 my $patron = $patrons->next;
1057 $value = $patron->userid || $patron->borrowernumber;
1061 $return = $value ? 1 : 0;
1066 ( $pki_field eq 'Common Name' && $ENV{'SSL_CLIENT_S_DN_CN'} )
1067 || ( $pki_field eq 'emailAddress'
1068 && $ENV{'SSL_CLIENT_S_DN_Email'} )
1072 if ( $pki_field eq 'Common Name' ) {
1073 $value = $ENV{'SSL_CLIENT_S_DN_CN'};
1075 elsif ( $pki_field eq 'emailAddress' ) {
1076 $value = $ENV{'SSL_CLIENT_S_DN_Email'};
1078 # If we're looking up the email, there's a chance that the person
1079 # doesn't have a userid. So if there is none, we pass along the
1080 # borrower number, and the bits of code that need to know the user
1081 # ID will have to be smart enough to handle that.
1082 my $patrons = Koha::Patrons->search({ email => $value });
1083 if ($patrons->count) {
1085 # First the userid, then the borrowernum
1086 my $patron = $patrons->next;
1087 $value = $patron->userid || $patron->borrowernumber;
1093 $return = $value ? 1 : 0;
1099 my $request_method = $query->request_method();
1102 $request_method eq 'POST'
1103 || ( C4::Context->preference('AutoSelfCheckID')
1104 && $q_userid eq C4::Context->preference('AutoSelfCheckID') )
1108 ( $return, $cardnumber, $retuserid, $cas_ticket ) =
1109 checkpw( $dbh, $q_userid, $password, $query, $type );
1110 $userid = $retuserid if ($retuserid);
1111 $info{'invalid_username_or_password'} = 1 unless ($return);
1116 # If shib configured and shibOnly enabled, we should ignore anything other than a shibboleth type login.
1123 && C4::Context->preference('OPACShibOnly')
1125 || ( ( $type ne 'opac' )
1126 && C4::Context->preference('staffShibOnly') )
1133 # $return: 1 = valid user
1136 if ( $flags = haspermission( $userid, $flagsrequired ) ) {
1140 $info{'nopermission'} = 1;
1141 C4::Context->_unset_userenv($sessionID);
1143 my ( $borrowernumber, $firstname, $surname, $userflags,
1144 $branchcode, $branchname, $emailaddress, $desk_id,
1145 $desk_name, $register_id, $register_name );
1147 if ( $return == 1 ) {
1149 SELECT borrowernumber, firstname, surname, flags, borrowers.branchcode,
1150 branches.branchname as branchname, email
1152 LEFT JOIN branches on borrowers.branchcode=branches.branchcode
1154 my $sth = $dbh->prepare("$select where userid=?");
1155 $sth->execute($userid);
1156 unless ( $sth->rows ) {
1157 $debug and print STDERR "AUTH_1: no rows for userid='$userid'\n";
1158 $sth = $dbh->prepare("$select where cardnumber=?");
1159 $sth->execute($cardnumber);
1161 unless ( $sth->rows ) {
1162 $debug and print STDERR "AUTH_2a: no rows for cardnumber='$cardnumber'\n";
1163 $sth->execute($userid);
1164 unless ( $sth->rows ) {
1165 $debug and print STDERR "AUTH_2b: no rows for userid='$userid' AS cardnumber\n";
1170 ( $borrowernumber, $firstname, $surname, $userflags,
1171 $branchcode, $branchname, $emailaddress ) = $sth->fetchrow;
1172 $debug and print STDERR "AUTH_3 results: " .
1173 "$cardnumber,$borrowernumber,$userid,$firstname,$surname,$userflags,$branchcode,$emailaddress\n";
1175 print STDERR "AUTH_3: no results for userid='$userid', cardnumber='$cardnumber'.\n";
1178 # launch a sequence to check if we have a ip for the branch, i
1179 # if we have one we replace the branchcode of the userenv by the branch bound in the ip.
1181 my $ip = $ENV{'REMOTE_ADDR'};
1183 # if they specify at login, use that
1184 if ( $query->param('branch') ) {
1185 $branchcode = $query->param('branch');
1186 my $library = Koha::Libraries->find($branchcode);
1187 $branchname = $library? $library->branchname: '';
1189 if ( $query->param('desk_id') ) {
1190 $desk_id = $query->param('desk_id');
1191 my $desk = Koha::Desks->find($desk_id);
1192 $desk_name = $desk ? $desk->desk_name : '';
1194 if ( C4::Context->preference('UseCashRegisters') ) {
1196 $query->param('register_id')
1197 ? Koha::Cash::Registers->find($query->param('register_id'))
1198 : Koha::Cash::Registers->search(
1199 { branch => $branchcode, branch_default => 1 },
1200 { rows => 1 } )->single;
1201 $register_id = $register->id if ($register);
1202 $register_name = $register->name if ($register);
1204 my $branches = { map { $_->branchcode => $_->unblessed } Koha::Libraries->search };
1205 if ( $type ne 'opac' and C4::Context->preference('AutoLocation') ) {
1207 # we have to check they are coming from the right ip range
1208 my $domain = $branches->{$branchcode}->{'branchip'};
1209 $domain =~ s|\.\*||g;
1210 if ( $ip !~ /^$domain/ ) {
1212 $cookie = $query->cookie(
1213 -name => 'CGISESSID',
1216 -secure => ( C4::Context->https_enabled() ? 1 : 0 ),
1218 $info{'wrongip'} = 1;
1222 foreach my $br ( keys %$branches ) {
1224 # now we work with the treatment of ip
1225 my $domain = $branches->{$br}->{'branchip'};
1226 if ( $domain && $ip =~ /^$domain/ ) {
1227 $branchcode = $branches->{$br}->{'branchcode'};
1229 # new op dev : add the branchname to the cookie
1230 $branchname = $branches->{$br}->{'branchname'};
1234 my $is_sco_user = 0;
1235 if ( $query->param('sco_user_login') && ( $query->param('sco_user_login') eq '1' ) ){
1239 $session->param( 'number', $borrowernumber );
1240 $session->param( 'id', $userid );
1241 $session->param( 'cardnumber', $cardnumber );
1242 $session->param( 'firstname', $firstname );
1243 $session->param( 'surname', $surname );
1244 $session->param( 'branch', $branchcode );
1245 $session->param( 'branchname', $branchname );
1246 $session->param( 'desk_id', $desk_id);
1247 $session->param( 'desk_name', $desk_name);
1248 $session->param( 'flags', $userflags );
1249 $session->param( 'emailaddress', $emailaddress );
1250 $session->param( 'ip', $session->remote_addr() );
1251 $session->param( 'lasttime', time() );
1252 $session->param( 'interface', $type);
1253 $session->param( 'shibboleth', $shibSuccess );
1254 $session->param( 'register_id', $register_id );
1255 $session->param( 'register_name', $register_name );
1256 $session->param( 'sco_user', $is_sco_user );
1257 $debug and printf STDERR "AUTH_4: (%s)\t%s %s - %s\n", map { $session->param($_) } qw(cardnumber firstname surname branch);
1259 $session->param('cas_ticket', $cas_ticket) if $cas_ticket;
1260 C4::Context->set_userenv(
1261 $session->param('number'), $session->param('id'),
1262 $session->param('cardnumber'), $session->param('firstname'),
1263 $session->param('surname'), $session->param('branch'),
1264 $session->param('branchname'), $session->param('flags'),
1265 $session->param('emailaddress'), $session->param('shibboleth'),
1266 $session->param('desk_id'), $session->param('desk_name'),
1267 $session->param('register_id'), $session->param('register_name')
1271 # $return: 0 = invalid user
1272 # reset to anonymous session
1274 $debug and warn "Login failed, resetting anonymous session...";
1276 $info{'invalid_username_or_password'} = 1;
1277 C4::Context->_unset_userenv($sessionID);
1279 $session->param( 'lasttime', time() );
1280 $session->param( 'ip', $session->remote_addr() );
1281 $session->param( 'sessiontype', 'anon' );
1282 $session->param( 'interface', $type);
1284 } # END if ( $q_userid
1285 elsif ( $type eq "opac" ) {
1287 # if we are here this is an anonymous session; add public lists to it and a few other items...
1288 # anonymous sessions are created only for the OPAC
1289 $debug and warn "Initiating an anonymous session...";
1291 # setting a couple of other session vars...
1292 $session->param( 'ip', $session->remote_addr() );
1293 $session->param( 'lasttime', time() );
1294 $session->param( 'sessiontype', 'anon' );
1295 $session->param( 'interface', $type);
1297 } # END unless ($userid)
1299 # finished authentification, now respond
1300 if ( $loggedin || $authnotrequired )
1304 $cookie = $query->cookie(
1305 -name => 'CGISESSID',
1308 -secure => ( C4::Context->https_enabled() ? 1 : 0 ),
1312 track_login_daily( $userid );
1314 # In case, that this request was a login attempt, we want to prevent that users can repost the opac login
1315 # request. We therefore redirect the user to the requested page again without the login parameters.
1316 # See Post/Redirect/Get (PRG) design pattern: https://en.wikipedia.org/wiki/Post/Redirect/Get
1317 if ( $type eq "opac" && $query->param('koha_login_context') && $query->param('koha_login_context') ne 'sco' && $query->param('password') && $query->param('userid') ) {
1318 my $uri = URI->new($query->url(-relative=>1, -query_string=>1));
1319 $uri->query_param_delete('userid');
1320 $uri->query_param_delete('password');
1321 $uri->query_param_delete('koha_login_context');
1322 print $query->redirect(-uri => $uri->as_string, -cookie => $cookie, -status=>'303 See other');
1326 return ( $userid, $cookie, $sessionID, $flags );
1331 # AUTH rejected, show the login/password template, after checking the DB.
1335 # get the inputs from the incoming query
1337 foreach my $name ( param $query) {
1338 (next) if ( $name eq 'userid' || $name eq 'password' || $name eq 'ticket' );
1339 my @value = $query->multi_param($name);
1340 push @inputs, { name => $name, value => $_ } for @value;
1343 my $patron = Koha::Patrons->find({ userid => $q_userid }); # Not necessary logged in!
1345 my $LibraryNameTitle = C4::Context->preference("LibraryName");
1346 $LibraryNameTitle =~ s/<(?:\/?)(?:br|p)\s*(?:\/?)>/ /sgi;
1347 $LibraryNameTitle =~ s/<(?:[^<>'"]|'(?:[^']*)'|"(?:[^"]*)")*>//sg;
1349 my $auth_template_name = ( $type eq 'opac' ) ? 'opac-auth.tt' : 'auth.tt';
1350 my $template = C4::Templates::gettemplate( $auth_template_name, $type, $query );
1354 script_name => get_script_name(),
1355 casAuthentication => C4::Context->preference("casAuthentication"),
1356 shibbolethAuthentication => $shib,
1357 SessionRestrictionByIP => C4::Context->preference("SessionRestrictionByIP"),
1358 suggestion => C4::Context->preference("suggestion"),
1359 virtualshelves => C4::Context->preference("virtualshelves"),
1360 LibraryName => "" . C4::Context->preference("LibraryName"),
1361 LibraryNameTitle => "" . $LibraryNameTitle,
1362 opacuserlogin => C4::Context->preference("opacuserlogin"),
1363 OpacNav => C4::Context->preference("OpacNav"),
1364 OpacNavBottom => C4::Context->preference("OpacNavBottom"),
1365 OpacFavicon => C4::Context->preference("OpacFavicon"),
1366 opacreadinghistory => C4::Context->preference("opacreadinghistory"),
1367 opaclanguagesdisplay => C4::Context->preference("opaclanguagesdisplay"),
1368 OPACUserJS => C4::Context->preference("OPACUserJS"),
1369 opacbookbag => "" . C4::Context->preference("opacbookbag"),
1370 OpacCloud => C4::Context->preference("OpacCloud"),
1371 OpacTopissue => C4::Context->preference("OpacTopissue"),
1372 OpacAuthorities => C4::Context->preference("OpacAuthorities"),
1373 OpacBrowser => C4::Context->preference("OpacBrowser"),
1374 TagsEnabled => C4::Context->preference("TagsEnabled"),
1375 OPACUserCSS => C4::Context->preference("OPACUserCSS"),
1376 intranetcolorstylesheet => C4::Context->preference("intranetcolorstylesheet"),
1377 intranetstylesheet => C4::Context->preference("intranetstylesheet"),
1378 IntranetNav => C4::Context->preference("IntranetNav"),
1379 IntranetFavicon => C4::Context->preference("IntranetFavicon"),
1380 IntranetUserCSS => C4::Context->preference("IntranetUserCSS"),
1381 IntranetUserJS => C4::Context->preference("IntranetUserJS"),
1382 IndependentBranches => C4::Context->preference("IndependentBranches"),
1383 AutoLocation => C4::Context->preference("AutoLocation"),
1384 wrongip => $info{'wrongip'},
1385 PatronSelfRegistration => C4::Context->preference("PatronSelfRegistration"),
1386 PatronSelfRegistrationDefaultCategory => C4::Context->preference("PatronSelfRegistrationDefaultCategory"),
1387 opac_css_override => $ENV{'OPAC_CSS_OVERRIDE'},
1388 too_many_login_attempts => ( $patron and $patron->account_locked )
1391 $template->param( SCO_login => 1 ) if ( $query->param('sco_user_login') );
1392 $template->param( SCI_login => 1 ) if ( $query->param('sci_user_login') );
1393 $template->param( OpacPublic => C4::Context->preference("OpacPublic") );
1394 $template->param( loginprompt => 1 ) unless $info{'nopermission'};
1396 if ( $type eq 'opac' ) {
1397 require Koha::Virtualshelves;
1398 my $some_public_shelves = Koha::Virtualshelves->get_some_shelves(
1404 some_public_shelves => $some_public_shelves,
1410 # Is authentication against multiple CAS servers enabled?
1411 if ( C4::Auth_with_cas::multipleAuth && !$casparam ) {
1412 my $casservers = C4::Auth_with_cas::getMultipleAuth();
1414 foreach my $key ( keys %$casservers ) {
1415 push @tmplservers, { name => $key, value => login_cas_url( $query, $key, $type ) . "?cas=$key" };
1418 casServersLoop => \@tmplservers
1422 casServerUrl => login_cas_url($query, undef, $type),
1427 invalidCasLogin => $info{'invalidCasLogin'}
1432 #If shibOnly is enabled just go ahead and redirect directly
1433 if ( (($type eq 'opac') && C4::Context->preference('OPACShibOnly')) || (($type ne 'opac') && C4::Context->preference('staffShibOnly')) ) {
1434 my $redirect_url = login_shib_url( $query );
1435 print $query->redirect( -uri => "$redirect_url", -status => 303 );
1440 shibbolethAuthentication => $shib,
1441 shibbolethLoginUrl => login_shib_url($query),
1445 if (C4::Context->preference('GoogleOpenIDConnect')) {
1446 if ($query->param("OpenIDConnectFailed")) {
1447 my $reason = $query->param('OpenIDConnectFailed');
1448 $template->param(invalidGoogleOpenIDConnectLogin => $reason);
1453 LibraryName => C4::Context->preference("LibraryName"),
1455 $template->param(%info);
1457 # $cookie = $query->cookie(CGISESSID => $session->id
1459 print $query->header(
1460 { type => 'text/html',
1463 'X-Frame-Options' => 'SAMEORIGIN'
1470 =head2 check_api_auth
1472 ($status, $cookie, $sessionId) = check_api_auth($query, $userflags);
1474 Given a CGI query containing the parameters 'userid' and 'password' and/or a session
1475 cookie, determine if the user has the privileges specified by C<$userflags>.
1477 C<check_api_auth> is is meant for authenticating users of web services, and
1478 consequently will always return and will not attempt to redirect the user
1481 If a valid session cookie is already present, check_api_auth will return a status
1482 of "ok", the cookie, and the Koha session ID.
1484 If no session cookie is present, check_api_auth will check the 'userid' and 'password
1485 parameters and create a session cookie and Koha session if the supplied credentials
1488 Possible return values in C<$status> are:
1492 =item "ok" -- user authenticated; C<$cookie> and C<$sessionid> have valid values.
1494 =item "failed" -- credentials are not correct; C<$cookie> and C<$sessionid> are undef
1496 =item "maintenance" -- DB is in maintenance mode; no login possible at the moment
1498 =item "expired -- session cookie has expired; API user should resubmit userid and password
1504 sub check_api_auth {
1507 my $flagsrequired = shift;
1508 my $dbh = C4::Context->dbh;
1509 my $timeout = _timeout_syspref();
1511 unless ( C4::Context->preference('Version') ) {
1513 # database has not been installed yet
1514 return ( "maintenance", undef, undef );
1516 my $kohaversion = Koha::version();
1517 $kohaversion =~ s/(.*\..*)\.(.*)\.(.*)/$1$2$3/;
1518 if ( C4::Context->preference('Version') < $kohaversion ) {
1520 # database in need of version update; assume that
1521 # no API should be called while databsae is in
1523 return ( "maintenance", undef, undef );
1526 # FIXME -- most of what follows is a copy-and-paste
1527 # of code from checkauth. There is an obvious need
1528 # for refactoring to separate the various parts of
1529 # the authentication code, but as of 2007-11-19 this
1530 # is deferred so as to not introduce bugs into the
1531 # regular authentication code for Koha 3.0.
1533 # see if we have a valid session cookie already
1534 # however, if a userid parameter is present (i.e., from
1535 # a form submission, assume that any current cookie
1537 my $sessionID = undef;
1538 unless ( $query->param('userid') ) {
1539 $sessionID = $query->cookie("CGISESSID");
1541 if ( $sessionID && not( $cas && $query->param('PT') ) ) {
1542 my $session = get_session($sessionID);
1543 C4::Context->_new_userenv($sessionID);
1545 C4::Context->interface($session->param('interface'));
1546 C4::Context->set_userenv(
1547 $session->param('number'), $session->param('id'),
1548 $session->param('cardnumber'), $session->param('firstname'),
1549 $session->param('surname'), $session->param('branch'),
1550 $session->param('branchname'), $session->param('flags'),
1551 $session->param('emailaddress'), $session->param('shibboleth'),
1552 $session->param('desk_id'), $session->param('desk_name'),
1553 $session->param('register_id'), $session->param('register_name')
1556 my $ip = $session->param('ip');
1557 my $lasttime = $session->param('lasttime');
1558 my $userid = $session->param('id');
1559 if ( $lasttime < time() - $timeout ) {
1564 C4::Context->_unset_userenv($sessionID);
1567 return ( "expired", undef, undef );
1568 } elsif ( C4::Context->preference('SessionRestrictionByIP') && $ip ne $ENV{'REMOTE_ADDR'} ) {
1570 # IP address changed
1573 C4::Context->_unset_userenv($sessionID);
1576 return ( "expired", undef, undef );
1578 my $cookie = $query->cookie(
1579 -name => 'CGISESSID',
1580 -value => $session->id,
1582 -secure => ( C4::Context->https_enabled() ? 1 : 0 ),
1584 $session->param( 'lasttime', time() );
1585 my $flags = haspermission( $userid, $flagsrequired );
1587 return ( "ok", $cookie, $sessionID );
1591 C4::Context->_unset_userenv($sessionID);
1594 return ( "failed", undef, undef );
1598 return ( "expired", undef, undef );
1603 my $userid = $query->param('userid');
1604 my $password = $query->param('password');
1605 my ( $return, $cardnumber, $cas_ticket );
1608 if ( $cas && $query->param('PT') ) {
1610 $debug and print STDERR "## check_api_auth - checking CAS\n";
1612 # In case of a CAS authentication, we use the ticket instead of the password
1613 my $PT = $query->param('PT');
1614 ( $return, $cardnumber, $userid, $cas_ticket ) = check_api_auth_cas( $dbh, $PT, $query ); # EXTERNAL AUTH
1617 # User / password auth
1618 unless ( $userid and $password ) {
1620 # caller did something wrong, fail the authenticateion
1621 return ( "failed", undef, undef );
1624 ( $return, $cardnumber, $newuserid, $cas_ticket ) = checkpw( $dbh, $userid, $password, $query );
1627 if ( $return and haspermission( $userid, $flagsrequired ) ) {
1628 my $session = get_session("");
1629 return ( "failed", undef, undef ) unless $session;
1631 my $sessionID = $session->id;
1632 C4::Context->_new_userenv($sessionID);
1633 my $cookie = $query->cookie(
1634 -name => 'CGISESSID',
1635 -value => $sessionID,
1637 -secure => ( C4::Context->https_enabled() ? 1 : 0 ),
1639 if ( $return == 1 ) {
1641 $borrowernumber, $firstname, $surname,
1642 $userflags, $branchcode, $branchname,
1647 "select borrowernumber, firstname, surname, flags, borrowers.branchcode, branches.branchname as branchname, email from borrowers left join branches on borrowers.branchcode=branches.branchcode where userid=?"
1649 $sth->execute($userid);
1651 $borrowernumber, $firstname, $surname,
1652 $userflags, $branchcode, $branchname,
1654 ) = $sth->fetchrow if ( $sth->rows );
1656 unless ( $sth->rows ) {
1657 my $sth = $dbh->prepare(
1658 "select borrowernumber, firstname, surname, flags, borrowers.branchcode, branches.branchname as branchname, email from borrowers left join branches on borrowers.branchcode=branches.branchcode where cardnumber=?"
1660 $sth->execute($cardnumber);
1662 $borrowernumber, $firstname, $surname,
1663 $userflags, $branchcode, $branchname,
1665 ) = $sth->fetchrow if ( $sth->rows );
1667 unless ( $sth->rows ) {
1668 $sth->execute($userid);
1670 $borrowernumber, $firstname, $surname, $userflags,
1671 $branchcode, $branchname, $emailaddress
1672 ) = $sth->fetchrow if ( $sth->rows );
1676 my $ip = $ENV{'REMOTE_ADDR'};
1678 # if they specify at login, use that
1679 if ( $query->param('branch') ) {
1680 $branchcode = $query->param('branch');
1681 my $library = Koha::Libraries->find($branchcode);
1682 $branchname = $library? $library->branchname: '';
1684 my $branches = { map { $_->branchcode => $_->unblessed } Koha::Libraries->search };
1685 foreach my $br ( keys %$branches ) {
1687 # now we work with the treatment of ip
1688 my $domain = $branches->{$br}->{'branchip'};
1689 if ( $domain && $ip =~ /^$domain/ ) {
1690 $branchcode = $branches->{$br}->{'branchcode'};
1692 # new op dev : add the branchname to the cookie
1693 $branchname = $branches->{$br}->{'branchname'};
1696 $session->param( 'number', $borrowernumber );
1697 $session->param( 'id', $userid );
1698 $session->param( 'cardnumber', $cardnumber );
1699 $session->param( 'firstname', $firstname );
1700 $session->param( 'surname', $surname );
1701 $session->param( 'branch', $branchcode );
1702 $session->param( 'branchname', $branchname );
1703 $session->param( 'flags', $userflags );
1704 $session->param( 'emailaddress', $emailaddress );
1705 $session->param( 'ip', $session->remote_addr() );
1706 $session->param( 'lasttime', time() );
1707 $session->param( 'interface', 'api' );
1709 $session->param( 'cas_ticket', $cas_ticket);
1710 C4::Context->set_userenv(
1711 $session->param('number'), $session->param('id'),
1712 $session->param('cardnumber'), $session->param('firstname'),
1713 $session->param('surname'), $session->param('branch'),
1714 $session->param('branchname'), $session->param('flags'),
1715 $session->param('emailaddress'), $session->param('shibboleth'),
1716 $session->param('desk_id'), $session->param('desk_name'),
1717 $session->param('register_id'), $session->param('register_name')
1719 return ( "ok", $cookie, $sessionID );
1721 return ( "failed", undef, undef );
1726 =head2 check_cookie_auth
1728 ($status, $sessionId) = check_api_auth($cookie, $userflags);
1730 Given a CGISESSID cookie set during a previous login to Koha, determine
1731 if the user has the privileges specified by C<$userflags>. C<$userflags>
1732 is passed unaltered into C<haspermission> and as such accepts all options
1733 avaiable to that routine with the one caveat that C<check_api_auth> will
1734 also allow 'undef' to be passed and in such a case the permissions check
1735 will be skipped altogether.
1737 C<check_cookie_auth> is meant for authenticating special services
1738 such as tools/upload-file.pl that are invoked by other pages that
1739 have been authenticated in the usual way.
1741 Possible return values in C<$status> are:
1745 =item "ok" -- user authenticated; C<$sessionID> have valid values.
1747 =item "anon" -- user not authenticated but valid for anonymous session.
1749 =item "failed" -- credentials are not correct; C<$sessionid> are undef
1751 =item "maintenance" -- DB is in maintenance mode; no login possible at the moment
1753 =item "expired -- session cookie has expired; API user should resubmit userid and password
1759 sub check_cookie_auth {
1761 my $flagsrequired = shift;
1764 my $remote_addr = $params->{remote_addr} || $ENV{REMOTE_ADDR};
1765 my $dbh = C4::Context->dbh;
1766 my $timeout = _timeout_syspref();
1768 unless ( C4::Context->preference('Version') ) {
1770 # database has not been installed yet
1771 return ( "maintenance", undef );
1773 my $kohaversion = Koha::version();
1774 $kohaversion =~ s/(.*\..*)\.(.*)\.(.*)/$1$2$3/;
1775 if ( C4::Context->preference('Version') < $kohaversion ) {
1777 # database in need of version update; assume that
1778 # no API should be called while databsae is in
1780 return ( "maintenance", undef );
1783 # FIXME -- most of what follows is a copy-and-paste
1784 # of code from checkauth. There is an obvious need
1785 # for refactoring to separate the various parts of
1786 # the authentication code, but as of 2007-11-23 this
1787 # is deferred so as to not introduce bugs into the
1788 # regular authentication code for Koha 3.0.
1790 # see if we have a valid session cookie already
1791 # however, if a userid parameter is present (i.e., from
1792 # a form submission, assume that any current cookie
1794 unless ( defined $cookie and $cookie ) {
1795 return ( "failed", undef );
1797 my $sessionID = $cookie;
1798 my $session = get_session($sessionID);
1799 C4::Context->_new_userenv($sessionID);
1801 C4::Context->interface($session->param('interface'));
1802 C4::Context->set_userenv(
1803 $session->param('number'), $session->param('id'),
1804 $session->param('cardnumber'), $session->param('firstname'),
1805 $session->param('surname'), $session->param('branch'),
1806 $session->param('branchname'), $session->param('flags'),
1807 $session->param('emailaddress'), $session->param('shibboleth'),
1808 $session->param('desk_id'), $session->param('desk_name'),
1809 $session->param('register_id'), $session->param('register_name')
1812 my $ip = $session->param('ip');
1813 my $lasttime = $session->param('lasttime');
1814 my $userid = $session->param('id');
1815 if ( $lasttime < time() - $timeout ) {
1820 C4::Context->_unset_userenv($sessionID);
1823 return ("expired", undef);
1824 } elsif ( C4::Context->preference('SessionRestrictionByIP') && $ip ne $remote_addr ) {
1826 # IP address changed
1829 C4::Context->_unset_userenv($sessionID);
1832 return ( "expired", undef );
1833 } elsif ( $userid ) {
1834 $session->param( 'lasttime', time() );
1835 my $flags = defined($flagsrequired) ? haspermission( $userid, $flagsrequired ) : 1;
1837 return ( "ok", $sessionID );
1840 return ( "anon", $session );
1842 # If here user was logged in, but doesn't have correct permissions
1843 # could be an 'else' at `if($flags) return "ok"` , but left here to catch any errors
1846 C4::Context->_unset_userenv($sessionID);
1849 return ( "failed", undef );
1851 return ( "expired", undef );
1858 my $session = get_session($sessionID);
1860 Given a session ID, retrieve the CGI::Session object used to store
1861 the session's state. The session object can be used to store
1862 data that needs to be accessed by different scripts during a
1865 If the C<$sessionID> parameter is an empty string, a new session
1870 sub _get_session_params {
1871 my $storage_method = C4::Context->preference('SessionStorage');
1872 if ( $storage_method eq 'mysql' ) {
1873 my $dbh = C4::Context->dbh;
1874 return { dsn => "serializer:yamlxs;driver:MySQL;id:md5", dsn_args => { Handle => $dbh } };
1876 elsif ( $storage_method eq 'Pg' ) {
1877 my $dbh = C4::Context->dbh;
1878 return { dsn => "serializer:yamlxs;driver:PostgreSQL;id:md5", dsn_args => { Handle => $dbh } };
1880 elsif ( $storage_method eq 'memcached' && Koha::Caches->get_instance->memcached_cache ) {
1881 my $memcached = Koha::Caches->get_instance()->memcached_cache;
1882 return { dsn => "serializer:yamlxs;driver:memcached;id:md5", dsn_args => { Memcached => $memcached } };
1885 # catch all defaults to tmp should work on all systems
1886 my $dir = C4::Context::temporary_directory;
1887 my $instance = C4::Context->config( 'database' ); #actually for packages not exactly the instance name, but generally safer to leave it as it is
1888 return { dsn => "serializer:yamlxs;driver:File;id:md5", dsn_args => { Directory => "$dir/cgisess_$instance" } };
1893 my $sessionID = shift;
1894 my $params = _get_session_params();
1895 my $session = CGI::Session->new( $params->{dsn}, $sessionID, $params->{dsn_args} );
1897 die CGI::Session->errstr();
1903 # FIXME no_set_userenv may be replaced with force_branchcode_for_userenv
1904 # (or something similar)
1905 # Currently it's only passed from C4::SIP::ILS::Patron::check_password, but
1906 # not having a userenv defined could cause a crash.
1908 my ( $dbh, $userid, $password, $query, $type, $no_set_userenv ) = @_;
1909 $type = 'opac' unless $type;
1911 # Get shibboleth login attribute
1912 my $shib = C4::Context->config('useshibboleth') && shib_ok();
1913 my $shib_login = $shib ? get_login_shib() : undef;
1917 if ( defined $userid ){
1918 $patron = Koha::Patrons->find({ userid => $userid });
1919 $patron = Koha::Patrons->find({ cardnumber => $userid }) unless $patron;
1921 my $check_internal_as_fallback = 0;
1923 # Note: checkpw_* routines returns:
1926 # -1 if user bind failed (LDAP only)
1928 if ( $patron and $patron->account_locked ) {
1929 # Nothing to check, account is locked
1930 } elsif ($ldap && defined($password)) {
1931 $debug and print STDERR "## checkpw - checking LDAP\n";
1932 my ( $retval, $retcard, $retuserid ) = checkpw_ldap(@_); # EXTERNAL AUTH
1933 if ( $retval == 1 ) {
1934 @return = ( $retval, $retcard, $retuserid );
1937 $check_internal_as_fallback = 1 if $retval == 0;
1939 } elsif ( $cas && $query && $query->param('ticket') ) {
1940 $debug and print STDERR "## checkpw - checking CAS\n";
1942 # In case of a CAS authentication, we use the ticket instead of the password
1943 my $ticket = $query->param('ticket');
1944 $query->delete('ticket'); # remove ticket to come back to original URL
1945 my ( $retval, $retcard, $retuserid, $cas_ticket ) = checkpw_cas( $dbh, $ticket, $query, $type ); # EXTERNAL AUTH
1947 @return = ( $retval, $retcard, $retuserid, $cas_ticket );
1951 $passwd_ok = $retval;
1954 # If we are in a shibboleth session (shibboleth is enabled, and a shibboleth match attribute is present)
1955 # Check for password to asertain whether we want to be testing against shibboleth or another method this
1957 elsif ( $shib && $shib_login && !$password ) {
1959 $debug and print STDERR "## checkpw - checking Shibboleth\n";
1961 # In case of a Shibboleth authentication, we expect a shibboleth user attribute
1962 # (defined under shibboleth mapping in koha-conf.xml) to contain the login of the
1963 # shibboleth-authenticated user
1965 # Then, we check if it matches a valid koha user
1967 my ( $retval, $retcard, $retuserid ) = C4::Auth_with_shibboleth::checkpw_shib($shib_login); # EXTERNAL AUTH
1969 @return = ( $retval, $retcard, $retuserid );
1971 $passwd_ok = $retval;
1974 $check_internal_as_fallback = 1;
1978 if ( $check_internal_as_fallback ) {
1979 @return = checkpw_internal( $dbh, $userid, $password, $no_set_userenv);
1980 $passwd_ok = 1 if $return[0] > 0; # 1 or 2
1985 $patron->update({ login_attempts => 0 });
1986 } elsif( !$patron->account_locked ) {
1987 $patron->update({ login_attempts => $patron->login_attempts + 1 });
1991 # Optionally log success or failure
1992 if( $patron && $passwd_ok && C4::Context->preference('AuthSuccessLog') ) {
1993 logaction( 'AUTH', 'SUCCESS', $patron->id, "Valid password for $userid", $type );
1994 } elsif( !$passwd_ok && C4::Context->preference('AuthFailureLog') ) {
1995 logaction( 'AUTH', 'FAILURE', $patron ? $patron->id : 0, "Wrong password for $userid", $type );
2001 sub checkpw_internal {
2002 my ( $dbh, $userid, $password, $no_set_userenv ) = @_;
2004 $password = Encode::encode( 'UTF-8', $password )
2005 if Encode::is_utf8($password);
2009 "select password,cardnumber,borrowernumber,userid,firstname,surname,borrowers.branchcode,branches.branchname,flags from borrowers join branches on borrowers.branchcode=branches.branchcode where userid=?"
2011 $sth->execute($userid);
2013 my ( $stored_hash, $cardnumber, $borrowernumber, $userid, $firstname,
2014 $surname, $branchcode, $branchname, $flags )
2017 if ( checkpw_hash( $password, $stored_hash ) ) {
2019 C4::Context->set_userenv( "$borrowernumber", $userid, $cardnumber,
2020 $firstname, $surname, $branchcode, $branchname, $flags ) unless $no_set_userenv;
2021 return 1, $cardnumber, $userid;
2026 "select password,cardnumber,borrowernumber,userid,firstname,surname,borrowers.branchcode,branches.branchname,flags from borrowers join branches on borrowers.branchcode=branches.branchcode where cardnumber=?"
2028 $sth->execute($userid);
2030 my ( $stored_hash, $cardnumber, $borrowernumber, $userid, $firstname,
2031 $surname, $branchcode, $branchname, $flags )
2034 if ( checkpw_hash( $password, $stored_hash ) ) {
2036 C4::Context->set_userenv( $borrowernumber, $userid, $cardnumber,
2037 $firstname, $surname, $branchcode, $branchname, $flags ) unless $no_set_userenv;
2038 return 1, $cardnumber, $userid;
2045 my ( $password, $stored_hash ) = @_;
2047 return if $stored_hash eq '!';
2049 # check what encryption algorithm was implemented: Bcrypt - if the hash starts with '$2' it is Bcrypt else md5
2051 if ( substr( $stored_hash, 0, 2 ) eq '$2' ) {
2052 $hash = hash_password( $password, $stored_hash );
2054 $hash = md5_base64($password);
2056 return $hash eq $stored_hash;
2061 my $authflags = getuserflags($flags, $userid, [$dbh]);
2063 Translates integer flags into permissions strings hash.
2065 C<$flags> is the integer userflags value ( borrowers.userflags )
2066 C<$userid> is the members.userid, used for building subpermissions
2067 C<$authflags> is a hashref of permissions
2074 my $dbh = @_ ? shift : C4::Context->dbh;
2077 # I don't want to do this, but if someone logs in as the database
2078 # user, it would be preferable not to spam them to death with
2079 # numeric warnings. So, we make $flags numeric.
2080 no warnings 'numeric';
2083 my $sth = $dbh->prepare("SELECT bit, flag, defaulton FROM userflags");
2086 while ( my ( $bit, $flag, $defaulton ) = $sth->fetchrow ) {
2087 if ( ( $flags & ( 2**$bit ) ) || $defaulton ) {
2088 $userflags->{$flag} = 1;
2091 $userflags->{$flag} = 0;
2095 # get subpermissions and merge with top-level permissions
2096 my $user_subperms = get_user_subpermissions($userid);
2097 foreach my $module ( keys %$user_subperms ) {
2098 next if $userflags->{$module} == 1; # user already has permission for everything in this module
2099 $userflags->{$module} = $user_subperms->{$module};
2105 =head2 get_user_subpermissions
2107 $user_perm_hashref = get_user_subpermissions($userid);
2109 Given the userid (note, not the borrowernumber) of a staff user,
2110 return a hashref of hashrefs of the specific subpermissions
2111 accorded to the user. An example return is
2115 export_catalog => 1,
2116 import_patrons => 1,
2120 The top-level hash-key is a module or function code from
2121 userflags.flag, while the second-level key is a code
2124 The results of this function do not give a complete picture
2125 of the functions that a staff user can access; it is also
2126 necessary to check borrowers.flags.
2130 sub get_user_subpermissions {
2133 my $dbh = C4::Context->dbh;
2134 my $sth = $dbh->prepare( "SELECT flag, user_permissions.code
2135 FROM user_permissions
2136 JOIN permissions USING (module_bit, code)
2137 JOIN userflags ON (module_bit = bit)
2138 JOIN borrowers USING (borrowernumber)
2139 WHERE userid = ?" );
2140 $sth->execute($userid);
2142 my $user_perms = {};
2143 while ( my $perm = $sth->fetchrow_hashref ) {
2144 $user_perms->{ $perm->{'flag'} }->{ $perm->{'code'} } = 1;
2149 =head2 get_all_subpermissions
2151 my $perm_hashref = get_all_subpermissions();
2153 Returns a hashref of hashrefs defining all specific
2154 permissions currently defined. The return value
2155 has the same structure as that of C<get_user_subpermissions>,
2156 except that the innermost hash value is the description
2157 of the subpermission.
2161 sub get_all_subpermissions {
2162 my $dbh = C4::Context->dbh;
2163 my $sth = $dbh->prepare( "SELECT flag, code
2165 JOIN userflags ON (module_bit = bit)" );
2169 while ( my $perm = $sth->fetchrow_hashref ) {
2170 $all_perms->{ $perm->{'flag'} }->{ $perm->{'code'} } = 1;
2175 =head2 haspermission
2177 $flagsrequired = '*'; # Any permission at all
2178 $flagsrequired = 'a_flag'; # a_flag must be satisfied (all subpermissions)
2179 $flagsrequired = [ 'a_flag', 'b_flag' ]; # a_flag OR b_flag must be satisfied
2180 $flagsrequired = { 'a_flag => 1, 'b_flag' => 1 }; # a_flag AND b_flag must be satisfied
2181 $flagsrequired = { 'a_flag' => 'sub_a' }; # sub_a of a_flag must be satisfied
2182 $flagsrequired = { 'a_flag' => [ 'sub_a, 'sub_b' ] }; # sub_a OR sub_b of a_flag must be satisfied
2184 $flags = ($userid, $flagsrequired);
2186 C<$userid> the userid of the member
2187 C<$flags> is a query structure similar to that used by SQL::Abstract that
2188 denotes the combination of flags required. It is a required parameter.
2190 The main logic of this method is that things in arrays are OR'ed, and things
2191 in hashes are AND'ed. The `*` character can be used, at any depth, to denote `ANY`
2193 Returns member's flags or 0 if a permission is not met.
2198 my ($required, $flags) = @_;
2200 my $ref = ref($required);
2202 if ($required eq '*') {
2203 return 0 unless ( $flags or ref( $flags ) );
2205 return 0 unless ( $flags and (!ref( $flags ) || $flags->{$required} ));
2207 } elsif ($ref eq 'HASH') {
2208 foreach my $key (keys %{$required}) {
2209 next if $flags == 1;
2210 my $require = $required->{$key};
2211 my $rflags = $flags->{$key};
2212 return 0 unless _dispatch($require, $rflags);
2214 } elsif ($ref eq 'ARRAY') {
2216 foreach my $require ( @{$required} ) {
2218 ( ref($flags) && !ref($require) && ( $require ne '*' ) )
2219 ? $flags->{$require}
2221 $satisfied++ if _dispatch( $require, $rflags );
2223 return 0 unless $satisfied;
2225 croak "Unexpected structure found: $ref";
2232 my ( $userid, $flagsrequired ) = @_;
2234 #Koha::Exceptions::WrongParameter->throw('$flagsrequired should not be undef')
2235 # unless defined($flagsrequired);
2237 my $sth = C4::Context->dbh->prepare("SELECT flags FROM borrowers WHERE userid=?");
2238 $sth->execute($userid);
2239 my $row = $sth->fetchrow();
2240 my $flags = getuserflags( $row, $userid );
2242 return $flags unless defined($flagsrequired);
2243 return $flags if $flags->{superlibrarian};
2244 return _dispatch($flagsrequired, $flags);
2246 #FIXME - This fcn should return the failed permission so a suitable error msg can be delivered.
2251 $flags = ($iprange);
2253 C<$iprange> A space separated string describing an IP range. Can include single IPs or ranges
2255 Returns 1 if the remote address is in the provided iprange, or 0 otherwise.
2262 my @allowedipranges = $iprange ? split(' ', $iprange) : ();
2263 if (scalar @allowedipranges > 0) {
2265 eval { @rangelist = Net::CIDR::range2cidr(@allowedipranges); }; return 0 if $@;
2266 eval { $result = Net::CIDR::cidrlookup($ENV{'REMOTE_ADDR'}, @rangelist) } || ( $ENV{DEBUG} && warn 'cidrlookup failed for ' . join(' ',@rangelist) );
2268 return $result ? 1 : 0;
2271 sub getborrowernumber {
2273 my $userenv = C4::Context->userenv;
2274 if ( defined($userenv) && ref($userenv) eq 'HASH' && $userenv->{number} ) {
2275 return $userenv->{number};
2277 my $dbh = C4::Context->dbh;
2278 for my $field ( 'userid', 'cardnumber' ) {
2280 $dbh->prepare("select borrowernumber from borrowers where $field=?");
2281 $sth->execute($userid);
2283 my ($bnumber) = $sth->fetchrow;
2290 =head2 track_login_daily
2292 track_login_daily( $userid );
2294 Wraps the call to $patron->track_login, the method used to update borrowers.lastseen. We only call track_login once a day.
2298 sub track_login_daily {
2300 return if !$userid || !C4::Context->preference('TrackLastPatronActivity');
2302 my $cache = Koha::Caches->get_instance();
2303 my $cache_key = "track_login_" . $userid;
2304 my $cached = $cache->get_from_cache($cache_key);
2305 my $today = dt_from_string()->ymd;
2306 return if $cached && $cached eq $today;
2308 my $patron = Koha::Patrons->find({ userid => $userid });
2309 return unless $patron;
2310 $patron->track_login;
2311 $cache->set_in_cache( $cache_key, $today );
2314 END { } # module clean-up code here (global destructor)
2324 Crypt::Eksblowfish::Bcrypt(3)