Bug 14586 - Update about page with new 3.18 release team
[koha.git] / C4 / Auth.pm
blob5ea4771d28b98f945f94330505b0ae9659bbd43f
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::Branch; # GetBranches
32 use C4::Search::History;
33 use C4::VirtualShelves;
34 use Koha::AuthUtils qw(hash_password);
35 use POSIX qw/strftime/;
36 use List::MoreUtils qw/ any /;
38 # use utf8;
39 use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS $debug $ldap $cas $caslogout $shib $shib_login);
41 BEGIN {
42 sub psgi_env { any { /^psgi\./ } keys %ENV }
44 sub safe_exit {
45 if (psgi_env) { die 'psgi:exit' }
46 else { exit }
48 $VERSION = 3.07.00.049; # set version for version checking
50 $debug = $ENV{DEBUG};
51 @ISA = qw(Exporter);
52 @EXPORT = qw(&checkauth &get_template_and_user &haspermission &get_user_subpermissions);
53 @EXPORT_OK = qw(&check_api_auth &get_session &check_cookie_auth &checkpw &checkpw_internal &checkpw_hash
54 &get_all_subpermissions &get_user_subpermissions
56 %EXPORT_TAGS = ( EditPermissions => [qw(get_all_subpermissions get_user_subpermissions)] );
57 $ldap = C4::Context->config('useldapserver') || 0;
58 $cas = C4::Context->preference('casAuthentication');
59 $shib = C4::Context->config('useshibboleth') || 0;
60 $caslogout = C4::Context->preference('casLogout');
61 require C4::Auth_with_cas; # no import
63 if ($ldap) {
64 require C4::Auth_with_ldap;
65 import C4::Auth_with_ldap qw(checkpw_ldap);
67 if ($shib) {
68 require C4::Auth_with_shibboleth;
69 import C4::Auth_with_shibboleth
70 qw(shib_ok checkpw_shib logout_shib login_shib_url get_login_shib);
72 # Check for good config
73 if ( shib_ok() ) {
75 # Get shibboleth login attribute
76 $shib_login = get_login_shib();
79 # Bad config, disable shibboleth
80 else {
81 $shib = 0;
84 if ($cas) {
85 import C4::Auth_with_cas qw(check_api_auth_cas checkpw_cas login_cas logout_cas login_cas_url);
90 =head1 NAME
92 C4::Auth - Authenticates Koha users
94 =head1 SYNOPSIS
96 use CGI;
97 use C4::Auth;
98 use C4::Output;
100 my $query = new CGI;
102 my ($template, $borrowernumber, $cookie)
103 = get_template_and_user(
105 template_name => "opac-main.tt",
106 query => $query,
107 type => "opac",
108 authnotrequired => 0,
109 flagsrequired => {borrow => 1, catalogue => '*', tools => 'import_patrons' },
113 output_html_with_http_headers $query, $cookie, $template->output;
115 =head1 DESCRIPTION
117 The main function of this module is to provide
118 authentification. However the get_template_and_user function has
119 been provided so that a users login information is passed along
120 automatically. This gets loaded into the template.
122 =head1 FUNCTIONS
124 =head2 get_template_and_user
126 my ($template, $borrowernumber, $cookie)
127 = get_template_and_user(
129 template_name => "opac-main.tt",
130 query => $query,
131 type => "opac",
132 authnotrequired => 0,
133 flagsrequired => {borrow => 1, catalogue => '*', tools => 'import_patrons' },
137 This call passes the C<query>, C<flagsrequired> and C<authnotrequired>
138 to C<&checkauth> (in this module) to perform authentification.
139 See C<&checkauth> for an explanation of these parameters.
141 The C<template_name> is then used to find the correct template for
142 the page. The authenticated users details are loaded onto the
143 template in the HTML::Template LOOP variable C<USER_INFO>. Also the
144 C<sessionID> is passed to the template. This can be used in templates
145 if cookies are disabled. It needs to be put as and input to every
146 authenticated page.
148 More information on the C<gettemplate> sub can be found in the
149 Output.pm module.
151 =cut
153 sub get_template_and_user {
155 my $in = shift;
156 my ( $user, $cookie, $sessionID, $flags );
158 C4::Context->interface( $in->{type} );
160 my $safe_chars = 'a-zA-Z0-9_\-\/';
161 die "bad template path" unless $in->{'template_name'} =~ m/^[$safe_chars]+\.tt$/ig; #sanitize input
163 $in->{'authnotrequired'} ||= 0;
164 my $template = C4::Templates::gettemplate(
165 $in->{'template_name'},
166 $in->{'type'},
167 $in->{'query'},
168 $in->{'is_plugin'}
171 if ( $in->{'template_name'} !~ m/maintenance/ ) {
172 ( $user, $cookie, $sessionID, $flags ) = checkauth(
173 $in->{'query'},
174 $in->{'authnotrequired'},
175 $in->{'flagsrequired'},
176 $in->{'type'}
180 my $borrowernumber;
181 if ($user) {
182 require C4::Members;
184 # It's possible for $user to be the borrowernumber if they don't have a
185 # userid defined (and are logging in through some other method, such
186 # as SSL certs against an email address)
187 $borrowernumber = getborrowernumber($user) if defined($user);
188 if ( !defined($borrowernumber) && defined($user) ) {
189 my $borrower = C4::Members::GetMember( borrowernumber => $user );
190 if ($borrower) {
191 $borrowernumber = $user;
193 # A bit of a hack, but I don't know there's a nicer way
194 # to do it.
195 $user = $borrower->{firstname} . ' ' . $borrower->{surname};
199 # user info
200 $template->param( loggedinusername => $user );
201 $template->param( loggedinusernumber => $borrowernumber );
202 $template->param( sessionID => $sessionID );
204 my ( $total, $pubshelves, $barshelves ) = C4::VirtualShelves::GetSomeShelfNames( $borrowernumber, 'MASTHEAD' );
205 $template->param(
206 pubshelves => $total->{pubtotal},
207 pubshelvesloop => $pubshelves,
208 barshelves => $total->{bartotal},
209 barshelvesloop => $barshelves,
212 my ($borr) = C4::Members::GetMemberDetails($borrowernumber);
213 my @bordat;
214 $bordat[0] = $borr;
215 $template->param( "USER_INFO" => \@bordat );
217 my $all_perms = get_all_subpermissions();
219 my @flagroots = qw(circulate catalogue parameters borrowers permissions reserveforothers borrow
220 editcatalogue updatecharges management tools editauthorities serials reports acquisition);
222 # We are going to use the $flags returned by checkauth
223 # to create the template's parameters that will indicate
224 # which menus the user can access.
225 if ( $flags && $flags->{superlibrarian} == 1 ) {
226 $template->param( CAN_user_circulate => 1 );
227 $template->param( CAN_user_catalogue => 1 );
228 $template->param( CAN_user_parameters => 1 );
229 $template->param( CAN_user_borrowers => 1 );
230 $template->param( CAN_user_permissions => 1 );
231 $template->param( CAN_user_reserveforothers => 1 );
232 $template->param( CAN_user_borrow => 1 );
233 $template->param( CAN_user_editcatalogue => 1 );
234 $template->param( CAN_user_updatecharges => 1 );
235 $template->param( CAN_user_acquisition => 1 );
236 $template->param( CAN_user_management => 1 );
237 $template->param( CAN_user_tools => 1 );
238 $template->param( CAN_user_editauthorities => 1 );
239 $template->param( CAN_user_serials => 1 );
240 $template->param( CAN_user_reports => 1 );
241 $template->param( CAN_user_staffaccess => 1 );
242 $template->param( CAN_user_plugins => 1 );
243 $template->param( CAN_user_coursereserves => 1 );
244 foreach my $module ( keys %$all_perms ) {
246 foreach my $subperm ( keys %{ $all_perms->{$module} } ) {
247 $template->param( "CAN_user_${module}_${subperm}" => 1 );
252 if ($flags) {
253 foreach my $module ( keys %$all_perms ) {
254 if ( $flags->{$module} == 1 ) {
255 foreach my $subperm ( keys %{ $all_perms->{$module} } ) {
256 $template->param( "CAN_user_${module}_${subperm}" => 1 );
258 } elsif ( ref( $flags->{$module} ) ) {
259 foreach my $subperm ( keys %{ $flags->{$module} } ) {
260 $template->param( "CAN_user_${module}_${subperm}" => 1 );
266 if ($flags) {
267 foreach my $module ( keys %$flags ) {
268 if ( $flags->{$module} == 1 or ref( $flags->{$module} ) ) {
269 $template->param( "CAN_user_$module" => 1 );
270 if ( $module eq "parameters" ) {
271 $template->param( CAN_user_management => 1 );
277 # Logged-in opac search history
278 # If the requested template is an opac one and opac search history is enabled
279 if ( $in->{type} eq 'opac' && C4::Context->preference('EnableOpacSearchHistory') ) {
280 my $dbh = C4::Context->dbh;
281 my $query = "SELECT COUNT(*) FROM search_history WHERE userid=?";
282 my $sth = $dbh->prepare($query);
283 $sth->execute($borrowernumber);
285 # If at least one search has already been performed
286 if ( $sth->fetchrow_array > 0 ) {
288 # We show the link in opac
289 $template->param( EnableOpacSearchHistory => 1 );
292 # And if there are searches performed when the user was not logged in,
293 # we add them to the logged-in search history
294 my @recentSearches = C4::Search::History::get_from_session( { cgi => $in->{'query'} } );
295 if (@recentSearches) {
296 my $dbh = C4::Context->dbh;
297 my $query = q{
298 INSERT INTO search_history(userid, sessionid, query_desc, query_cgi, type, total, time )
299 VALUES (?, ?, ?, ?, ?, ?, ?)
302 my $sth = $dbh->prepare($query);
303 $sth->execute( $borrowernumber,
304 $in->{query}->cookie("CGISESSID"),
305 $_->{query_desc},
306 $_->{query_cgi},
307 $_->{type} || 'biblio',
308 $_->{total},
309 $_->{time},
310 ) foreach @recentSearches;
312 # clear out the search history from the session now that
313 # we've saved it to the database
314 C4::Search::History::set_to_session( { cgi => $in->{'query'}, search_history => [] } );
316 } elsif ( $in->{type} eq 'intranet' and C4::Context->preference('EnableSearchHistory') ) {
317 $template->param( EnableSearchHistory => 1 );
320 else { # if this is an anonymous session, setup to display public lists...
322 # If shibboleth is enabled, and we're in an anonymous session, we should allow
323 # the user to attemp login via shibboleth.
324 if ($shib) {
325 $template->param( shibbolethAuthentication => $shib,
326 shibbolethLoginUrl => login_shib_url( $in->{'query'} ),
329 # If shibboleth is enabled and we have a shibboleth login attribute,
330 # but we are in an anonymous session, then we clearly have an invalid
331 # shibboleth koha account.
332 if ($shib_login) {
333 $template->param( invalidShibLogin => '1' );
337 $template->param( sessionID => $sessionID );
339 my ( $total, $pubshelves ) = C4::VirtualShelves::GetSomeShelfNames( undef, 'MASTHEAD' );
340 $template->param(
341 pubshelves => $total->{pubtotal},
342 pubshelvesloop => $pubshelves,
346 # Anonymous opac search history
347 # If opac search history is enabled and at least one search has already been performed
348 if ( C4::Context->preference('EnableOpacSearchHistory') ) {
349 my @recentSearches = C4::Search::History::get_from_session( { cgi => $in->{'query'} } );
350 if (@recentSearches) {
351 $template->param( EnableOpacSearchHistory => 1 );
355 if ( C4::Context->preference('dateformat') ) {
356 $template->param( dateformat => C4::Context->preference('dateformat') );
359 # these template parameters are set the same regardless of $in->{'type'}
361 # Set the using_https variable for templates
362 # FIXME Under Plack the CGI->https method always returns 'OFF'
363 my $https = $in->{query}->https();
364 my $using_https = ( defined $https and $https ne 'OFF' ) ? 1 : 0;
366 $template->param(
367 "BiblioDefaultView" . C4::Context->preference("BiblioDefaultView") => 1,
368 EnhancedMessagingPreferences => C4::Context->preference('EnhancedMessagingPreferences'),
369 GoogleJackets => C4::Context->preference("GoogleJackets"),
370 OpenLibraryCovers => C4::Context->preference("OpenLibraryCovers"),
371 KohaAdminEmailAddress => "" . C4::Context->preference("KohaAdminEmailAddress"),
372 LoginBranchcode => ( C4::Context->userenv ? C4::Context->userenv->{"branch"} : undef ),
373 LoginFirstname => ( C4::Context->userenv ? C4::Context->userenv->{"firstname"} : "Bel" ),
374 LoginSurname => C4::Context->userenv ? C4::Context->userenv->{"surname"} : "Inconnu",
375 emailaddress => C4::Context->userenv ? C4::Context->userenv->{"emailaddress"} : undef,
376 loggedinpersona => C4::Context->userenv ? C4::Context->userenv->{"persona"} : undef,
377 TagsEnabled => C4::Context->preference("TagsEnabled"),
378 hide_marc => C4::Context->preference("hide_marc"),
379 item_level_itypes => C4::Context->preference('item-level_itypes'),
380 patronimages => C4::Context->preference("patronimages"),
381 singleBranchMode => C4::Context->preference("singleBranchMode"),
382 XSLTDetailsDisplay => C4::Context->preference("XSLTDetailsDisplay"),
383 XSLTResultsDisplay => C4::Context->preference("XSLTResultsDisplay"),
384 using_https => $using_https,
385 noItemTypeImages => C4::Context->preference("noItemTypeImages"),
386 marcflavour => C4::Context->preference("marcflavour"),
387 persona => C4::Context->preference("persona"),
389 if ( $in->{'type'} eq "intranet" ) {
390 $template->param(
391 AmazonCoverImages => C4::Context->preference("AmazonCoverImages"),
392 AutoLocation => C4::Context->preference("AutoLocation"),
393 "BiblioDefaultView" . C4::Context->preference("IntranetBiblioDefaultView") => 1,
394 CalendarFirstDayOfWeek => ( C4::Context->preference("CalendarFirstDayOfWeek") eq "Sunday" ) ? 0 : 1,
395 CircAutocompl => C4::Context->preference("CircAutocompl"),
396 FRBRizeEditions => C4::Context->preference("FRBRizeEditions"),
397 IndependentBranches => C4::Context->preference("IndependentBranches"),
398 IntranetNav => C4::Context->preference("IntranetNav"),
399 IntranetmainUserblock => C4::Context->preference("IntranetmainUserblock"),
400 LibraryName => C4::Context->preference("LibraryName"),
401 LoginBranchname => ( C4::Context->userenv ? C4::Context->userenv->{"branchname"} : undef ),
402 advancedMARCEditor => C4::Context->preference("advancedMARCEditor"),
403 canreservefromotherbranches => C4::Context->preference('canreservefromotherbranches'),
404 intranetcolorstylesheet => C4::Context->preference("intranetcolorstylesheet"),
405 IntranetFavicon => C4::Context->preference("IntranetFavicon"),
406 intranetreadinghistory => C4::Context->preference("intranetreadinghistory"),
407 intranetstylesheet => C4::Context->preference("intranetstylesheet"),
408 IntranetUserCSS => C4::Context->preference("IntranetUserCSS"),
409 intranetuserjs => C4::Context->preference("intranetuserjs"),
410 intranetbookbag => C4::Context->preference("intranetbookbag"),
411 suggestion => C4::Context->preference("suggestion"),
412 virtualshelves => C4::Context->preference("virtualshelves"),
413 StaffSerialIssueDisplayCount => C4::Context->preference("StaffSerialIssueDisplayCount"),
414 EasyAnalyticalRecords => C4::Context->preference('EasyAnalyticalRecords'),
415 LocalCoverImages => C4::Context->preference('LocalCoverImages'),
416 OPACLocalCoverImages => C4::Context->preference('OPACLocalCoverImages'),
417 AllowMultipleCovers => C4::Context->preference('AllowMultipleCovers'),
418 EnableBorrowerFiles => C4::Context->preference('EnableBorrowerFiles'),
419 UseKohaPlugins => C4::Context->preference('UseKohaPlugins'),
420 UseCourseReserves => C4::Context->preference("UseCourseReserves"),
423 else {
424 warn "template type should be OPAC, here it is=[" . $in->{'type'} . "]" unless ( $in->{'type'} eq 'opac' );
426 #TODO : replace LibraryName syspref with 'system name', and remove this html processing
427 my $LibraryNameTitle = C4::Context->preference("LibraryName");
428 $LibraryNameTitle =~ s/<(?:\/?)(?:br|p)\s*(?:\/?)>/ /sgi;
429 $LibraryNameTitle =~ s/<(?:[^<>'"]|'(?:[^']*)'|"(?:[^"]*)")*>//sg;
431 # clean up the busc param in the session
432 # if the page is not opac-detail and not the "add to list" page
433 # and not the "edit comments" page
434 if ( C4::Context->preference("OpacBrowseResults")
435 && $in->{'template_name'} =~ /opac-(.+)\.(?:tt|tmpl)$/ ) {
436 my $pagename = $1;
437 unless ( $pagename =~ /^(?:MARC|ISBD)?detail$/
438 or $pagename =~ /^addbybiblionumber$/
439 or $pagename =~ /^review$/ ) {
440 my $sessionSearch = get_session( $sessionID || $in->{'query'}->cookie("CGISESSID") );
441 $sessionSearch->clear( ["busc"] ) if ( $sessionSearch->param("busc") );
445 # variables passed from CGI: opac_css_override and opac_search_limits.
446 my $opac_search_limit = $ENV{'OPAC_SEARCH_LIMIT'};
447 my $opac_limit_override = $ENV{'OPAC_LIMIT_OVERRIDE'};
448 my $opac_name = '';
449 if (
450 ( $opac_limit_override && $opac_search_limit && $opac_search_limit =~ /branch:(\w+)/ ) ||
451 ( $in->{'query'}->param('limit') && $in->{'query'}->param('limit') =~ /branch:(\w+)/ ) ||
452 ( $in->{'query'}->param('multibranchlimit') && $in->{'query'}->param('multibranchlimit') =~ /multibranchlimit-(\w+)/ )
454 $opac_name = $1; # opac_search_limit is a branch, so we use it.
455 } elsif ( $in->{'query'}->param('multibranchlimit') ) {
456 $opac_name = $in->{'query'}->param('multibranchlimit');
457 } elsif ( C4::Context->preference("SearchMyLibraryFirst") && C4::Context->userenv && C4::Context->userenv->{'branch'} ) {
458 $opac_name = C4::Context->userenv->{'branch'};
461 # FIXME Under Plack the CGI->https method always returns 'OFF' ($using_https will be set to 0 in this case)
462 my $opac_base_url = C4::Context->preference("OPACBaseURL"); #FIXME uses $using_https below as well
463 if ( !$opac_base_url ) {
464 $opac_base_url = $ENV{'SERVER_NAME'} . ( $ENV{'SERVER_PORT'} eq ( $using_https ? "443" : "80" ) ? '' : ":$ENV{'SERVER_PORT'}" );
466 $template->param(
467 opaccolorstylesheet => C4::Context->preference("opaccolorstylesheet"),
468 AnonSuggestions => "" . C4::Context->preference("AnonSuggestions"),
469 AuthorisedValueImages => C4::Context->preference("AuthorisedValueImages"),
470 BranchesLoop => GetBranchesLoop($opac_name),
471 BranchCategoriesLoop => GetBranchCategories( 'searchdomain', 1, $opac_name ),
472 CalendarFirstDayOfWeek => ( C4::Context->preference("CalendarFirstDayOfWeek") eq "Sunday" ) ? 0 : 1,
473 LibraryName => "" . C4::Context->preference("LibraryName"),
474 LibraryNameTitle => "" . $LibraryNameTitle,
475 LoginBranchname => C4::Context->userenv ? C4::Context->userenv->{"branchname"} : "",
476 OPACAmazonCoverImages => C4::Context->preference("OPACAmazonCoverImages"),
477 OPACFRBRizeEditions => C4::Context->preference("OPACFRBRizeEditions"),
478 OpacHighlightedWords => C4::Context->preference("OpacHighlightedWords"),
479 OPACItemHolds => C4::Context->preference("OPACItemHolds"),
480 OPACShelfBrowser => "" . C4::Context->preference("OPACShelfBrowser"),
481 OPACURLOpenInNewWindow => "" . C4::Context->preference("OPACURLOpenInNewWindow"),
482 OPACUserCSS => "" . C4::Context->preference("OPACUserCSS"),
483 OpacAuthorities => C4::Context->preference("OpacAuthorities"),
484 OPACBaseURL => ( $using_https ? "https://" : "http://" ) . $opac_base_url,
485 opac_css_override => $ENV{'OPAC_CSS_OVERRIDE'},
486 opac_search_limit => $opac_search_limit,
487 opac_limit_override => $opac_limit_override,
488 OpacBrowser => C4::Context->preference("OpacBrowser"),
489 OpacCloud => C4::Context->preference("OpacCloud"),
490 OpacKohaUrl => C4::Context->preference("OpacKohaUrl"),
491 OpacMainUserBlock => "" . C4::Context->preference("OpacMainUserBlock"),
492 OpacNav => "" . C4::Context->preference("OpacNav"),
493 OpacNavRight => "" . C4::Context->preference("OpacNavRight"),
494 OpacNavBottom => "" . C4::Context->preference("OpacNavBottom"),
495 OpacPasswordChange => C4::Context->preference("OpacPasswordChange"),
496 OPACPatronDetails => C4::Context->preference("OPACPatronDetails"),
497 OPACPrivacy => C4::Context->preference("OPACPrivacy"),
498 OPACFinesTab => C4::Context->preference("OPACFinesTab"),
499 OpacTopissue => C4::Context->preference("OpacTopissue"),
500 RequestOnOpac => C4::Context->preference("RequestOnOpac"),
501 'Version' => C4::Context->preference('Version'),
502 hidelostitems => C4::Context->preference("hidelostitems"),
503 mylibraryfirst => ( C4::Context->preference("SearchMyLibraryFirst") && C4::Context->userenv ) ? C4::Context->userenv->{'branch'} : '',
504 opaclayoutstylesheet => "" . C4::Context->preference("opaclayoutstylesheet"),
505 opacbookbag => "" . C4::Context->preference("opacbookbag"),
506 opaccredits => "" . C4::Context->preference("opaccredits"),
507 OpacFavicon => C4::Context->preference("OpacFavicon"),
508 opacheader => "" . C4::Context->preference("opacheader"),
509 opaclanguagesdisplay => "" . C4::Context->preference("opaclanguagesdisplay"),
510 opacreadinghistory => C4::Context->preference("opacreadinghistory"),
511 opacuserjs => C4::Context->preference("opacuserjs"),
512 opacuserlogin => "" . C4::Context->preference("opacuserlogin"),
513 ShowReviewer => C4::Context->preference("ShowReviewer"),
514 ShowReviewerPhoto => C4::Context->preference("ShowReviewerPhoto"),
515 suggestion => "" . C4::Context->preference("suggestion"),
516 virtualshelves => "" . C4::Context->preference("virtualshelves"),
517 OPACSerialIssueDisplayCount => C4::Context->preference("OPACSerialIssueDisplayCount"),
518 OPACXSLTDetailsDisplay => C4::Context->preference("OPACXSLTDetailsDisplay"),
519 OPACXSLTResultsDisplay => C4::Context->preference("OPACXSLTResultsDisplay"),
520 SyndeticsClientCode => C4::Context->preference("SyndeticsClientCode"),
521 SyndeticsEnabled => C4::Context->preference("SyndeticsEnabled"),
522 SyndeticsCoverImages => C4::Context->preference("SyndeticsCoverImages"),
523 SyndeticsTOC => C4::Context->preference("SyndeticsTOC"),
524 SyndeticsSummary => C4::Context->preference("SyndeticsSummary"),
525 SyndeticsEditions => C4::Context->preference("SyndeticsEditions"),
526 SyndeticsExcerpt => C4::Context->preference("SyndeticsExcerpt"),
527 SyndeticsReviews => C4::Context->preference("SyndeticsReviews"),
528 SyndeticsAuthorNotes => C4::Context->preference("SyndeticsAuthorNotes"),
529 SyndeticsAwards => C4::Context->preference("SyndeticsAwards"),
530 SyndeticsSeries => C4::Context->preference("SyndeticsSeries"),
531 SyndeticsCoverImageSize => C4::Context->preference("SyndeticsCoverImageSize"),
532 OPACLocalCoverImages => C4::Context->preference("OPACLocalCoverImages"),
533 PatronSelfRegistration => C4::Context->preference("PatronSelfRegistration"),
534 PatronSelfRegistrationDefaultCategory => C4::Context->preference("PatronSelfRegistrationDefaultCategory"),
537 $template->param( OpacPublic => '1' ) if ( $user || C4::Context->preference("OpacPublic") );
540 # Check if we were asked using parameters to force a specific language
541 if ( defined $in->{'query'}->param('language') ) {
543 # Extract the language, let C4::Languages::getlanguage choose
544 # what to do
545 my $language = C4::Languages::getlanguage( $in->{'query'} );
546 my $languagecookie = C4::Templates::getlanguagecookie( $in->{'query'}, $language );
547 if ( ref $cookie eq 'ARRAY' ) {
548 push @{$cookie}, $languagecookie;
549 } else {
550 $cookie = [ $cookie, $languagecookie ];
554 return ( $template, $borrowernumber, $cookie, $flags );
557 =head2 checkauth
559 ($userid, $cookie, $sessionID) = &checkauth($query, $noauth, $flagsrequired, $type);
561 Verifies that the user is authorized to run this script. If
562 the user is authorized, a (userid, cookie, session-id, flags)
563 quadruple is returned. If the user is not authorized but does
564 not have the required privilege (see $flagsrequired below), it
565 displays an error page and exits. Otherwise, it displays the
566 login page and exits.
568 Note that C<&checkauth> will return if and only if the user
569 is authorized, so it should be called early on, before any
570 unfinished operations (e.g., if you've opened a file, then
571 C<&checkauth> won't close it for you).
573 C<$query> is the CGI object for the script calling C<&checkauth>.
575 The C<$noauth> argument is optional. If it is set, then no
576 authorization is required for the script.
578 C<&checkauth> fetches user and session information from C<$query> and
579 ensures that the user is authorized to run scripts that require
580 authorization.
582 The C<$flagsrequired> argument specifies the required privileges
583 the user must have if the username and password are correct.
584 It should be specified as a reference-to-hash; keys in the hash
585 should be the "flags" for the user, as specified in the Members
586 intranet module. Any key specified must correspond to a "flag"
587 in the userflags table. E.g., { circulate => 1 } would specify
588 that the user must have the "circulate" privilege in order to
589 proceed. To make sure that access control is correct, the
590 C<$flagsrequired> parameter must be specified correctly.
592 Koha also has a concept of sub-permissions, also known as
593 granular permissions. This makes the value of each key
594 in the C<flagsrequired> hash take on an additional
595 meaning, i.e.,
599 The user must have access to all subfunctions of the module
600 specified by the hash key.
604 The user must have access to at least one subfunction of the module
605 specified by the hash key.
607 specific permission, e.g., 'export_catalog'
609 The user must have access to the specific subfunction list, which
610 must correspond to a row in the permissions table.
612 The C<$type> argument specifies whether the template should be
613 retrieved from the opac or intranet directory tree. "opac" is
614 assumed if it is not specified; however, if C<$type> is specified,
615 "intranet" is assumed if it is not "opac".
617 If C<$query> does not have a valid session ID associated with it
618 (i.e., the user has not logged in) or if the session has expired,
619 C<&checkauth> presents the user with a login page (from the point of
620 view of the original script, C<&checkauth> does not return). Once the
621 user has authenticated, C<&checkauth> restarts the original script
622 (this time, C<&checkauth> returns).
624 The login page is provided using a HTML::Template, which is set in the
625 systempreferences table or at the top of this file. The variable C<$type>
626 selects which template to use, either the opac or the intranet
627 authentification template.
629 C<&checkauth> returns a user ID, a cookie, and a session ID. The
630 cookie should be sent back to the browser; it verifies that the user
631 has authenticated.
633 =cut
635 sub _version_check {
636 my $type = shift;
637 my $query = shift;
638 my $version;
640 # If Version syspref is unavailable, it means Koha is beeing installed,
641 # and so we must redirect to OPAC maintenance page or to the WebInstaller
642 # also, if OpacMaintenance is ON, OPAC should redirect to maintenance
643 if ( C4::Context->preference('OpacMaintenance') && $type eq 'opac' ) {
644 warn "OPAC Install required, redirecting to maintenance";
645 print $query->redirect("/cgi-bin/koha/maintenance.pl");
646 safe_exit;
648 unless ( $version = C4::Context->preference('Version') ) { # assignment, not comparison
649 if ( $type ne 'opac' ) {
650 warn "Install required, redirecting to Installer";
651 print $query->redirect("/cgi-bin/koha/installer/install.pl");
652 } else {
653 warn "OPAC Install required, redirecting to maintenance";
654 print $query->redirect("/cgi-bin/koha/maintenance.pl");
656 safe_exit;
659 # check that database and koha version are the same
660 # there is no DB version, it's a fresh install,
661 # go to web installer
662 # there is a DB version, compare it to the code version
663 my $kohaversion = C4::Context::KOHAVERSION;
665 # remove the 3 last . to have a Perl number
666 $kohaversion =~ s/(.*\..*)\.(.*)\.(.*)/$1$2$3/;
667 $debug and print STDERR "kohaversion : $kohaversion\n";
668 if ( $version < $kohaversion ) {
669 my $warning = "Database update needed, redirecting to %s. Database is $version and Koha is $kohaversion";
670 if ( $type ne 'opac' ) {
671 warn sprintf( $warning, 'Installer' );
672 print $query->redirect("/cgi-bin/koha/installer/install.pl?step=3");
673 } else {
674 warn sprintf( "OPAC: " . $warning, 'maintenance' );
675 print $query->redirect("/cgi-bin/koha/maintenance.pl");
677 safe_exit;
681 sub _session_log {
682 (@_) or return 0;
683 open my $fh, '>>', "/tmp/sessionlog" or warn "ERROR: Cannot append to /tmp/sessionlog";
684 printf $fh join( "\n", @_ );
685 close $fh;
688 sub _timeout_syspref {
689 my $timeout = C4::Context->preference('timeout') || 600;
691 # value in days, convert in seconds
692 if ( $timeout =~ /(\d+)[dD]/ ) {
693 $timeout = $1 * 86400;
695 return $timeout;
698 sub checkauth {
699 my $query = shift;
700 $debug and warn "Checking Auth";
702 # $authnotrequired will be set for scripts which will run without authentication
703 my $authnotrequired = shift;
704 my $flagsrequired = shift;
705 my $type = shift;
706 my $persona = shift;
707 $type = 'opac' unless $type;
709 my $dbh = C4::Context->dbh;
710 my $timeout = _timeout_syspref();
712 _version_check( $type, $query );
714 # state variables
715 my $loggedin = 0;
716 my %info;
717 my ( $userid, $cookie, $sessionID, $flags, $barshelves, $pubshelves );
718 my $logout = $query->param('logout.x');
720 my $anon_search_history;
722 # This parameter is the name of the CAS server we want to authenticate against,
723 # when using authentication against multiple CAS servers, as configured in Auth_cas_servers.yaml
724 my $casparam = $query->param('cas');
725 my $q_userid = $query->param('userid') // '';
727 # Basic authentication is incompatible with the use of Shibboleth,
728 # as Shibboleth may return REMOTE_USER as a Shibboleth attribute,
729 # and it may not be the attribute we want to use to match the koha login.
731 # Also, do not consider an empty REMOTE_USER.
733 # Finally, after those tests, we can assume (although if it would be better with
734 # a syspref) that if we get a REMOTE_USER, that's from basic authentication,
735 # and we can affect it to $userid.
736 if ( !$shib and defined( $ENV{'REMOTE_USER'} ) and $ENV{'REMOTE_USER'} ne '' and $userid = $ENV{'REMOTE_USER'} ) {
738 # Using Basic Authentication, no cookies required
739 $cookie = $query->cookie(
740 -name => 'CGISESSID',
741 -value => '',
742 -expires => '',
743 -HttpOnly => 1,
745 $loggedin = 1;
747 elsif ($persona) {
749 # we dont want to set a session because we are being called by a persona callback
751 elsif ( $sessionID = $query->cookie("CGISESSID") )
752 { # assignment, not comparison
753 my $session = get_session($sessionID);
754 C4::Context->_new_userenv($sessionID);
755 my ( $ip, $lasttime, $sessiontype );
756 my $s_userid = '';
757 if ($session) {
758 $s_userid = $session->param('id') // '';
759 C4::Context::set_userenv(
760 $session->param('number'), $s_userid,
761 $session->param('cardnumber'), $session->param('firstname'),
762 $session->param('surname'), $session->param('branch'),
763 $session->param('branchname'), $session->param('flags'),
764 $session->param('emailaddress'), $session->param('branchprinter'),
765 $session->param('persona'), $session->param('shibboleth')
767 C4::Context::set_shelves_userenv( 'bar', $session->param('barshelves') );
768 C4::Context::set_shelves_userenv( 'pub', $session->param('pubshelves') );
769 C4::Context::set_shelves_userenv( 'tot', $session->param('totshelves') );
770 $debug and printf STDERR "AUTH_SESSION: (%s)\t%s %s - %s\n", map { $session->param($_) } qw(cardnumber firstname surname branch);
771 $ip = $session->param('ip');
772 $lasttime = $session->param('lasttime');
773 $userid = $s_userid;
774 $sessiontype = $session->param('sessiontype') || '';
776 if ( ( $query->param('koha_login_context') && ( $q_userid ne $s_userid ) )
777 || ( $cas && $query->param('ticket') && !C4::Context->userenv->{'id'} ) || ( $shib && $shib_login && !$logout ) ) {
779 #if a user enters an id ne to the id in the current session, we need to log them in...
780 #first we need to clear the anonymous session...
781 $debug and warn "query id = $q_userid but session id = $s_userid";
782 $anon_search_history = $session->param('search_history');
783 $session->delete();
784 $session->flush;
785 C4::Context->_unset_userenv($sessionID);
786 $sessionID = undef;
787 $userid = undef;
789 elsif ($logout) {
791 # voluntary logout the user
792 # check wether the user was using their shibboleth session or a local one
793 my $shibSuccess = C4::Context->userenv->{'shibboleth'};
794 $session->delete();
795 $session->flush;
796 C4::Context->_unset_userenv($sessionID);
798 #_session_log(sprintf "%20s from %16s logged out at %30s (manually).\n", $userid,$ip,(strftime "%c",localtime));
799 $sessionID = undef;
800 $userid = undef;
802 if ( $cas and $caslogout ) {
803 logout_cas($query);
806 # If we are in a shibboleth session (shibboleth is enabled, a shibboleth match attribute is set and matches koha matchpoint)
807 if ( $shib and $shib_login and $shibSuccess and $type eq 'opac' ) {
809 # (Note: $type eq 'opac' condition should be removed when shibboleth authentication for intranet will be implemented)
810 logout_shib($query);
813 elsif ( !$lasttime || ( $lasttime < time() - $timeout ) ) {
815 # timed logout
816 $info{'timed_out'} = 1;
817 if ($session) {
818 $session->delete();
819 $session->flush;
821 C4::Context->_unset_userenv($sessionID);
823 #_session_log(sprintf "%20s from %16s logged out at %30s (inactivity).\n", $userid,$ip,(strftime "%c",localtime));
824 $userid = undef;
825 $sessionID = undef;
827 elsif ( C4::Context->preference('SessionRestrictionByIP') && $ip ne $ENV{'REMOTE_ADDR'} ) {
829 # Different ip than originally logged in from
830 $info{'oldip'} = $ip;
831 $info{'newip'} = $ENV{'REMOTE_ADDR'};
832 $info{'different_ip'} = 1;
833 $session->delete();
834 $session->flush;
835 C4::Context->_unset_userenv($sessionID);
837 #_session_log(sprintf "%20s from %16s logged out at %30s (ip changed to %16s).\n", $userid,$ip,(strftime "%c",localtime), $info{'newip'});
838 $sessionID = undef;
839 $userid = undef;
841 else {
842 $cookie = $query->cookie(
843 -name => 'CGISESSID',
844 -value => $session->id,
845 -HttpOnly => 1
847 $session->param( 'lasttime', time() );
848 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...
849 $flags = haspermission( $userid, $flagsrequired );
850 if ($flags) {
851 $loggedin = 1;
852 } else {
853 $info{'nopermission'} = 1;
858 unless ( $userid || $sessionID ) {
860 #we initiate a session prior to checking for a username to allow for anonymous sessions...
861 my $session = get_session("") or die "Auth ERROR: Cannot get_session()";
863 # Save anonymous search history in new session so it can be retrieved
864 # by get_template_and_user to store it in user's search history after
865 # a successful login.
866 if ($anon_search_history) {
867 $session->param( 'search_history', $anon_search_history );
870 my $sessionID = $session->id;
871 C4::Context->_new_userenv($sessionID);
872 $cookie = $query->cookie(
873 -name => 'CGISESSID',
874 -value => $session->id,
875 -HttpOnly => 1
877 $userid = $q_userid;
878 my $pki_field = C4::Context->preference('AllowPKIAuth');
879 if ( !defined($pki_field) ) {
880 print STDERR "ERROR: Missing system preference AllowPKIAuth.\n";
881 $pki_field = 'None';
883 if ( ( $cas && $query->param('ticket') )
884 || $userid
885 || ( $shib && $shib_login )
886 || $pki_field ne 'None'
887 || $persona )
889 my $password = $query->param('password');
890 my $shibSuccess = 0;
892 my ( $return, $cardnumber );
894 # If shib is enabled and we have a shib login, does the login match a valid koha user
895 if ( $shib && $shib_login && $type eq 'opac' ) {
896 my $retuserid;
898 # Do not pass password here, else shib will not be checked in checkpw.
899 ( $return, $cardnumber, $retuserid ) = checkpw( $dbh, $userid, undef, $query );
900 $userid = $retuserid;
901 $shibSuccess = $return;
902 $info{'invalidShibLogin'} = 1 unless ($return);
905 # If shib login and match were successfull, skip further login methods
906 unless ($shibSuccess) {
907 if ( $cas && $query->param('ticket') ) {
908 my $retuserid;
909 ( $return, $cardnumber, $retuserid ) =
910 checkpw( $dbh, $userid, $password, $query );
911 $userid = $retuserid;
912 $info{'invalidCasLogin'} = 1 unless ($return);
915 elsif ($persona) {
916 my $value = $persona;
918 # If we're looking up the email, there's a chance that the person
919 # doesn't have a userid. So if there is none, we pass along the
920 # borrower number, and the bits of code that need to know the user
921 # ID will have to be smart enough to handle that.
922 require C4::Members;
923 my @users_info = C4::Members::GetBorrowersWithEmail($value);
924 if (@users_info) {
926 # First the userid, then the borrowernum
927 $value = $users_info[0][1] || $users_info[0][0];
929 else {
930 undef $value;
932 $return = $value ? 1 : 0;
933 $userid = $value;
936 elsif (
937 ( $pki_field eq 'Common Name' && $ENV{'SSL_CLIENT_S_DN_CN'} )
938 || ( $pki_field eq 'emailAddress'
939 && $ENV{'SSL_CLIENT_S_DN_Email'} )
942 my $value;
943 if ( $pki_field eq 'Common Name' ) {
944 $value = $ENV{'SSL_CLIENT_S_DN_CN'};
946 elsif ( $pki_field eq 'emailAddress' ) {
947 $value = $ENV{'SSL_CLIENT_S_DN_Email'};
949 # If we're looking up the email, there's a chance that the person
950 # doesn't have a userid. So if there is none, we pass along the
951 # borrower number, and the bits of code that need to know the user
952 # ID will have to be smart enough to handle that.
953 require C4::Members;
954 my @users_info = C4::Members::GetBorrowersWithEmail($value);
955 if (@users_info) {
957 # First the userid, then the borrowernum
958 $value = $users_info[0][1] || $users_info[0][0];
959 } else {
960 undef $value;
964 $return = $value ? 1 : 0;
965 $userid = $value;
968 else {
969 my $retuserid;
970 ( $return, $cardnumber, $retuserid ) =
971 checkpw( $dbh, $userid, $password, $query );
972 $userid = $retuserid if ($retuserid);
973 $info{'invalid_username_or_password'} = 1 unless ($return);
977 # $return: 1 = valid user, 2 = superlibrarian
978 if ($return) {
980 #_session_log(sprintf "%20s from %16s logged in at %30s.\n", $userid,$ENV{'REMOTE_ADDR'},(strftime '%c', localtime));
981 if ( $flags = haspermission( $userid, $flagsrequired ) ) {
982 $loggedin = 1;
984 else {
985 $info{'nopermission'} = 1;
986 C4::Context->_unset_userenv($sessionID);
988 my ( $borrowernumber, $firstname, $surname, $userflags,
989 $branchcode, $branchname, $branchprinter, $emailaddress );
991 if ( $return == 1 ) {
992 my $select = "
993 SELECT borrowernumber, firstname, surname, flags, borrowers.branchcode,
994 branches.branchname as branchname,
995 branches.branchprinter as branchprinter,
996 email
997 FROM borrowers
998 LEFT JOIN branches on borrowers.branchcode=branches.branchcode
1000 my $sth = $dbh->prepare("$select where userid=?");
1001 $sth->execute($userid);
1002 unless ( $sth->rows ) {
1003 $debug and print STDERR "AUTH_1: no rows for userid='$userid'\n";
1004 $sth = $dbh->prepare("$select where cardnumber=?");
1005 $sth->execute($cardnumber);
1007 unless ( $sth->rows ) {
1008 $debug and print STDERR "AUTH_2a: no rows for cardnumber='$cardnumber'\n";
1009 $sth->execute($userid);
1010 unless ( $sth->rows ) {
1011 $debug and print STDERR "AUTH_2b: no rows for userid='$userid' AS cardnumber\n";
1015 if ( $sth->rows ) {
1016 ( $borrowernumber, $firstname, $surname, $userflags,
1017 $branchcode, $branchname, $branchprinter, $emailaddress ) = $sth->fetchrow;
1018 $debug and print STDERR "AUTH_3 results: " .
1019 "$cardnumber,$borrowernumber,$userid,$firstname,$surname,$userflags,$branchcode,$emailaddress\n";
1020 } else {
1021 print STDERR "AUTH_3: no results for userid='$userid', cardnumber='$cardnumber'.\n";
1024 # launch a sequence to check if we have a ip for the branch, i
1025 # if we have one we replace the branchcode of the userenv by the branch bound in the ip.
1027 my $ip = $ENV{'REMOTE_ADDR'};
1029 # if they specify at login, use that
1030 if ( $query->param('branch') ) {
1031 $branchcode = $query->param('branch');
1032 $branchname = GetBranchName($branchcode);
1034 my $branches = GetBranches();
1035 if ( C4::Context->boolean_preference('IndependentBranches') && C4::Context->boolean_preference('Autolocation') ) {
1037 # we have to check they are coming from the right ip range
1038 my $domain = $branches->{$branchcode}->{'branchip'};
1039 if ( $ip !~ /^$domain/ ) {
1040 $loggedin = 0;
1041 $info{'wrongip'} = 1;
1045 my @branchesloop;
1046 foreach my $br ( keys %$branches ) {
1048 # now we work with the treatment of ip
1049 my $domain = $branches->{$br}->{'branchip'};
1050 if ( $domain && $ip =~ /^$domain/ ) {
1051 $branchcode = $branches->{$br}->{'branchcode'};
1053 # new op dev : add the branchprinter and branchname in the cookie
1054 $branchprinter = $branches->{$br}->{'branchprinter'};
1055 $branchname = $branches->{$br}->{'branchname'};
1058 $session->param( 'number', $borrowernumber );
1059 $session->param( 'id', $userid );
1060 $session->param( 'cardnumber', $cardnumber );
1061 $session->param( 'firstname', $firstname );
1062 $session->param( 'surname', $surname );
1063 $session->param( 'branch', $branchcode );
1064 $session->param( 'branchname', $branchname );
1065 $session->param( 'flags', $userflags );
1066 $session->param( 'emailaddress', $emailaddress );
1067 $session->param( 'ip', $session->remote_addr() );
1068 $session->param( 'lasttime', time() );
1069 $session->param( 'shibboleth', $shibSuccess );
1070 $debug and printf STDERR "AUTH_4: (%s)\t%s %s - %s\n", map { $session->param($_) } qw(cardnumber firstname surname branch);
1072 elsif ( $return == 2 ) {
1074 #We suppose the user is the superlibrarian
1075 $borrowernumber = 0;
1076 $session->param( 'number', 0 );
1077 $session->param( 'id', C4::Context->config('user') );
1078 $session->param( 'cardnumber', C4::Context->config('user') );
1079 $session->param( 'firstname', C4::Context->config('user') );
1080 $session->param( 'surname', C4::Context->config('user') );
1081 $session->param( 'branch', 'NO_LIBRARY_SET' );
1082 $session->param( 'branchname', 'NO_LIBRARY_SET' );
1083 $session->param( 'flags', 1 );
1084 $session->param( 'emailaddress', C4::Context->preference('KohaAdminEmailAddress') );
1085 $session->param( 'ip', $session->remote_addr() );
1086 $session->param( 'lasttime', time() );
1088 if ($persona) {
1089 $session->param( 'persona', 1 );
1091 C4::Context::set_userenv(
1092 $session->param('number'), $session->param('id'),
1093 $session->param('cardnumber'), $session->param('firstname'),
1094 $session->param('surname'), $session->param('branch'),
1095 $session->param('branchname'), $session->param('flags'),
1096 $session->param('emailaddress'), $session->param('branchprinter'),
1097 $session->param('persona'), $session->param('shibboleth')
1101 # $return: 0 = invalid user
1102 # reset to anonymous session
1103 else {
1104 $debug and warn "Login failed, resetting anonymous session...";
1105 if ($userid) {
1106 $info{'invalid_username_or_password'} = 1;
1107 C4::Context->_unset_userenv($sessionID);
1109 $session->param( 'lasttime', time() );
1110 $session->param( 'ip', $session->remote_addr() );
1111 $session->param( 'sessiontype', 'anon' );
1113 } # END if ( $userid = $query->param('userid') )
1114 elsif ( $type eq "opac" ) {
1116 # if we are here this is an anonymous session; add public lists to it and a few other items...
1117 # anonymous sessions are created only for the OPAC
1118 $debug and warn "Initiating an anonymous session...";
1120 # setting a couple of other session vars...
1121 $session->param( 'ip', $session->remote_addr() );
1122 $session->param( 'lasttime', time() );
1123 $session->param( 'sessiontype', 'anon' );
1125 } # END unless ($userid)
1127 # finished authentification, now respond
1128 if ( $loggedin || $authnotrequired )
1130 # successful login
1131 unless ($cookie) {
1132 $cookie = $query->cookie(
1133 -name => 'CGISESSID',
1134 -value => '',
1135 -HttpOnly => 1
1138 return ( $userid, $cookie, $sessionID, $flags );
1143 # AUTH rejected, show the login/password template, after checking the DB.
1147 # get the inputs from the incoming query
1148 my @inputs = ();
1149 foreach my $name ( param $query) {
1150 (next) if ( $name eq 'userid' || $name eq 'password' || $name eq 'ticket' );
1151 my $value = $query->param($name);
1152 push @inputs, { name => $name, value => $value };
1155 my $LibraryNameTitle = C4::Context->preference("LibraryName");
1156 $LibraryNameTitle =~ s/<(?:\/?)(?:br|p)\s*(?:\/?)>/ /sgi;
1157 $LibraryNameTitle =~ s/<(?:[^<>'"]|'(?:[^']*)'|"(?:[^"]*)")*>//sg;
1159 my $template_name = ( $type eq 'opac' ) ? 'opac-auth.tt' : 'auth.tt';
1160 my $template = C4::Templates::gettemplate( $template_name, $type, $query );
1161 $template->param(
1162 branchloop => GetBranchesLoop(),
1163 opaccolorstylesheet => C4::Context->preference("opaccolorstylesheet"),
1164 opaclayoutstylesheet => C4::Context->preference("opaclayoutstylesheet"),
1165 login => 1,
1166 INPUTS => \@inputs,
1167 casAuthentication => C4::Context->preference("casAuthentication"),
1168 shibbolethAuthentication => $shib,
1169 SessionRestrictionByIP => C4::Context->preference("SessionRestrictionByIP"),
1170 suggestion => C4::Context->preference("suggestion"),
1171 virtualshelves => C4::Context->preference("virtualshelves"),
1172 LibraryName => "" . C4::Context->preference("LibraryName"),
1173 LibraryNameTitle => "" . $LibraryNameTitle,
1174 opacuserlogin => C4::Context->preference("opacuserlogin"),
1175 OpacNav => C4::Context->preference("OpacNav"),
1176 OpacNavRight => C4::Context->preference("OpacNavRight"),
1177 OpacNavBottom => C4::Context->preference("OpacNavBottom"),
1178 opaccredits => C4::Context->preference("opaccredits"),
1179 OpacFavicon => C4::Context->preference("OpacFavicon"),
1180 opacreadinghistory => C4::Context->preference("opacreadinghistory"),
1181 opaclanguagesdisplay => C4::Context->preference("opaclanguagesdisplay"),
1182 opacuserjs => C4::Context->preference("opacuserjs"),
1183 opacbookbag => "" . C4::Context->preference("opacbookbag"),
1184 OpacCloud => C4::Context->preference("OpacCloud"),
1185 OpacTopissue => C4::Context->preference("OpacTopissue"),
1186 OpacAuthorities => C4::Context->preference("OpacAuthorities"),
1187 OpacBrowser => C4::Context->preference("OpacBrowser"),
1188 opacheader => C4::Context->preference("opacheader"),
1189 TagsEnabled => C4::Context->preference("TagsEnabled"),
1190 OPACUserCSS => C4::Context->preference("OPACUserCSS"),
1191 intranetcolorstylesheet => C4::Context->preference("intranetcolorstylesheet"),
1192 intranetstylesheet => C4::Context->preference("intranetstylesheet"),
1193 intranetbookbag => C4::Context->preference("intranetbookbag"),
1194 IntranetNav => C4::Context->preference("IntranetNav"),
1195 IntranetFavicon => C4::Context->preference("IntranetFavicon"),
1196 intranetuserjs => C4::Context->preference("intranetuserjs"),
1197 IndependentBranches => C4::Context->preference("IndependentBranches"),
1198 AutoLocation => C4::Context->preference("AutoLocation"),
1199 wrongip => $info{'wrongip'},
1200 PatronSelfRegistration => C4::Context->preference("PatronSelfRegistration"),
1201 PatronSelfRegistrationDefaultCategory => C4::Context->preference("PatronSelfRegistrationDefaultCategory"),
1202 persona => C4::Context->preference("Persona"),
1203 opac_css_override => $ENV{'OPAC_CSS_OVERRIDE'},
1206 $template->param( OpacPublic => C4::Context->preference("OpacPublic") );
1207 $template->param( loginprompt => 1 ) unless $info{'nopermission'};
1209 if ( $type eq 'opac' ) {
1210 my ( $total, $pubshelves ) = C4::VirtualShelves::GetSomeShelfNames( undef, 'MASTHEAD' );
1211 $template->param(
1212 pubshelves => $total->{pubtotal},
1213 pubshelvesloop => $pubshelves,
1217 if ($cas) {
1219 # Is authentication against multiple CAS servers enabled?
1220 if ( C4::Auth_with_cas::multipleAuth && !$casparam ) {
1221 my $casservers = C4::Auth_with_cas::getMultipleAuth();
1222 my @tmplservers;
1223 foreach my $key ( keys %$casservers ) {
1224 push @tmplservers, { name => $key, value => login_cas_url( $query, $key ) . "?cas=$key" };
1226 $template->param(
1227 casServersLoop => \@tmplservers
1229 } else {
1230 $template->param(
1231 casServerUrl => login_cas_url($query),
1235 $template->param(
1236 invalidCasLogin => $info{'invalidCasLogin'}
1240 if ($shib) {
1241 $template->param(
1242 shibbolethAuthentication => $shib,
1243 shibbolethLoginUrl => login_shib_url($query),
1247 my $self_url = $query->url( -absolute => 1 );
1248 $template->param(
1249 url => $self_url,
1250 LibraryName => C4::Context->preference("LibraryName"),
1252 $template->param(%info);
1254 # $cookie = $query->cookie(CGISESSID => $session->id
1255 # );
1256 print $query->header(
1257 -type => 'text/html',
1258 -charset => 'utf-8',
1259 -cookie => $cookie
1261 $template->output;
1262 safe_exit;
1265 =head2 check_api_auth
1267 ($status, $cookie, $sessionId) = check_api_auth($query, $userflags);
1269 Given a CGI query containing the parameters 'userid' and 'password' and/or a session
1270 cookie, determine if the user has the privileges specified by C<$userflags>.
1272 C<check_api_auth> is is meant for authenticating users of web services, and
1273 consequently will always return and will not attempt to redirect the user
1274 agent.
1276 If a valid session cookie is already present, check_api_auth will return a status
1277 of "ok", the cookie, and the Koha session ID.
1279 If no session cookie is present, check_api_auth will check the 'userid' and 'password
1280 parameters and create a session cookie and Koha session if the supplied credentials
1281 are OK.
1283 Possible return values in C<$status> are:
1285 =over
1287 =item "ok" -- user authenticated; C<$cookie> and C<$sessionid> have valid values.
1289 =item "failed" -- credentials are not correct; C<$cookie> and C<$sessionid> are undef
1291 =item "maintenance" -- DB is in maintenance mode; no login possible at the moment
1293 =item "expired -- session cookie has expired; API user should resubmit userid and password
1295 =back
1297 =cut
1299 sub check_api_auth {
1300 my $query = shift;
1301 my $flagsrequired = shift;
1303 my $dbh = C4::Context->dbh;
1304 my $timeout = _timeout_syspref();
1306 unless ( C4::Context->preference('Version') ) {
1308 # database has not been installed yet
1309 return ( "maintenance", undef, undef );
1311 my $kohaversion = C4::Context::KOHAVERSION;
1312 $kohaversion =~ s/(.*\..*)\.(.*)\.(.*)/$1$2$3/;
1313 if ( C4::Context->preference('Version') < $kohaversion ) {
1315 # database in need of version update; assume that
1316 # no API should be called while databsae is in
1317 # this condition.
1318 return ( "maintenance", undef, undef );
1321 # FIXME -- most of what follows is a copy-and-paste
1322 # of code from checkauth. There is an obvious need
1323 # for refactoring to separate the various parts of
1324 # the authentication code, but as of 2007-11-19 this
1325 # is deferred so as to not introduce bugs into the
1326 # regular authentication code for Koha 3.0.
1328 # see if we have a valid session cookie already
1329 # however, if a userid parameter is present (i.e., from
1330 # a form submission, assume that any current cookie
1331 # is to be ignored
1332 my $sessionID = undef;
1333 unless ( $query->param('userid') ) {
1334 $sessionID = $query->cookie("CGISESSID");
1336 if ( $sessionID && not( $cas && $query->param('PT') ) ) {
1337 my $session = get_session($sessionID);
1338 C4::Context->_new_userenv($sessionID);
1339 if ($session) {
1340 C4::Context::set_userenv(
1341 $session->param('number'), $session->param('id'),
1342 $session->param('cardnumber'), $session->param('firstname'),
1343 $session->param('surname'), $session->param('branch'),
1344 $session->param('branchname'), $session->param('flags'),
1345 $session->param('emailaddress'), $session->param('branchprinter')
1348 my $ip = $session->param('ip');
1349 my $lasttime = $session->param('lasttime');
1350 my $userid = $session->param('id');
1351 if ( $lasttime < time() - $timeout ) {
1353 # time out
1354 $session->delete();
1355 $session->flush;
1356 C4::Context->_unset_userenv($sessionID);
1357 $userid = undef;
1358 $sessionID = undef;
1359 return ( "expired", undef, undef );
1360 } elsif ( C4::Context->preference('SessionRestrictionByIP') && $ip ne $ENV{'REMOTE_ADDR'} ) {
1362 # IP address changed
1363 $session->delete();
1364 $session->flush;
1365 C4::Context->_unset_userenv($sessionID);
1366 $userid = undef;
1367 $sessionID = undef;
1368 return ( "expired", undef, undef );
1369 } else {
1370 my $cookie = $query->cookie(
1371 -name => 'CGISESSID',
1372 -value => $session->id,
1373 -HttpOnly => 1,
1375 $session->param( 'lasttime', time() );
1376 my $flags = haspermission( $userid, $flagsrequired );
1377 if ($flags) {
1378 return ( "ok", $cookie, $sessionID );
1379 } else {
1380 $session->delete();
1381 $session->flush;
1382 C4::Context->_unset_userenv($sessionID);
1383 $userid = undef;
1384 $sessionID = undef;
1385 return ( "failed", undef, undef );
1388 } else {
1389 return ( "expired", undef, undef );
1391 } else {
1393 # new login
1394 my $userid = $query->param('userid');
1395 my $password = $query->param('password');
1396 my ( $return, $cardnumber );
1398 # Proxy CAS auth
1399 if ( $cas && $query->param('PT') ) {
1400 my $retuserid;
1401 $debug and print STDERR "## check_api_auth - checking CAS\n";
1403 # In case of a CAS authentication, we use the ticket instead of the password
1404 my $PT = $query->param('PT');
1405 ( $return, $cardnumber, $userid ) = check_api_auth_cas( $dbh, $PT, $query ); # EXTERNAL AUTH
1406 } else {
1408 # User / password auth
1409 unless ( $userid and $password ) {
1411 # caller did something wrong, fail the authenticateion
1412 return ( "failed", undef, undef );
1414 ( $return, $cardnumber ) = checkpw( $dbh, $userid, $password, $query );
1417 if ( $return and haspermission( $userid, $flagsrequired ) ) {
1418 my $session = get_session("");
1419 return ( "failed", undef, undef ) unless $session;
1421 my $sessionID = $session->id;
1422 C4::Context->_new_userenv($sessionID);
1423 my $cookie = $query->cookie(
1424 -name => 'CGISESSID',
1425 -value => $sessionID,
1426 -HttpOnly => 1,
1428 if ( $return == 1 ) {
1429 my (
1430 $borrowernumber, $firstname, $surname,
1431 $userflags, $branchcode, $branchname,
1432 $branchprinter, $emailaddress
1434 my $sth =
1435 $dbh->prepare(
1436 "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=?"
1438 $sth->execute($userid);
1440 $borrowernumber, $firstname, $surname,
1441 $userflags, $branchcode, $branchname,
1442 $branchprinter, $emailaddress
1443 ) = $sth->fetchrow if ( $sth->rows );
1445 unless ( $sth->rows ) {
1446 my $sth = $dbh->prepare(
1447 "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=?"
1449 $sth->execute($cardnumber);
1451 $borrowernumber, $firstname, $surname,
1452 $userflags, $branchcode, $branchname,
1453 $branchprinter, $emailaddress
1454 ) = $sth->fetchrow if ( $sth->rows );
1456 unless ( $sth->rows ) {
1457 $sth->execute($userid);
1459 $borrowernumber, $firstname, $surname, $userflags,
1460 $branchcode, $branchname, $branchprinter, $emailaddress
1461 ) = $sth->fetchrow if ( $sth->rows );
1465 my $ip = $ENV{'REMOTE_ADDR'};
1467 # if they specify at login, use that
1468 if ( $query->param('branch') ) {
1469 $branchcode = $query->param('branch');
1470 $branchname = GetBranchName($branchcode);
1472 my $branches = GetBranches();
1473 my @branchesloop;
1474 foreach my $br ( keys %$branches ) {
1476 # now we work with the treatment of ip
1477 my $domain = $branches->{$br}->{'branchip'};
1478 if ( $domain && $ip =~ /^$domain/ ) {
1479 $branchcode = $branches->{$br}->{'branchcode'};
1481 # new op dev : add the branchprinter and branchname in the cookie
1482 $branchprinter = $branches->{$br}->{'branchprinter'};
1483 $branchname = $branches->{$br}->{'branchname'};
1486 $session->param( 'number', $borrowernumber );
1487 $session->param( 'id', $userid );
1488 $session->param( 'cardnumber', $cardnumber );
1489 $session->param( 'firstname', $firstname );
1490 $session->param( 'surname', $surname );
1491 $session->param( 'branch', $branchcode );
1492 $session->param( 'branchname', $branchname );
1493 $session->param( 'flags', $userflags );
1494 $session->param( 'emailaddress', $emailaddress );
1495 $session->param( 'ip', $session->remote_addr() );
1496 $session->param( 'lasttime', time() );
1497 } elsif ( $return == 2 ) {
1499 #We suppose the user is the superlibrarian
1500 $session->param( 'number', 0 );
1501 $session->param( 'id', C4::Context->config('user') );
1502 $session->param( 'cardnumber', C4::Context->config('user') );
1503 $session->param( 'firstname', C4::Context->config('user') );
1504 $session->param( 'surname', C4::Context->config('user') );
1505 $session->param( 'branch', 'NO_LIBRARY_SET' );
1506 $session->param( 'branchname', 'NO_LIBRARY_SET' );
1507 $session->param( 'flags', 1 );
1508 $session->param( 'emailaddress', C4::Context->preference('KohaAdminEmailAddress') );
1509 $session->param( 'ip', $session->remote_addr() );
1510 $session->param( 'lasttime', time() );
1512 C4::Context::set_userenv(
1513 $session->param('number'), $session->param('id'),
1514 $session->param('cardnumber'), $session->param('firstname'),
1515 $session->param('surname'), $session->param('branch'),
1516 $session->param('branchname'), $session->param('flags'),
1517 $session->param('emailaddress'), $session->param('branchprinter')
1519 return ( "ok", $cookie, $sessionID );
1520 } else {
1521 return ( "failed", undef, undef );
1526 =head2 check_cookie_auth
1528 ($status, $sessionId) = check_api_auth($cookie, $userflags);
1530 Given a CGISESSID cookie set during a previous login to Koha, determine
1531 if the user has the privileges specified by C<$userflags>.
1533 C<check_cookie_auth> is meant for authenticating special services
1534 such as tools/upload-file.pl that are invoked by other pages that
1535 have been authenticated in the usual way.
1537 Possible return values in C<$status> are:
1539 =over
1541 =item "ok" -- user authenticated; C<$sessionID> have valid values.
1543 =item "failed" -- credentials are not correct; C<$sessionid> are undef
1545 =item "maintenance" -- DB is in maintenance mode; no login possible at the moment
1547 =item "expired -- session cookie has expired; API user should resubmit userid and password
1549 =back
1551 =cut
1553 sub check_cookie_auth {
1554 my $cookie = shift;
1555 my $flagsrequired = shift;
1557 my $dbh = C4::Context->dbh;
1558 my $timeout = _timeout_syspref();
1560 unless ( C4::Context->preference('Version') ) {
1562 # database has not been installed yet
1563 return ( "maintenance", undef );
1565 my $kohaversion = C4::Context::KOHAVERSION;
1566 $kohaversion =~ s/(.*\..*)\.(.*)\.(.*)/$1$2$3/;
1567 if ( C4::Context->preference('Version') < $kohaversion ) {
1569 # database in need of version update; assume that
1570 # no API should be called while databsae is in
1571 # this condition.
1572 return ( "maintenance", undef );
1575 # FIXME -- most of what follows is a copy-and-paste
1576 # of code from checkauth. There is an obvious need
1577 # for refactoring to separate the various parts of
1578 # the authentication code, but as of 2007-11-23 this
1579 # is deferred so as to not introduce bugs into the
1580 # regular authentication code for Koha 3.0.
1582 # see if we have a valid session cookie already
1583 # however, if a userid parameter is present (i.e., from
1584 # a form submission, assume that any current cookie
1585 # is to be ignored
1586 unless ( defined $cookie and $cookie ) {
1587 return ( "failed", undef );
1589 my $sessionID = $cookie;
1590 my $session = get_session($sessionID);
1591 C4::Context->_new_userenv($sessionID);
1592 if ($session) {
1593 C4::Context::set_userenv(
1594 $session->param('number'), $session->param('id'),
1595 $session->param('cardnumber'), $session->param('firstname'),
1596 $session->param('surname'), $session->param('branch'),
1597 $session->param('branchname'), $session->param('flags'),
1598 $session->param('emailaddress'), $session->param('branchprinter')
1601 my $ip = $session->param('ip');
1602 my $lasttime = $session->param('lasttime');
1603 my $userid = $session->param('id');
1604 if ( $lasttime < time() - $timeout ) {
1606 # time out
1607 $session->delete();
1608 $session->flush;
1609 C4::Context->_unset_userenv($sessionID);
1610 $userid = undef;
1611 $sessionID = undef;
1612 return ("expired", undef);
1613 } elsif ( C4::Context->preference('SessionRestrictionByIP') && $ip ne $ENV{'REMOTE_ADDR'} ) {
1615 # IP address changed
1616 $session->delete();
1617 $session->flush;
1618 C4::Context->_unset_userenv($sessionID);
1619 $userid = undef;
1620 $sessionID = undef;
1621 return ( "expired", undef );
1622 } else {
1623 $session->param( 'lasttime', time() );
1624 my $flags = haspermission( $userid, $flagsrequired );
1625 if ($flags) {
1626 return ( "ok", $sessionID );
1627 } else {
1628 $session->delete();
1629 $session->flush;
1630 C4::Context->_unset_userenv($sessionID);
1631 $userid = undef;
1632 $sessionID = undef;
1633 return ( "failed", undef );
1636 } else {
1637 return ( "expired", undef );
1641 =head2 get_session
1643 use CGI::Session;
1644 my $session = get_session($sessionID);
1646 Given a session ID, retrieve the CGI::Session object used to store
1647 the session's state. The session object can be used to store
1648 data that needs to be accessed by different scripts during a
1649 user's session.
1651 If the C<$sessionID> parameter is an empty string, a new session
1652 will be created.
1654 =cut
1656 sub get_session {
1657 my $sessionID = shift;
1658 my $storage_method = C4::Context->preference('SessionStorage');
1659 my $dbh = C4::Context->dbh;
1660 my $session;
1661 if ( $storage_method eq 'mysql' ) {
1662 $session = new CGI::Session( "driver:MySQL;serializer:yaml;id:md5", $sessionID, { Handle => $dbh } );
1664 elsif ( $storage_method eq 'Pg' ) {
1665 $session = new CGI::Session( "driver:PostgreSQL;serializer:yaml;id:md5", $sessionID, { Handle => $dbh } );
1667 elsif ( $storage_method eq 'memcached' && C4::Context->ismemcached ) {
1668 $session = new CGI::Session( "driver:memcached;serializer:yaml;id:md5", $sessionID, { Memcached => C4::Context->memcached } );
1670 else {
1671 # catch all defaults to tmp should work on all systems
1672 $session = new CGI::Session( "driver:File;serializer:yaml;id:md5", $sessionID, { Directory => '/tmp' } );
1674 return $session;
1677 sub checkpw {
1678 my ( $dbh, $userid, $password, $query ) = @_;
1679 if ($ldap) {
1680 $debug and print STDERR "## checkpw - checking LDAP\n";
1681 my ( $retval, $retcard, $retuserid ) = checkpw_ldap(@_); # EXTERNAL AUTH
1682 return 0 if $retval == -1; # Incorrect password for LDAP login attempt
1683 ($retval) and return ( $retval, $retcard, $retuserid );
1686 if ( $cas && $query && $query->param('ticket') ) {
1687 $debug and print STDERR "## checkpw - checking CAS\n";
1689 # In case of a CAS authentication, we use the ticket instead of the password
1690 my $ticket = $query->param('ticket');
1691 $query->delete('ticket'); # remove ticket to come back to original URL
1692 my ( $retval, $retcard, $retuserid ) = checkpw_cas( $dbh, $ticket, $query ); # EXTERNAL AUTH
1693 ($retval) and return ( $retval, $retcard, $retuserid );
1694 return 0;
1697 # If we are in a shibboleth session (shibboleth is enabled, and a shibboleth match attribute is present)
1698 # Check for password to asertain whether we want to be testing against shibboleth or another method this
1699 # time around.
1700 if ( $shib && $shib_login && !$password ) {
1702 $debug and print STDERR "## checkpw - checking Shibboleth\n";
1704 # In case of a Shibboleth authentication, we expect a shibboleth user attribute
1705 # (defined under shibboleth mapping in koha-conf.xml) to contain the login of the
1706 # shibboleth-authenticated user
1708 # Then, we check if it matches a valid koha user
1709 if ($shib_login) {
1710 my ( $retval, $retcard, $retuserid ) = C4::Auth_with_shibboleth::checkpw_shib($shib_login); # EXTERNAL AUTH
1711 ($retval) and return ( $retval, $retcard, $retuserid );
1712 return 0;
1716 # INTERNAL AUTH
1717 return checkpw_internal(@_)
1720 sub checkpw_internal {
1721 my ( $dbh, $userid, $password ) = @_;
1723 if ( $userid && $userid eq C4::Context->config('user') ) {
1724 if ( $password && $password eq C4::Context->config('pass') ) {
1726 # Koha superuser account
1727 # C4::Context->set_userenv(0,0,C4::Context->config('user'),C4::Context->config('user'),C4::Context->config('user'),"",1);
1728 return 2;
1730 else {
1731 return 0;
1735 my $sth =
1736 $dbh->prepare(
1737 "select password,cardnumber,borrowernumber,userid,firstname,surname,branchcode,flags from borrowers where userid=?"
1739 $sth->execute($userid);
1740 if ( $sth->rows ) {
1741 my ( $stored_hash, $cardnumber, $borrowernumber, $userid, $firstname,
1742 $surname, $branchcode, $flags )
1743 = $sth->fetchrow;
1745 if ( checkpw_hash( $password, $stored_hash ) ) {
1747 C4::Context->set_userenv( "$borrowernumber", $userid, $cardnumber,
1748 $firstname, $surname, $branchcode, $flags );
1749 return 1, $cardnumber, $userid;
1752 $sth =
1753 $dbh->prepare(
1754 "select password,cardnumber,borrowernumber,userid, firstname,surname,branchcode,flags from borrowers where cardnumber=?"
1756 $sth->execute($userid);
1757 if ( $sth->rows ) {
1758 my ( $stored_hash, $cardnumber, $borrowernumber, $userid, $firstname,
1759 $surname, $branchcode, $flags )
1760 = $sth->fetchrow;
1762 if ( checkpw_hash( $password, $stored_hash ) ) {
1764 C4::Context->set_userenv( $borrowernumber, $userid, $cardnumber,
1765 $firstname, $surname, $branchcode, $flags );
1766 return 1, $cardnumber, $userid;
1769 if ( $userid && $userid eq 'demo'
1770 && "$password" eq 'demo'
1771 && C4::Context->config('demo') )
1774 # DEMO => the demo user is allowed to do everything (if demo set to 1 in koha.conf
1775 # some features won't be effective : modify systempref, modify MARC structure,
1776 return 2;
1778 return 0;
1781 sub checkpw_hash {
1782 my ( $password, $stored_hash ) = @_;
1784 return if $stored_hash eq '!';
1786 # check what encryption algorithm was implemented: Bcrypt - if the hash starts with '$2' it is Bcrypt else md5
1787 my $hash;
1788 if ( substr( $stored_hash, 0, 2 ) eq '$2' ) {
1789 $hash = hash_password( $password, $stored_hash );
1790 } else {
1791 $hash = md5_base64($password);
1793 return $hash eq $stored_hash;
1796 =head2 getuserflags
1798 my $authflags = getuserflags($flags, $userid, [$dbh]);
1800 Translates integer flags into permissions strings hash.
1802 C<$flags> is the integer userflags value ( borrowers.userflags )
1803 C<$userid> is the members.userid, used for building subpermissions
1804 C<$authflags> is a hashref of permissions
1806 =cut
1808 sub getuserflags {
1809 my $flags = shift;
1810 my $userid = shift;
1811 my $dbh = @_ ? shift : C4::Context->dbh;
1812 my $userflags;
1814 # I don't want to do this, but if someone logs in as the database
1815 # user, it would be preferable not to spam them to death with
1816 # numeric warnings. So, we make $flags numeric.
1817 no warnings 'numeric';
1818 $flags += 0;
1820 my $sth = $dbh->prepare("SELECT bit, flag, defaulton FROM userflags");
1821 $sth->execute;
1823 while ( my ( $bit, $flag, $defaulton ) = $sth->fetchrow ) {
1824 if ( ( $flags & ( 2**$bit ) ) || $defaulton ) {
1825 $userflags->{$flag} = 1;
1827 else {
1828 $userflags->{$flag} = 0;
1832 # get subpermissions and merge with top-level permissions
1833 my $user_subperms = get_user_subpermissions($userid);
1834 foreach my $module ( keys %$user_subperms ) {
1835 next if $userflags->{$module} == 1; # user already has permission for everything in this module
1836 $userflags->{$module} = $user_subperms->{$module};
1839 return $userflags;
1842 =head2 get_user_subpermissions
1844 $user_perm_hashref = get_user_subpermissions($userid);
1846 Given the userid (note, not the borrowernumber) of a staff user,
1847 return a hashref of hashrefs of the specific subpermissions
1848 accorded to the user. An example return is
1851 tools => {
1852 export_catalog => 1,
1853 import_patrons => 1,
1857 The top-level hash-key is a module or function code from
1858 userflags.flag, while the second-level key is a code
1859 from permissions.
1861 The results of this function do not give a complete picture
1862 of the functions that a staff user can access; it is also
1863 necessary to check borrowers.flags.
1865 =cut
1867 sub get_user_subpermissions {
1868 my $userid = shift;
1870 my $dbh = C4::Context->dbh;
1871 my $sth = $dbh->prepare( "SELECT flag, user_permissions.code
1872 FROM user_permissions
1873 JOIN permissions USING (module_bit, code)
1874 JOIN userflags ON (module_bit = bit)
1875 JOIN borrowers USING (borrowernumber)
1876 WHERE userid = ?" );
1877 $sth->execute($userid);
1879 my $user_perms = {};
1880 while ( my $perm = $sth->fetchrow_hashref ) {
1881 $user_perms->{ $perm->{'flag'} }->{ $perm->{'code'} } = 1;
1883 return $user_perms;
1886 =head2 get_all_subpermissions
1888 my $perm_hashref = get_all_subpermissions();
1890 Returns a hashref of hashrefs defining all specific
1891 permissions currently defined. The return value
1892 has the same structure as that of C<get_user_subpermissions>,
1893 except that the innermost hash value is the description
1894 of the subpermission.
1896 =cut
1898 sub get_all_subpermissions {
1899 my $dbh = C4::Context->dbh;
1900 my $sth = $dbh->prepare( "SELECT flag, code, description
1901 FROM permissions
1902 JOIN userflags ON (module_bit = bit)" );
1903 $sth->execute();
1905 my $all_perms = {};
1906 while ( my $perm = $sth->fetchrow_hashref ) {
1907 $all_perms->{ $perm->{'flag'} }->{ $perm->{'code'} } = $perm->{'description'};
1909 return $all_perms;
1912 =head2 haspermission
1914 $flags = ($userid, $flagsrequired);
1916 C<$userid> the userid of the member
1917 C<$flags> is a hashref of required flags like C<$borrower-&lt;{authflags}>
1919 Returns member's flags or 0 if a permission is not met.
1921 =cut
1923 sub haspermission {
1924 my ( $userid, $flagsrequired ) = @_;
1925 my $sth = C4::Context->dbh->prepare("SELECT flags FROM borrowers WHERE userid=?");
1926 $sth->execute($userid);
1927 my $row = $sth->fetchrow();
1928 my $flags = getuserflags( $row, $userid );
1929 if ( $userid eq C4::Context->config('user') ) {
1931 # Super User Account from /etc/koha.conf
1932 $flags->{'superlibrarian'} = 1;
1934 elsif ( $userid eq 'demo' && C4::Context->config('demo') ) {
1936 # Demo user that can do "anything" (demo=1 in /etc/koha.conf)
1937 $flags->{'superlibrarian'} = 1;
1940 return $flags if $flags->{superlibrarian};
1942 foreach my $module ( keys %$flagsrequired ) {
1943 my $subperm = $flagsrequired->{$module};
1944 if ( $subperm eq '*' ) {
1945 return 0 unless ( $flags->{$module} == 1 or ref( $flags->{$module} ) );
1946 } else {
1947 return 0 unless ( $flags->{$module} == 1 or
1948 ( ref( $flags->{$module} ) and
1949 exists $flags->{$module}->{$subperm} and
1950 $flags->{$module}->{$subperm} == 1
1955 return $flags;
1957 #FIXME - This fcn should return the failed permission so a suitable error msg can be delivered.
1960 sub getborrowernumber {
1961 my ($userid) = @_;
1962 my $userenv = C4::Context->userenv;
1963 if ( defined($userenv) && ref($userenv) eq 'HASH' && $userenv->{number} ) {
1964 return $userenv->{number};
1966 my $dbh = C4::Context->dbh;
1967 for my $field ( 'userid', 'cardnumber' ) {
1968 my $sth =
1969 $dbh->prepare("select borrowernumber from borrowers where $field=?");
1970 $sth->execute($userid);
1971 if ( $sth->rows ) {
1972 my ($bnumber) = $sth->fetchrow;
1973 return $bnumber;
1976 return 0;
1979 END { } # module clean-up code here (global destructor)
1981 __END__
1983 =head1 SEE ALSO
1985 CGI(3)
1987 C4::Output(3)
1989 Crypt::Eksblowfish::Bcrypt(3)
1991 Digest::MD5(3)
1993 =cut