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;
42 use Koha::Patron::Consents;
43 use POSIX qw/strftime/;
44 use List::MoreUtils qw/ any /;
45 use Encode qw( encode is_utf8);
46 use C4::Auth_with_shibboleth;
48 use C4::Log qw/logaction/;
51 use vars qw(@ISA @EXPORT @EXPORT_OK %EXPORT_TAGS $debug $ldap $cas $caslogout);
54 sub psgi_env { any { /^psgi\./ } keys %ENV }
57 if (psgi_env) { die 'psgi:exit' }
61 C4::Context->set_remote_address;
65 @EXPORT = qw(&checkauth &get_template_and_user &haspermission &get_user_subpermissions);
66 @EXPORT_OK = qw(&check_api_auth &get_session &check_cookie_auth &checkpw &checkpw_internal &checkpw_hash
67 &get_all_subpermissions &get_user_subpermissions track_login_daily &in_iprange
69 %EXPORT_TAGS = ( EditPermissions => [qw(get_all_subpermissions get_user_subpermissions)] );
70 $ldap = C4::Context->config('useldapserver') || 0;
71 $cas = C4::Context->preference('casAuthentication');
72 $caslogout = C4::Context->preference('casLogout');
73 require C4::Auth_with_cas; # no import
76 require C4::Auth_with_ldap;
77 import C4::Auth_with_ldap qw(checkpw_ldap);
80 import C4::Auth_with_cas qw(check_api_auth_cas checkpw_cas login_cas logout_cas login_cas_url logout_if_required);
87 C4::Auth - Authenticates Koha users
97 my ($template, $borrowernumber, $cookie)
98 = get_template_and_user(
100 template_name => "opac-main.tt",
103 authnotrequired => 0,
104 flagsrequired => { catalogue => '*', tools => 'import_patrons' },
108 output_html_with_http_headers $query, $cookie, $template->output;
112 The main function of this module is to provide
113 authentification. However the get_template_and_user function has
114 been provided so that a users login information is passed along
115 automatically. This gets loaded into the template.
119 =head2 get_template_and_user
121 my ($template, $borrowernumber, $cookie)
122 = get_template_and_user(
124 template_name => "opac-main.tt",
127 authnotrequired => 0,
128 flagsrequired => { catalogue => '*', tools => 'import_patrons' },
132 This call passes the C<query>, C<flagsrequired> and C<authnotrequired>
133 to C<&checkauth> (in this module) to perform authentification.
134 See C<&checkauth> for an explanation of these parameters.
136 The C<template_name> is then used to find the correct template for
137 the page. The authenticated users details are loaded onto the
138 template in the logged_in_user variable (which is a Koha::Patron object). Also the
139 C<sessionID> is passed to the template. This can be used in templates
140 if cookies are disabled. It needs to be put as and input to every
143 More information on the C<gettemplate> sub can be found in the
148 sub get_template_and_user {
151 my ( $user, $cookie, $sessionID, $flags );
153 # Get shibboleth login attribute
154 my $shib = C4::Context->config('useshibboleth') && shib_ok();
155 my $shib_login = $shib ? get_login_shib() : undef;
157 C4::Context->interface( $in->{type} );
159 $in->{'authnotrequired'} ||= 0;
161 # the following call includes a bad template check; might croak
162 my $template = C4::Templates::gettemplate(
163 $in->{'template_name'},
168 if ( $in->{'template_name'} !~ m/maintenance/ ) {
169 ( $user, $cookie, $sessionID, $flags ) = checkauth(
171 $in->{'authnotrequired'},
172 $in->{'flagsrequired'},
175 $in->{template_name},
179 # If we enforce GDPR and the user did not consent, redirect
180 # Exceptions for consent page itself and SCI/SCO system
181 if( $in->{type} eq 'opac' && $user &&
182 $in->{'template_name'} !~ /^(opac-patron-consent|sc[io]\/)/ &&
183 C4::Context->preference('GDPR_Policy') eq 'Enforced' )
185 my $consent = Koha::Patron::Consents->search({
186 borrowernumber => getborrowernumber($user),
187 type => 'GDPR_PROCESSING',
188 given_on => { '!=', undef },
191 print $in->{query}->redirect(-uri => '/cgi-bin/koha/opac-patron-consent.pl', -cookie => $cookie);
196 if ( $in->{type} eq 'opac' && $user ) {
200 # If the user logged in is the SCO user and they try to go out of the SCO module,
201 # log the user out removing the CGISESSID cookie
202 $in->{template_name} !~ m|sco/| && $in->{template_name} !~ m|errors/errorpage.tt|
203 && C4::Context->preference('AutoSelfCheckID')
204 && $user eq C4::Context->preference('AutoSelfCheckID')
210 # If the user logged in is the SCI user and they try to go out of the SCI module,
211 # kick them out unless it is SCO with a valid permission
212 # or they are a superlibrarian
213 $in->{template_name} !~ m|sci/|
214 && haspermission( $user, { self_check => 'self_checkin_module' } )
216 $in->{template_name} =~ m|sco/| && haspermission(
217 $user, { self_check => 'self_checkout_module' }
220 && $flags && $flags->{superlibrarian} != 1
227 $template = C4::Templates::gettemplate( 'opac-auth.tt', 'opac',
229 $cookie = $in->{query}->cookie(
230 -name => 'CGISESSID',
234 -secure => ( C4::Context->https_enabled() ? 1 : 0 ),
239 script_name => get_script_name(),
242 print $in->{query}->header(
247 'X-Frame-Options' => 'SAMEORIGIN'
258 # It's possible for $user to be the borrowernumber if they don't have a
259 # userid defined (and are logging in through some other method, such
260 # as SSL certs against an email address)
262 $borrowernumber = getborrowernumber($user) if defined($user);
263 if ( !defined($borrowernumber) && defined($user) ) {
264 $patron = Koha::Patrons->find( $user );
266 $borrowernumber = $user;
268 # A bit of a hack, but I don't know there's a nicer way
270 $user = $patron->firstname . ' ' . $patron->surname;
273 $patron = Koha::Patrons->find( $borrowernumber );
274 # FIXME What to do if $patron does not exist?
278 $template->param( loggedinusername => $user ); # OBSOLETE - Do not reuse this in template, use logged_in_user.userid instead
279 $template->param( loggedinusernumber => $borrowernumber ); # FIXME Should be replaced with logged_in_user.borrowernumber
280 $template->param( logged_in_user => $patron );
281 $template->param( sessionID => $sessionID );
283 if ( $in->{'type'} eq 'opac' ) {
284 require Koha::Virtualshelves;
285 my $some_private_shelves = Koha::Virtualshelves->get_some_shelves(
287 borrowernumber => $borrowernumber,
291 my $some_public_shelves = Koha::Virtualshelves->get_some_shelves(
297 some_private_shelves => $some_private_shelves,
298 some_public_shelves => $some_public_shelves,
302 my $all_perms = get_all_subpermissions();
304 my @flagroots = qw(circulate catalogue parameters borrowers permissions reserveforothers borrow
305 editcatalogue updatecharges tools editauthorities serials reports acquisition clubs problem_reports);
307 # We are going to use the $flags returned by checkauth
308 # to create the template's parameters that will indicate
309 # which menus the user can access.
310 if ( $flags && $flags->{superlibrarian} == 1 ) {
311 $template->param( CAN_user_circulate => 1 );
312 $template->param( CAN_user_catalogue => 1 );
313 $template->param( CAN_user_parameters => 1 );
314 $template->param( CAN_user_borrowers => 1 );
315 $template->param( CAN_user_permissions => 1 );
316 $template->param( CAN_user_reserveforothers => 1 );
317 $template->param( CAN_user_editcatalogue => 1 );
318 $template->param( CAN_user_updatecharges => 1 );
319 $template->param( CAN_user_acquisition => 1 );
320 $template->param( CAN_user_suggestions => 1 );
321 $template->param( CAN_user_tools => 1 );
322 $template->param( CAN_user_editauthorities => 1 );
323 $template->param( CAN_user_serials => 1 );
324 $template->param( CAN_user_reports => 1 );
325 $template->param( CAN_user_staffaccess => 1 );
326 $template->param( CAN_user_coursereserves => 1 );
327 $template->param( CAN_user_plugins => 1 );
328 $template->param( CAN_user_lists => 1 );
329 $template->param( CAN_user_clubs => 1 );
330 $template->param( CAN_user_ill => 1 );
331 $template->param( CAN_user_stockrotation => 1 );
332 $template->param( CAN_user_cash_management => 1 );
333 $template->param( CAN_user_problem_reports => 1 );
335 foreach my $module ( keys %$all_perms ) {
336 foreach my $subperm ( keys %{ $all_perms->{$module} } ) {
337 $template->param( "CAN_user_${module}_${subperm}" => 1 );
343 foreach my $module ( keys %$all_perms ) {
344 if ( defined($flags->{$module}) && $flags->{$module} == 1 ) {
345 foreach my $subperm ( keys %{ $all_perms->{$module} } ) {
346 $template->param( "CAN_user_${module}_${subperm}" => 1 );
348 } elsif ( ref( $flags->{$module} ) ) {
349 foreach my $subperm ( keys %{ $flags->{$module} } ) {
350 $template->param( "CAN_user_${module}_${subperm}" => 1 );
357 foreach my $module ( keys %$flags ) {
358 if ( $flags->{$module} == 1 or ref( $flags->{$module} ) ) {
359 $template->param( "CAN_user_$module" => 1 );
364 # Logged-in opac search history
365 # If the requested template is an opac one and opac search history is enabled
366 if ( $in->{type} eq 'opac' && C4::Context->preference('EnableOpacSearchHistory') ) {
367 my $dbh = C4::Context->dbh;
368 my $query = "SELECT COUNT(*) FROM search_history WHERE userid=?";
369 my $sth = $dbh->prepare($query);
370 $sth->execute($borrowernumber);
372 # If at least one search has already been performed
373 if ( $sth->fetchrow_array > 0 ) {
375 # We show the link in opac
376 $template->param( EnableOpacSearchHistory => 1 );
378 if (C4::Context->preference('LoadSearchHistoryToTheFirstLoggedUser'))
380 # And if there are searches performed when the user was not logged in,
381 # we add them to the logged-in search history
382 my @recentSearches = C4::Search::History::get_from_session( { cgi => $in->{'query'} } );
383 if (@recentSearches) {
384 my $dbh = C4::Context->dbh;
386 INSERT INTO search_history(userid, sessionid, query_desc, query_cgi, type, total, time )
387 VALUES (?, ?, ?, ?, ?, ?, ?)
389 my $sth = $dbh->prepare($query);
390 $sth->execute( $borrowernumber,
391 $in->{query}->cookie("CGISESSID"),
394 $_->{type} || 'biblio',
397 ) foreach @recentSearches;
399 # clear out the search history from the session now that
400 # we've saved it to the database
403 C4::Search::History::set_to_session( { cgi => $in->{'query'}, search_history => [] } );
405 } elsif ( $in->{type} eq 'intranet' and C4::Context->preference('EnableSearchHistory') ) {
406 $template->param( EnableSearchHistory => 1 );
409 else { # if this is an anonymous session, setup to display public lists...
411 # If shibboleth is enabled, and we're in an anonymous session, we should allow
412 # the user to attempt login via shibboleth.
414 $template->param( shibbolethAuthentication => $shib,
415 shibbolethLoginUrl => login_shib_url( $in->{'query'} ),
418 # If shibboleth is enabled and we have a shibboleth login attribute,
419 # but we are in an anonymous session, then we clearly have an invalid
420 # shibboleth koha account.
422 $template->param( invalidShibLogin => '1' );
426 $template->param( sessionID => $sessionID );
428 if ( $in->{'type'} eq 'opac' ){
429 require Koha::Virtualshelves;
430 my $some_public_shelves = Koha::Virtualshelves->get_some_shelves(
436 some_public_shelves => $some_public_shelves,
441 # Sysprefs disabled via URL param
442 # Note that value must be defined in order to override via ENV
443 foreach my $syspref (
449 OpacAdditionalStylesheet
451 intranetcolorstylesheet
456 $ENV{"OVERRIDE_SYSPREF_$syspref"} = q{}
457 if $in->{'query'}->param("DISABLE_SYSPREF_$syspref");
460 # Anonymous opac search history
461 # If opac search history is enabled and at least one search has already been performed
462 if ( C4::Context->preference('EnableOpacSearchHistory') ) {
463 my @recentSearches = C4::Search::History::get_from_session( { cgi => $in->{'query'} } );
464 if (@recentSearches) {
465 $template->param( EnableOpacSearchHistory => 1 );
469 if ( C4::Context->preference('dateformat') ) {
470 $template->param( dateformat => C4::Context->preference('dateformat') );
473 $template->param(auth_forwarded_hash => scalar $in->{'query'}->param('auth_forwarded_hash'));
475 # these template parameters are set the same regardless of $in->{'type'}
477 my $minPasswordLength = C4::Context->preference('minPasswordLength');
478 $minPasswordLength = 3 if not $minPasswordLength or $minPasswordLength < 3;
480 "BiblioDefaultView" . C4::Context->preference("BiblioDefaultView") => 1,
481 EnhancedMessagingPreferences => C4::Context->preference('EnhancedMessagingPreferences'),
482 GoogleJackets => C4::Context->preference("GoogleJackets"),
483 OpenLibraryCovers => C4::Context->preference("OpenLibraryCovers"),
484 KohaAdminEmailAddress => "" . C4::Context->preference("KohaAdminEmailAddress"),
485 LoginFirstname => ( C4::Context->userenv ? C4::Context->userenv->{"firstname"} : "Bel" ),
486 LoginSurname => C4::Context->userenv ? C4::Context->userenv->{"surname"} : "Inconnu",
487 emailaddress => C4::Context->userenv ? C4::Context->userenv->{"emailaddress"} : undef,
488 TagsEnabled => C4::Context->preference("TagsEnabled"),
489 hide_marc => C4::Context->preference("hide_marc"),
490 item_level_itypes => C4::Context->preference('item-level_itypes'),
491 patronimages => C4::Context->preference("patronimages"),
492 singleBranchMode => ( Koha::Libraries->search->count == 1 ),
493 XSLTDetailsDisplay => C4::Context->preference("XSLTDetailsDisplay"),
494 XSLTResultsDisplay => C4::Context->preference("XSLTResultsDisplay"),
495 noItemTypeImages => C4::Context->preference("noItemTypeImages"),
496 marcflavour => C4::Context->preference("marcflavour"),
497 OPACBaseURL => C4::Context->preference('OPACBaseURL'),
498 minPasswordLength => $minPasswordLength,
500 if ( $in->{'type'} eq "intranet" ) {
502 AmazonCoverImages => C4::Context->preference("AmazonCoverImages"),
503 AutoLocation => C4::Context->preference("AutoLocation"),
504 "BiblioDefaultView" . C4::Context->preference("IntranetBiblioDefaultView") => 1,
505 PatronAutoComplete => C4::Context->preference("PatronAutoComplete"),
506 FRBRizeEditions => C4::Context->preference("FRBRizeEditions"),
507 IndependentBranches => C4::Context->preference("IndependentBranches"),
508 IntranetNav => C4::Context->preference("IntranetNav"),
509 IntranetmainUserblock => C4::Context->preference("IntranetmainUserblock"),
510 LibraryName => C4::Context->preference("LibraryName"),
511 advancedMARCEditor => C4::Context->preference("advancedMARCEditor"),
512 canreservefromotherbranches => C4::Context->preference('canreservefromotherbranches'),
513 intranetcolorstylesheet => C4::Context->preference("intranetcolorstylesheet"),
514 IntranetFavicon => C4::Context->preference("IntranetFavicon"),
515 intranetreadinghistory => C4::Context->preference("intranetreadinghistory"),
516 intranetstylesheet => C4::Context->preference("intranetstylesheet"),
517 IntranetUserCSS => C4::Context->preference("IntranetUserCSS"),
518 IntranetUserJS => C4::Context->preference("IntranetUserJS"),
519 intranetbookbag => C4::Context->preference("intranetbookbag"),
520 suggestion => C4::Context->preference("suggestion"),
521 virtualshelves => C4::Context->preference("virtualshelves"),
522 StaffSerialIssueDisplayCount => C4::Context->preference("StaffSerialIssueDisplayCount"),
523 EasyAnalyticalRecords => C4::Context->preference('EasyAnalyticalRecords'),
524 LocalCoverImages => C4::Context->preference('LocalCoverImages'),
525 OPACLocalCoverImages => C4::Context->preference('OPACLocalCoverImages'),
526 AllowMultipleCovers => C4::Context->preference('AllowMultipleCovers'),
527 EnableBorrowerFiles => C4::Context->preference('EnableBorrowerFiles'),
528 UseCourseReserves => C4::Context->preference("UseCourseReserves"),
529 useDischarge => C4::Context->preference('useDischarge'),
530 pending_checkout_notes => scalar Koha::Checkouts->search({ noteseen => 0 }),
534 warn "template type should be OPAC, here it is=[" . $in->{'type'} . "]" unless ( $in->{'type'} eq 'opac' );
536 #TODO : replace LibraryName syspref with 'system name', and remove this html processing
537 my $LibraryNameTitle = C4::Context->preference("LibraryName");
538 $LibraryNameTitle =~ s/<(?:\/?)(?:br|p)\s*(?:\/?)>/ /sgi;
539 $LibraryNameTitle =~ s/<(?:[^<>'"]|'(?:[^']*)'|"(?:[^"]*)")*>//sg;
541 # clean up the busc param in the session
542 # if the page is not opac-detail and not the "add to list" page
543 # and not the "edit comments" page
544 if ( C4::Context->preference("OpacBrowseResults")
545 && $in->{'template_name'} =~ /opac-(.+)\.(?:tt|tmpl)$/ ) {
547 unless ( $pagename =~ /^(?:MARC|ISBD)?detail$/
548 or $pagename =~ /^addbybiblionumber$/
549 or $pagename =~ /^review$/ ) {
550 my $sessionSearch = get_session( $sessionID || $in->{'query'}->cookie("CGISESSID") );
551 $sessionSearch->clear( ["busc"] ) if ( $sessionSearch->param("busc") );
555 # variables passed from CGI: opac_css_override and opac_search_limits.
556 my $opac_search_limit = $ENV{'OPAC_SEARCH_LIMIT'};
557 my $opac_limit_override = $ENV{'OPAC_LIMIT_OVERRIDE'};
560 ( $opac_limit_override && $opac_search_limit && $opac_search_limit =~ /branch:([\w-]+)/ ) ||
561 ( $in->{'query'}->param('limit') && $in->{'query'}->param('limit') =~ /branch:([\w-]+)/ ) ||
562 ( $in->{'query'}->param('multibranchlimit') && $in->{'query'}->param('multibranchlimit') =~ /multibranchlimit-(\w+)/ )
564 $opac_name = $1; # opac_search_limit is a branch, so we use it.
565 } elsif ( $in->{'query'}->param('multibranchlimit') ) {
566 $opac_name = $in->{'query'}->param('multibranchlimit');
567 } elsif ( C4::Context->preference("SearchMyLibraryFirst") && C4::Context->userenv && C4::Context->userenv->{'branch'} ) {
568 $opac_name = C4::Context->userenv->{'branch'};
571 my @search_groups = Koha::Library::Groups->get_search_groups({ interface => 'opac' });
573 AnonSuggestions => "" . C4::Context->preference("AnonSuggestions"),
574 LibrarySearchGroups => \@search_groups,
575 opac_name => $opac_name,
576 LibraryName => "" . C4::Context->preference("LibraryName"),
577 LibraryNameTitle => "" . $LibraryNameTitle,
578 OPACAmazonCoverImages => C4::Context->preference("OPACAmazonCoverImages"),
579 OPACFRBRizeEditions => C4::Context->preference("OPACFRBRizeEditions"),
580 OpacHighlightedWords => C4::Context->preference("OpacHighlightedWords"),
581 OPACShelfBrowser => "" . C4::Context->preference("OPACShelfBrowser"),
582 OPACURLOpenInNewWindow => "" . C4::Context->preference("OPACURLOpenInNewWindow"),
583 OPACUserCSS => "" . C4::Context->preference("OPACUserCSS"),
584 OpacAuthorities => C4::Context->preference("OpacAuthorities"),
585 opac_css_override => $ENV{'OPAC_CSS_OVERRIDE'},
586 opac_search_limit => $opac_search_limit,
587 opac_limit_override => $opac_limit_override,
588 OpacBrowser => C4::Context->preference("OpacBrowser"),
589 OpacCloud => C4::Context->preference("OpacCloud"),
590 OpacKohaUrl => C4::Context->preference("OpacKohaUrl"),
591 OpacNav => "" . C4::Context->preference("OpacNav"),
592 OpacNavBottom => "" . C4::Context->preference("OpacNavBottom"),
593 OpacPasswordChange => C4::Context->preference("OpacPasswordChange"),
594 OPACPatronDetails => C4::Context->preference("OPACPatronDetails"),
595 OPACPrivacy => C4::Context->preference("OPACPrivacy"),
596 OPACFinesTab => C4::Context->preference("OPACFinesTab"),
597 OpacTopissue => C4::Context->preference("OpacTopissue"),
598 RequestOnOpac => C4::Context->preference("RequestOnOpac"),
599 'Version' => C4::Context->preference('Version'),
600 hidelostitems => C4::Context->preference("hidelostitems"),
601 mylibraryfirst => ( C4::Context->preference("SearchMyLibraryFirst") && C4::Context->userenv ) ? C4::Context->userenv->{'branch'} : '',
602 opacbookbag => "" . C4::Context->preference("opacbookbag"),
603 OpacFavicon => C4::Context->preference("OpacFavicon"),
604 opaclanguagesdisplay => "" . C4::Context->preference("opaclanguagesdisplay"),
605 opacreadinghistory => C4::Context->preference("opacreadinghistory"),
606 OPACUserJS => C4::Context->preference("OPACUserJS"),
607 opacuserlogin => "" . C4::Context->preference("opacuserlogin"),
608 OpenLibrarySearch => C4::Context->preference("OpenLibrarySearch"),
609 ShowReviewer => C4::Context->preference("ShowReviewer"),
610 ShowReviewerPhoto => C4::Context->preference("ShowReviewerPhoto"),
611 suggestion => "" . C4::Context->preference("suggestion"),
612 virtualshelves => "" . C4::Context->preference("virtualshelves"),
613 OPACSerialIssueDisplayCount => C4::Context->preference("OPACSerialIssueDisplayCount"),
614 OPACXSLTDetailsDisplay => C4::Context->preference("OPACXSLTDetailsDisplay"),
615 OPACXSLTResultsDisplay => C4::Context->preference("OPACXSLTResultsDisplay"),
616 SyndeticsClientCode => C4::Context->preference("SyndeticsClientCode"),
617 SyndeticsEnabled => C4::Context->preference("SyndeticsEnabled"),
618 SyndeticsCoverImages => C4::Context->preference("SyndeticsCoverImages"),
619 SyndeticsTOC => C4::Context->preference("SyndeticsTOC"),
620 SyndeticsSummary => C4::Context->preference("SyndeticsSummary"),
621 SyndeticsEditions => C4::Context->preference("SyndeticsEditions"),
622 SyndeticsExcerpt => C4::Context->preference("SyndeticsExcerpt"),
623 SyndeticsReviews => C4::Context->preference("SyndeticsReviews"),
624 SyndeticsAuthorNotes => C4::Context->preference("SyndeticsAuthorNotes"),
625 SyndeticsAwards => C4::Context->preference("SyndeticsAwards"),
626 SyndeticsSeries => C4::Context->preference("SyndeticsSeries"),
627 SyndeticsCoverImageSize => C4::Context->preference("SyndeticsCoverImageSize"),
628 OPACLocalCoverImages => C4::Context->preference("OPACLocalCoverImages"),
629 PatronSelfRegistration => C4::Context->preference("PatronSelfRegistration"),
630 PatronSelfRegistrationDefaultCategory => C4::Context->preference("PatronSelfRegistrationDefaultCategory"),
631 useDischarge => C4::Context->preference('useDischarge'),
634 $template->param( OpacPublic => '1' ) if ( $user || C4::Context->preference("OpacPublic") );
637 # Check if we were asked using parameters to force a specific language
638 if ( defined $in->{'query'}->param('language') ) {
640 # Extract the language, let C4::Languages::getlanguage choose
642 my $language = C4::Languages::getlanguage( $in->{'query'} );
643 my $languagecookie = C4::Templates::getlanguagecookie( $in->{'query'}, $language );
644 if ( ref $cookie eq 'ARRAY' ) {
645 push @{$cookie}, $languagecookie;
647 $cookie = [ $cookie, $languagecookie ];
651 return ( $template, $borrowernumber, $cookie, $flags );
656 ($userid, $cookie, $sessionID) = &checkauth($query, $noauth, $flagsrequired, $type);
658 Verifies that the user is authorized to run this script. If
659 the user is authorized, a (userid, cookie, session-id, flags)
660 quadruple is returned. If the user is not authorized but does
661 not have the required privilege (see $flagsrequired below), it
662 displays an error page and exits. Otherwise, it displays the
663 login page and exits.
665 Note that C<&checkauth> will return if and only if the user
666 is authorized, so it should be called early on, before any
667 unfinished operations (e.g., if you've opened a file, then
668 C<&checkauth> won't close it for you).
670 C<$query> is the CGI object for the script calling C<&checkauth>.
672 The C<$noauth> argument is optional. If it is set, then no
673 authorization is required for the script.
675 C<&checkauth> fetches user and session information from C<$query> and
676 ensures that the user is authorized to run scripts that require
679 The C<$flagsrequired> argument specifies the required privileges
680 the user must have if the username and password are correct.
681 It should be specified as a reference-to-hash; keys in the hash
682 should be the "flags" for the user, as specified in the Members
683 intranet module. Any key specified must correspond to a "flag"
684 in the userflags table. E.g., { circulate => 1 } would specify
685 that the user must have the "circulate" privilege in order to
686 proceed. To make sure that access control is correct, the
687 C<$flagsrequired> parameter must be specified correctly.
689 Koha also has a concept of sub-permissions, also known as
690 granular permissions. This makes the value of each key
691 in the C<flagsrequired> hash take on an additional
696 The user must have access to all subfunctions of the module
697 specified by the hash key.
701 The user must have access to at least one subfunction of the module
702 specified by the hash key.
704 specific permission, e.g., 'export_catalog'
706 The user must have access to the specific subfunction list, which
707 must correspond to a row in the permissions table.
709 The C<$type> argument specifies whether the template should be
710 retrieved from the opac or intranet directory tree. "opac" is
711 assumed if it is not specified; however, if C<$type> is specified,
712 "intranet" is assumed if it is not "opac".
714 If C<$query> does not have a valid session ID associated with it
715 (i.e., the user has not logged in) or if the session has expired,
716 C<&checkauth> presents the user with a login page (from the point of
717 view of the original script, C<&checkauth> does not return). Once the
718 user has authenticated, C<&checkauth> restarts the original script
719 (this time, C<&checkauth> returns).
721 The login page is provided using a HTML::Template, which is set in the
722 systempreferences table or at the top of this file. The variable C<$type>
723 selects which template to use, either the opac or the intranet
724 authentification template.
726 C<&checkauth> returns a user ID, a cookie, and a session ID. The
727 cookie should be sent back to the browser; it verifies that the user
737 # If version syspref is unavailable, it means Koha is being installed,
738 # and so we must redirect to OPAC maintenance page or to the WebInstaller
739 # also, if OpacMaintenance is ON, OPAC should redirect to maintenance
740 if ( C4::Context->preference('OpacMaintenance') && $type eq 'opac' ) {
741 warn "OPAC Install required, redirecting to maintenance";
742 print $query->redirect("/cgi-bin/koha/maintenance.pl");
745 unless ( $version = C4::Context->preference('Version') ) { # assignment, not comparison
746 if ( $type ne 'opac' ) {
747 warn "Install required, redirecting to Installer";
748 print $query->redirect("/cgi-bin/koha/installer/install.pl");
750 warn "OPAC Install required, redirecting to maintenance";
751 print $query->redirect("/cgi-bin/koha/maintenance.pl");
756 # check that database and koha version are the same
757 # there is no DB version, it's a fresh install,
758 # go to web installer
759 # there is a DB version, compare it to the code version
760 my $kohaversion = Koha::version();
762 # remove the 3 last . to have a Perl number
763 $kohaversion =~ s/(.*\..*)\.(.*)\.(.*)/$1$2$3/;
764 $debug and print STDERR "kohaversion : $kohaversion\n";
765 if ( $version < $kohaversion ) {
766 my $warning = "Database update needed, redirecting to %s. Database is $version and Koha is $kohaversion";
767 if ( $type ne 'opac' ) {
768 warn sprintf( $warning, 'Installer' );
769 print $query->redirect("/cgi-bin/koha/installer/install.pl?step=1&op=updatestructure");
771 warn sprintf( "OPAC: " . $warning, 'maintenance' );
772 print $query->redirect("/cgi-bin/koha/maintenance.pl");
780 open my $fh, '>>', "/tmp/sessionlog" or warn "ERROR: Cannot append to /tmp/sessionlog";
781 printf $fh join( "\n", @_ );
785 sub _timeout_syspref {
786 my $default_timeout = 600;
787 my $timeout = C4::Context->preference('timeout') || $default_timeout;
789 # value in days, convert in seconds
790 if ( $timeout =~ /^(\d+)[dD]$/ ) {
791 $timeout = $1 * 86400;
793 # value in hours, convert in seconds
794 elsif ( $timeout =~ /^(\d+)[hH]$/ ) {
795 $timeout = $1 * 3600;
797 elsif ( $timeout !~ m/^\d+$/ ) {
798 warn "The value of the system preference 'timeout' is not correct, defaulting to $default_timeout";
799 $timeout = $default_timeout;
807 $debug and warn "Checking Auth";
809 # Get shibboleth login attribute
810 my $shib = C4::Context->config('useshibboleth') && shib_ok();
811 my $shib_login = $shib ? get_login_shib() : undef;
813 # $authnotrequired will be set for scripts which will run without authentication
814 my $authnotrequired = shift;
815 my $flagsrequired = shift;
817 my $emailaddress = shift;
818 my $template_name = shift;
819 $type = 'opac' unless $type;
821 unless ( C4::Context->preference("OpacPublic") ) {
822 my @allowed_scripts_for_private_opac = qw(
824 opac-registration-email-sent.tt
825 opac-registration-confirmation.tt
826 opac-memberentry-update-submitted.tt
827 opac-password-recovery.tt
829 $authnotrequired = 0 unless grep { $_ eq $template_name }
830 @allowed_scripts_for_private_opac;
833 my $dbh = C4::Context->dbh;
834 my $timeout = _timeout_syspref();
836 _version_check( $type, $query );
841 my ( $userid, $cookie, $sessionID, $flags );
842 my $logout = $query->param('logout.x');
844 my $anon_search_history;
846 # This parameter is the name of the CAS server we want to authenticate against,
847 # when using authentication against multiple CAS servers, as configured in Auth_cas_servers.yaml
848 my $casparam = $query->param('cas');
849 my $q_userid = $query->param('userid') // '';
853 # Basic authentication is incompatible with the use of Shibboleth,
854 # as Shibboleth may return REMOTE_USER as a Shibboleth attribute,
855 # and it may not be the attribute we want to use to match the koha login.
857 # Also, do not consider an empty REMOTE_USER.
859 # Finally, after those tests, we can assume (although if it would be better with
860 # a syspref) that if we get a REMOTE_USER, that's from basic authentication,
861 # and we can affect it to $userid.
862 if ( !$shib and defined( $ENV{'REMOTE_USER'} ) and $ENV{'REMOTE_USER'} ne '' and $userid = $ENV{'REMOTE_USER'} ) {
864 # Using Basic Authentication, no cookies required
865 $cookie = $query->cookie(
866 -name => 'CGISESSID',
870 -secure => ( C4::Context->https_enabled() ? 1 : 0 ),
874 elsif ( $emailaddress) {
875 # the Google OpenID Connect passes an email address
877 elsif ( $sessionID = $query->cookie("CGISESSID") )
878 { # assignment, not comparison
879 $session = get_session($sessionID);
880 C4::Context->_new_userenv($sessionID);
881 my ( $ip, $lasttime, $sessiontype );
884 $s_userid = $session->param('id') // '';
885 C4::Context->set_userenv(
886 $session->param('number'), $s_userid,
887 $session->param('cardnumber'), $session->param('firstname'),
888 $session->param('surname'), $session->param('branch'),
889 $session->param('branchname'), $session->param('flags'),
890 $session->param('emailaddress'),
891 $session->param('shibboleth')
893 C4::Context::set_shelves_userenv( 'bar', $session->param('barshelves') );
894 C4::Context::set_shelves_userenv( 'pub', $session->param('pubshelves') );
895 C4::Context::set_shelves_userenv( 'tot', $session->param('totshelves') );
896 $debug and printf STDERR "AUTH_SESSION: (%s)\t%s %s - %s\n", map { $session->param($_) } qw(cardnumber firstname surname branch);
897 $ip = $session->param('ip');
898 $lasttime = $session->param('lasttime');
900 $sessiontype = $session->param('sessiontype') || '';
902 if ( ( $query->param('koha_login_context') && ( $q_userid ne $s_userid ) )
903 || ( $cas && $query->param('ticket') && !C4::Context->userenv->{'id'} )
904 || ( $shib && $shib_login && !$logout && !C4::Context->userenv->{'id'} )
907 #if a user enters an id ne to the id in the current session, we need to log them in...
908 #first we need to clear the anonymous session...
909 $debug and warn "query id = $q_userid but session id = $s_userid";
910 $anon_search_history = $session->param('search_history');
913 C4::Context->_unset_userenv($sessionID);
919 # voluntary logout the user
920 # check wether the user was using their shibboleth session or a local one
921 my $shibSuccess = C4::Context->userenv->{'shibboleth'};
924 C4::Context->_unset_userenv($sessionID);
926 #_session_log(sprintf "%20s from %16s logged out at %30s (manually).\n", $userid,$ip,(strftime "%c",localtime));
930 if ($cas and $caslogout) {
931 logout_cas($query, $type);
934 # If we are in a shibboleth session (shibboleth is enabled, a shibboleth match attribute is set and matches koha matchpoint)
935 if ( $shib and $shib_login and $shibSuccess) {
939 elsif ( !$lasttime || ( $lasttime < time() - $timeout ) ) {
942 $info{'timed_out'} = 1;
947 C4::Context->_unset_userenv($sessionID);
949 #_session_log(sprintf "%20s from %16s logged out at %30s (inactivity).\n", $userid,$ip,(strftime "%c",localtime));
953 elsif ( C4::Context->preference('SessionRestrictionByIP') && $ip ne $ENV{'REMOTE_ADDR'} ) {
955 # Different ip than originally logged in from
956 $info{'oldip'} = $ip;
957 $info{'newip'} = $ENV{'REMOTE_ADDR'};
958 $info{'different_ip'} = 1;
961 C4::Context->_unset_userenv($sessionID);
963 #_session_log(sprintf "%20s from %16s logged out at %30s (ip changed to %16s).\n", $userid,$ip,(strftime "%c",localtime), $info{'newip'});
968 $cookie = $query->cookie(
969 -name => 'CGISESSID',
970 -value => $session->id,
972 -secure => ( C4::Context->https_enabled() ? 1 : 0 ),
974 $session->param( 'lasttime', time() );
975 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...
976 $flags = haspermission( $userid, $flagsrequired );
980 $info{'nopermission'} = 1;
985 unless ( $userid || $sessionID ) {
986 #we initiate a session prior to checking for a username to allow for anonymous sessions...
987 my $session = get_session("") or die "Auth ERROR: Cannot get_session()";
989 # Save anonymous search history in new session so it can be retrieved
990 # by get_template_and_user to store it in user's search history after
991 # a successful login.
992 if ($anon_search_history) {
993 $session->param( 'search_history', $anon_search_history );
996 $sessionID = $session->id;
997 C4::Context->_new_userenv($sessionID);
998 $cookie = $query->cookie(
999 -name => 'CGISESSID',
1000 -value => $session->id,
1002 -secure => ( C4::Context->https_enabled() ? 1 : 0 ),
1004 my $pki_field = C4::Context->preference('AllowPKIAuth');
1005 if ( !defined($pki_field) ) {
1006 print STDERR "ERROR: Missing system preference AllowPKIAuth.\n";
1007 $pki_field = 'None';
1009 if ( ( $cas && $query->param('ticket') )
1011 || ( $shib && $shib_login )
1012 || $pki_field ne 'None'
1015 my $password = $query->param('password');
1016 my $shibSuccess = 0;
1017 my ( $return, $cardnumber );
1019 # If shib is enabled and we have a shib login, does the login match a valid koha user
1020 if ( $shib && $shib_login ) {
1023 # Do not pass password here, else shib will not be checked in checkpw.
1024 ( $return, $cardnumber, $retuserid ) = checkpw( $dbh, $q_userid, undef, $query );
1025 $userid = $retuserid;
1026 $shibSuccess = $return;
1027 $info{'invalidShibLogin'} = 1 unless ($return);
1030 # If shib login and match were successful, skip further login methods
1031 unless ($shibSuccess) {
1032 if ( $cas && $query->param('ticket') ) {
1034 ( $return, $cardnumber, $retuserid, $cas_ticket ) =
1035 checkpw( $dbh, $userid, $password, $query, $type );
1036 $userid = $retuserid;
1037 $info{'invalidCasLogin'} = 1 unless ($return);
1040 elsif ( $emailaddress ) {
1041 my $value = $emailaddress;
1043 # If we're looking up the email, there's a chance that the person
1044 # doesn't have a userid. So if there is none, we pass along the
1045 # borrower number, and the bits of code that need to know the user
1046 # ID will have to be smart enough to handle that.
1047 my $patrons = Koha::Patrons->search({ email => $value });
1048 if ($patrons->count) {
1050 # First the userid, then the borrowernum
1051 my $patron = $patrons->next;
1052 $value = $patron->userid || $patron->borrowernumber;
1056 $return = $value ? 1 : 0;
1061 ( $pki_field eq 'Common Name' && $ENV{'SSL_CLIENT_S_DN_CN'} )
1062 || ( $pki_field eq 'emailAddress'
1063 && $ENV{'SSL_CLIENT_S_DN_Email'} )
1067 if ( $pki_field eq 'Common Name' ) {
1068 $value = $ENV{'SSL_CLIENT_S_DN_CN'};
1070 elsif ( $pki_field eq 'emailAddress' ) {
1071 $value = $ENV{'SSL_CLIENT_S_DN_Email'};
1073 # If we're looking up the email, there's a chance that the person
1074 # doesn't have a userid. So if there is none, we pass along the
1075 # borrower number, and the bits of code that need to know the user
1076 # ID will have to be smart enough to handle that.
1077 my $patrons = Koha::Patrons->search({ email => $value });
1078 if ($patrons->count) {
1080 # First the userid, then the borrowernum
1081 my $patron = $patrons->next;
1082 $value = $patron->userid || $patron->borrowernumber;
1088 $return = $value ? 1 : 0;
1094 ( $return, $cardnumber, $retuserid, $cas_ticket ) =
1095 checkpw( $dbh, $q_userid, $password, $query, $type );
1096 $userid = $retuserid if ($retuserid);
1097 $info{'invalid_username_or_password'} = 1 unless ($return);
1101 # $return: 1 = valid user
1104 #_session_log(sprintf "%20s from %16s logged in at %30s.\n", $userid,$ENV{'REMOTE_ADDR'},(strftime '%c', localtime));
1105 if ( $flags = haspermission( $userid, $flagsrequired ) ) {
1109 $info{'nopermission'} = 1;
1110 C4::Context->_unset_userenv($sessionID);
1112 my ( $borrowernumber, $firstname, $surname, $userflags,
1113 $branchcode, $branchname, $emailaddress );
1115 if ( $return == 1 ) {
1117 SELECT borrowernumber, firstname, surname, flags, borrowers.branchcode,
1118 branches.branchname as branchname, email
1120 LEFT JOIN branches on borrowers.branchcode=branches.branchcode
1122 my $sth = $dbh->prepare("$select where userid=?");
1123 $sth->execute($userid);
1124 unless ( $sth->rows ) {
1125 $debug and print STDERR "AUTH_1: no rows for userid='$userid'\n";
1126 $sth = $dbh->prepare("$select where cardnumber=?");
1127 $sth->execute($cardnumber);
1129 unless ( $sth->rows ) {
1130 $debug and print STDERR "AUTH_2a: no rows for cardnumber='$cardnumber'\n";
1131 $sth->execute($userid);
1132 unless ( $sth->rows ) {
1133 $debug and print STDERR "AUTH_2b: no rows for userid='$userid' AS cardnumber\n";
1138 ( $borrowernumber, $firstname, $surname, $userflags,
1139 $branchcode, $branchname, $emailaddress ) = $sth->fetchrow;
1140 $debug and print STDERR "AUTH_3 results: " .
1141 "$cardnumber,$borrowernumber,$userid,$firstname,$surname,$userflags,$branchcode,$emailaddress\n";
1143 print STDERR "AUTH_3: no results for userid='$userid', cardnumber='$cardnumber'.\n";
1146 # launch a sequence to check if we have a ip for the branch, i
1147 # if we have one we replace the branchcode of the userenv by the branch bound in the ip.
1149 my $ip = $ENV{'REMOTE_ADDR'};
1151 # if they specify at login, use that
1152 if ( $query->param('branch') ) {
1153 $branchcode = $query->param('branch');
1154 my $library = Koha::Libraries->find($branchcode);
1155 $branchname = $library? $library->branchname: '';
1157 my $branches = { map { $_->branchcode => $_->unblessed } Koha::Libraries->search };
1158 if ( $type ne 'opac' and C4::Context->boolean_preference('AutoLocation') ) {
1160 # we have to check they are coming from the right ip range
1161 my $domain = $branches->{$branchcode}->{'branchip'};
1162 $domain =~ s|\.\*||g;
1163 if ( $ip !~ /^$domain/ ) {
1165 $cookie = $query->cookie(
1166 -name => 'CGISESSID',
1169 -secure => ( C4::Context->https_enabled() ? 1 : 0 ),
1171 $info{'wrongip'} = 1;
1175 foreach my $br ( keys %$branches ) {
1177 # now we work with the treatment of ip
1178 my $domain = $branches->{$br}->{'branchip'};
1179 if ( $domain && $ip =~ /^$domain/ ) {
1180 $branchcode = $branches->{$br}->{'branchcode'};
1182 # new op dev : add the branchname to the cookie
1183 $branchname = $branches->{$br}->{'branchname'};
1186 $session->param( 'number', $borrowernumber );
1187 $session->param( 'id', $userid );
1188 $session->param( 'cardnumber', $cardnumber );
1189 $session->param( 'firstname', $firstname );
1190 $session->param( 'surname', $surname );
1191 $session->param( 'branch', $branchcode );
1192 $session->param( 'branchname', $branchname );
1193 $session->param( 'flags', $userflags );
1194 $session->param( 'emailaddress', $emailaddress );
1195 $session->param( 'ip', $session->remote_addr() );
1196 $session->param( 'lasttime', time() );
1197 $session->param( 'interface', $type);
1198 $session->param( 'shibboleth', $shibSuccess );
1199 $debug and printf STDERR "AUTH_4: (%s)\t%s %s - %s\n", map { $session->param($_) } qw(cardnumber firstname surname branch);
1201 $session->param('cas_ticket', $cas_ticket) if $cas_ticket;
1202 C4::Context->set_userenv(
1203 $session->param('number'), $session->param('id'),
1204 $session->param('cardnumber'), $session->param('firstname'),
1205 $session->param('surname'), $session->param('branch'),
1206 $session->param('branchname'), $session->param('flags'),
1207 $session->param('emailaddress'), $session->param('shibboleth')
1211 # $return: 0 = invalid user
1212 # reset to anonymous session
1214 $debug and warn "Login failed, resetting anonymous session...";
1216 $info{'invalid_username_or_password'} = 1;
1217 C4::Context->_unset_userenv($sessionID);
1219 $session->param( 'lasttime', time() );
1220 $session->param( 'ip', $session->remote_addr() );
1221 $session->param( 'sessiontype', 'anon' );
1222 $session->param( 'interface', $type);
1224 } # END if ( $q_userid
1225 elsif ( $type eq "opac" ) {
1227 # if we are here this is an anonymous session; add public lists to it and a few other items...
1228 # anonymous sessions are created only for the OPAC
1229 $debug and warn "Initiating an anonymous session...";
1231 # setting a couple of other session vars...
1232 $session->param( 'ip', $session->remote_addr() );
1233 $session->param( 'lasttime', time() );
1234 $session->param( 'sessiontype', 'anon' );
1235 $session->param( 'interface', $type);
1237 } # END unless ($userid)
1239 # finished authentification, now respond
1240 if ( $loggedin || $authnotrequired )
1244 $cookie = $query->cookie(
1245 -name => 'CGISESSID',
1248 -secure => ( C4::Context->https_enabled() ? 1 : 0 ),
1252 track_login_daily( $userid );
1254 # In case, that this request was a login attempt, we want to prevent that users can repost the opac login
1255 # request. We therefore redirect the user to the requested page again without the login parameters.
1256 # See Post/Redirect/Get (PRG) design pattern: https://en.wikipedia.org/wiki/Post/Redirect/Get
1257 if ( $type eq "opac" && $query->param('koha_login_context') && $query->param('koha_login_context') ne 'sco' && $query->param('password') && $query->param('userid') ) {
1258 my $uri = URI->new($query->url(-relative=>1, -query_string=>1));
1259 $uri->query_param_delete('userid');
1260 $uri->query_param_delete('password');
1261 $uri->query_param_delete('koha_login_context');
1262 print $query->redirect(-uri => $uri->as_string, -cookie => $cookie, -status=>'303 See other');
1266 return ( $userid, $cookie, $sessionID, $flags );
1271 # AUTH rejected, show the login/password template, after checking the DB.
1275 # get the inputs from the incoming query
1277 foreach my $name ( param $query) {
1278 (next) if ( $name eq 'userid' || $name eq 'password' || $name eq 'ticket' );
1279 my @value = $query->multi_param($name);
1280 push @inputs, { name => $name, value => $_ } for @value;
1283 my $patron = Koha::Patrons->find({ userid => $q_userid }); # Not necessary logged in!
1285 my $LibraryNameTitle = C4::Context->preference("LibraryName");
1286 $LibraryNameTitle =~ s/<(?:\/?)(?:br|p)\s*(?:\/?)>/ /sgi;
1287 $LibraryNameTitle =~ s/<(?:[^<>'"]|'(?:[^']*)'|"(?:[^"]*)")*>//sg;
1289 my $auth_template_name = ( $type eq 'opac' ) ? 'opac-auth.tt' : 'auth.tt';
1290 my $template = C4::Templates::gettemplate( $auth_template_name, $type, $query );
1294 script_name => get_script_name(),
1295 casAuthentication => C4::Context->preference("casAuthentication"),
1296 shibbolethAuthentication => $shib,
1297 SessionRestrictionByIP => C4::Context->preference("SessionRestrictionByIP"),
1298 suggestion => C4::Context->preference("suggestion"),
1299 virtualshelves => C4::Context->preference("virtualshelves"),
1300 LibraryName => "" . C4::Context->preference("LibraryName"),
1301 LibraryNameTitle => "" . $LibraryNameTitle,
1302 opacuserlogin => C4::Context->preference("opacuserlogin"),
1303 OpacNav => C4::Context->preference("OpacNav"),
1304 OpacNavBottom => C4::Context->preference("OpacNavBottom"),
1305 OpacFavicon => C4::Context->preference("OpacFavicon"),
1306 opacreadinghistory => C4::Context->preference("opacreadinghistory"),
1307 opaclanguagesdisplay => C4::Context->preference("opaclanguagesdisplay"),
1308 OPACUserJS => C4::Context->preference("OPACUserJS"),
1309 opacbookbag => "" . C4::Context->preference("opacbookbag"),
1310 OpacCloud => C4::Context->preference("OpacCloud"),
1311 OpacTopissue => C4::Context->preference("OpacTopissue"),
1312 OpacAuthorities => C4::Context->preference("OpacAuthorities"),
1313 OpacBrowser => C4::Context->preference("OpacBrowser"),
1314 TagsEnabled => C4::Context->preference("TagsEnabled"),
1315 OPACUserCSS => C4::Context->preference("OPACUserCSS"),
1316 intranetcolorstylesheet => C4::Context->preference("intranetcolorstylesheet"),
1317 intranetstylesheet => C4::Context->preference("intranetstylesheet"),
1318 intranetbookbag => C4::Context->preference("intranetbookbag"),
1319 IntranetNav => C4::Context->preference("IntranetNav"),
1320 IntranetFavicon => C4::Context->preference("IntranetFavicon"),
1321 IntranetUserCSS => C4::Context->preference("IntranetUserCSS"),
1322 IntranetUserJS => C4::Context->preference("IntranetUserJS"),
1323 IndependentBranches => C4::Context->preference("IndependentBranches"),
1324 AutoLocation => C4::Context->preference("AutoLocation"),
1325 wrongip => $info{'wrongip'},
1326 PatronSelfRegistration => C4::Context->preference("PatronSelfRegistration"),
1327 PatronSelfRegistrationDefaultCategory => C4::Context->preference("PatronSelfRegistrationDefaultCategory"),
1328 opac_css_override => $ENV{'OPAC_CSS_OVERRIDE'},
1329 too_many_login_attempts => ( $patron and $patron->account_locked )
1332 $template->param( SCO_login => 1 ) if ( $query->param('sco_user_login') );
1333 $template->param( SCI_login => 1 ) if ( $query->param('sci_user_login') );
1334 $template->param( OpacPublic => C4::Context->preference("OpacPublic") );
1335 $template->param( loginprompt => 1 ) unless $info{'nopermission'};
1337 if ( $type eq 'opac' ) {
1338 require Koha::Virtualshelves;
1339 my $some_public_shelves = Koha::Virtualshelves->get_some_shelves(
1345 some_public_shelves => $some_public_shelves,
1351 # Is authentication against multiple CAS servers enabled?
1352 if ( C4::Auth_with_cas::multipleAuth && !$casparam ) {
1353 my $casservers = C4::Auth_with_cas::getMultipleAuth();
1355 foreach my $key ( keys %$casservers ) {
1356 push @tmplservers, { name => $key, value => login_cas_url( $query, $key, $type ) . "?cas=$key" };
1359 casServersLoop => \@tmplservers
1363 casServerUrl => login_cas_url($query, undef, $type),
1368 invalidCasLogin => $info{'invalidCasLogin'}
1374 shibbolethAuthentication => $shib,
1375 shibbolethLoginUrl => login_shib_url($query),
1379 if (C4::Context->preference('GoogleOpenIDConnect')) {
1380 if ($query->param("OpenIDConnectFailed")) {
1381 my $reason = $query->param('OpenIDConnectFailed');
1382 $template->param(invalidGoogleOpenIDConnectLogin => $reason);
1387 LibraryName => C4::Context->preference("LibraryName"),
1389 $template->param(%info);
1391 # $cookie = $query->cookie(CGISESSID => $session->id
1393 print $query->header(
1394 { type => 'text/html',
1397 'X-Frame-Options' => 'SAMEORIGIN'
1404 =head2 check_api_auth
1406 ($status, $cookie, $sessionId) = check_api_auth($query, $userflags);
1408 Given a CGI query containing the parameters 'userid' and 'password' and/or a session
1409 cookie, determine if the user has the privileges specified by C<$userflags>.
1411 C<check_api_auth> is is meant for authenticating users of web services, and
1412 consequently will always return and will not attempt to redirect the user
1415 If a valid session cookie is already present, check_api_auth will return a status
1416 of "ok", the cookie, and the Koha session ID.
1418 If no session cookie is present, check_api_auth will check the 'userid' and 'password
1419 parameters and create a session cookie and Koha session if the supplied credentials
1422 Possible return values in C<$status> are:
1426 =item "ok" -- user authenticated; C<$cookie> and C<$sessionid> have valid values.
1428 =item "failed" -- credentials are not correct; C<$cookie> and C<$sessionid> are undef
1430 =item "maintenance" -- DB is in maintenance mode; no login possible at the moment
1432 =item "expired -- session cookie has expired; API user should resubmit userid and password
1438 sub check_api_auth {
1441 my $flagsrequired = shift;
1442 my $dbh = C4::Context->dbh;
1443 my $timeout = _timeout_syspref();
1445 unless ( C4::Context->preference('Version') ) {
1447 # database has not been installed yet
1448 return ( "maintenance", undef, undef );
1450 my $kohaversion = Koha::version();
1451 $kohaversion =~ s/(.*\..*)\.(.*)\.(.*)/$1$2$3/;
1452 if ( C4::Context->preference('Version') < $kohaversion ) {
1454 # database in need of version update; assume that
1455 # no API should be called while databsae is in
1457 return ( "maintenance", undef, undef );
1460 # FIXME -- most of what follows is a copy-and-paste
1461 # of code from checkauth. There is an obvious need
1462 # for refactoring to separate the various parts of
1463 # the authentication code, but as of 2007-11-19 this
1464 # is deferred so as to not introduce bugs into the
1465 # regular authentication code for Koha 3.0.
1467 # see if we have a valid session cookie already
1468 # however, if a userid parameter is present (i.e., from
1469 # a form submission, assume that any current cookie
1471 my $sessionID = undef;
1472 unless ( $query->param('userid') ) {
1473 $sessionID = $query->cookie("CGISESSID");
1475 if ( $sessionID && not( $cas && $query->param('PT') ) ) {
1476 my $session = get_session($sessionID);
1477 C4::Context->_new_userenv($sessionID);
1479 C4::Context->interface($session->param('interface'));
1480 C4::Context->set_userenv(
1481 $session->param('number'), $session->param('id'),
1482 $session->param('cardnumber'), $session->param('firstname'),
1483 $session->param('surname'), $session->param('branch'),
1484 $session->param('branchname'), $session->param('flags'),
1485 $session->param('emailaddress')
1488 my $ip = $session->param('ip');
1489 my $lasttime = $session->param('lasttime');
1490 my $userid = $session->param('id');
1491 if ( $lasttime < time() - $timeout ) {
1496 C4::Context->_unset_userenv($sessionID);
1499 return ( "expired", undef, undef );
1500 } elsif ( C4::Context->preference('SessionRestrictionByIP') && $ip ne $ENV{'REMOTE_ADDR'} ) {
1502 # IP address changed
1505 C4::Context->_unset_userenv($sessionID);
1508 return ( "expired", undef, undef );
1510 my $cookie = $query->cookie(
1511 -name => 'CGISESSID',
1512 -value => $session->id,
1514 -secure => ( C4::Context->https_enabled() ? 1 : 0 ),
1516 $session->param( 'lasttime', time() );
1517 my $flags = haspermission( $userid, $flagsrequired );
1519 return ( "ok", $cookie, $sessionID );
1523 C4::Context->_unset_userenv($sessionID);
1526 return ( "failed", undef, undef );
1530 return ( "expired", undef, undef );
1535 my $userid = $query->param('userid');
1536 my $password = $query->param('password');
1537 my ( $return, $cardnumber, $cas_ticket );
1540 if ( $cas && $query->param('PT') ) {
1542 $debug and print STDERR "## check_api_auth - checking CAS\n";
1544 # In case of a CAS authentication, we use the ticket instead of the password
1545 my $PT = $query->param('PT');
1546 ( $return, $cardnumber, $userid, $cas_ticket ) = check_api_auth_cas( $dbh, $PT, $query ); # EXTERNAL AUTH
1549 # User / password auth
1550 unless ( $userid and $password ) {
1552 # caller did something wrong, fail the authenticateion
1553 return ( "failed", undef, undef );
1556 ( $return, $cardnumber, $newuserid, $cas_ticket ) = checkpw( $dbh, $userid, $password, $query );
1559 if ( $return and haspermission( $userid, $flagsrequired ) ) {
1560 my $session = get_session("");
1561 return ( "failed", undef, undef ) unless $session;
1563 my $sessionID = $session->id;
1564 C4::Context->_new_userenv($sessionID);
1565 my $cookie = $query->cookie(
1566 -name => 'CGISESSID',
1567 -value => $sessionID,
1569 -secure => ( C4::Context->https_enabled() ? 1 : 0 ),
1571 if ( $return == 1 ) {
1573 $borrowernumber, $firstname, $surname,
1574 $userflags, $branchcode, $branchname,
1579 "select borrowernumber, firstname, surname, flags, borrowers.branchcode, branches.branchname as branchname, email from borrowers left join branches on borrowers.branchcode=branches.branchcode where userid=?"
1581 $sth->execute($userid);
1583 $borrowernumber, $firstname, $surname,
1584 $userflags, $branchcode, $branchname,
1586 ) = $sth->fetchrow if ( $sth->rows );
1588 unless ( $sth->rows ) {
1589 my $sth = $dbh->prepare(
1590 "select borrowernumber, firstname, surname, flags, borrowers.branchcode, branches.branchname as branchname, email from borrowers left join branches on borrowers.branchcode=branches.branchcode where cardnumber=?"
1592 $sth->execute($cardnumber);
1594 $borrowernumber, $firstname, $surname,
1595 $userflags, $branchcode, $branchname,
1597 ) = $sth->fetchrow if ( $sth->rows );
1599 unless ( $sth->rows ) {
1600 $sth->execute($userid);
1602 $borrowernumber, $firstname, $surname, $userflags,
1603 $branchcode, $branchname, $emailaddress
1604 ) = $sth->fetchrow if ( $sth->rows );
1608 my $ip = $ENV{'REMOTE_ADDR'};
1610 # if they specify at login, use that
1611 if ( $query->param('branch') ) {
1612 $branchcode = $query->param('branch');
1613 my $library = Koha::Libraries->find($branchcode);
1614 $branchname = $library? $library->branchname: '';
1616 my $branches = { map { $_->branchcode => $_->unblessed } Koha::Libraries->search };
1617 foreach my $br ( keys %$branches ) {
1619 # now we work with the treatment of ip
1620 my $domain = $branches->{$br}->{'branchip'};
1621 if ( $domain && $ip =~ /^$domain/ ) {
1622 $branchcode = $branches->{$br}->{'branchcode'};
1624 # new op dev : add the branchname to the cookie
1625 $branchname = $branches->{$br}->{'branchname'};
1628 $session->param( 'number', $borrowernumber );
1629 $session->param( 'id', $userid );
1630 $session->param( 'cardnumber', $cardnumber );
1631 $session->param( 'firstname', $firstname );
1632 $session->param( 'surname', $surname );
1633 $session->param( 'branch', $branchcode );
1634 $session->param( 'branchname', $branchname );
1635 $session->param( 'flags', $userflags );
1636 $session->param( 'emailaddress', $emailaddress );
1637 $session->param( 'ip', $session->remote_addr() );
1638 $session->param( 'lasttime', time() );
1639 $session->param( 'interface', 'api' );
1641 $session->param( 'cas_ticket', $cas_ticket);
1642 C4::Context->set_userenv(
1643 $session->param('number'), $session->param('id'),
1644 $session->param('cardnumber'), $session->param('firstname'),
1645 $session->param('surname'), $session->param('branch'),
1646 $session->param('branchname'), $session->param('flags'),
1647 $session->param('emailaddress')
1649 return ( "ok", $cookie, $sessionID );
1651 return ( "failed", undef, undef );
1656 =head2 check_cookie_auth
1658 ($status, $sessionId) = check_api_auth($cookie, $userflags);
1660 Given a CGISESSID cookie set during a previous login to Koha, determine
1661 if the user has the privileges specified by C<$userflags>. C<$userflags>
1662 is passed unaltered into C<haspermission> and as such accepts all options
1663 avaiable to that routine with the one caveat that C<check_api_auth> will
1664 also allow 'undef' to be passed and in such a case the permissions check
1665 will be skipped altogether.
1667 C<check_cookie_auth> is meant for authenticating special services
1668 such as tools/upload-file.pl that are invoked by other pages that
1669 have been authenticated in the usual way.
1671 Possible return values in C<$status> are:
1675 =item "ok" -- user authenticated; C<$sessionID> have valid values.
1677 =item "failed" -- credentials are not correct; C<$sessionid> are undef
1679 =item "maintenance" -- DB is in maintenance mode; no login possible at the moment
1681 =item "expired -- session cookie has expired; API user should resubmit userid and password
1687 sub check_cookie_auth {
1689 my $flagsrequired = shift;
1692 my $remote_addr = $params->{remote_addr} || $ENV{REMOTE_ADDR};
1693 my $dbh = C4::Context->dbh;
1694 my $timeout = _timeout_syspref();
1696 unless ( C4::Context->preference('Version') ) {
1698 # database has not been installed yet
1699 return ( "maintenance", undef );
1701 my $kohaversion = Koha::version();
1702 $kohaversion =~ s/(.*\..*)\.(.*)\.(.*)/$1$2$3/;
1703 if ( C4::Context->preference('Version') < $kohaversion ) {
1705 # database in need of version update; assume that
1706 # no API should be called while databsae is in
1708 return ( "maintenance", undef );
1711 # FIXME -- most of what follows is a copy-and-paste
1712 # of code from checkauth. There is an obvious need
1713 # for refactoring to separate the various parts of
1714 # the authentication code, but as of 2007-11-23 this
1715 # is deferred so as to not introduce bugs into the
1716 # regular authentication code for Koha 3.0.
1718 # see if we have a valid session cookie already
1719 # however, if a userid parameter is present (i.e., from
1720 # a form submission, assume that any current cookie
1722 unless ( defined $cookie and $cookie ) {
1723 return ( "failed", undef );
1725 my $sessionID = $cookie;
1726 my $session = get_session($sessionID);
1727 C4::Context->_new_userenv($sessionID);
1729 C4::Context->interface($session->param('interface'));
1730 C4::Context->set_userenv(
1731 $session->param('number'), $session->param('id'),
1732 $session->param('cardnumber'), $session->param('firstname'),
1733 $session->param('surname'), $session->param('branch'),
1734 $session->param('branchname'), $session->param('flags'),
1735 $session->param('emailaddress')
1738 my $ip = $session->param('ip');
1739 my $lasttime = $session->param('lasttime');
1740 my $userid = $session->param('id');
1741 if ( $lasttime < time() - $timeout ) {
1746 C4::Context->_unset_userenv($sessionID);
1749 return ("expired", undef);
1750 } elsif ( C4::Context->preference('SessionRestrictionByIP') && $ip ne $remote_addr ) {
1752 # IP address changed
1755 C4::Context->_unset_userenv($sessionID);
1758 return ( "expired", undef );
1760 $session->param( 'lasttime', time() );
1761 my $flags = defined($flagsrequired) ? haspermission( $userid, $flagsrequired ) : 1;
1763 return ( "ok", $sessionID );
1767 C4::Context->_unset_userenv($sessionID);
1770 return ( "failed", undef );
1774 return ( "expired", undef );
1781 my $session = get_session($sessionID);
1783 Given a session ID, retrieve the CGI::Session object used to store
1784 the session's state. The session object can be used to store
1785 data that needs to be accessed by different scripts during a
1788 If the C<$sessionID> parameter is an empty string, a new session
1793 sub _get_session_params {
1794 my $storage_method = C4::Context->preference('SessionStorage');
1795 if ( $storage_method eq 'mysql' ) {
1796 my $dbh = C4::Context->dbh;
1797 return { dsn => "driver:MySQL;serializer:yaml;id:md5", dsn_args => { Handle => $dbh } };
1799 elsif ( $storage_method eq 'Pg' ) {
1800 my $dbh = C4::Context->dbh;
1801 return { dsn => "driver:PostgreSQL;serializer:yaml;id:md5", dsn_args => { Handle => $dbh } };
1803 elsif ( $storage_method eq 'memcached' && Koha::Caches->get_instance->memcached_cache ) {
1804 my $memcached = Koha::Caches->get_instance()->memcached_cache;
1805 return { dsn => "driver:memcached;serializer:yaml;id:md5", dsn_args => { Memcached => $memcached } };
1808 # catch all defaults to tmp should work on all systems
1809 my $dir = C4::Context::temporary_directory;
1810 my $instance = C4::Context->config( 'database' ); #actually for packages not exactly the instance name, but generally safer to leave it as it is
1811 return { dsn => "driver:File;serializer:yaml;id:md5", dsn_args => { Directory => "$dir/cgisess_$instance" } };
1816 my $sessionID = shift;
1817 my $params = _get_session_params();
1818 return new CGI::Session( $params->{dsn}, $sessionID, $params->{dsn_args} );
1822 # FIXME no_set_userenv may be replaced with force_branchcode_for_userenv
1823 # (or something similar)
1824 # Currently it's only passed from C4::SIP::ILS::Patron::check_password, but
1825 # not having a userenv defined could cause a crash.
1827 my ( $dbh, $userid, $password, $query, $type, $no_set_userenv ) = @_;
1828 $type = 'opac' unless $type;
1830 # Get shibboleth login attribute
1831 my $shib = C4::Context->config('useshibboleth') && shib_ok();
1832 my $shib_login = $shib ? get_login_shib() : undef;
1836 if ( defined $userid ){
1837 $patron = Koha::Patrons->find({ userid => $userid });
1838 $patron = Koha::Patrons->find({ cardnumber => $userid }) unless $patron;
1840 my $check_internal_as_fallback = 0;
1842 # Note: checkpw_* routines returns:
1845 # -1 if user bind failed (LDAP only)
1847 if ( $patron and $patron->account_locked ) {
1848 # Nothing to check, account is locked
1849 } elsif ($ldap && defined($password)) {
1850 $debug and print STDERR "## checkpw - checking LDAP\n";
1851 my ( $retval, $retcard, $retuserid ) = checkpw_ldap(@_); # EXTERNAL AUTH
1852 if ( $retval == 1 ) {
1853 @return = ( $retval, $retcard, $retuserid );
1856 $check_internal_as_fallback = 1 if $retval == 0;
1858 } elsif ( $cas && $query && $query->param('ticket') ) {
1859 $debug and print STDERR "## checkpw - checking CAS\n";
1861 # In case of a CAS authentication, we use the ticket instead of the password
1862 my $ticket = $query->param('ticket');
1863 $query->delete('ticket'); # remove ticket to come back to original URL
1864 my ( $retval, $retcard, $retuserid, $cas_ticket ) = checkpw_cas( $dbh, $ticket, $query, $type ); # EXTERNAL AUTH
1866 @return = ( $retval, $retcard, $retuserid, $cas_ticket );
1870 $passwd_ok = $retval;
1873 # If we are in a shibboleth session (shibboleth is enabled, and a shibboleth match attribute is present)
1874 # Check for password to asertain whether we want to be testing against shibboleth or another method this
1876 elsif ( $shib && $shib_login && !$password ) {
1878 $debug and print STDERR "## checkpw - checking Shibboleth\n";
1880 # In case of a Shibboleth authentication, we expect a shibboleth user attribute
1881 # (defined under shibboleth mapping in koha-conf.xml) to contain the login of the
1882 # shibboleth-authenticated user
1884 # Then, we check if it matches a valid koha user
1886 my ( $retval, $retcard, $retuserid ) = C4::Auth_with_shibboleth::checkpw_shib($shib_login); # EXTERNAL AUTH
1888 @return = ( $retval, $retcard, $retuserid );
1890 $passwd_ok = $retval;
1893 $check_internal_as_fallback = 1;
1897 if ( $check_internal_as_fallback ) {
1898 @return = checkpw_internal( $dbh, $userid, $password, $no_set_userenv);
1899 $passwd_ok = 1 if $return[0] > 0; # 1 or 2
1904 $patron->update({ login_attempts => 0 });
1905 } elsif( !$patron->account_locked ) {
1906 $patron->update({ login_attempts => $patron->login_attempts + 1 });
1910 # Optionally log success or failure
1911 if( $patron && $passwd_ok && C4::Context->preference('AuthSuccessLog') ) {
1912 logaction( 'AUTH', 'SUCCESS', $patron->id, "Valid password for $userid", $type );
1913 } elsif( !$passwd_ok && C4::Context->preference('AuthFailureLog') ) {
1914 logaction( 'AUTH', 'FAILURE', $patron ? $patron->id : 0, "Wrong password for $userid", $type );
1920 sub checkpw_internal {
1921 my ( $dbh, $userid, $password, $no_set_userenv ) = @_;
1923 $password = Encode::encode( 'UTF-8', $password )
1924 if Encode::is_utf8($password);
1928 "select password,cardnumber,borrowernumber,userid,firstname,surname,borrowers.branchcode,branches.branchname,flags from borrowers join branches on borrowers.branchcode=branches.branchcode where userid=?"
1930 $sth->execute($userid);
1932 my ( $stored_hash, $cardnumber, $borrowernumber, $userid, $firstname,
1933 $surname, $branchcode, $branchname, $flags )
1936 if ( checkpw_hash( $password, $stored_hash ) ) {
1938 C4::Context->set_userenv( "$borrowernumber", $userid, $cardnumber,
1939 $firstname, $surname, $branchcode, $branchname, $flags ) unless $no_set_userenv;
1940 return 1, $cardnumber, $userid;
1945 "select password,cardnumber,borrowernumber,userid,firstname,surname,borrowers.branchcode,branches.branchname,flags from borrowers join branches on borrowers.branchcode=branches.branchcode where cardnumber=?"
1947 $sth->execute($userid);
1949 my ( $stored_hash, $cardnumber, $borrowernumber, $userid, $firstname,
1950 $surname, $branchcode, $branchname, $flags )
1953 if ( checkpw_hash( $password, $stored_hash ) ) {
1955 C4::Context->set_userenv( $borrowernumber, $userid, $cardnumber,
1956 $firstname, $surname, $branchcode, $branchname, $flags ) unless $no_set_userenv;
1957 return 1, $cardnumber, $userid;
1964 my ( $password, $stored_hash ) = @_;
1966 return if $stored_hash eq '!';
1968 # check what encryption algorithm was implemented: Bcrypt - if the hash starts with '$2' it is Bcrypt else md5
1970 if ( substr( $stored_hash, 0, 2 ) eq '$2' ) {
1971 $hash = hash_password( $password, $stored_hash );
1973 $hash = md5_base64($password);
1975 return $hash eq $stored_hash;
1980 my $authflags = getuserflags($flags, $userid, [$dbh]);
1982 Translates integer flags into permissions strings hash.
1984 C<$flags> is the integer userflags value ( borrowers.userflags )
1985 C<$userid> is the members.userid, used for building subpermissions
1986 C<$authflags> is a hashref of permissions
1993 my $dbh = @_ ? shift : C4::Context->dbh;
1996 # I don't want to do this, but if someone logs in as the database
1997 # user, it would be preferable not to spam them to death with
1998 # numeric warnings. So, we make $flags numeric.
1999 no warnings 'numeric';
2002 my $sth = $dbh->prepare("SELECT bit, flag, defaulton FROM userflags");
2005 while ( my ( $bit, $flag, $defaulton ) = $sth->fetchrow ) {
2006 if ( ( $flags & ( 2**$bit ) ) || $defaulton ) {
2007 $userflags->{$flag} = 1;
2010 $userflags->{$flag} = 0;
2014 # get subpermissions and merge with top-level permissions
2015 my $user_subperms = get_user_subpermissions($userid);
2016 foreach my $module ( keys %$user_subperms ) {
2017 next if $userflags->{$module} == 1; # user already has permission for everything in this module
2018 $userflags->{$module} = $user_subperms->{$module};
2024 =head2 get_user_subpermissions
2026 $user_perm_hashref = get_user_subpermissions($userid);
2028 Given the userid (note, not the borrowernumber) of a staff user,
2029 return a hashref of hashrefs of the specific subpermissions
2030 accorded to the user. An example return is
2034 export_catalog => 1,
2035 import_patrons => 1,
2039 The top-level hash-key is a module or function code from
2040 userflags.flag, while the second-level key is a code
2043 The results of this function do not give a complete picture
2044 of the functions that a staff user can access; it is also
2045 necessary to check borrowers.flags.
2049 sub get_user_subpermissions {
2052 my $dbh = C4::Context->dbh;
2053 my $sth = $dbh->prepare( "SELECT flag, user_permissions.code
2054 FROM user_permissions
2055 JOIN permissions USING (module_bit, code)
2056 JOIN userflags ON (module_bit = bit)
2057 JOIN borrowers USING (borrowernumber)
2058 WHERE userid = ?" );
2059 $sth->execute($userid);
2061 my $user_perms = {};
2062 while ( my $perm = $sth->fetchrow_hashref ) {
2063 $user_perms->{ $perm->{'flag'} }->{ $perm->{'code'} } = 1;
2068 =head2 get_all_subpermissions
2070 my $perm_hashref = get_all_subpermissions();
2072 Returns a hashref of hashrefs defining all specific
2073 permissions currently defined. The return value
2074 has the same structure as that of C<get_user_subpermissions>,
2075 except that the innermost hash value is the description
2076 of the subpermission.
2080 sub get_all_subpermissions {
2081 my $dbh = C4::Context->dbh;
2082 my $sth = $dbh->prepare( "SELECT flag, code
2084 JOIN userflags ON (module_bit = bit)" );
2088 while ( my $perm = $sth->fetchrow_hashref ) {
2089 $all_perms->{ $perm->{'flag'} }->{ $perm->{'code'} } = 1;
2094 =head2 haspermission
2096 $flagsrequired = '*'; # Any permission at all
2097 $flagsrequired = 'a_flag'; # a_flag must be satisfied (all subpermissions)
2098 $flagsrequired = [ 'a_flag', 'b_flag' ]; # a_flag OR b_flag must be satisfied
2099 $flagsrequired = { 'a_flag => 1, 'b_flag' => 1 }; # a_flag AND b_flag must be satisfied
2100 $flagsrequired = { 'a_flag' => 'sub_a' }; # sub_a of a_flag must be satisfied
2101 $flagsrequired = { 'a_flag' => [ 'sub_a, 'sub_b' ] }; # sub_a OR sub_b of a_flag must be satisfied
2103 $flags = ($userid, $flagsrequired);
2105 C<$userid> the userid of the member
2106 C<$flags> is a query structure similar to that used by SQL::Abstract that
2107 denotes the combination of flags required. It is a required parameter.
2109 The main logic of this method is that things in arrays are OR'ed, and things
2110 in hashes are AND'ed. The `*` character can be used, at any depth, to denote `ANY`
2112 Returns member's flags or 0 if a permission is not met.
2117 my ($required, $flags) = @_;
2119 my $ref = ref($required);
2121 if ($required eq '*') {
2122 return 0 unless ( $flags or ref( $flags ) );
2124 return 0 unless ( $flags and (!ref( $flags ) || $flags->{$required} ));
2126 } elsif ($ref eq 'HASH') {
2127 foreach my $key (keys %{$required}) {
2128 next if $flags == 1;
2129 my $require = $required->{$key};
2130 my $rflags = $flags->{$key};
2131 return 0 unless _dispatch($require, $rflags);
2133 } elsif ($ref eq 'ARRAY') {
2135 foreach my $require ( @{$required} ) {
2137 ( ref($flags) && !ref($require) && ( $require ne '*' ) )
2138 ? $flags->{$require}
2140 $satisfied++ if _dispatch( $require, $rflags );
2142 return 0 unless $satisfied;
2144 croak "Unexpected structure found: $ref";
2151 my ( $userid, $flagsrequired ) = @_;
2153 #Koha::Exceptions::WrongParameter->throw('$flagsrequired should not be undef')
2154 # unless defined($flagsrequired);
2156 my $sth = C4::Context->dbh->prepare("SELECT flags FROM borrowers WHERE userid=?");
2157 $sth->execute($userid);
2158 my $row = $sth->fetchrow();
2159 my $flags = getuserflags( $row, $userid );
2161 return $flags unless defined($flagsrequired);
2162 return $flags if $flags->{superlibrarian};
2163 return _dispatch($flagsrequired, $flags);
2165 #FIXME - This fcn should return the failed permission so a suitable error msg can be delivered.
2170 $flags = ($iprange);
2172 C<$iprange> A space separated string describing an IP range. Can include single IPs or ranges
2174 Returns 1 if the remote address is in the provided iprange, or 0 otherwise.
2181 my @allowedipranges = $iprange ? split(' ', $iprange) : ();
2182 if (scalar @allowedipranges > 0) {
2184 eval { @rangelist = Net::CIDR::range2cidr(@allowedipranges); }; return 0 if $@;
2185 eval { $result = Net::CIDR::cidrlookup($ENV{'REMOTE_ADDR'}, @rangelist) } || ( $ENV{DEBUG} && warn 'cidrlookup failed for ' . join(' ',@rangelist) );
2187 return $result ? 1 : 0;
2190 sub getborrowernumber {
2192 my $userenv = C4::Context->userenv;
2193 if ( defined($userenv) && ref($userenv) eq 'HASH' && $userenv->{number} ) {
2194 return $userenv->{number};
2196 my $dbh = C4::Context->dbh;
2197 for my $field ( 'userid', 'cardnumber' ) {
2199 $dbh->prepare("select borrowernumber from borrowers where $field=?");
2200 $sth->execute($userid);
2202 my ($bnumber) = $sth->fetchrow;
2209 =head2 track_login_daily
2211 track_login_daily( $userid );
2213 Wraps the call to $patron->track_login, the method used to update borrowers.lastseen. We only call track_login once a day.
2217 sub track_login_daily {
2219 return if !$userid || !C4::Context->preference('TrackLastPatronActivity');
2221 my $cache = Koha::Caches->get_instance();
2222 my $cache_key = "track_login_" . $userid;
2223 my $cached = $cache->get_from_cache($cache_key);
2224 my $today = dt_from_string()->ymd;
2225 return if $cached && $cached eq $today;
2227 my $patron = Koha::Patrons->find({ userid => $userid });
2228 return unless $patron;
2229 $patron->track_login;
2230 $cache->set_in_cache( $cache_key, $today );
2233 END { } # module clean-up code here (global destructor)
2243 Crypt::Eksblowfish::Bcrypt(3)