Bug 20811: (QA follow-up) Prevent calling AddItemBatchFromMarc and ModBiblioMarc...
[koha.git] / C4 / Auth.pm
blob2731ff2512c69c71206c1989be538d16b923c659
1 package C4::Auth;
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>.
20 use strict;
21 use warnings;
22 use Digest::MD5 qw(md5_base64);
23 use JSON qw/encode_json/;
24 use URI::Escape;
25 use CGI::Session;
27 require Exporter;
28 use C4::Context;
29 use C4::Templates; # to get the template
30 use C4::Languages;
31 use C4::Search::History;
32 use Koha;
33 use Koha::Caches;
34 use Koha::AuthUtils qw(get_script_name hash_password);
35 use Koha::DateUtils qw(dt_from_string);
36 use Koha::Library::Groups;
37 use Koha::Libraries;
38 use Koha::Patrons;
39 use POSIX qw/strftime/;
40 use List::MoreUtils qw/ any /;
41 use Encode qw( encode is_utf8);
43 # use utf8;
44 use vars qw(@ISA @EXPORT @EXPORT_OK %EXPORT_TAGS $debug $ldap $cas $caslogout $shib $shib_login);
46 BEGIN {
47 sub psgi_env { any { /^psgi\./ } keys %ENV }
49 sub safe_exit {
50 if (psgi_env) { die 'psgi:exit' }
51 else { exit }
54 $debug = $ENV{DEBUG};
55 @ISA = qw(Exporter);
56 @EXPORT = qw(&checkauth &get_template_and_user &haspermission &get_user_subpermissions);
57 @EXPORT_OK = qw(&check_api_auth &get_session &check_cookie_auth &checkpw &checkpw_internal &checkpw_hash
58 &get_all_subpermissions &get_user_subpermissions track_login_daily
60 %EXPORT_TAGS = ( EditPermissions => [qw(get_all_subpermissions get_user_subpermissions)] );
61 $ldap = C4::Context->config('useldapserver') || 0;
62 $cas = C4::Context->preference('casAuthentication');
63 $shib = C4::Context->config('useshibboleth') || 0;
64 $caslogout = C4::Context->preference('casLogout');
65 require C4::Auth_with_cas; # no import
67 if ($ldap) {
68 require C4::Auth_with_ldap;
69 import C4::Auth_with_ldap qw(checkpw_ldap);
71 if ($shib) {
72 require C4::Auth_with_shibboleth;
73 import C4::Auth_with_shibboleth
74 qw(shib_ok checkpw_shib logout_shib login_shib_url get_login_shib);
76 # Check for good config
77 if ( shib_ok() ) {
79 # Get shibboleth login attribute
80 $shib_login = get_login_shib();
83 # Bad config, disable shibboleth
84 else {
85 $shib = 0;
88 if ($cas) {
89 import C4::Auth_with_cas qw(check_api_auth_cas checkpw_cas login_cas logout_cas login_cas_url logout_if_required);
94 =head1 NAME
96 C4::Auth - Authenticates Koha users
98 =head1 SYNOPSIS
100 use CGI qw ( -utf8 );
101 use C4::Auth;
102 use C4::Output;
104 my $query = new CGI;
106 my ($template, $borrowernumber, $cookie)
107 = get_template_and_user(
109 template_name => "opac-main.tt",
110 query => $query,
111 type => "opac",
112 authnotrequired => 0,
113 flagsrequired => { catalogue => '*', tools => 'import_patrons' },
117 output_html_with_http_headers $query, $cookie, $template->output;
119 =head1 DESCRIPTION
121 The main function of this module is to provide
122 authentification. However the get_template_and_user function has
123 been provided so that a users login information is passed along
124 automatically. This gets loaded into the template.
126 =head1 FUNCTIONS
128 =head2 get_template_and_user
130 my ($template, $borrowernumber, $cookie)
131 = get_template_and_user(
133 template_name => "opac-main.tt",
134 query => $query,
135 type => "opac",
136 authnotrequired => 0,
137 flagsrequired => { catalogue => '*', tools => 'import_patrons' },
141 This call passes the C<query>, C<flagsrequired> and C<authnotrequired>
142 to C<&checkauth> (in this module) to perform authentification.
143 See C<&checkauth> for an explanation of these parameters.
145 The C<template_name> is then used to find the correct template for
146 the page. The authenticated users details are loaded onto the
147 template in the HTML::Template LOOP variable C<USER_INFO>. Also the
148 C<sessionID> is passed to the template. This can be used in templates
149 if cookies are disabled. It needs to be put as and input to every
150 authenticated page.
152 More information on the C<gettemplate> sub can be found in the
153 Output.pm module.
155 =cut
157 sub get_template_and_user {
159 my $in = shift;
160 my ( $user, $cookie, $sessionID, $flags );
162 C4::Context->interface( $in->{type} );
164 $in->{'authnotrequired'} ||= 0;
166 # the following call includes a bad template check; might croak
167 my $template = C4::Templates::gettemplate(
168 $in->{'template_name'},
169 $in->{'type'},
170 $in->{'query'},
173 if ( $in->{'template_name'} !~ m/maintenance/ ) {
174 ( $user, $cookie, $sessionID, $flags ) = checkauth(
175 $in->{'query'},
176 $in->{'authnotrequired'},
177 $in->{'flagsrequired'},
178 $in->{'type'}
182 if ( $in->{type} eq 'opac' && $user ) {
183 my $kick_out;
185 if (
186 # If the user logged in is the SCO user and they try to go out of the SCO module,
187 # log the user out removing the CGISESSID cookie
188 $in->{template_name} !~ m|sco/|
189 && C4::Context->preference('AutoSelfCheckID')
190 && $user eq C4::Context->preference('AutoSelfCheckID')
193 $kick_out = 1;
195 elsif (
196 # If the user logged in is the SCI user and they try to go out of the SCI module,
197 # kick them out unless it is SCO with a valid permission
198 # or they are a superlibrarian
199 $in->{template_name} !~ m|sci/|
200 && haspermission( $user, { self_check => 'self_checkin_module' } )
201 && !(
202 $in->{template_name} =~ m|sco/| && haspermission(
203 $user, { self_check => 'self_checkout_module' }
206 && $flags && $flags->{superlibrarian} != 1
209 $kick_out = 1;
212 if ($kick_out) {
213 $template = C4::Templates::gettemplate( 'opac-auth.tt', 'opac',
214 $in->{query} );
215 $cookie = $in->{query}->cookie(
216 -name => 'CGISESSID',
217 -value => '',
218 -expires => '',
219 -HttpOnly => 1,
222 $template->param(
223 loginprompt => 1,
224 script_name => get_script_name(),
227 print $in->{query}->header(
229 type => 'text/html',
230 charset => 'utf-8',
231 cookie => $cookie,
232 'X-Frame-Options' => 'SAMEORIGIN'
235 $template->output;
236 safe_exit;
240 my $borrowernumber;
241 if ($user) {
243 # It's possible for $user to be the borrowernumber if they don't have a
244 # userid defined (and are logging in through some other method, such
245 # as SSL certs against an email address)
246 my $patron;
247 $borrowernumber = getborrowernumber($user) if defined($user);
248 if ( !defined($borrowernumber) && defined($user) ) {
249 $patron = Koha::Patrons->find( $user );
250 if ($patron) {
251 $borrowernumber = $user;
253 # A bit of a hack, but I don't know there's a nicer way
254 # to do it.
255 $user = $patron->firstname . ' ' . $patron->surname;
257 } else {
258 $patron = Koha::Patrons->find( $borrowernumber );
259 # FIXME What to do if $patron does not exist?
262 # user info
263 $template->param( loggedinusername => $user ); # FIXME Should be replaced with something like patron-title.inc
264 $template->param( loggedinusernumber => $borrowernumber ); # FIXME Should be replaced with logged_in_user.borrowernumber
265 $template->param( logged_in_user => $patron );
266 $template->param( sessionID => $sessionID );
268 if ( $in->{'type'} eq 'opac' ) {
269 require Koha::Virtualshelves;
270 my $some_private_shelves = Koha::Virtualshelves->get_some_shelves(
272 borrowernumber => $borrowernumber,
273 category => 1,
276 my $some_public_shelves = Koha::Virtualshelves->get_some_shelves(
278 category => 2,
281 $template->param(
282 some_private_shelves => $some_private_shelves,
283 some_public_shelves => $some_public_shelves,
287 $template->param( "USER_INFO" => $patron->unblessed ) if $borrowernumber != 0;
289 my $all_perms = get_all_subpermissions();
291 my @flagroots = qw(circulate catalogue parameters borrowers permissions reserveforothers borrow
292 editcatalogue updatecharges tools editauthorities serials reports acquisition clubs);
294 # We are going to use the $flags returned by checkauth
295 # to create the template's parameters that will indicate
296 # which menus the user can access.
297 if ( $flags && $flags->{superlibrarian} == 1 ) {
298 $template->param( CAN_user_circulate => 1 );
299 $template->param( CAN_user_catalogue => 1 );
300 $template->param( CAN_user_parameters => 1 );
301 $template->param( CAN_user_borrowers => 1 );
302 $template->param( CAN_user_permissions => 1 );
303 $template->param( CAN_user_reserveforothers => 1 );
304 $template->param( CAN_user_editcatalogue => 1 );
305 $template->param( CAN_user_updatecharges => 1 );
306 $template->param( CAN_user_acquisition => 1 );
307 $template->param( CAN_user_tools => 1 );
308 $template->param( CAN_user_editauthorities => 1 );
309 $template->param( CAN_user_serials => 1 );
310 $template->param( CAN_user_reports => 1 );
311 $template->param( CAN_user_staffaccess => 1 );
312 $template->param( CAN_user_plugins => 1 );
313 $template->param( CAN_user_coursereserves => 1 );
314 $template->param( CAN_user_clubs => 1 );
315 $template->param( CAN_user_ill => 1 );
317 foreach my $module ( keys %$all_perms ) {
318 foreach my $subperm ( keys %{ $all_perms->{$module} } ) {
319 $template->param( "CAN_user_${module}_${subperm}" => 1 );
324 if ($flags) {
325 foreach my $module ( keys %$all_perms ) {
326 if ( defined($flags->{$module}) && $flags->{$module} == 1 ) {
327 foreach my $subperm ( keys %{ $all_perms->{$module} } ) {
328 $template->param( "CAN_user_${module}_${subperm}" => 1 );
330 } elsif ( ref( $flags->{$module} ) ) {
331 foreach my $subperm ( keys %{ $flags->{$module} } ) {
332 $template->param( "CAN_user_${module}_${subperm}" => 1 );
338 if ($flags) {
339 foreach my $module ( keys %$flags ) {
340 if ( $flags->{$module} == 1 or ref( $flags->{$module} ) ) {
341 $template->param( "CAN_user_$module" => 1 );
346 # Logged-in opac search history
347 # If the requested template is an opac one and opac search history is enabled
348 if ( $in->{type} eq 'opac' && C4::Context->preference('EnableOpacSearchHistory') ) {
349 my $dbh = C4::Context->dbh;
350 my $query = "SELECT COUNT(*) FROM search_history WHERE userid=?";
351 my $sth = $dbh->prepare($query);
352 $sth->execute($borrowernumber);
354 # If at least one search has already been performed
355 if ( $sth->fetchrow_array > 0 ) {
357 # We show the link in opac
358 $template->param( EnableOpacSearchHistory => 1 );
360 if (C4::Context->preference('LoadSearchHistoryToTheFirstLoggedUser'))
362 # And if there are searches performed when the user was not logged in,
363 # we add them to the logged-in search history
364 my @recentSearches = C4::Search::History::get_from_session( { cgi => $in->{'query'} } );
365 if (@recentSearches) {
366 my $dbh = C4::Context->dbh;
367 my $query = q{
368 INSERT INTO search_history(userid, sessionid, query_desc, query_cgi, type, total, time )
369 VALUES (?, ?, ?, ?, ?, ?, ?)
371 my $sth = $dbh->prepare($query);
372 $sth->execute( $borrowernumber,
373 $in->{query}->cookie("CGISESSID"),
374 $_->{query_desc},
375 $_->{query_cgi},
376 $_->{type} || 'biblio',
377 $_->{total},
378 $_->{time},
379 ) foreach @recentSearches;
381 # clear out the search history from the session now that
382 # we've saved it to the database
385 C4::Search::History::set_to_session( { cgi => $in->{'query'}, search_history => [] } );
387 } elsif ( $in->{type} eq 'intranet' and C4::Context->preference('EnableSearchHistory') ) {
388 $template->param( EnableSearchHistory => 1 );
391 else { # if this is an anonymous session, setup to display public lists...
393 # If shibboleth is enabled, and we're in an anonymous session, we should allow
394 # the user to attempt login via shibboleth.
395 if ($shib) {
396 $template->param( shibbolethAuthentication => $shib,
397 shibbolethLoginUrl => login_shib_url( $in->{'query'} ),
400 # If shibboleth is enabled and we have a shibboleth login attribute,
401 # but we are in an anonymous session, then we clearly have an invalid
402 # shibboleth koha account.
403 if ($shib_login) {
404 $template->param( invalidShibLogin => '1' );
408 $template->param( sessionID => $sessionID );
410 if ( $in->{'type'} eq 'opac' ){
411 require Koha::Virtualshelves;
412 my $some_public_shelves = Koha::Virtualshelves->get_some_shelves(
414 category => 2,
417 $template->param(
418 some_public_shelves => $some_public_shelves,
423 # Anonymous opac search history
424 # If opac search history is enabled and at least one search has already been performed
425 if ( C4::Context->preference('EnableOpacSearchHistory') ) {
426 my @recentSearches = C4::Search::History::get_from_session( { cgi => $in->{'query'} } );
427 if (@recentSearches) {
428 $template->param( EnableOpacSearchHistory => 1 );
432 if ( C4::Context->preference('dateformat') ) {
433 $template->param( dateformat => C4::Context->preference('dateformat') );
436 $template->param(auth_forwarded_hash => scalar $in->{'query'}->param('auth_forwarded_hash'));
438 # these template parameters are set the same regardless of $in->{'type'}
440 # Set the using_https variable for templates
441 # FIXME Under Plack the CGI->https method always returns 'OFF'
442 my $https = $in->{query}->https();
443 my $using_https = ( defined $https and $https ne 'OFF' ) ? 1 : 0;
445 my $minPasswordLength = C4::Context->preference('minPasswordLength');
446 $minPasswordLength = 3 if not $minPasswordLength or $minPasswordLength < 3;
447 $template->param(
448 "BiblioDefaultView" . C4::Context->preference("BiblioDefaultView") => 1,
449 EnhancedMessagingPreferences => C4::Context->preference('EnhancedMessagingPreferences'),
450 GoogleJackets => C4::Context->preference("GoogleJackets"),
451 OpenLibraryCovers => C4::Context->preference("OpenLibraryCovers"),
452 KohaAdminEmailAddress => "" . C4::Context->preference("KohaAdminEmailAddress"),
453 LoginBranchcode => ( C4::Context->userenv ? C4::Context->userenv->{"branch"} : undef ),
454 LoginFirstname => ( C4::Context->userenv ? C4::Context->userenv->{"firstname"} : "Bel" ),
455 LoginSurname => C4::Context->userenv ? C4::Context->userenv->{"surname"} : "Inconnu",
456 emailaddress => C4::Context->userenv ? C4::Context->userenv->{"emailaddress"} : undef,
457 TagsEnabled => C4::Context->preference("TagsEnabled"),
458 hide_marc => C4::Context->preference("hide_marc"),
459 item_level_itypes => C4::Context->preference('item-level_itypes'),
460 patronimages => C4::Context->preference("patronimages"),
461 singleBranchMode => ( Koha::Libraries->search->count == 1 ),
462 XSLTDetailsDisplay => C4::Context->preference("XSLTDetailsDisplay"),
463 XSLTResultsDisplay => C4::Context->preference("XSLTResultsDisplay"),
464 using_https => $using_https,
465 noItemTypeImages => C4::Context->preference("noItemTypeImages"),
466 marcflavour => C4::Context->preference("marcflavour"),
467 OPACBaseURL => C4::Context->preference('OPACBaseURL'),
468 minPasswordLength => $minPasswordLength,
470 if ( $in->{'type'} eq "intranet" ) {
471 $template->param(
472 AmazonCoverImages => C4::Context->preference("AmazonCoverImages"),
473 AutoLocation => C4::Context->preference("AutoLocation"),
474 "BiblioDefaultView" . C4::Context->preference("IntranetBiblioDefaultView") => 1,
475 CircAutocompl => C4::Context->preference("CircAutocompl"),
476 FRBRizeEditions => C4::Context->preference("FRBRizeEditions"),
477 IndependentBranches => C4::Context->preference("IndependentBranches"),
478 IntranetNav => C4::Context->preference("IntranetNav"),
479 IntranetmainUserblock => C4::Context->preference("IntranetmainUserblock"),
480 LibraryName => C4::Context->preference("LibraryName"),
481 LoginBranchname => ( C4::Context->userenv ? C4::Context->userenv->{"branchname"} : undef ),
482 advancedMARCEditor => C4::Context->preference("advancedMARCEditor"),
483 canreservefromotherbranches => C4::Context->preference('canreservefromotherbranches'),
484 intranetcolorstylesheet => C4::Context->preference("intranetcolorstylesheet"),
485 IntranetFavicon => C4::Context->preference("IntranetFavicon"),
486 intranetreadinghistory => C4::Context->preference("intranetreadinghistory"),
487 intranetstylesheet => C4::Context->preference("intranetstylesheet"),
488 IntranetUserCSS => C4::Context->preference("IntranetUserCSS"),
489 IntranetUserJS => C4::Context->preference("IntranetUserJS"),
490 intranetbookbag => C4::Context->preference("intranetbookbag"),
491 suggestion => C4::Context->preference("suggestion"),
492 virtualshelves => C4::Context->preference("virtualshelves"),
493 StaffSerialIssueDisplayCount => C4::Context->preference("StaffSerialIssueDisplayCount"),
494 EasyAnalyticalRecords => C4::Context->preference('EasyAnalyticalRecords'),
495 LocalCoverImages => C4::Context->preference('LocalCoverImages'),
496 OPACLocalCoverImages => C4::Context->preference('OPACLocalCoverImages'),
497 AllowMultipleCovers => C4::Context->preference('AllowMultipleCovers'),
498 EnableBorrowerFiles => C4::Context->preference('EnableBorrowerFiles'),
499 UseKohaPlugins => C4::Context->preference('UseKohaPlugins'),
500 UseCourseReserves => C4::Context->preference("UseCourseReserves"),
501 useDischarge => C4::Context->preference('useDischarge')
504 else {
505 warn "template type should be OPAC, here it is=[" . $in->{'type'} . "]" unless ( $in->{'type'} eq 'opac' );
507 #TODO : replace LibraryName syspref with 'system name', and remove this html processing
508 my $LibraryNameTitle = C4::Context->preference("LibraryName");
509 $LibraryNameTitle =~ s/<(?:\/?)(?:br|p)\s*(?:\/?)>/ /sgi;
510 $LibraryNameTitle =~ s/<(?:[^<>'"]|'(?:[^']*)'|"(?:[^"]*)")*>//sg;
512 # clean up the busc param in the session
513 # if the page is not opac-detail and not the "add to list" page
514 # and not the "edit comments" page
515 if ( C4::Context->preference("OpacBrowseResults")
516 && $in->{'template_name'} =~ /opac-(.+)\.(?:tt|tmpl)$/ ) {
517 my $pagename = $1;
518 unless ( $pagename =~ /^(?:MARC|ISBD)?detail$/
519 or $pagename =~ /^addbybiblionumber$/
520 or $pagename =~ /^review$/ ) {
521 my $sessionSearch = get_session( $sessionID || $in->{'query'}->cookie("CGISESSID") );
522 $sessionSearch->clear( ["busc"] ) if ( $sessionSearch->param("busc") );
526 # variables passed from CGI: opac_css_override and opac_search_limits.
527 my $opac_search_limit = $ENV{'OPAC_SEARCH_LIMIT'};
528 my $opac_limit_override = $ENV{'OPAC_LIMIT_OVERRIDE'};
529 my $opac_name = '';
530 if (
531 ( $opac_limit_override && $opac_search_limit && $opac_search_limit =~ /branch:(\w+)/ ) ||
532 ( $in->{'query'}->param('limit') && $in->{'query'}->param('limit') =~ /branch:(\w+)/ ) ||
533 ( $in->{'query'}->param('multibranchlimit') && $in->{'query'}->param('multibranchlimit') =~ /multibranchlimit-(\w+)/ )
535 $opac_name = $1; # opac_search_limit is a branch, so we use it.
536 } elsif ( $in->{'query'}->param('multibranchlimit') ) {
537 $opac_name = $in->{'query'}->param('multibranchlimit');
538 } elsif ( C4::Context->preference("SearchMyLibraryFirst") && C4::Context->userenv && C4::Context->userenv->{'branch'} ) {
539 $opac_name = C4::Context->userenv->{'branch'};
542 my @search_groups = Koha::Library::Groups->get_search_groups({ interface => 'opac' });
543 $template->param(
544 OpacAdditionalStylesheet => C4::Context->preference("OpacAdditionalStylesheet"),
545 AnonSuggestions => "" . C4::Context->preference("AnonSuggestions"),
546 LibrarySearchGroups => \@search_groups,
547 opac_name => $opac_name,
548 LibraryName => "" . C4::Context->preference("LibraryName"),
549 LibraryNameTitle => "" . $LibraryNameTitle,
550 LoginBranchname => C4::Context->userenv ? C4::Context->userenv->{"branchname"} : "",
551 OPACAmazonCoverImages => C4::Context->preference("OPACAmazonCoverImages"),
552 OPACFRBRizeEditions => C4::Context->preference("OPACFRBRizeEditions"),
553 OpacHighlightedWords => C4::Context->preference("OpacHighlightedWords"),
554 OPACShelfBrowser => "" . C4::Context->preference("OPACShelfBrowser"),
555 OPACURLOpenInNewWindow => "" . C4::Context->preference("OPACURLOpenInNewWindow"),
556 OPACUserCSS => "" . C4::Context->preference("OPACUserCSS"),
557 OpacAuthorities => C4::Context->preference("OpacAuthorities"),
558 opac_css_override => $ENV{'OPAC_CSS_OVERRIDE'},
559 opac_search_limit => $opac_search_limit,
560 opac_limit_override => $opac_limit_override,
561 OpacBrowser => C4::Context->preference("OpacBrowser"),
562 OpacCloud => C4::Context->preference("OpacCloud"),
563 OpacKohaUrl => C4::Context->preference("OpacKohaUrl"),
564 OpacMainUserBlock => "" . C4::Context->preference("OpacMainUserBlock"),
565 OpacNav => "" . C4::Context->preference("OpacNav"),
566 OpacNavRight => "" . C4::Context->preference("OpacNavRight"),
567 OpacNavBottom => "" . C4::Context->preference("OpacNavBottom"),
568 OpacPasswordChange => C4::Context->preference("OpacPasswordChange"),
569 OPACPatronDetails => C4::Context->preference("OPACPatronDetails"),
570 OPACPrivacy => C4::Context->preference("OPACPrivacy"),
571 OPACFinesTab => C4::Context->preference("OPACFinesTab"),
572 OpacTopissue => C4::Context->preference("OpacTopissue"),
573 RequestOnOpac => C4::Context->preference("RequestOnOpac"),
574 'Version' => C4::Context->preference('Version'),
575 hidelostitems => C4::Context->preference("hidelostitems"),
576 mylibraryfirst => ( C4::Context->preference("SearchMyLibraryFirst") && C4::Context->userenv ) ? C4::Context->userenv->{'branch'} : '',
577 opaclayoutstylesheet => "" . C4::Context->preference("opaclayoutstylesheet"),
578 opacbookbag => "" . C4::Context->preference("opacbookbag"),
579 opaccredits => "" . C4::Context->preference("opaccredits"),
580 OpacFavicon => C4::Context->preference("OpacFavicon"),
581 opacheader => "" . C4::Context->preference("opacheader"),
582 opaclanguagesdisplay => "" . C4::Context->preference("opaclanguagesdisplay"),
583 opacreadinghistory => C4::Context->preference("opacreadinghistory"),
584 OPACUserJS => C4::Context->preference("OPACUserJS"),
585 opacuserlogin => "" . C4::Context->preference("opacuserlogin"),
586 OpenLibrarySearch => C4::Context->preference("OpenLibrarySearch"),
587 ShowReviewer => C4::Context->preference("ShowReviewer"),
588 ShowReviewerPhoto => C4::Context->preference("ShowReviewerPhoto"),
589 suggestion => "" . C4::Context->preference("suggestion"),
590 virtualshelves => "" . C4::Context->preference("virtualshelves"),
591 OPACSerialIssueDisplayCount => C4::Context->preference("OPACSerialIssueDisplayCount"),
592 OPACXSLTDetailsDisplay => C4::Context->preference("OPACXSLTDetailsDisplay"),
593 OPACXSLTResultsDisplay => C4::Context->preference("OPACXSLTResultsDisplay"),
594 SyndeticsClientCode => C4::Context->preference("SyndeticsClientCode"),
595 SyndeticsEnabled => C4::Context->preference("SyndeticsEnabled"),
596 SyndeticsCoverImages => C4::Context->preference("SyndeticsCoverImages"),
597 SyndeticsTOC => C4::Context->preference("SyndeticsTOC"),
598 SyndeticsSummary => C4::Context->preference("SyndeticsSummary"),
599 SyndeticsEditions => C4::Context->preference("SyndeticsEditions"),
600 SyndeticsExcerpt => C4::Context->preference("SyndeticsExcerpt"),
601 SyndeticsReviews => C4::Context->preference("SyndeticsReviews"),
602 SyndeticsAuthorNotes => C4::Context->preference("SyndeticsAuthorNotes"),
603 SyndeticsAwards => C4::Context->preference("SyndeticsAwards"),
604 SyndeticsSeries => C4::Context->preference("SyndeticsSeries"),
605 SyndeticsCoverImageSize => C4::Context->preference("SyndeticsCoverImageSize"),
606 OPACLocalCoverImages => C4::Context->preference("OPACLocalCoverImages"),
607 PatronSelfRegistration => C4::Context->preference("PatronSelfRegistration"),
608 PatronSelfRegistrationDefaultCategory => C4::Context->preference("PatronSelfRegistrationDefaultCategory"),
609 useDischarge => C4::Context->preference('useDischarge'),
612 $template->param( OpacPublic => '1' ) if ( $user || C4::Context->preference("OpacPublic") );
615 # Check if we were asked using parameters to force a specific language
616 if ( defined $in->{'query'}->param('language') ) {
618 # Extract the language, let C4::Languages::getlanguage choose
619 # what to do
620 my $language = C4::Languages::getlanguage( $in->{'query'} );
621 my $languagecookie = C4::Templates::getlanguagecookie( $in->{'query'}, $language );
622 if ( ref $cookie eq 'ARRAY' ) {
623 push @{$cookie}, $languagecookie;
624 } else {
625 $cookie = [ $cookie, $languagecookie ];
629 return ( $template, $borrowernumber, $cookie, $flags );
632 =head2 checkauth
634 ($userid, $cookie, $sessionID) = &checkauth($query, $noauth, $flagsrequired, $type);
636 Verifies that the user is authorized to run this script. If
637 the user is authorized, a (userid, cookie, session-id, flags)
638 quadruple is returned. If the user is not authorized but does
639 not have the required privilege (see $flagsrequired below), it
640 displays an error page and exits. Otherwise, it displays the
641 login page and exits.
643 Note that C<&checkauth> will return if and only if the user
644 is authorized, so it should be called early on, before any
645 unfinished operations (e.g., if you've opened a file, then
646 C<&checkauth> won't close it for you).
648 C<$query> is the CGI object for the script calling C<&checkauth>.
650 The C<$noauth> argument is optional. If it is set, then no
651 authorization is required for the script.
653 C<&checkauth> fetches user and session information from C<$query> and
654 ensures that the user is authorized to run scripts that require
655 authorization.
657 The C<$flagsrequired> argument specifies the required privileges
658 the user must have if the username and password are correct.
659 It should be specified as a reference-to-hash; keys in the hash
660 should be the "flags" for the user, as specified in the Members
661 intranet module. Any key specified must correspond to a "flag"
662 in the userflags table. E.g., { circulate => 1 } would specify
663 that the user must have the "circulate" privilege in order to
664 proceed. To make sure that access control is correct, the
665 C<$flagsrequired> parameter must be specified correctly.
667 Koha also has a concept of sub-permissions, also known as
668 granular permissions. This makes the value of each key
669 in the C<flagsrequired> hash take on an additional
670 meaning, i.e.,
674 The user must have access to all subfunctions of the module
675 specified by the hash key.
679 The user must have access to at least one subfunction of the module
680 specified by the hash key.
682 specific permission, e.g., 'export_catalog'
684 The user must have access to the specific subfunction list, which
685 must correspond to a row in the permissions table.
687 The C<$type> argument specifies whether the template should be
688 retrieved from the opac or intranet directory tree. "opac" is
689 assumed if it is not specified; however, if C<$type> is specified,
690 "intranet" is assumed if it is not "opac".
692 If C<$query> does not have a valid session ID associated with it
693 (i.e., the user has not logged in) or if the session has expired,
694 C<&checkauth> presents the user with a login page (from the point of
695 view of the original script, C<&checkauth> does not return). Once the
696 user has authenticated, C<&checkauth> restarts the original script
697 (this time, C<&checkauth> returns).
699 The login page is provided using a HTML::Template, which is set in the
700 systempreferences table or at the top of this file. The variable C<$type>
701 selects which template to use, either the opac or the intranet
702 authentification template.
704 C<&checkauth> returns a user ID, a cookie, and a session ID. The
705 cookie should be sent back to the browser; it verifies that the user
706 has authenticated.
708 =cut
710 sub _version_check {
711 my $type = shift;
712 my $query = shift;
713 my $version;
715 # If version syspref is unavailable, it means Koha is being installed,
716 # and so we must redirect to OPAC maintenance page or to the WebInstaller
717 # also, if OpacMaintenance is ON, OPAC should redirect to maintenance
718 if ( C4::Context->preference('OpacMaintenance') && $type eq 'opac' ) {
719 warn "OPAC Install required, redirecting to maintenance";
720 print $query->redirect("/cgi-bin/koha/maintenance.pl");
721 safe_exit;
723 unless ( $version = C4::Context->preference('Version') ) { # assignment, not comparison
724 if ( $type ne 'opac' ) {
725 warn "Install required, redirecting to Installer";
726 print $query->redirect("/cgi-bin/koha/installer/install.pl");
727 } else {
728 warn "OPAC Install required, redirecting to maintenance";
729 print $query->redirect("/cgi-bin/koha/maintenance.pl");
731 safe_exit;
734 # check that database and koha version are the same
735 # there is no DB version, it's a fresh install,
736 # go to web installer
737 # there is a DB version, compare it to the code version
738 my $kohaversion = Koha::version();
740 # remove the 3 last . to have a Perl number
741 $kohaversion =~ s/(.*\..*)\.(.*)\.(.*)/$1$2$3/;
742 $debug and print STDERR "kohaversion : $kohaversion\n";
743 if ( $version < $kohaversion ) {
744 my $warning = "Database update needed, redirecting to %s. Database is $version and Koha is $kohaversion";
745 if ( $type ne 'opac' ) {
746 warn sprintf( $warning, 'Installer' );
747 print $query->redirect("/cgi-bin/koha/installer/install.pl?step=1&op=updatestructure");
748 } else {
749 warn sprintf( "OPAC: " . $warning, 'maintenance' );
750 print $query->redirect("/cgi-bin/koha/maintenance.pl");
752 safe_exit;
756 sub _session_log {
757 (@_) or return 0;
758 open my $fh, '>>', "/tmp/sessionlog" or warn "ERROR: Cannot append to /tmp/sessionlog";
759 printf $fh join( "\n", @_ );
760 close $fh;
763 sub _timeout_syspref {
764 my $timeout = C4::Context->preference('timeout') || 600;
766 # value in days, convert in seconds
767 if ( $timeout =~ /(\d+)[dD]/ ) {
768 $timeout = $1 * 86400;
770 return $timeout;
773 sub checkauth {
774 my $query = shift;
775 $debug and warn "Checking Auth";
776 # $authnotrequired will be set for scripts which will run without authentication
777 my $authnotrequired = shift;
778 my $flagsrequired = shift;
779 my $type = shift;
780 my $emailaddress = shift;
781 $type = 'opac' unless $type;
783 my $dbh = C4::Context->dbh;
784 my $timeout = _timeout_syspref();
786 _version_check( $type, $query );
788 # state variables
789 my $loggedin = 0;
790 my %info;
791 my ( $userid, $cookie, $sessionID, $flags );
792 my $logout = $query->param('logout.x');
794 my $anon_search_history;
795 my $cas_ticket = '';
796 # This parameter is the name of the CAS server we want to authenticate against,
797 # when using authentication against multiple CAS servers, as configured in Auth_cas_servers.yaml
798 my $casparam = $query->param('cas');
799 my $q_userid = $query->param('userid') // '';
801 my $session;
803 # Basic authentication is incompatible with the use of Shibboleth,
804 # as Shibboleth may return REMOTE_USER as a Shibboleth attribute,
805 # and it may not be the attribute we want to use to match the koha login.
807 # Also, do not consider an empty REMOTE_USER.
809 # Finally, after those tests, we can assume (although if it would be better with
810 # a syspref) that if we get a REMOTE_USER, that's from basic authentication,
811 # and we can affect it to $userid.
812 if ( !$shib and defined( $ENV{'REMOTE_USER'} ) and $ENV{'REMOTE_USER'} ne '' and $userid = $ENV{'REMOTE_USER'} ) {
814 # Using Basic Authentication, no cookies required
815 $cookie = $query->cookie(
816 -name => 'CGISESSID',
817 -value => '',
818 -expires => '',
819 -HttpOnly => 1,
821 $loggedin = 1;
823 elsif ( $emailaddress) {
824 # the Google OpenID Connect passes an email address
826 elsif ( $sessionID = $query->cookie("CGISESSID") )
827 { # assignment, not comparison
828 $session = get_session($sessionID);
829 C4::Context->_new_userenv($sessionID);
830 my ( $ip, $lasttime, $sessiontype );
831 my $s_userid = '';
832 if ($session) {
833 $s_userid = $session->param('id') // '';
834 C4::Context->set_userenv(
835 $session->param('number'), $s_userid,
836 $session->param('cardnumber'), $session->param('firstname'),
837 $session->param('surname'), $session->param('branch'),
838 $session->param('branchname'), $session->param('flags'),
839 $session->param('emailaddress'), $session->param('branchprinter'),
840 $session->param('shibboleth')
842 C4::Context::set_shelves_userenv( 'bar', $session->param('barshelves') );
843 C4::Context::set_shelves_userenv( 'pub', $session->param('pubshelves') );
844 C4::Context::set_shelves_userenv( 'tot', $session->param('totshelves') );
845 $debug and printf STDERR "AUTH_SESSION: (%s)\t%s %s - %s\n", map { $session->param($_) } qw(cardnumber firstname surname branch);
846 $ip = $session->param('ip');
847 $lasttime = $session->param('lasttime');
848 $userid = $s_userid;
849 $sessiontype = $session->param('sessiontype') || '';
851 if ( ( $query->param('koha_login_context') && ( $q_userid ne $s_userid ) )
852 || ( $cas && $query->param('ticket') && !C4::Context->userenv->{'id'} )
853 || ( $shib && $shib_login && !$logout && !C4::Context->userenv->{'id'} )
856 #if a user enters an id ne to the id in the current session, we need to log them in...
857 #first we need to clear the anonymous session...
858 $debug and warn "query id = $q_userid but session id = $s_userid";
859 $anon_search_history = $session->param('search_history');
860 $session->delete();
861 $session->flush;
862 C4::Context->_unset_userenv($sessionID);
863 $sessionID = undef;
864 $userid = undef;
866 elsif ($logout) {
868 # voluntary logout the user
869 # check wether the user was using their shibboleth session or a local one
870 my $shibSuccess = C4::Context->userenv->{'shibboleth'};
871 $session->delete();
872 $session->flush;
873 C4::Context->_unset_userenv($sessionID);
875 #_session_log(sprintf "%20s from %16s logged out at %30s (manually).\n", $userid,$ip,(strftime "%c",localtime));
876 $sessionID = undef;
877 $userid = undef;
879 if ($cas and $caslogout) {
880 logout_cas($query, $type);
883 # If we are in a shibboleth session (shibboleth is enabled, a shibboleth match attribute is set and matches koha matchpoint)
884 if ( $shib and $shib_login and $shibSuccess and $type eq 'opac' ) {
886 # (Note: $type eq 'opac' condition should be removed when shibboleth authentication for intranet will be implemented)
887 logout_shib($query);
890 elsif ( !$lasttime || ( $lasttime < time() - $timeout ) ) {
892 # timed logout
893 $info{'timed_out'} = 1;
894 if ($session) {
895 $session->delete();
896 $session->flush;
898 C4::Context->_unset_userenv($sessionID);
900 #_session_log(sprintf "%20s from %16s logged out at %30s (inactivity).\n", $userid,$ip,(strftime "%c",localtime));
901 $userid = undef;
902 $sessionID = undef;
904 elsif ( C4::Context->preference('SessionRestrictionByIP') && $ip ne $ENV{'REMOTE_ADDR'} ) {
906 # Different ip than originally logged in from
907 $info{'oldip'} = $ip;
908 $info{'newip'} = $ENV{'REMOTE_ADDR'};
909 $info{'different_ip'} = 1;
910 $session->delete();
911 $session->flush;
912 C4::Context->_unset_userenv($sessionID);
914 #_session_log(sprintf "%20s from %16s logged out at %30s (ip changed to %16s).\n", $userid,$ip,(strftime "%c",localtime), $info{'newip'});
915 $sessionID = undef;
916 $userid = undef;
918 else {
919 $cookie = $query->cookie(
920 -name => 'CGISESSID',
921 -value => $session->id,
922 -HttpOnly => 1
924 $session->param( 'lasttime', time() );
925 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...
926 $flags = haspermission( $userid, $flagsrequired );
927 if ($flags) {
928 $loggedin = 1;
929 } else {
930 $info{'nopermission'} = 1;
935 unless ( $userid || $sessionID ) {
936 #we initiate a session prior to checking for a username to allow for anonymous sessions...
937 my $session = get_session("") or die "Auth ERROR: Cannot get_session()";
939 # Save anonymous search history in new session so it can be retrieved
940 # by get_template_and_user to store it in user's search history after
941 # a successful login.
942 if ($anon_search_history) {
943 $session->param( 'search_history', $anon_search_history );
946 my $sessionID = $session->id;
947 C4::Context->_new_userenv($sessionID);
948 $cookie = $query->cookie(
949 -name => 'CGISESSID',
950 -value => $session->id,
951 -HttpOnly => 1
953 my $pki_field = C4::Context->preference('AllowPKIAuth');
954 if ( !defined($pki_field) ) {
955 print STDERR "ERROR: Missing system preference AllowPKIAuth.\n";
956 $pki_field = 'None';
958 if ( ( $cas && $query->param('ticket') )
959 || $q_userid
960 || ( $shib && $shib_login )
961 || $pki_field ne 'None'
962 || $emailaddress )
964 my $password = $query->param('password');
965 my $shibSuccess = 0;
966 my ( $return, $cardnumber );
968 # If shib is enabled and we have a shib login, does the login match a valid koha user
969 if ( $shib && $shib_login && $type eq 'opac' ) {
970 my $retuserid;
972 # Do not pass password here, else shib will not be checked in checkpw.
973 ( $return, $cardnumber, $retuserid ) = checkpw( $dbh, $q_userid, undef, $query );
974 $userid = $retuserid;
975 $shibSuccess = $return;
976 $info{'invalidShibLogin'} = 1 unless ($return);
979 # If shib login and match were successful, skip further login methods
980 unless ($shibSuccess) {
981 if ( $cas && $query->param('ticket') ) {
982 my $retuserid;
983 ( $return, $cardnumber, $retuserid, $cas_ticket ) =
984 checkpw( $dbh, $userid, $password, $query, $type );
985 $userid = $retuserid;
986 $info{'invalidCasLogin'} = 1 unless ($return);
989 elsif ( $emailaddress ) {
990 my $value = $emailaddress;
992 # If we're looking up the email, there's a chance that the person
993 # doesn't have a userid. So if there is none, we pass along the
994 # borrower number, and the bits of code that need to know the user
995 # ID will have to be smart enough to handle that.
996 my $patrons = Koha::Patrons->search({ email => $value });
997 if ($patrons->count) {
999 # First the userid, then the borrowernum
1000 my $patron = $patrons->next;
1001 $value = $patron->userid || $patron->borrowernumber;
1002 } else {
1003 undef $value;
1005 $return = $value ? 1 : 0;
1006 $userid = $value;
1009 elsif (
1010 ( $pki_field eq 'Common Name' && $ENV{'SSL_CLIENT_S_DN_CN'} )
1011 || ( $pki_field eq 'emailAddress'
1012 && $ENV{'SSL_CLIENT_S_DN_Email'} )
1015 my $value;
1016 if ( $pki_field eq 'Common Name' ) {
1017 $value = $ENV{'SSL_CLIENT_S_DN_CN'};
1019 elsif ( $pki_field eq 'emailAddress' ) {
1020 $value = $ENV{'SSL_CLIENT_S_DN_Email'};
1022 # If we're looking up the email, there's a chance that the person
1023 # doesn't have a userid. So if there is none, we pass along the
1024 # borrower number, and the bits of code that need to know the user
1025 # ID will have to be smart enough to handle that.
1026 my $patrons = Koha::Patrons->search({ email => $value });
1027 if ($patrons->count) {
1029 # First the userid, then the borrowernum
1030 my $patron = $patrons->next;
1031 $value = $patron->userid || $patron->borrowernumber;
1032 } else {
1033 undef $value;
1037 $return = $value ? 1 : 0;
1038 $userid = $value;
1041 else {
1042 my $retuserid;
1043 ( $return, $cardnumber, $retuserid, $cas_ticket ) =
1044 checkpw( $dbh, $q_userid, $password, $query, $type );
1045 $userid = $retuserid if ($retuserid);
1046 $info{'invalid_username_or_password'} = 1 unless ($return);
1050 # $return: 1 = valid user
1051 if ($return) {
1053 #_session_log(sprintf "%20s from %16s logged in at %30s.\n", $userid,$ENV{'REMOTE_ADDR'},(strftime '%c', localtime));
1054 if ( $flags = haspermission( $userid, $flagsrequired ) ) {
1055 $loggedin = 1;
1057 else {
1058 $info{'nopermission'} = 1;
1059 C4::Context->_unset_userenv($sessionID);
1061 my ( $borrowernumber, $firstname, $surname, $userflags,
1062 $branchcode, $branchname, $branchprinter, $emailaddress );
1064 if ( $return == 1 ) {
1065 my $select = "
1066 SELECT borrowernumber, firstname, surname, flags, borrowers.branchcode,
1067 branches.branchname as branchname,
1068 branches.branchprinter as branchprinter,
1069 email
1070 FROM borrowers
1071 LEFT JOIN branches on borrowers.branchcode=branches.branchcode
1073 my $sth = $dbh->prepare("$select where userid=?");
1074 $sth->execute($userid);
1075 unless ( $sth->rows ) {
1076 $debug and print STDERR "AUTH_1: no rows for userid='$userid'\n";
1077 $sth = $dbh->prepare("$select where cardnumber=?");
1078 $sth->execute($cardnumber);
1080 unless ( $sth->rows ) {
1081 $debug and print STDERR "AUTH_2a: no rows for cardnumber='$cardnumber'\n";
1082 $sth->execute($userid);
1083 unless ( $sth->rows ) {
1084 $debug and print STDERR "AUTH_2b: no rows for userid='$userid' AS cardnumber\n";
1088 if ( $sth->rows ) {
1089 ( $borrowernumber, $firstname, $surname, $userflags,
1090 $branchcode, $branchname, $branchprinter, $emailaddress ) = $sth->fetchrow;
1091 $debug and print STDERR "AUTH_3 results: " .
1092 "$cardnumber,$borrowernumber,$userid,$firstname,$surname,$userflags,$branchcode,$emailaddress\n";
1093 } else {
1094 print STDERR "AUTH_3: no results for userid='$userid', cardnumber='$cardnumber'.\n";
1097 # launch a sequence to check if we have a ip for the branch, i
1098 # if we have one we replace the branchcode of the userenv by the branch bound in the ip.
1100 my $ip = $ENV{'REMOTE_ADDR'};
1102 # if they specify at login, use that
1103 if ( $query->param('branch') ) {
1104 $branchcode = $query->param('branch');
1105 my $library = Koha::Libraries->find($branchcode);
1106 $branchname = $library? $library->branchname: '';
1108 my $branches = { map { $_->branchcode => $_->unblessed } Koha::Libraries->search };
1109 if ( $type ne 'opac' and C4::Context->boolean_preference('AutoLocation') ) {
1111 # we have to check they are coming from the right ip range
1112 my $domain = $branches->{$branchcode}->{'branchip'};
1113 $domain =~ s|\.\*||g;
1114 if ( $ip !~ /^$domain/ ) {
1115 $loggedin = 0;
1116 $cookie = $query->cookie(
1117 -name => 'CGISESSID',
1118 -value => '',
1119 -HttpOnly => 1
1121 $info{'wrongip'} = 1;
1125 foreach my $br ( keys %$branches ) {
1127 # now we work with the treatment of ip
1128 my $domain = $branches->{$br}->{'branchip'};
1129 if ( $domain && $ip =~ /^$domain/ ) {
1130 $branchcode = $branches->{$br}->{'branchcode'};
1132 # new op dev : add the branchprinter and branchname in the cookie
1133 $branchprinter = $branches->{$br}->{'branchprinter'};
1134 $branchname = $branches->{$br}->{'branchname'};
1137 $session->param( 'number', $borrowernumber );
1138 $session->param( 'id', $userid );
1139 $session->param( 'cardnumber', $cardnumber );
1140 $session->param( 'firstname', $firstname );
1141 $session->param( 'surname', $surname );
1142 $session->param( 'branch', $branchcode );
1143 $session->param( 'branchname', $branchname );
1144 $session->param( 'flags', $userflags );
1145 $session->param( 'emailaddress', $emailaddress );
1146 $session->param( 'ip', $session->remote_addr() );
1147 $session->param( 'lasttime', time() );
1148 $session->param( 'shibboleth', $shibSuccess );
1149 $debug and printf STDERR "AUTH_4: (%s)\t%s %s - %s\n", map { $session->param($_) } qw(cardnumber firstname surname branch);
1151 $session->param('cas_ticket', $cas_ticket) if $cas_ticket;
1152 C4::Context->set_userenv(
1153 $session->param('number'), $session->param('id'),
1154 $session->param('cardnumber'), $session->param('firstname'),
1155 $session->param('surname'), $session->param('branch'),
1156 $session->param('branchname'), $session->param('flags'),
1157 $session->param('emailaddress'), $session->param('branchprinter'),
1158 $session->param('shibboleth')
1162 # $return: 0 = invalid user
1163 # reset to anonymous session
1164 else {
1165 $debug and warn "Login failed, resetting anonymous session...";
1166 if ($userid) {
1167 $info{'invalid_username_or_password'} = 1;
1168 C4::Context->_unset_userenv($sessionID);
1170 $session->param( 'lasttime', time() );
1171 $session->param( 'ip', $session->remote_addr() );
1172 $session->param( 'sessiontype', 'anon' );
1174 } # END if ( $q_userid
1175 elsif ( $type eq "opac" ) {
1177 # if we are here this is an anonymous session; add public lists to it and a few other items...
1178 # anonymous sessions are created only for the OPAC
1179 $debug and warn "Initiating an anonymous session...";
1181 # setting a couple of other session vars...
1182 $session->param( 'ip', $session->remote_addr() );
1183 $session->param( 'lasttime', time() );
1184 $session->param( 'sessiontype', 'anon' );
1186 } # END unless ($userid)
1188 # finished authentification, now respond
1189 if ( $loggedin || $authnotrequired )
1191 # successful login
1192 unless ($cookie) {
1193 $cookie = $query->cookie(
1194 -name => 'CGISESSID',
1195 -value => '',
1196 -HttpOnly => 1
1200 track_login_daily( $userid );
1202 return ( $userid, $cookie, $sessionID, $flags );
1207 # AUTH rejected, show the login/password template, after checking the DB.
1211 # get the inputs from the incoming query
1212 my @inputs = ();
1213 foreach my $name ( param $query) {
1214 (next) if ( $name eq 'userid' || $name eq 'password' || $name eq 'ticket' );
1215 my $value = $query->param($name);
1216 push @inputs, { name => $name, value => $value };
1219 my $patron = Koha::Patrons->find({ userid => $q_userid }); # Not necessary logged in!
1221 my $LibraryNameTitle = C4::Context->preference("LibraryName");
1222 $LibraryNameTitle =~ s/<(?:\/?)(?:br|p)\s*(?:\/?)>/ /sgi;
1223 $LibraryNameTitle =~ s/<(?:[^<>'"]|'(?:[^']*)'|"(?:[^"]*)")*>//sg;
1225 my $template_name = ( $type eq 'opac' ) ? 'opac-auth.tt' : 'auth.tt';
1226 my $template = C4::Templates::gettemplate( $template_name, $type, $query );
1227 $template->param(
1228 OpacAdditionalStylesheet => C4::Context->preference("OpacAdditionalStylesheet"),
1229 opaclayoutstylesheet => C4::Context->preference("opaclayoutstylesheet"),
1230 login => 1,
1231 INPUTS => \@inputs,
1232 script_name => get_script_name(),
1233 casAuthentication => C4::Context->preference("casAuthentication"),
1234 shibbolethAuthentication => $shib,
1235 SessionRestrictionByIP => C4::Context->preference("SessionRestrictionByIP"),
1236 suggestion => C4::Context->preference("suggestion"),
1237 virtualshelves => C4::Context->preference("virtualshelves"),
1238 LibraryName => "" . C4::Context->preference("LibraryName"),
1239 LibraryNameTitle => "" . $LibraryNameTitle,
1240 opacuserlogin => C4::Context->preference("opacuserlogin"),
1241 OpacNav => C4::Context->preference("OpacNav"),
1242 OpacNavRight => C4::Context->preference("OpacNavRight"),
1243 OpacNavBottom => C4::Context->preference("OpacNavBottom"),
1244 opaccredits => C4::Context->preference("opaccredits"),
1245 OpacFavicon => C4::Context->preference("OpacFavicon"),
1246 opacreadinghistory => C4::Context->preference("opacreadinghistory"),
1247 opaclanguagesdisplay => C4::Context->preference("opaclanguagesdisplay"),
1248 OPACUserJS => C4::Context->preference("OPACUserJS"),
1249 opacbookbag => "" . C4::Context->preference("opacbookbag"),
1250 OpacCloud => C4::Context->preference("OpacCloud"),
1251 OpacTopissue => C4::Context->preference("OpacTopissue"),
1252 OpacAuthorities => C4::Context->preference("OpacAuthorities"),
1253 OpacBrowser => C4::Context->preference("OpacBrowser"),
1254 opacheader => C4::Context->preference("opacheader"),
1255 TagsEnabled => C4::Context->preference("TagsEnabled"),
1256 OPACUserCSS => C4::Context->preference("OPACUserCSS"),
1257 intranetcolorstylesheet => C4::Context->preference("intranetcolorstylesheet"),
1258 intranetstylesheet => C4::Context->preference("intranetstylesheet"),
1259 intranetbookbag => C4::Context->preference("intranetbookbag"),
1260 IntranetNav => C4::Context->preference("IntranetNav"),
1261 IntranetFavicon => C4::Context->preference("IntranetFavicon"),
1262 IntranetUserCSS => C4::Context->preference("IntranetUserCSS"),
1263 IntranetUserJS => C4::Context->preference("IntranetUserJS"),
1264 IndependentBranches => C4::Context->preference("IndependentBranches"),
1265 AutoLocation => C4::Context->preference("AutoLocation"),
1266 wrongip => $info{'wrongip'},
1267 PatronSelfRegistration => C4::Context->preference("PatronSelfRegistration"),
1268 PatronSelfRegistrationDefaultCategory => C4::Context->preference("PatronSelfRegistrationDefaultCategory"),
1269 opac_css_override => $ENV{'OPAC_CSS_OVERRIDE'},
1270 too_many_login_attempts => ( $patron and $patron->account_locked )
1273 $template->param( SCO_login => 1 ) if ( $query->param('sco_user_login') );
1274 $template->param( SCI_login => 1 ) if ( $query->param('sci_user_login') );
1275 $template->param( OpacPublic => C4::Context->preference("OpacPublic") );
1276 $template->param( loginprompt => 1 ) unless $info{'nopermission'};
1278 if ( $type eq 'opac' ) {
1279 require Koha::Virtualshelves;
1280 my $some_public_shelves = Koha::Virtualshelves->get_some_shelves(
1282 category => 2,
1285 $template->param(
1286 some_public_shelves => $some_public_shelves,
1290 if ($cas) {
1292 # Is authentication against multiple CAS servers enabled?
1293 if ( C4::Auth_with_cas::multipleAuth && !$casparam ) {
1294 my $casservers = C4::Auth_with_cas::getMultipleAuth();
1295 my @tmplservers;
1296 foreach my $key ( keys %$casservers ) {
1297 push @tmplservers, { name => $key, value => login_cas_url( $query, $key, $type ) . "?cas=$key" };
1299 $template->param(
1300 casServersLoop => \@tmplservers
1302 } else {
1303 $template->param(
1304 casServerUrl => login_cas_url($query, undef, $type),
1308 $template->param(
1309 invalidCasLogin => $info{'invalidCasLogin'}
1313 if ($shib) {
1314 $template->param(
1315 shibbolethAuthentication => $shib,
1316 shibbolethLoginUrl => login_shib_url($query),
1320 if (C4::Context->preference('GoogleOpenIDConnect')) {
1321 if ($query->param("OpenIDConnectFailed")) {
1322 my $reason = $query->param('OpenIDConnectFailed');
1323 $template->param(invalidGoogleOpenIDConnectLogin => $reason);
1327 $template->param(
1328 LibraryName => C4::Context->preference("LibraryName"),
1330 $template->param(%info);
1332 # $cookie = $query->cookie(CGISESSID => $session->id
1333 # );
1334 print $query->header(
1335 { type => 'text/html',
1336 charset => 'utf-8',
1337 cookie => $cookie,
1338 'X-Frame-Options' => 'SAMEORIGIN'
1341 $template->output;
1342 safe_exit;
1345 =head2 check_api_auth
1347 ($status, $cookie, $sessionId) = check_api_auth($query, $userflags);
1349 Given a CGI query containing the parameters 'userid' and 'password' and/or a session
1350 cookie, determine if the user has the privileges specified by C<$userflags>.
1352 C<check_api_auth> is is meant for authenticating users of web services, and
1353 consequently will always return and will not attempt to redirect the user
1354 agent.
1356 If a valid session cookie is already present, check_api_auth will return a status
1357 of "ok", the cookie, and the Koha session ID.
1359 If no session cookie is present, check_api_auth will check the 'userid' and 'password
1360 parameters and create a session cookie and Koha session if the supplied credentials
1361 are OK.
1363 Possible return values in C<$status> are:
1365 =over
1367 =item "ok" -- user authenticated; C<$cookie> and C<$sessionid> have valid values.
1369 =item "failed" -- credentials are not correct; C<$cookie> and C<$sessionid> are undef
1371 =item "maintenance" -- DB is in maintenance mode; no login possible at the moment
1373 =item "expired -- session cookie has expired; API user should resubmit userid and password
1375 =back
1377 =cut
1379 sub check_api_auth {
1381 my $query = shift;
1382 my $flagsrequired = shift;
1383 my $dbh = C4::Context->dbh;
1384 my $timeout = _timeout_syspref();
1386 unless ( C4::Context->preference('Version') ) {
1388 # database has not been installed yet
1389 return ( "maintenance", undef, undef );
1391 my $kohaversion = Koha::version();
1392 $kohaversion =~ s/(.*\..*)\.(.*)\.(.*)/$1$2$3/;
1393 if ( C4::Context->preference('Version') < $kohaversion ) {
1395 # database in need of version update; assume that
1396 # no API should be called while databsae is in
1397 # this condition.
1398 return ( "maintenance", undef, undef );
1401 # FIXME -- most of what follows is a copy-and-paste
1402 # of code from checkauth. There is an obvious need
1403 # for refactoring to separate the various parts of
1404 # the authentication code, but as of 2007-11-19 this
1405 # is deferred so as to not introduce bugs into the
1406 # regular authentication code for Koha 3.0.
1408 # see if we have a valid session cookie already
1409 # however, if a userid parameter is present (i.e., from
1410 # a form submission, assume that any current cookie
1411 # is to be ignored
1412 my $sessionID = undef;
1413 unless ( $query->param('userid') ) {
1414 $sessionID = $query->cookie("CGISESSID");
1416 if ( $sessionID && not( $cas && $query->param('PT') ) ) {
1417 my $session = get_session($sessionID);
1418 C4::Context->_new_userenv($sessionID);
1419 if ($session) {
1420 C4::Context->set_userenv(
1421 $session->param('number'), $session->param('id'),
1422 $session->param('cardnumber'), $session->param('firstname'),
1423 $session->param('surname'), $session->param('branch'),
1424 $session->param('branchname'), $session->param('flags'),
1425 $session->param('emailaddress'), $session->param('branchprinter')
1428 my $ip = $session->param('ip');
1429 my $lasttime = $session->param('lasttime');
1430 my $userid = $session->param('id');
1431 if ( $lasttime < time() - $timeout ) {
1433 # time out
1434 $session->delete();
1435 $session->flush;
1436 C4::Context->_unset_userenv($sessionID);
1437 $userid = undef;
1438 $sessionID = undef;
1439 return ( "expired", undef, undef );
1440 } elsif ( C4::Context->preference('SessionRestrictionByIP') && $ip ne $ENV{'REMOTE_ADDR'} ) {
1442 # IP address changed
1443 $session->delete();
1444 $session->flush;
1445 C4::Context->_unset_userenv($sessionID);
1446 $userid = undef;
1447 $sessionID = undef;
1448 return ( "expired", undef, undef );
1449 } else {
1450 my $cookie = $query->cookie(
1451 -name => 'CGISESSID',
1452 -value => $session->id,
1453 -HttpOnly => 1,
1455 $session->param( 'lasttime', time() );
1456 my $flags = haspermission( $userid, $flagsrequired );
1457 if ($flags) {
1458 return ( "ok", $cookie, $sessionID );
1459 } else {
1460 $session->delete();
1461 $session->flush;
1462 C4::Context->_unset_userenv($sessionID);
1463 $userid = undef;
1464 $sessionID = undef;
1465 return ( "failed", undef, undef );
1468 } else {
1469 return ( "expired", undef, undef );
1471 } else {
1473 # new login
1474 my $userid = $query->param('userid');
1475 my $password = $query->param('password');
1476 my ( $return, $cardnumber, $cas_ticket );
1478 # Proxy CAS auth
1479 if ( $cas && $query->param('PT') ) {
1480 my $retuserid;
1481 $debug and print STDERR "## check_api_auth - checking CAS\n";
1483 # In case of a CAS authentication, we use the ticket instead of the password
1484 my $PT = $query->param('PT');
1485 ( $return, $cardnumber, $userid, $cas_ticket ) = check_api_auth_cas( $dbh, $PT, $query ); # EXTERNAL AUTH
1486 } else {
1488 # User / password auth
1489 unless ( $userid and $password ) {
1491 # caller did something wrong, fail the authenticateion
1492 return ( "failed", undef, undef );
1494 my $newuserid;
1495 ( $return, $cardnumber, $newuserid, $cas_ticket ) = checkpw( $dbh, $userid, $password, $query );
1498 if ( $return and haspermission( $userid, $flagsrequired ) ) {
1499 my $session = get_session("");
1500 return ( "failed", undef, undef ) unless $session;
1502 my $sessionID = $session->id;
1503 C4::Context->_new_userenv($sessionID);
1504 my $cookie = $query->cookie(
1505 -name => 'CGISESSID',
1506 -value => $sessionID,
1507 -HttpOnly => 1,
1509 if ( $return == 1 ) {
1510 my (
1511 $borrowernumber, $firstname, $surname,
1512 $userflags, $branchcode, $branchname,
1513 $branchprinter, $emailaddress
1515 my $sth =
1516 $dbh->prepare(
1517 "select borrowernumber, firstname, surname, flags, borrowers.branchcode, branches.branchname as branchname,branches.branchprinter as branchprinter, email from borrowers left join branches on borrowers.branchcode=branches.branchcode where userid=?"
1519 $sth->execute($userid);
1521 $borrowernumber, $firstname, $surname,
1522 $userflags, $branchcode, $branchname,
1523 $branchprinter, $emailaddress
1524 ) = $sth->fetchrow if ( $sth->rows );
1526 unless ( $sth->rows ) {
1527 my $sth = $dbh->prepare(
1528 "select borrowernumber, firstname, surname, flags, borrowers.branchcode, branches.branchname as branchname, branches.branchprinter as branchprinter, email from borrowers left join branches on borrowers.branchcode=branches.branchcode where cardnumber=?"
1530 $sth->execute($cardnumber);
1532 $borrowernumber, $firstname, $surname,
1533 $userflags, $branchcode, $branchname,
1534 $branchprinter, $emailaddress
1535 ) = $sth->fetchrow if ( $sth->rows );
1537 unless ( $sth->rows ) {
1538 $sth->execute($userid);
1540 $borrowernumber, $firstname, $surname, $userflags,
1541 $branchcode, $branchname, $branchprinter, $emailaddress
1542 ) = $sth->fetchrow if ( $sth->rows );
1546 my $ip = $ENV{'REMOTE_ADDR'};
1548 # if they specify at login, use that
1549 if ( $query->param('branch') ) {
1550 $branchcode = $query->param('branch');
1551 my $library = Koha::Libraries->find($branchcode);
1552 $branchname = $library? $library->branchname: '';
1554 my $branches = { map { $_->branchcode => $_->unblessed } Koha::Libraries->search };
1555 foreach my $br ( keys %$branches ) {
1557 # now we work with the treatment of ip
1558 my $domain = $branches->{$br}->{'branchip'};
1559 if ( $domain && $ip =~ /^$domain/ ) {
1560 $branchcode = $branches->{$br}->{'branchcode'};
1562 # new op dev : add the branchprinter and branchname in the cookie
1563 $branchprinter = $branches->{$br}->{'branchprinter'};
1564 $branchname = $branches->{$br}->{'branchname'};
1567 $session->param( 'number', $borrowernumber );
1568 $session->param( 'id', $userid );
1569 $session->param( 'cardnumber', $cardnumber );
1570 $session->param( 'firstname', $firstname );
1571 $session->param( 'surname', $surname );
1572 $session->param( 'branch', $branchcode );
1573 $session->param( 'branchname', $branchname );
1574 $session->param( 'flags', $userflags );
1575 $session->param( 'emailaddress', $emailaddress );
1576 $session->param( 'ip', $session->remote_addr() );
1577 $session->param( 'lasttime', time() );
1579 $session->param( 'cas_ticket', $cas_ticket);
1580 C4::Context->set_userenv(
1581 $session->param('number'), $session->param('id'),
1582 $session->param('cardnumber'), $session->param('firstname'),
1583 $session->param('surname'), $session->param('branch'),
1584 $session->param('branchname'), $session->param('flags'),
1585 $session->param('emailaddress'), $session->param('branchprinter')
1587 return ( "ok", $cookie, $sessionID );
1588 } else {
1589 return ( "failed", undef, undef );
1594 =head2 check_cookie_auth
1596 ($status, $sessionId) = check_api_auth($cookie, $userflags);
1598 Given a CGISESSID cookie set during a previous login to Koha, determine
1599 if the user has the privileges specified by C<$userflags>.
1601 C<check_cookie_auth> is meant for authenticating special services
1602 such as tools/upload-file.pl that are invoked by other pages that
1603 have been authenticated in the usual way.
1605 Possible return values in C<$status> are:
1607 =over
1609 =item "ok" -- user authenticated; C<$sessionID> have valid values.
1611 =item "failed" -- credentials are not correct; C<$sessionid> are undef
1613 =item "maintenance" -- DB is in maintenance mode; no login possible at the moment
1615 =item "expired -- session cookie has expired; API user should resubmit userid and password
1617 =back
1619 =cut
1621 sub check_cookie_auth {
1622 my $cookie = shift;
1623 my $flagsrequired = shift;
1624 my $params = shift;
1626 my $remote_addr = $params->{remote_addr} || $ENV{REMOTE_ADDR};
1627 my $dbh = C4::Context->dbh;
1628 my $timeout = _timeout_syspref();
1630 unless ( C4::Context->preference('Version') ) {
1632 # database has not been installed yet
1633 return ( "maintenance", undef );
1635 my $kohaversion = Koha::version();
1636 $kohaversion =~ s/(.*\..*)\.(.*)\.(.*)/$1$2$3/;
1637 if ( C4::Context->preference('Version') < $kohaversion ) {
1639 # database in need of version update; assume that
1640 # no API should be called while databsae is in
1641 # this condition.
1642 return ( "maintenance", undef );
1645 # FIXME -- most of what follows is a copy-and-paste
1646 # of code from checkauth. There is an obvious need
1647 # for refactoring to separate the various parts of
1648 # the authentication code, but as of 2007-11-23 this
1649 # is deferred so as to not introduce bugs into the
1650 # regular authentication code for Koha 3.0.
1652 # see if we have a valid session cookie already
1653 # however, if a userid parameter is present (i.e., from
1654 # a form submission, assume that any current cookie
1655 # is to be ignored
1656 unless ( defined $cookie and $cookie ) {
1657 return ( "failed", undef );
1659 my $sessionID = $cookie;
1660 my $session = get_session($sessionID);
1661 C4::Context->_new_userenv($sessionID);
1662 if ($session) {
1663 C4::Context->set_userenv(
1664 $session->param('number'), $session->param('id'),
1665 $session->param('cardnumber'), $session->param('firstname'),
1666 $session->param('surname'), $session->param('branch'),
1667 $session->param('branchname'), $session->param('flags'),
1668 $session->param('emailaddress'), $session->param('branchprinter')
1671 my $ip = $session->param('ip');
1672 my $lasttime = $session->param('lasttime');
1673 my $userid = $session->param('id');
1674 if ( $lasttime < time() - $timeout ) {
1676 # time out
1677 $session->delete();
1678 $session->flush;
1679 C4::Context->_unset_userenv($sessionID);
1680 $userid = undef;
1681 $sessionID = undef;
1682 return ("expired", undef);
1683 } elsif ( C4::Context->preference('SessionRestrictionByIP') && $ip ne $remote_addr ) {
1685 # IP address changed
1686 $session->delete();
1687 $session->flush;
1688 C4::Context->_unset_userenv($sessionID);
1689 $userid = undef;
1690 $sessionID = undef;
1691 return ( "expired", undef );
1692 } else {
1693 $session->param( 'lasttime', time() );
1694 my $flags = haspermission( $userid, $flagsrequired );
1695 if ($flags) {
1696 return ( "ok", $sessionID );
1697 } else {
1698 $session->delete();
1699 $session->flush;
1700 C4::Context->_unset_userenv($sessionID);
1701 $userid = undef;
1702 $sessionID = undef;
1703 return ( "failed", undef );
1706 } else {
1707 return ( "expired", undef );
1711 =head2 get_session
1713 use CGI::Session;
1714 my $session = get_session($sessionID);
1716 Given a session ID, retrieve the CGI::Session object used to store
1717 the session's state. The session object can be used to store
1718 data that needs to be accessed by different scripts during a
1719 user's session.
1721 If the C<$sessionID> parameter is an empty string, a new session
1722 will be created.
1724 =cut
1726 sub _get_session_params {
1727 my $storage_method = C4::Context->preference('SessionStorage');
1728 if ( $storage_method eq 'mysql' ) {
1729 my $dbh = C4::Context->dbh;
1730 return { dsn => "driver:MySQL;serializer:yaml;id:md5", dsn_args => { Handle => $dbh } };
1732 elsif ( $storage_method eq 'Pg' ) {
1733 my $dbh = C4::Context->dbh;
1734 return { dsn => "driver:PostgreSQL;serializer:yaml;id:md5", dsn_args => { Handle => $dbh } };
1736 elsif ( $storage_method eq 'memcached' && Koha::Caches->get_instance->memcached_cache ) {
1737 my $memcached = Koha::Caches->get_instance()->memcached_cache;
1738 return { dsn => "driver:memcached;serializer:yaml;id:md5", dsn_args => { Memcached => $memcached } };
1740 else {
1741 # catch all defaults to tmp should work on all systems
1742 my $dir = C4::Context::temporary_directory;
1743 my $instance = C4::Context->config( 'database' ); #actually for packages not exactly the instance name, but generally safer to leave it as it is
1744 return { dsn => "driver:File;serializer:yaml;id:md5", dsn_args => { Directory => "$dir/cgisess_$instance" } };
1748 sub get_session {
1749 my $sessionID = shift;
1750 my $params = _get_session_params();
1751 return new CGI::Session( $params->{dsn}, $sessionID, $params->{dsn_args} );
1755 # FIXME no_set_userenv may be replaced with force_branchcode_for_userenv
1756 # (or something similar)
1757 # Currently it's only passed from C4::SIP::ILS::Patron::check_password, but
1758 # not having a userenv defined could cause a crash.
1759 sub checkpw {
1760 my ( $dbh, $userid, $password, $query, $type, $no_set_userenv ) = @_;
1761 $type = 'opac' unless $type;
1763 my @return;
1764 my $patron = Koha::Patrons->find({ userid => $userid });
1765 my $check_internal_as_fallback = 0;
1766 my $passwd_ok = 0;
1767 # Note: checkpw_* routines returns:
1768 # 1 if auth is ok
1769 # 0 if auth is nok
1770 # -1 if user bind failed (LDAP only)
1772 if ( $patron and $patron->account_locked ) {
1773 # Nothing to check, account is locked
1774 } elsif ($ldap && defined($password)) {
1775 $debug and print STDERR "## checkpw - checking LDAP\n";
1776 my ( $retval, $retcard, $retuserid ) = checkpw_ldap(@_); # EXTERNAL AUTH
1777 if ( $retval == 1 ) {
1778 @return = ( $retval, $retcard, $retuserid );
1779 $passwd_ok = 1;
1781 $check_internal_as_fallback = 1 if $retval == 0;
1783 } elsif ( $cas && $query && $query->param('ticket') ) {
1784 $debug and print STDERR "## checkpw - checking CAS\n";
1786 # In case of a CAS authentication, we use the ticket instead of the password
1787 my $ticket = $query->param('ticket');
1788 $query->delete('ticket'); # remove ticket to come back to original URL
1789 my ( $retval, $retcard, $retuserid, $cas_ticket ) = checkpw_cas( $dbh, $ticket, $query, $type ); # EXTERNAL AUTH
1790 if ( $retval ) {
1791 @return = ( $retval, $retcard, $retuserid, $cas_ticket );
1792 } else {
1793 @return = (0);
1795 $passwd_ok = $retval;
1798 # If we are in a shibboleth session (shibboleth is enabled, and a shibboleth match attribute is present)
1799 # Check for password to asertain whether we want to be testing against shibboleth or another method this
1800 # time around.
1801 elsif ( $shib && $shib_login && !$password ) {
1803 $debug and print STDERR "## checkpw - checking Shibboleth\n";
1805 # In case of a Shibboleth authentication, we expect a shibboleth user attribute
1806 # (defined under shibboleth mapping in koha-conf.xml) to contain the login of the
1807 # shibboleth-authenticated user
1809 # Then, we check if it matches a valid koha user
1810 if ($shib_login) {
1811 my ( $retval, $retcard, $retuserid ) = C4::Auth_with_shibboleth::checkpw_shib($shib_login); # EXTERNAL AUTH
1812 if ( $retval ) {
1813 @return = ( $retval, $retcard, $retuserid );
1815 $passwd_ok = $retval;
1817 } else {
1818 $check_internal_as_fallback = 1;
1821 # INTERNAL AUTH
1822 if ( $check_internal_as_fallback ) {
1823 @return = checkpw_internal( $dbh, $userid, $password, $no_set_userenv);
1824 $passwd_ok = 1 if $return[0] > 0; # 1 or 2
1827 if( $patron ) {
1828 if ( $passwd_ok ) {
1829 $patron->update({ login_attempts => 0 });
1830 } else {
1831 $patron->update({ login_attempts => $patron->login_attempts + 1 });
1834 return @return;
1837 sub checkpw_internal {
1838 my ( $dbh, $userid, $password, $no_set_userenv ) = @_;
1840 $password = Encode::encode( 'UTF-8', $password )
1841 if Encode::is_utf8($password);
1843 my $sth =
1844 $dbh->prepare(
1845 "select password,cardnumber,borrowernumber,userid,firstname,surname,borrowers.branchcode,branches.branchname,flags from borrowers join branches on borrowers.branchcode=branches.branchcode where userid=?"
1847 $sth->execute($userid);
1848 if ( $sth->rows ) {
1849 my ( $stored_hash, $cardnumber, $borrowernumber, $userid, $firstname,
1850 $surname, $branchcode, $branchname, $flags )
1851 = $sth->fetchrow;
1853 if ( checkpw_hash( $password, $stored_hash ) ) {
1855 C4::Context->set_userenv( "$borrowernumber", $userid, $cardnumber,
1856 $firstname, $surname, $branchcode, $branchname, $flags ) unless $no_set_userenv;
1857 return 1, $cardnumber, $userid;
1860 $sth =
1861 $dbh->prepare(
1862 "select password,cardnumber,borrowernumber,userid,firstname,surname,borrowers.branchcode,branches.branchname,flags from borrowers join branches on borrowers.branchcode=branches.branchcode where cardnumber=?"
1864 $sth->execute($userid);
1865 if ( $sth->rows ) {
1866 my ( $stored_hash, $cardnumber, $borrowernumber, $userid, $firstname,
1867 $surname, $branchcode, $branchname, $flags )
1868 = $sth->fetchrow;
1870 if ( checkpw_hash( $password, $stored_hash ) ) {
1872 C4::Context->set_userenv( $borrowernumber, $userid, $cardnumber,
1873 $firstname, $surname, $branchcode, $branchname, $flags ) unless $no_set_userenv;
1874 return 1, $cardnumber, $userid;
1877 return 0;
1880 sub checkpw_hash {
1881 my ( $password, $stored_hash ) = @_;
1883 return if $stored_hash eq '!';
1885 # check what encryption algorithm was implemented: Bcrypt - if the hash starts with '$2' it is Bcrypt else md5
1886 my $hash;
1887 if ( substr( $stored_hash, 0, 2 ) eq '$2' ) {
1888 $hash = hash_password( $password, $stored_hash );
1889 } else {
1890 $hash = md5_base64($password);
1892 return $hash eq $stored_hash;
1895 =head2 getuserflags
1897 my $authflags = getuserflags($flags, $userid, [$dbh]);
1899 Translates integer flags into permissions strings hash.
1901 C<$flags> is the integer userflags value ( borrowers.userflags )
1902 C<$userid> is the members.userid, used for building subpermissions
1903 C<$authflags> is a hashref of permissions
1905 =cut
1907 sub getuserflags {
1908 my $flags = shift;
1909 my $userid = shift;
1910 my $dbh = @_ ? shift : C4::Context->dbh;
1911 my $userflags;
1913 # I don't want to do this, but if someone logs in as the database
1914 # user, it would be preferable not to spam them to death with
1915 # numeric warnings. So, we make $flags numeric.
1916 no warnings 'numeric';
1917 $flags += 0;
1919 my $sth = $dbh->prepare("SELECT bit, flag, defaulton FROM userflags");
1920 $sth->execute;
1922 while ( my ( $bit, $flag, $defaulton ) = $sth->fetchrow ) {
1923 if ( ( $flags & ( 2**$bit ) ) || $defaulton ) {
1924 $userflags->{$flag} = 1;
1926 else {
1927 $userflags->{$flag} = 0;
1931 # get subpermissions and merge with top-level permissions
1932 my $user_subperms = get_user_subpermissions($userid);
1933 foreach my $module ( keys %$user_subperms ) {
1934 next if $userflags->{$module} == 1; # user already has permission for everything in this module
1935 $userflags->{$module} = $user_subperms->{$module};
1938 return $userflags;
1941 =head2 get_user_subpermissions
1943 $user_perm_hashref = get_user_subpermissions($userid);
1945 Given the userid (note, not the borrowernumber) of a staff user,
1946 return a hashref of hashrefs of the specific subpermissions
1947 accorded to the user. An example return is
1950 tools => {
1951 export_catalog => 1,
1952 import_patrons => 1,
1956 The top-level hash-key is a module or function code from
1957 userflags.flag, while the second-level key is a code
1958 from permissions.
1960 The results of this function do not give a complete picture
1961 of the functions that a staff user can access; it is also
1962 necessary to check borrowers.flags.
1964 =cut
1966 sub get_user_subpermissions {
1967 my $userid = shift;
1969 my $dbh = C4::Context->dbh;
1970 my $sth = $dbh->prepare( "SELECT flag, user_permissions.code
1971 FROM user_permissions
1972 JOIN permissions USING (module_bit, code)
1973 JOIN userflags ON (module_bit = bit)
1974 JOIN borrowers USING (borrowernumber)
1975 WHERE userid = ?" );
1976 $sth->execute($userid);
1978 my $user_perms = {};
1979 while ( my $perm = $sth->fetchrow_hashref ) {
1980 $user_perms->{ $perm->{'flag'} }->{ $perm->{'code'} } = 1;
1982 return $user_perms;
1985 =head2 get_all_subpermissions
1987 my $perm_hashref = get_all_subpermissions();
1989 Returns a hashref of hashrefs defining all specific
1990 permissions currently defined. The return value
1991 has the same structure as that of C<get_user_subpermissions>,
1992 except that the innermost hash value is the description
1993 of the subpermission.
1995 =cut
1997 sub get_all_subpermissions {
1998 my $dbh = C4::Context->dbh;
1999 my $sth = $dbh->prepare( "SELECT flag, code
2000 FROM permissions
2001 JOIN userflags ON (module_bit = bit)" );
2002 $sth->execute();
2004 my $all_perms = {};
2005 while ( my $perm = $sth->fetchrow_hashref ) {
2006 $all_perms->{ $perm->{'flag'} }->{ $perm->{'code'} } = 1;
2008 return $all_perms;
2011 =head2 haspermission
2013 $flags = ($userid, $flagsrequired);
2015 C<$userid> the userid of the member
2016 C<$flags> is a hashref of required flags like C<$borrower-&lt;{authflags}>
2018 Returns member's flags or 0 if a permission is not met.
2020 =cut
2022 sub haspermission {
2023 my ( $userid, $flagsrequired ) = @_;
2024 my $sth = C4::Context->dbh->prepare("SELECT flags FROM borrowers WHERE userid=?");
2025 $sth->execute($userid);
2026 my $row = $sth->fetchrow();
2027 my $flags = getuserflags( $row, $userid );
2029 return $flags if $flags->{superlibrarian};
2031 foreach my $module ( keys %$flagsrequired ) {
2032 my $subperm = $flagsrequired->{$module};
2033 if ( $subperm eq '*' ) {
2034 return 0 unless ( $flags->{$module} == 1 or ref( $flags->{$module} ) );
2035 } else {
2036 return 0 unless (
2037 ( defined $flags->{$module} and
2038 $flags->{$module} == 1 )
2040 ( ref( $flags->{$module} ) and
2041 exists $flags->{$module}->{$subperm} and
2042 $flags->{$module}->{$subperm} == 1 )
2046 return $flags;
2048 #FIXME - This fcn should return the failed permission so a suitable error msg can be delivered.
2051 sub getborrowernumber {
2052 my ($userid) = @_;
2053 my $userenv = C4::Context->userenv;
2054 if ( defined($userenv) && ref($userenv) eq 'HASH' && $userenv->{number} ) {
2055 return $userenv->{number};
2057 my $dbh = C4::Context->dbh;
2058 for my $field ( 'userid', 'cardnumber' ) {
2059 my $sth =
2060 $dbh->prepare("select borrowernumber from borrowers where $field=?");
2061 $sth->execute($userid);
2062 if ( $sth->rows ) {
2063 my ($bnumber) = $sth->fetchrow;
2064 return $bnumber;
2067 return 0;
2070 =head2 track_login_daily
2072 track_login_daily( $userid );
2074 Wraps the call to $patron->track_login, the method used to update borrowers.lastseen. We only call track_login once a day.
2076 =cut
2078 sub track_login_daily {
2079 my $userid = shift;
2080 return if !$userid || !C4::Context->preference('TrackLastPatronActivity');
2082 my $cache = Koha::Caches->get_instance();
2083 my $cache_key = "track_login_" . $userid;
2084 my $cached = $cache->get_from_cache($cache_key);
2085 my $today = dt_from_string()->ymd;
2086 return if $cached && $cached eq $today;
2088 my $patron = Koha::Patrons->find({ userid => $userid });
2089 return unless $patron;
2090 $patron->track_login;
2091 $cache->set_in_cache( $cache_key, $today );
2094 END { } # module clean-up code here (global destructor)
2096 __END__
2098 =head1 SEE ALSO
2100 CGI(3)
2102 C4::Output(3)
2104 Crypt::Eksblowfish::Bcrypt(3)
2106 Digest::MD5(3)
2108 =cut