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;
43 use Koha::Patron::Consents;
44 use POSIX qw/strftime/;
45 use List::MoreUtils qw/ any /;
46 use Encode qw( encode is_utf8);
47 use C4::Auth_with_shibboleth;
49 use C4::Log qw/logaction/;
52 use vars qw(@ISA @EXPORT @EXPORT_OK %EXPORT_TAGS $debug $ldap $cas $caslogout);
55 sub psgi_env { any { /^psgi\./ } keys %ENV }
58 if (psgi_env) { die 'psgi:exit' }
62 C4::Context->set_remote_address;
66 @EXPORT = qw(&checkauth &get_template_and_user &haspermission &get_user_subpermissions);
67 @EXPORT_OK = qw(&check_api_auth &get_session &check_cookie_auth &checkpw &checkpw_internal &checkpw_hash
68 &get_all_subpermissions &get_user_subpermissions track_login_daily &in_iprange
70 %EXPORT_TAGS = ( EditPermissions => [qw(get_all_subpermissions get_user_subpermissions)] );
71 $ldap = C4::Context->config('useldapserver') || 0;
72 $cas = C4::Context->preference('casAuthentication');
73 $caslogout = C4::Context->preference('casLogout');
74 require C4::Auth_with_cas; # no import
77 require C4::Auth_with_ldap;
78 import C4::Auth_with_ldap qw(checkpw_ldap);
81 import C4::Auth_with_cas qw(check_api_auth_cas checkpw_cas login_cas logout_cas login_cas_url logout_if_required);
88 C4::Auth - Authenticates Koha users
98 my ($template, $borrowernumber, $cookie)
99 = get_template_and_user(
101 template_name => "opac-main.tt",
104 authnotrequired => 0,
105 flagsrequired => { catalogue => '*', tools => 'import_patrons' },
109 output_html_with_http_headers $query, $cookie, $template->output;
113 The main function of this module is to provide
114 authentification. However the get_template_and_user function has
115 been provided so that a users login information is passed along
116 automatically. This gets loaded into the template.
120 =head2 get_template_and_user
122 my ($template, $borrowernumber, $cookie)
123 = get_template_and_user(
125 template_name => "opac-main.tt",
128 authnotrequired => 0,
129 flagsrequired => { catalogue => '*', tools => 'import_patrons' },
133 This call passes the C<query>, C<flagsrequired> and C<authnotrequired>
134 to C<&checkauth> (in this module) to perform authentification.
135 See C<&checkauth> for an explanation of these parameters.
137 The C<template_name> is then used to find the correct template for
138 the page. The authenticated users details are loaded onto the
139 template in the logged_in_user variable (which is a Koha::Patron object). Also the
140 C<sessionID> is passed to the template. This can be used in templates
141 if cookies are disabled. It needs to be put as and input to every
144 More information on the C<gettemplate> sub can be found in the
149 sub get_template_and_user {
152 my ( $user, $cookie, $sessionID, $flags );
154 # Get shibboleth login attribute
155 my $shib = C4::Context->config('useshibboleth') && shib_ok();
156 my $shib_login = $shib ? get_login_shib() : undef;
158 C4::Context->interface( $in->{type} );
160 $in->{'authnotrequired'} ||= 0;
162 # the following call includes a bad template check; might croak
163 my $template = C4::Templates::gettemplate(
164 $in->{'template_name'},
169 if ( $in->{'template_name'} !~ m/maintenance/ ) {
170 ( $user, $cookie, $sessionID, $flags ) = checkauth(
172 $in->{'authnotrequired'},
173 $in->{'flagsrequired'},
176 $in->{template_name},
180 # If we enforce GDPR and the user did not consent, redirect
181 # Exceptions for consent page itself and SCI/SCO system
182 if( $in->{type} eq 'opac' && $user &&
183 $in->{'template_name'} !~ /^(opac-patron-consent|sc[io]\/)/ &&
184 C4::Context->preference('GDPR_Policy') eq 'Enforced' )
186 my $consent = Koha::Patron::Consents->search({
187 borrowernumber => getborrowernumber($user),
188 type => 'GDPR_PROCESSING',
189 given_on => { '!=', undef },
192 print $in->{query}->redirect(-uri => '/cgi-bin/koha/opac-patron-consent.pl', -cookie => $cookie);
197 if ( $in->{type} eq 'opac' && $user ) {
201 # If the user logged in is the SCO user and they try to go out of the SCO module,
202 # log the user out removing the CGISESSID cookie
203 $in->{template_name} !~ m|sco/| && $in->{template_name} !~ m|errors/errorpage.tt|
204 && C4::Context->preference('AutoSelfCheckID')
205 && $user eq C4::Context->preference('AutoSelfCheckID')
211 # If the user logged in is the SCI user and they try to go out of the SCI module,
212 # kick them out unless it is SCO with a valid permission
213 # or they are a superlibrarian
214 $in->{template_name} !~ m|sci/|
215 && haspermission( $user, { self_check => 'self_checkin_module' } )
217 $in->{template_name} =~ m|sco/| && haspermission(
218 $user, { self_check => 'self_checkout_module' }
221 && $flags && $flags->{superlibrarian} != 1
228 $template = C4::Templates::gettemplate( 'opac-auth.tt', 'opac',
230 $cookie = $in->{query}->cookie(
231 -name => 'CGISESSID',
235 -secure => ( C4::Context->https_enabled() ? 1 : 0 ),
240 script_name => get_script_name(),
243 print $in->{query}->header(
248 'X-Frame-Options' => 'SAMEORIGIN'
259 # It's possible for $user to be the borrowernumber if they don't have a
260 # userid defined (and are logging in through some other method, such
261 # as SSL certs against an email address)
263 $borrowernumber = getborrowernumber($user) if defined($user);
264 if ( !defined($borrowernumber) && defined($user) ) {
265 $patron = Koha::Patrons->find( $user );
267 $borrowernumber = $user;
269 # A bit of a hack, but I don't know there's a nicer way
271 $user = $patron->firstname . ' ' . $patron->surname;
274 $patron = Koha::Patrons->find( $borrowernumber );
275 # FIXME What to do if $patron does not exist?
279 $template->param( loggedinusername => $user ); # OBSOLETE - Do not reuse this in template, use logged_in_user.userid instead
280 $template->param( loggedinusernumber => $borrowernumber ); # FIXME Should be replaced with logged_in_user.borrowernumber
281 $template->param( logged_in_user => $patron );
282 $template->param( sessionID => $sessionID );
284 if ( $in->{'type'} eq 'opac' ) {
285 require Koha::Virtualshelves;
286 my $some_private_shelves = Koha::Virtualshelves->get_some_shelves(
288 borrowernumber => $borrowernumber,
292 my $some_public_shelves = Koha::Virtualshelves->get_some_shelves(
298 some_private_shelves => $some_private_shelves,
299 some_public_shelves => $some_public_shelves,
303 my $all_perms = get_all_subpermissions();
305 my @flagroots = qw(circulate catalogue parameters borrowers permissions reserveforothers borrow
306 editcatalogue updatecharges tools editauthorities serials reports acquisition clubs problem_reports);
308 # We are going to use the $flags returned by checkauth
309 # to create the template's parameters that will indicate
310 # which menus the user can access.
311 if ( $flags && $flags->{superlibrarian} == 1 ) {
312 $template->param( CAN_user_circulate => 1 );
313 $template->param( CAN_user_catalogue => 1 );
314 $template->param( CAN_user_parameters => 1 );
315 $template->param( CAN_user_borrowers => 1 );
316 $template->param( CAN_user_permissions => 1 );
317 $template->param( CAN_user_reserveforothers => 1 );
318 $template->param( CAN_user_editcatalogue => 1 );
319 $template->param( CAN_user_updatecharges => 1 );
320 $template->param( CAN_user_acquisition => 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_plugins => 1 );
327 $template->param( CAN_user_coursereserves => 1 );
328 $template->param( CAN_user_clubs => 1 );
329 $template->param( CAN_user_ill => 1 );
330 $template->param( CAN_user_stockrotation => 1 );
331 $template->param( CAN_user_problem_reports => 1 );
333 foreach my $module ( keys %$all_perms ) {
334 foreach my $subperm ( keys %{ $all_perms->{$module} } ) {
335 $template->param( "CAN_user_${module}_${subperm}" => 1 );
341 foreach my $module ( keys %$all_perms ) {
342 if ( defined($flags->{$module}) && $flags->{$module} == 1 ) {
343 foreach my $subperm ( keys %{ $all_perms->{$module} } ) {
344 $template->param( "CAN_user_${module}_${subperm}" => 1 );
346 } elsif ( ref( $flags->{$module} ) ) {
347 foreach my $subperm ( keys %{ $flags->{$module} } ) {
348 $template->param( "CAN_user_${module}_${subperm}" => 1 );
355 foreach my $module ( keys %$flags ) {
356 if ( $flags->{$module} == 1 or ref( $flags->{$module} ) ) {
357 $template->param( "CAN_user_$module" => 1 );
362 # Logged-in opac search history
363 # If the requested template is an opac one and opac search history is enabled
364 if ( $in->{type} eq 'opac' && C4::Context->preference('EnableOpacSearchHistory') ) {
365 my $dbh = C4::Context->dbh;
366 my $query = "SELECT COUNT(*) FROM search_history WHERE userid=?";
367 my $sth = $dbh->prepare($query);
368 $sth->execute($borrowernumber);
370 # If at least one search has already been performed
371 if ( $sth->fetchrow_array > 0 ) {
373 # We show the link in opac
374 $template->param( EnableOpacSearchHistory => 1 );
376 if (C4::Context->preference('LoadSearchHistoryToTheFirstLoggedUser'))
378 # And if there are searches performed when the user was not logged in,
379 # we add them to the logged-in search history
380 my @recentSearches = C4::Search::History::get_from_session( { cgi => $in->{'query'} } );
381 if (@recentSearches) {
382 my $dbh = C4::Context->dbh;
384 INSERT INTO search_history(userid, sessionid, query_desc, query_cgi, type, total, time )
385 VALUES (?, ?, ?, ?, ?, ?, ?)
387 my $sth = $dbh->prepare($query);
388 $sth->execute( $borrowernumber,
389 $in->{query}->cookie("CGISESSID"),
392 $_->{type} || 'biblio',
395 ) foreach @recentSearches;
397 # clear out the search history from the session now that
398 # we've saved it to the database
401 C4::Search::History::set_to_session( { cgi => $in->{'query'}, search_history => [] } );
403 } elsif ( $in->{type} eq 'intranet' and C4::Context->preference('EnableSearchHistory') ) {
404 $template->param( EnableSearchHistory => 1 );
407 else { # if this is an anonymous session, setup to display public lists...
409 # If shibboleth is enabled, and we're in an anonymous session, we should allow
410 # the user to attempt login via shibboleth.
412 $template->param( shibbolethAuthentication => $shib,
413 shibbolethLoginUrl => login_shib_url( $in->{'query'} ),
416 # If shibboleth is enabled and we have a shibboleth login attribute,
417 # but we are in an anonymous session, then we clearly have an invalid
418 # shibboleth koha account.
420 $template->param( invalidShibLogin => '1' );
424 $template->param( sessionID => $sessionID );
426 if ( $in->{'type'} eq 'opac' ){
427 require Koha::Virtualshelves;
428 my $some_public_shelves = Koha::Virtualshelves->get_some_shelves(
434 some_public_shelves => $some_public_shelves,
439 # Anonymous opac search history
440 # If opac search history is enabled and at least one search has already been performed
441 if ( C4::Context->preference('EnableOpacSearchHistory') ) {
442 my @recentSearches = C4::Search::History::get_from_session( { cgi => $in->{'query'} } );
443 if (@recentSearches) {
444 $template->param( EnableOpacSearchHistory => 1 );
448 if ( C4::Context->preference('dateformat') ) {
449 $template->param( dateformat => C4::Context->preference('dateformat') );
452 $template->param(auth_forwarded_hash => scalar $in->{'query'}->param('auth_forwarded_hash'));
454 # these template parameters are set the same regardless of $in->{'type'}
456 my $minPasswordLength = C4::Context->preference('minPasswordLength');
457 $minPasswordLength = 3 if not $minPasswordLength or $minPasswordLength < 3;
459 "BiblioDefaultView" . C4::Context->preference("BiblioDefaultView") => 1,
460 EnhancedMessagingPreferences => C4::Context->preference('EnhancedMessagingPreferences'),
461 GoogleJackets => C4::Context->preference("GoogleJackets"),
462 OpenLibraryCovers => C4::Context->preference("OpenLibraryCovers"),
463 KohaAdminEmailAddress => "" . C4::Context->preference("KohaAdminEmailAddress"),
464 LoginFirstname => ( C4::Context->userenv ? C4::Context->userenv->{"firstname"} : "Bel" ),
465 LoginSurname => C4::Context->userenv ? C4::Context->userenv->{"surname"} : "Inconnu",
466 emailaddress => C4::Context->userenv ? C4::Context->userenv->{"emailaddress"} : undef,
467 TagsEnabled => C4::Context->preference("TagsEnabled"),
468 hide_marc => C4::Context->preference("hide_marc"),
469 item_level_itypes => C4::Context->preference('item-level_itypes'),
470 patronimages => C4::Context->preference("patronimages"),
471 singleBranchMode => ( Koha::Libraries->search->count == 1 ),
472 XSLTDetailsDisplay => C4::Context->preference("XSLTDetailsDisplay"),
473 XSLTResultsDisplay => C4::Context->preference("XSLTResultsDisplay"),
474 noItemTypeImages => C4::Context->preference("noItemTypeImages"),
475 marcflavour => C4::Context->preference("marcflavour"),
476 OPACBaseURL => C4::Context->preference('OPACBaseURL'),
477 minPasswordLength => $minPasswordLength,
479 if ( $in->{'type'} eq "intranet" ) {
481 AmazonCoverImages => C4::Context->preference("AmazonCoverImages"),
482 AutoLocation => C4::Context->preference("AutoLocation"),
483 "BiblioDefaultView" . C4::Context->preference("IntranetBiblioDefaultView") => 1,
484 PatronAutoComplete => C4::Context->preference("PatronAutoComplete"),
485 FRBRizeEditions => C4::Context->preference("FRBRizeEditions"),
486 IndependentBranches => C4::Context->preference("IndependentBranches"),
487 IntranetNav => C4::Context->preference("IntranetNav"),
488 IntranetmainUserblock => C4::Context->preference("IntranetmainUserblock"),
489 LibraryName => C4::Context->preference("LibraryName"),
490 advancedMARCEditor => C4::Context->preference("advancedMARCEditor"),
491 canreservefromotherbranches => C4::Context->preference('canreservefromotherbranches'),
492 intranetcolorstylesheet => C4::Context->preference("intranetcolorstylesheet"),
493 IntranetFavicon => C4::Context->preference("IntranetFavicon"),
494 intranetreadinghistory => C4::Context->preference("intranetreadinghistory"),
495 intranetstylesheet => C4::Context->preference("intranetstylesheet"),
496 IntranetUserCSS => C4::Context->preference("IntranetUserCSS"),
497 IntranetUserJS => C4::Context->preference("IntranetUserJS"),
498 intranetbookbag => C4::Context->preference("intranetbookbag"),
499 suggestion => C4::Context->preference("suggestion"),
500 virtualshelves => C4::Context->preference("virtualshelves"),
501 StaffSerialIssueDisplayCount => C4::Context->preference("StaffSerialIssueDisplayCount"),
502 EasyAnalyticalRecords => C4::Context->preference('EasyAnalyticalRecords'),
503 LocalCoverImages => C4::Context->preference('LocalCoverImages'),
504 OPACLocalCoverImages => C4::Context->preference('OPACLocalCoverImages'),
505 AllowMultipleCovers => C4::Context->preference('AllowMultipleCovers'),
506 EnableBorrowerFiles => C4::Context->preference('EnableBorrowerFiles'),
507 UseCourseReserves => C4::Context->preference("UseCourseReserves"),
508 useDischarge => C4::Context->preference('useDischarge'),
509 pending_checkout_notes => scalar Koha::Checkouts->search({ noteseen => 0 }),
513 warn "template type should be OPAC, here it is=[" . $in->{'type'} . "]" unless ( $in->{'type'} eq 'opac' );
515 #TODO : replace LibraryName syspref with 'system name', and remove this html processing
516 my $LibraryNameTitle = C4::Context->preference("LibraryName");
517 $LibraryNameTitle =~ s/<(?:\/?)(?:br|p)\s*(?:\/?)>/ /sgi;
518 $LibraryNameTitle =~ s/<(?:[^<>'"]|'(?:[^']*)'|"(?:[^"]*)")*>//sg;
520 # clean up the busc param in the session
521 # if the page is not opac-detail and not the "add to list" page
522 # and not the "edit comments" page
523 if ( C4::Context->preference("OpacBrowseResults")
524 && $in->{'template_name'} =~ /opac-(.+)\.(?:tt|tmpl)$/ ) {
526 unless ( $pagename =~ /^(?:MARC|ISBD)?detail$/
527 or $pagename =~ /^addbybiblionumber$/
528 or $pagename =~ /^review$/ ) {
529 my $sessionSearch = get_session( $sessionID || $in->{'query'}->cookie("CGISESSID") );
530 $sessionSearch->clear( ["busc"] ) if ( $sessionSearch->param("busc") );
534 # variables passed from CGI: opac_css_override and opac_search_limits.
535 my $opac_search_limit = $ENV{'OPAC_SEARCH_LIMIT'};
536 my $opac_limit_override = $ENV{'OPAC_LIMIT_OVERRIDE'};
539 ( $opac_limit_override && $opac_search_limit && $opac_search_limit =~ /branch:([\w-]+)/ ) ||
540 ( $in->{'query'}->param('limit') && $in->{'query'}->param('limit') =~ /branch:([\w-]+)/ ) ||
541 ( $in->{'query'}->param('multibranchlimit') && $in->{'query'}->param('multibranchlimit') =~ /multibranchlimit-(\w+)/ )
543 $opac_name = $1; # opac_search_limit is a branch, so we use it.
544 } elsif ( $in->{'query'}->param('multibranchlimit') ) {
545 $opac_name = $in->{'query'}->param('multibranchlimit');
546 } elsif ( C4::Context->preference("SearchMyLibraryFirst") && C4::Context->userenv && C4::Context->userenv->{'branch'} ) {
547 $opac_name = C4::Context->userenv->{'branch'};
550 my @search_groups = Koha::Library::Groups->get_search_groups({ interface => 'opac' });
552 AnonSuggestions => "" . C4::Context->preference("AnonSuggestions"),
553 LibrarySearchGroups => \@search_groups,
554 opac_name => $opac_name,
555 LibraryName => "" . C4::Context->preference("LibraryName"),
556 LibraryNameTitle => "" . $LibraryNameTitle,
557 OPACAmazonCoverImages => C4::Context->preference("OPACAmazonCoverImages"),
558 OPACFRBRizeEditions => C4::Context->preference("OPACFRBRizeEditions"),
559 OpacHighlightedWords => C4::Context->preference("OpacHighlightedWords"),
560 OPACShelfBrowser => "" . C4::Context->preference("OPACShelfBrowser"),
561 OPACURLOpenInNewWindow => "" . C4::Context->preference("OPACURLOpenInNewWindow"),
562 OPACUserCSS => "" . C4::Context->preference("OPACUserCSS"),
563 OpacAuthorities => C4::Context->preference("OpacAuthorities"),
564 opac_css_override => $ENV{'OPAC_CSS_OVERRIDE'},
565 opac_search_limit => $opac_search_limit,
566 opac_limit_override => $opac_limit_override,
567 OpacBrowser => C4::Context->preference("OpacBrowser"),
568 OpacCloud => C4::Context->preference("OpacCloud"),
569 OpacKohaUrl => C4::Context->preference("OpacKohaUrl"),
570 OpacNav => "" . C4::Context->preference("OpacNav"),
571 OpacNavBottom => "" . C4::Context->preference("OpacNavBottom"),
572 OpacPasswordChange => C4::Context->preference("OpacPasswordChange"),
573 OPACPatronDetails => C4::Context->preference("OPACPatronDetails"),
574 OPACPrivacy => C4::Context->preference("OPACPrivacy"),
575 OPACFinesTab => C4::Context->preference("OPACFinesTab"),
576 OpacTopissue => C4::Context->preference("OpacTopissue"),
577 RequestOnOpac => C4::Context->preference("RequestOnOpac"),
578 'Version' => C4::Context->preference('Version'),
579 hidelostitems => C4::Context->preference("hidelostitems"),
580 mylibraryfirst => ( C4::Context->preference("SearchMyLibraryFirst") && C4::Context->userenv ) ? C4::Context->userenv->{'branch'} : '',
581 opacbookbag => "" . C4::Context->preference("opacbookbag"),
582 OpacFavicon => C4::Context->preference("OpacFavicon"),
583 opaclanguagesdisplay => "" . C4::Context->preference("opaclanguagesdisplay"),
584 opacreadinghistory => C4::Context->preference("opacreadinghistory"),
585 OPACUserJS => C4::Context->preference("OPACUserJS"),
586 opacuserlogin => "" . C4::Context->preference("opacuserlogin"),
587 OpenLibrarySearch => C4::Context->preference("OpenLibrarySearch"),
588 ShowReviewer => C4::Context->preference("ShowReviewer"),
589 ShowReviewerPhoto => C4::Context->preference("ShowReviewerPhoto"),
590 suggestion => "" . C4::Context->preference("suggestion"),
591 virtualshelves => "" . C4::Context->preference("virtualshelves"),
592 OPACSerialIssueDisplayCount => C4::Context->preference("OPACSerialIssueDisplayCount"),
593 OPACXSLTDetailsDisplay => C4::Context->preference("OPACXSLTDetailsDisplay"),
594 OPACXSLTResultsDisplay => C4::Context->preference("OPACXSLTResultsDisplay"),
595 SyndeticsClientCode => C4::Context->preference("SyndeticsClientCode"),
596 SyndeticsEnabled => C4::Context->preference("SyndeticsEnabled"),
597 SyndeticsCoverImages => C4::Context->preference("SyndeticsCoverImages"),
598 SyndeticsTOC => C4::Context->preference("SyndeticsTOC"),
599 SyndeticsSummary => C4::Context->preference("SyndeticsSummary"),
600 SyndeticsEditions => C4::Context->preference("SyndeticsEditions"),
601 SyndeticsExcerpt => C4::Context->preference("SyndeticsExcerpt"),
602 SyndeticsReviews => C4::Context->preference("SyndeticsReviews"),
603 SyndeticsAuthorNotes => C4::Context->preference("SyndeticsAuthorNotes"),
604 SyndeticsAwards => C4::Context->preference("SyndeticsAwards"),
605 SyndeticsSeries => C4::Context->preference("SyndeticsSeries"),
606 SyndeticsCoverImageSize => C4::Context->preference("SyndeticsCoverImageSize"),
607 OPACLocalCoverImages => C4::Context->preference("OPACLocalCoverImages"),
608 PatronSelfRegistration => C4::Context->preference("PatronSelfRegistration"),
609 PatronSelfRegistrationDefaultCategory => C4::Context->preference("PatronSelfRegistrationDefaultCategory"),
610 useDischarge => C4::Context->preference('useDischarge'),
613 $template->param( OpacPublic => '1' ) if ( $user || C4::Context->preference("OpacPublic") );
616 # Check if we were asked using parameters to force a specific language
617 if ( defined $in->{'query'}->param('language') ) {
619 # Extract the language, let C4::Languages::getlanguage choose
621 my $language = C4::Languages::getlanguage( $in->{'query'} );
622 my $languagecookie = C4::Templates::getlanguagecookie( $in->{'query'}, $language );
623 if ( ref $cookie eq 'ARRAY' ) {
624 push @{$cookie}, $languagecookie;
626 $cookie = [ $cookie, $languagecookie ];
630 return ( $template, $borrowernumber, $cookie, $flags );
635 ($userid, $cookie, $sessionID) = &checkauth($query, $noauth, $flagsrequired, $type);
637 Verifies that the user is authorized to run this script. If
638 the user is authorized, a (userid, cookie, session-id, flags)
639 quadruple is returned. If the user is not authorized but does
640 not have the required privilege (see $flagsrequired below), it
641 displays an error page and exits. Otherwise, it displays the
642 login page and exits.
644 Note that C<&checkauth> will return if and only if the user
645 is authorized, so it should be called early on, before any
646 unfinished operations (e.g., if you've opened a file, then
647 C<&checkauth> won't close it for you).
649 C<$query> is the CGI object for the script calling C<&checkauth>.
651 The C<$noauth> argument is optional. If it is set, then no
652 authorization is required for the script.
654 C<&checkauth> fetches user and session information from C<$query> and
655 ensures that the user is authorized to run scripts that require
658 The C<$flagsrequired> argument specifies the required privileges
659 the user must have if the username and password are correct.
660 It should be specified as a reference-to-hash; keys in the hash
661 should be the "flags" for the user, as specified in the Members
662 intranet module. Any key specified must correspond to a "flag"
663 in the userflags table. E.g., { circulate => 1 } would specify
664 that the user must have the "circulate" privilege in order to
665 proceed. To make sure that access control is correct, the
666 C<$flagsrequired> parameter must be specified correctly.
668 Koha also has a concept of sub-permissions, also known as
669 granular permissions. This makes the value of each key
670 in the C<flagsrequired> hash take on an additional
675 The user must have access to all subfunctions of the module
676 specified by the hash key.
680 The user must have access to at least one subfunction of the module
681 specified by the hash key.
683 specific permission, e.g., 'export_catalog'
685 The user must have access to the specific subfunction list, which
686 must correspond to a row in the permissions table.
688 The C<$type> argument specifies whether the template should be
689 retrieved from the opac or intranet directory tree. "opac" is
690 assumed if it is not specified; however, if C<$type> is specified,
691 "intranet" is assumed if it is not "opac".
693 If C<$query> does not have a valid session ID associated with it
694 (i.e., the user has not logged in) or if the session has expired,
695 C<&checkauth> presents the user with a login page (from the point of
696 view of the original script, C<&checkauth> does not return). Once the
697 user has authenticated, C<&checkauth> restarts the original script
698 (this time, C<&checkauth> returns).
700 The login page is provided using a HTML::Template, which is set in the
701 systempreferences table or at the top of this file. The variable C<$type>
702 selects which template to use, either the opac or the intranet
703 authentification template.
705 C<&checkauth> returns a user ID, a cookie, and a session ID. The
706 cookie should be sent back to the browser; it verifies that the user
716 # If version syspref is unavailable, it means Koha is being installed,
717 # and so we must redirect to OPAC maintenance page or to the WebInstaller
718 # also, if OpacMaintenance is ON, OPAC should redirect to maintenance
719 if ( C4::Context->preference('OpacMaintenance') && $type eq 'opac' ) {
720 warn "OPAC Install required, redirecting to maintenance";
721 print $query->redirect("/cgi-bin/koha/maintenance.pl");
724 unless ( $version = C4::Context->preference('Version') ) { # assignment, not comparison
725 if ( $type ne 'opac' ) {
726 warn "Install required, redirecting to Installer";
727 print $query->redirect("/cgi-bin/koha/installer/install.pl");
729 warn "OPAC Install required, redirecting to maintenance";
730 print $query->redirect("/cgi-bin/koha/maintenance.pl");
735 # check that database and koha version are the same
736 # there is no DB version, it's a fresh install,
737 # go to web installer
738 # there is a DB version, compare it to the code version
739 my $kohaversion = Koha::version();
741 # remove the 3 last . to have a Perl number
742 $kohaversion =~ s/(.*\..*)\.(.*)\.(.*)/$1$2$3/;
743 $debug and print STDERR "kohaversion : $kohaversion\n";
744 if ( $version < $kohaversion ) {
745 my $warning = "Database update needed, redirecting to %s. Database is $version and Koha is $kohaversion";
746 if ( $type ne 'opac' ) {
747 warn sprintf( $warning, 'Installer' );
748 print $query->redirect("/cgi-bin/koha/installer/install.pl?step=1&op=updatestructure");
750 warn sprintf( "OPAC: " . $warning, 'maintenance' );
751 print $query->redirect("/cgi-bin/koha/maintenance.pl");
759 open my $fh, '>>', "/tmp/sessionlog" or warn "ERROR: Cannot append to /tmp/sessionlog";
760 printf $fh join( "\n", @_ );
764 sub _timeout_syspref {
765 my $default_timeout = 600;
766 my $timeout = C4::Context->preference('timeout') || $default_timeout;
768 # value in days, convert in seconds
769 if ( $timeout =~ /^(\d+)[dD]$/ ) {
770 $timeout = $1 * 86400;
772 # value in hours, convert in seconds
773 elsif ( $timeout =~ /^(\d+)[hH]$/ ) {
774 $timeout = $1 * 3600;
776 elsif ( $timeout !~ m/^\d+$/ ) {
777 warn "The value of the system preference 'timeout' is not correct, defaulting to $default_timeout";
778 $timeout = $default_timeout;
786 $debug and warn "Checking Auth";
788 # Get shibboleth login attribute
789 my $shib = C4::Context->config('useshibboleth') && shib_ok();
790 my $shib_login = $shib ? get_login_shib() : undef;
792 # $authnotrequired will be set for scripts which will run without authentication
793 my $authnotrequired = shift;
794 my $flagsrequired = shift;
796 my $emailaddress = shift;
797 my $template_name = shift;
798 $type = 'opac' unless $type;
800 unless ( C4::Context->preference("OpacPublic") ) {
801 my @allowed_scripts_for_private_opac = qw(
803 opac-registration-email-sent.tt
804 opac-registration-confirmation.tt
805 opac-memberentry-update-submitted.tt
806 opac-password-recovery.tt
808 $authnotrequired = 0 unless grep { $_ eq $template_name }
809 @allowed_scripts_for_private_opac;
812 my $dbh = C4::Context->dbh;
813 my $timeout = _timeout_syspref();
815 _version_check( $type, $query );
820 my ( $userid, $cookie, $sessionID, $flags );
821 my $logout = $query->param('logout.x');
823 my $anon_search_history;
825 # This parameter is the name of the CAS server we want to authenticate against,
826 # when using authentication against multiple CAS servers, as configured in Auth_cas_servers.yaml
827 my $casparam = $query->param('cas');
828 my $q_userid = $query->param('userid') // '';
832 # Basic authentication is incompatible with the use of Shibboleth,
833 # as Shibboleth may return REMOTE_USER as a Shibboleth attribute,
834 # and it may not be the attribute we want to use to match the koha login.
836 # Also, do not consider an empty REMOTE_USER.
838 # Finally, after those tests, we can assume (although if it would be better with
839 # a syspref) that if we get a REMOTE_USER, that's from basic authentication,
840 # and we can affect it to $userid.
841 if ( !$shib and defined( $ENV{'REMOTE_USER'} ) and $ENV{'REMOTE_USER'} ne '' and $userid = $ENV{'REMOTE_USER'} ) {
843 # Using Basic Authentication, no cookies required
844 $cookie = $query->cookie(
845 -name => 'CGISESSID',
849 -secure => ( C4::Context->https_enabled() ? 1 : 0 ),
853 elsif ( $emailaddress) {
854 # the Google OpenID Connect passes an email address
856 elsif ( $sessionID = $query->cookie("CGISESSID") )
857 { # assignment, not comparison
858 $session = get_session($sessionID);
859 C4::Context->_new_userenv($sessionID);
860 my ( $ip, $lasttime, $sessiontype );
863 $s_userid = $session->param('id') // '';
864 C4::Context->set_userenv(
865 $session->param('number'), $s_userid,
866 $session->param('cardnumber'), $session->param('firstname'),
867 $session->param('surname'), $session->param('branch'),
868 $session->param('branchname'), $session->param('flags'),
869 $session->param('emailaddress'), $session->param('shibboleth'),
870 $session->param('desk_id'), $session->param('desk_name'),
871 $session->param('register_id')
873 C4::Context::set_shelves_userenv( 'bar', $session->param('barshelves') );
874 C4::Context::set_shelves_userenv( 'pub', $session->param('pubshelves') );
875 C4::Context::set_shelves_userenv( 'tot', $session->param('totshelves') );
876 $debug and printf STDERR "AUTH_SESSION: (%s)\t%s %s - %s\n", map { $session->param($_) } qw(cardnumber firstname surname branch);
877 $ip = $session->param('ip');
878 $lasttime = $session->param('lasttime');
880 $sessiontype = $session->param('sessiontype') || '';
882 if ( ( $query->param('koha_login_context') && ( $q_userid ne $s_userid ) )
883 || ( $cas && $query->param('ticket') && !C4::Context->userenv->{'id'} )
884 || ( $shib && $shib_login && !$logout && !C4::Context->userenv->{'id'} )
887 #if a user enters an id ne to the id in the current session, we need to log them in...
888 #first we need to clear the anonymous session...
889 $debug and warn "query id = $q_userid but session id = $s_userid";
890 $anon_search_history = $session->param('search_history');
893 C4::Context->_unset_userenv($sessionID);
899 # voluntary logout the user
900 # check wether the user was using their shibboleth session or a local one
901 my $shibSuccess = C4::Context->userenv->{'shibboleth'};
904 C4::Context->_unset_userenv($sessionID);
906 #_session_log(sprintf "%20s from %16s logged out at %30s (manually).\n", $userid,$ip,(strftime "%c",localtime));
910 if ($cas and $caslogout) {
911 logout_cas($query, $type);
914 # If we are in a shibboleth session (shibboleth is enabled, a shibboleth match attribute is set and matches koha matchpoint)
915 if ( $shib and $shib_login and $shibSuccess) {
919 elsif ( !$lasttime || ( $lasttime < time() - $timeout ) ) {
922 $info{'timed_out'} = 1;
927 C4::Context->_unset_userenv($sessionID);
929 #_session_log(sprintf "%20s from %16s logged out at %30s (inactivity).\n", $userid,$ip,(strftime "%c",localtime));
933 elsif ( C4::Context->preference('SessionRestrictionByIP') && $ip ne $ENV{'REMOTE_ADDR'} ) {
935 # Different ip than originally logged in from
936 $info{'oldip'} = $ip;
937 $info{'newip'} = $ENV{'REMOTE_ADDR'};
938 $info{'different_ip'} = 1;
941 C4::Context->_unset_userenv($sessionID);
943 #_session_log(sprintf "%20s from %16s logged out at %30s (ip changed to %16s).\n", $userid,$ip,(strftime "%c",localtime), $info{'newip'});
948 $cookie = $query->cookie(
949 -name => 'CGISESSID',
950 -value => $session->id,
952 -secure => ( C4::Context->https_enabled() ? 1 : 0 ),
954 $session->param( 'lasttime', time() );
955 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...
956 $flags = haspermission( $userid, $flagsrequired );
960 $info{'nopermission'} = 1;
965 unless ( $userid || $sessionID ) {
966 #we initiate a session prior to checking for a username to allow for anonymous sessions...
967 my $session = get_session("") or die "Auth ERROR: Cannot get_session()";
969 # Save anonymous search history in new session so it can be retrieved
970 # by get_template_and_user to store it in user's search history after
971 # a successful login.
972 if ($anon_search_history) {
973 $session->param( 'search_history', $anon_search_history );
976 $sessionID = $session->id;
977 C4::Context->_new_userenv($sessionID);
978 $cookie = $query->cookie(
979 -name => 'CGISESSID',
980 -value => $session->id,
982 -secure => ( C4::Context->https_enabled() ? 1 : 0 ),
984 my $pki_field = C4::Context->preference('AllowPKIAuth');
985 if ( !defined($pki_field) ) {
986 print STDERR "ERROR: Missing system preference AllowPKIAuth.\n";
989 if ( ( $cas && $query->param('ticket') )
991 || ( $shib && $shib_login )
992 || $pki_field ne 'None'
995 my $password = $query->param('password');
997 my ( $return, $cardnumber );
999 # If shib is enabled and we have a shib login, does the login match a valid koha user
1000 if ( $shib && $shib_login ) {
1003 # Do not pass password here, else shib will not be checked in checkpw.
1004 ( $return, $cardnumber, $retuserid ) = checkpw( $dbh, $q_userid, undef, $query );
1005 $userid = $retuserid;
1006 $shibSuccess = $return;
1007 $info{'invalidShibLogin'} = 1 unless ($return);
1010 # If shib login and match were successful, skip further login methods
1011 unless ($shibSuccess) {
1012 if ( $cas && $query->param('ticket') ) {
1014 ( $return, $cardnumber, $retuserid, $cas_ticket ) =
1015 checkpw( $dbh, $userid, $password, $query, $type );
1016 $userid = $retuserid;
1017 $info{'invalidCasLogin'} = 1 unless ($return);
1020 elsif ( $emailaddress ) {
1021 my $value = $emailaddress;
1023 # If we're looking up the email, there's a chance that the person
1024 # doesn't have a userid. So if there is none, we pass along the
1025 # borrower number, and the bits of code that need to know the user
1026 # ID will have to be smart enough to handle that.
1027 my $patrons = Koha::Patrons->search({ email => $value });
1028 if ($patrons->count) {
1030 # First the userid, then the borrowernum
1031 my $patron = $patrons->next;
1032 $value = $patron->userid || $patron->borrowernumber;
1036 $return = $value ? 1 : 0;
1041 ( $pki_field eq 'Common Name' && $ENV{'SSL_CLIENT_S_DN_CN'} )
1042 || ( $pki_field eq 'emailAddress'
1043 && $ENV{'SSL_CLIENT_S_DN_Email'} )
1047 if ( $pki_field eq 'Common Name' ) {
1048 $value = $ENV{'SSL_CLIENT_S_DN_CN'};
1050 elsif ( $pki_field eq 'emailAddress' ) {
1051 $value = $ENV{'SSL_CLIENT_S_DN_Email'};
1053 # If we're looking up the email, there's a chance that the person
1054 # doesn't have a userid. So if there is none, we pass along the
1055 # borrower number, and the bits of code that need to know the user
1056 # ID will have to be smart enough to handle that.
1057 my $patrons = Koha::Patrons->search({ email => $value });
1058 if ($patrons->count) {
1060 # First the userid, then the borrowernum
1061 my $patron = $patrons->next;
1062 $value = $patron->userid || $patron->borrowernumber;
1068 $return = $value ? 1 : 0;
1074 ( $return, $cardnumber, $retuserid, $cas_ticket ) =
1075 checkpw( $dbh, $q_userid, $password, $query, $type );
1076 $userid = $retuserid if ($retuserid);
1077 $info{'invalid_username_or_password'} = 1 unless ($return);
1081 # $return: 1 = valid user
1084 #_session_log(sprintf "%20s from %16s logged in at %30s.\n", $userid,$ENV{'REMOTE_ADDR'},(strftime '%c', localtime));
1085 if ( $flags = haspermission( $userid, $flagsrequired ) ) {
1089 $info{'nopermission'} = 1;
1090 C4::Context->_unset_userenv($sessionID);
1092 my ( $borrowernumber, $firstname, $surname, $userflags,
1093 $branchcode, $branchname, $emailaddress, $desk_id,
1094 $desk_name, $register_id );
1096 if ( $return == 1 ) {
1098 SELECT borrowernumber, firstname, surname, flags, borrowers.branchcode,
1099 branches.branchname as branchname, email
1101 LEFT JOIN branches on borrowers.branchcode=branches.branchcode
1103 my $sth = $dbh->prepare("$select where userid=?");
1104 $sth->execute($userid);
1105 unless ( $sth->rows ) {
1106 $debug and print STDERR "AUTH_1: no rows for userid='$userid'\n";
1107 $sth = $dbh->prepare("$select where cardnumber=?");
1108 $sth->execute($cardnumber);
1110 unless ( $sth->rows ) {
1111 $debug and print STDERR "AUTH_2a: no rows for cardnumber='$cardnumber'\n";
1112 $sth->execute($userid);
1113 unless ( $sth->rows ) {
1114 $debug and print STDERR "AUTH_2b: no rows for userid='$userid' AS cardnumber\n";
1119 ( $borrowernumber, $firstname, $surname, $userflags,
1120 $branchcode, $branchname, $emailaddress ) = $sth->fetchrow;
1121 $debug and print STDERR "AUTH_3 results: " .
1122 "$cardnumber,$borrowernumber,$userid,$firstname,$surname,$userflags,$branchcode,$emailaddress\n";
1124 print STDERR "AUTH_3: no results for userid='$userid', cardnumber='$cardnumber'.\n";
1127 # launch a sequence to check if we have a ip for the branch, i
1128 # if we have one we replace the branchcode of the userenv by the branch bound in the ip.
1130 my $ip = $ENV{'REMOTE_ADDR'};
1132 # if they specify at login, use that
1133 if ( $query->param('branch') ) {
1134 $branchcode = $query->param('branch');
1135 my $library = Koha::Libraries->find($branchcode);
1136 $branchname = $library? $library->branchname: '';
1138 if ( $query->param('desk_id') ) {
1139 $desk_id = $query->param('desk_id');
1140 my $desk = Koha::Desks->find($desk_id);
1141 $desk_name = $desk ? $desk->desk_name : '';
1143 if ( $query->param('register_id') ) {
1144 $register_id = $query->param('register_id');
1146 my $branches = { map { $_->branchcode => $_->unblessed } Koha::Libraries->search };
1147 if ( $type ne 'opac' and C4::Context->boolean_preference('AutoLocation') ) {
1149 # we have to check they are coming from the right ip range
1150 my $domain = $branches->{$branchcode}->{'branchip'};
1151 $domain =~ s|\.\*||g;
1152 if ( $ip !~ /^$domain/ ) {
1154 $cookie = $query->cookie(
1155 -name => 'CGISESSID',
1158 -secure => ( C4::Context->https_enabled() ? 1 : 0 ),
1160 $info{'wrongip'} = 1;
1164 foreach my $br ( keys %$branches ) {
1166 # now we work with the treatment of ip
1167 my $domain = $branches->{$br}->{'branchip'};
1168 if ( $domain && $ip =~ /^$domain/ ) {
1169 $branchcode = $branches->{$br}->{'branchcode'};
1171 # new op dev : add the branchname to the cookie
1172 $branchname = $branches->{$br}->{'branchname'};
1175 $session->param( 'number', $borrowernumber );
1176 $session->param( 'id', $userid );
1177 $session->param( 'cardnumber', $cardnumber );
1178 $session->param( 'firstname', $firstname );
1179 $session->param( 'surname', $surname );
1180 $session->param( 'branch', $branchcode );
1181 $session->param( 'branchname', $branchname );
1182 $session->param( 'desk_id', $desk_id);
1183 $session->param( 'desk_name', $desk_name);
1184 $session->param( 'flags', $userflags );
1185 $session->param( 'emailaddress', $emailaddress );
1186 $session->param( 'ip', $session->remote_addr() );
1187 $session->param( 'lasttime', time() );
1188 $session->param( 'interface', $type);
1189 $session->param( 'shibboleth', $shibSuccess );
1190 $session->param( 'register_id', $register_id );
1191 $debug and printf STDERR "AUTH_4: (%s)\t%s %s - %s\n", map { $session->param($_) } qw(cardnumber firstname surname branch);
1193 $session->param('cas_ticket', $cas_ticket) if $cas_ticket;
1194 C4::Context->set_userenv(
1195 $session->param('number'), $session->param('id'),
1196 $session->param('cardnumber'), $session->param('firstname'),
1197 $session->param('surname'), $session->param('branch'),
1198 $session->param('branchname'), $session->param('flags'),
1199 $session->param('emailaddress'), $session->param('shibboleth'),
1200 $session->param('desk_id'), $session->param('desk_name'),
1201 $session->param('register_id')
1205 # $return: 0 = invalid user
1206 # reset to anonymous session
1208 $debug and warn "Login failed, resetting anonymous session...";
1210 $info{'invalid_username_or_password'} = 1;
1211 C4::Context->_unset_userenv($sessionID);
1213 $session->param( 'lasttime', time() );
1214 $session->param( 'ip', $session->remote_addr() );
1215 $session->param( 'sessiontype', 'anon' );
1216 $session->param( 'interface', $type);
1218 } # END if ( $q_userid
1219 elsif ( $type eq "opac" ) {
1221 # if we are here this is an anonymous session; add public lists to it and a few other items...
1222 # anonymous sessions are created only for the OPAC
1223 $debug and warn "Initiating an anonymous session...";
1225 # setting a couple of other session vars...
1226 $session->param( 'ip', $session->remote_addr() );
1227 $session->param( 'lasttime', time() );
1228 $session->param( 'sessiontype', 'anon' );
1229 $session->param( 'interface', $type);
1231 } # END unless ($userid)
1233 # finished authentification, now respond
1234 if ( $loggedin || $authnotrequired )
1238 $cookie = $query->cookie(
1239 -name => 'CGISESSID',
1242 -secure => ( C4::Context->https_enabled() ? 1 : 0 ),
1246 track_login_daily( $userid );
1248 # In case, that this request was a login attempt, we want to prevent that users can repost the opac login
1249 # request. We therefore redirect the user to the requested page again without the login parameters.
1250 # See Post/Redirect/Get (PRG) design pattern: https://en.wikipedia.org/wiki/Post/Redirect/Get
1251 if ( $type eq "opac" && $query->param('koha_login_context') && $query->param('koha_login_context') ne 'sco' && $query->param('password') && $query->param('userid') ) {
1252 my $uri = URI->new($query->url(-relative=>1, -query_string=>1));
1253 $uri->query_param_delete('userid');
1254 $uri->query_param_delete('password');
1255 $uri->query_param_delete('koha_login_context');
1256 print $query->redirect(-uri => $uri->as_string, -cookie => $cookie, -status=>'303 See other');
1260 return ( $userid, $cookie, $sessionID, $flags );
1265 # AUTH rejected, show the login/password template, after checking the DB.
1269 # get the inputs from the incoming query
1271 foreach my $name ( param $query) {
1272 (next) if ( $name eq 'userid' || $name eq 'password' || $name eq 'ticket' );
1273 my @value = $query->multi_param($name);
1274 push @inputs, { name => $name, value => $_ } for @value;
1277 my $patron = Koha::Patrons->find({ userid => $q_userid }); # Not necessary logged in!
1279 my $LibraryNameTitle = C4::Context->preference("LibraryName");
1280 $LibraryNameTitle =~ s/<(?:\/?)(?:br|p)\s*(?:\/?)>/ /sgi;
1281 $LibraryNameTitle =~ s/<(?:[^<>'"]|'(?:[^']*)'|"(?:[^"]*)")*>//sg;
1283 my $auth_template_name = ( $type eq 'opac' ) ? 'opac-auth.tt' : 'auth.tt';
1284 my $template = C4::Templates::gettemplate( $auth_template_name, $type, $query );
1288 script_name => get_script_name(),
1289 casAuthentication => C4::Context->preference("casAuthentication"),
1290 shibbolethAuthentication => $shib,
1291 SessionRestrictionByIP => C4::Context->preference("SessionRestrictionByIP"),
1292 suggestion => C4::Context->preference("suggestion"),
1293 virtualshelves => C4::Context->preference("virtualshelves"),
1294 LibraryName => "" . C4::Context->preference("LibraryName"),
1295 LibraryNameTitle => "" . $LibraryNameTitle,
1296 opacuserlogin => C4::Context->preference("opacuserlogin"),
1297 OpacNav => C4::Context->preference("OpacNav"),
1298 OpacNavBottom => C4::Context->preference("OpacNavBottom"),
1299 OpacFavicon => C4::Context->preference("OpacFavicon"),
1300 opacreadinghistory => C4::Context->preference("opacreadinghistory"),
1301 opaclanguagesdisplay => C4::Context->preference("opaclanguagesdisplay"),
1302 OPACUserJS => C4::Context->preference("OPACUserJS"),
1303 opacbookbag => "" . C4::Context->preference("opacbookbag"),
1304 OpacCloud => C4::Context->preference("OpacCloud"),
1305 OpacTopissue => C4::Context->preference("OpacTopissue"),
1306 OpacAuthorities => C4::Context->preference("OpacAuthorities"),
1307 OpacBrowser => C4::Context->preference("OpacBrowser"),
1308 TagsEnabled => C4::Context->preference("TagsEnabled"),
1309 OPACUserCSS => C4::Context->preference("OPACUserCSS"),
1310 intranetcolorstylesheet => C4::Context->preference("intranetcolorstylesheet"),
1311 intranetstylesheet => C4::Context->preference("intranetstylesheet"),
1312 intranetbookbag => C4::Context->preference("intranetbookbag"),
1313 IntranetNav => C4::Context->preference("IntranetNav"),
1314 IntranetFavicon => C4::Context->preference("IntranetFavicon"),
1315 IntranetUserCSS => C4::Context->preference("IntranetUserCSS"),
1316 IntranetUserJS => C4::Context->preference("IntranetUserJS"),
1317 IndependentBranches => C4::Context->preference("IndependentBranches"),
1318 AutoLocation => C4::Context->preference("AutoLocation"),
1319 wrongip => $info{'wrongip'},
1320 PatronSelfRegistration => C4::Context->preference("PatronSelfRegistration"),
1321 PatronSelfRegistrationDefaultCategory => C4::Context->preference("PatronSelfRegistrationDefaultCategory"),
1322 opac_css_override => $ENV{'OPAC_CSS_OVERRIDE'},
1323 too_many_login_attempts => ( $patron and $patron->account_locked )
1326 $template->param( SCO_login => 1 ) if ( $query->param('sco_user_login') );
1327 $template->param( SCI_login => 1 ) if ( $query->param('sci_user_login') );
1328 $template->param( OpacPublic => C4::Context->preference("OpacPublic") );
1329 $template->param( loginprompt => 1 ) unless $info{'nopermission'};
1331 if ( $type eq 'opac' ) {
1332 require Koha::Virtualshelves;
1333 my $some_public_shelves = Koha::Virtualshelves->get_some_shelves(
1339 some_public_shelves => $some_public_shelves,
1345 # Is authentication against multiple CAS servers enabled?
1346 if ( C4::Auth_with_cas::multipleAuth && !$casparam ) {
1347 my $casservers = C4::Auth_with_cas::getMultipleAuth();
1349 foreach my $key ( keys %$casservers ) {
1350 push @tmplservers, { name => $key, value => login_cas_url( $query, $key, $type ) . "?cas=$key" };
1353 casServersLoop => \@tmplservers
1357 casServerUrl => login_cas_url($query, undef, $type),
1362 invalidCasLogin => $info{'invalidCasLogin'}
1368 shibbolethAuthentication => $shib,
1369 shibbolethLoginUrl => login_shib_url($query),
1373 if (C4::Context->preference('GoogleOpenIDConnect')) {
1374 if ($query->param("OpenIDConnectFailed")) {
1375 my $reason = $query->param('OpenIDConnectFailed');
1376 $template->param(invalidGoogleOpenIDConnectLogin => $reason);
1381 LibraryName => C4::Context->preference("LibraryName"),
1383 $template->param(%info);
1385 # $cookie = $query->cookie(CGISESSID => $session->id
1387 print $query->header(
1388 { type => 'text/html',
1391 'X-Frame-Options' => 'SAMEORIGIN'
1398 =head2 check_api_auth
1400 ($status, $cookie, $sessionId) = check_api_auth($query, $userflags);
1402 Given a CGI query containing the parameters 'userid' and 'password' and/or a session
1403 cookie, determine if the user has the privileges specified by C<$userflags>.
1405 C<check_api_auth> is is meant for authenticating users of web services, and
1406 consequently will always return and will not attempt to redirect the user
1409 If a valid session cookie is already present, check_api_auth will return a status
1410 of "ok", the cookie, and the Koha session ID.
1412 If no session cookie is present, check_api_auth will check the 'userid' and 'password
1413 parameters and create a session cookie and Koha session if the supplied credentials
1416 Possible return values in C<$status> are:
1420 =item "ok" -- user authenticated; C<$cookie> and C<$sessionid> have valid values.
1422 =item "failed" -- credentials are not correct; C<$cookie> and C<$sessionid> are undef
1424 =item "maintenance" -- DB is in maintenance mode; no login possible at the moment
1426 =item "expired -- session cookie has expired; API user should resubmit userid and password
1432 sub check_api_auth {
1435 my $flagsrequired = shift;
1436 my $dbh = C4::Context->dbh;
1437 my $timeout = _timeout_syspref();
1439 unless ( C4::Context->preference('Version') ) {
1441 # database has not been installed yet
1442 return ( "maintenance", undef, undef );
1444 my $kohaversion = Koha::version();
1445 $kohaversion =~ s/(.*\..*)\.(.*)\.(.*)/$1$2$3/;
1446 if ( C4::Context->preference('Version') < $kohaversion ) {
1448 # database in need of version update; assume that
1449 # no API should be called while databsae is in
1451 return ( "maintenance", undef, undef );
1454 # FIXME -- most of what follows is a copy-and-paste
1455 # of code from checkauth. There is an obvious need
1456 # for refactoring to separate the various parts of
1457 # the authentication code, but as of 2007-11-19 this
1458 # is deferred so as to not introduce bugs into the
1459 # regular authentication code for Koha 3.0.
1461 # see if we have a valid session cookie already
1462 # however, if a userid parameter is present (i.e., from
1463 # a form submission, assume that any current cookie
1465 my $sessionID = undef;
1466 unless ( $query->param('userid') ) {
1467 $sessionID = $query->cookie("CGISESSID");
1469 if ( $sessionID && not( $cas && $query->param('PT') ) ) {
1470 my $session = get_session($sessionID);
1471 C4::Context->_new_userenv($sessionID);
1473 C4::Context->interface($session->param('interface'));
1474 C4::Context->set_userenv(
1475 $session->param('number'), $session->param('id'),
1476 $session->param('cardnumber'), $session->param('firstname'),
1477 $session->param('surname'), $session->param('branch'),
1478 $session->param('branchname'), $session->param('flags'),
1479 $session->param('emailaddress'), $session->param('shibboleth'),
1480 $session->param('desk_id'), $session->param('desk_name'),
1481 $session->param('register_id')
1484 my $ip = $session->param('ip');
1485 my $lasttime = $session->param('lasttime');
1486 my $userid = $session->param('id');
1487 if ( $lasttime < time() - $timeout ) {
1492 C4::Context->_unset_userenv($sessionID);
1495 return ( "expired", undef, undef );
1496 } elsif ( C4::Context->preference('SessionRestrictionByIP') && $ip ne $ENV{'REMOTE_ADDR'} ) {
1498 # IP address changed
1501 C4::Context->_unset_userenv($sessionID);
1504 return ( "expired", undef, undef );
1506 my $cookie = $query->cookie(
1507 -name => 'CGISESSID',
1508 -value => $session->id,
1510 -secure => ( C4::Context->https_enabled() ? 1 : 0 ),
1512 $session->param( 'lasttime', time() );
1513 my $flags = haspermission( $userid, $flagsrequired );
1515 return ( "ok", $cookie, $sessionID );
1519 C4::Context->_unset_userenv($sessionID);
1522 return ( "failed", undef, undef );
1526 return ( "expired", undef, undef );
1531 my $userid = $query->param('userid');
1532 my $password = $query->param('password');
1533 my ( $return, $cardnumber, $cas_ticket );
1536 if ( $cas && $query->param('PT') ) {
1538 $debug and print STDERR "## check_api_auth - checking CAS\n";
1540 # In case of a CAS authentication, we use the ticket instead of the password
1541 my $PT = $query->param('PT');
1542 ( $return, $cardnumber, $userid, $cas_ticket ) = check_api_auth_cas( $dbh, $PT, $query ); # EXTERNAL AUTH
1545 # User / password auth
1546 unless ( $userid and $password ) {
1548 # caller did something wrong, fail the authenticateion
1549 return ( "failed", undef, undef );
1552 ( $return, $cardnumber, $newuserid, $cas_ticket ) = checkpw( $dbh, $userid, $password, $query );
1555 if ( $return and haspermission( $userid, $flagsrequired ) ) {
1556 my $session = get_session("");
1557 return ( "failed", undef, undef ) unless $session;
1559 my $sessionID = $session->id;
1560 C4::Context->_new_userenv($sessionID);
1561 my $cookie = $query->cookie(
1562 -name => 'CGISESSID',
1563 -value => $sessionID,
1565 -secure => ( C4::Context->https_enabled() ? 1 : 0 ),
1567 if ( $return == 1 ) {
1569 $borrowernumber, $firstname, $surname,
1570 $userflags, $branchcode, $branchname,
1575 "select borrowernumber, firstname, surname, flags, borrowers.branchcode, branches.branchname as branchname, email from borrowers left join branches on borrowers.branchcode=branches.branchcode where userid=?"
1577 $sth->execute($userid);
1579 $borrowernumber, $firstname, $surname,
1580 $userflags, $branchcode, $branchname,
1582 ) = $sth->fetchrow if ( $sth->rows );
1584 unless ( $sth->rows ) {
1585 my $sth = $dbh->prepare(
1586 "select borrowernumber, firstname, surname, flags, borrowers.branchcode, branches.branchname as branchname, email from borrowers left join branches on borrowers.branchcode=branches.branchcode where cardnumber=?"
1588 $sth->execute($cardnumber);
1590 $borrowernumber, $firstname, $surname,
1591 $userflags, $branchcode, $branchname,
1593 ) = $sth->fetchrow if ( $sth->rows );
1595 unless ( $sth->rows ) {
1596 $sth->execute($userid);
1598 $borrowernumber, $firstname, $surname, $userflags,
1599 $branchcode, $branchname, $emailaddress
1600 ) = $sth->fetchrow if ( $sth->rows );
1604 my $ip = $ENV{'REMOTE_ADDR'};
1606 # if they specify at login, use that
1607 if ( $query->param('branch') ) {
1608 $branchcode = $query->param('branch');
1609 my $library = Koha::Libraries->find($branchcode);
1610 $branchname = $library? $library->branchname: '';
1612 my $branches = { map { $_->branchcode => $_->unblessed } Koha::Libraries->search };
1613 foreach my $br ( keys %$branches ) {
1615 # now we work with the treatment of ip
1616 my $domain = $branches->{$br}->{'branchip'};
1617 if ( $domain && $ip =~ /^$domain/ ) {
1618 $branchcode = $branches->{$br}->{'branchcode'};
1620 # new op dev : add the branchname to the cookie
1621 $branchname = $branches->{$br}->{'branchname'};
1624 $session->param( 'number', $borrowernumber );
1625 $session->param( 'id', $userid );
1626 $session->param( 'cardnumber', $cardnumber );
1627 $session->param( 'firstname', $firstname );
1628 $session->param( 'surname', $surname );
1629 $session->param( 'branch', $branchcode );
1630 $session->param( 'branchname', $branchname );
1631 $session->param( 'flags', $userflags );
1632 $session->param( 'emailaddress', $emailaddress );
1633 $session->param( 'ip', $session->remote_addr() );
1634 $session->param( 'lasttime', time() );
1635 $session->param( 'interface', 'api' );
1637 $session->param( 'cas_ticket', $cas_ticket);
1638 C4::Context->set_userenv(
1639 $session->param('number'), $session->param('id'),
1640 $session->param('cardnumber'), $session->param('firstname'),
1641 $session->param('surname'), $session->param('branch'),
1642 $session->param('branchname'), $session->param('flags'),
1643 $session->param('emailaddress'), $session->param('shibboleth'),
1644 $session->param('desk_id'), $session->param('desk_name'),
1645 $session->param('register_id')
1647 return ( "ok", $cookie, $sessionID );
1649 return ( "failed", undef, undef );
1654 =head2 check_cookie_auth
1656 ($status, $sessionId) = check_api_auth($cookie, $userflags);
1658 Given a CGISESSID cookie set during a previous login to Koha, determine
1659 if the user has the privileges specified by C<$userflags>. C<$userflags>
1660 is passed unaltered into C<haspermission> and as such accepts all options
1661 avaiable to that routine with the one caveat that C<check_api_auth> will
1662 also allow 'undef' to be passed and in such a case the permissions check
1663 will be skipped altogether.
1665 C<check_cookie_auth> is meant for authenticating special services
1666 such as tools/upload-file.pl that are invoked by other pages that
1667 have been authenticated in the usual way.
1669 Possible return values in C<$status> are:
1673 =item "ok" -- user authenticated; C<$sessionID> have valid values.
1675 =item "failed" -- credentials are not correct; C<$sessionid> are undef
1677 =item "maintenance" -- DB is in maintenance mode; no login possible at the moment
1679 =item "expired -- session cookie has expired; API user should resubmit userid and password
1685 sub check_cookie_auth {
1687 my $flagsrequired = shift;
1690 my $remote_addr = $params->{remote_addr} || $ENV{REMOTE_ADDR};
1691 my $dbh = C4::Context->dbh;
1692 my $timeout = _timeout_syspref();
1694 unless ( C4::Context->preference('Version') ) {
1696 # database has not been installed yet
1697 return ( "maintenance", undef );
1699 my $kohaversion = Koha::version();
1700 $kohaversion =~ s/(.*\..*)\.(.*)\.(.*)/$1$2$3/;
1701 if ( C4::Context->preference('Version') < $kohaversion ) {
1703 # database in need of version update; assume that
1704 # no API should be called while databsae is in
1706 return ( "maintenance", undef );
1709 # FIXME -- most of what follows is a copy-and-paste
1710 # of code from checkauth. There is an obvious need
1711 # for refactoring to separate the various parts of
1712 # the authentication code, but as of 2007-11-23 this
1713 # is deferred so as to not introduce bugs into the
1714 # regular authentication code for Koha 3.0.
1716 # see if we have a valid session cookie already
1717 # however, if a userid parameter is present (i.e., from
1718 # a form submission, assume that any current cookie
1720 unless ( defined $cookie and $cookie ) {
1721 return ( "failed", undef );
1723 my $sessionID = $cookie;
1724 my $session = get_session($sessionID);
1725 C4::Context->_new_userenv($sessionID);
1727 C4::Context->interface($session->param('interface'));
1728 C4::Context->set_userenv(
1729 $session->param('number'), $session->param('id'),
1730 $session->param('cardnumber'), $session->param('firstname'),
1731 $session->param('surname'), $session->param('branch'),
1732 $session->param('branchname'), $session->param('flags'),
1733 $session->param('emailaddress'), $session->param('shibboleth'),
1734 $session->param('desk_id'), $session->param('desk_name'),
1735 $session->param('register_id')
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 CGI::Session->new( $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)