Bug 14423: XSS issues in marc_subfields_structure
[koha.git] / C4 / Auth.pm
blob34c3f91ffe80a4d3f8533dc0566e3c096ed1352e
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 Koha;
34 use Koha::AuthUtils qw(hash_password);
35 use POSIX qw/strftime/;
36 use List::MoreUtils qw/ any /;
37 use Encode qw( encode is_utf8);
39 # use utf8;
40 use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS $debug $ldap $cas $caslogout $shib $shib_login);
42 BEGIN {
43 sub psgi_env { any { /^psgi\./ } keys %ENV }
45 sub safe_exit {
46 if (psgi_env) { die 'psgi:exit' }
47 else { exit }
49 $VERSION = 3.07.00.049; # set version for version checking
51 $debug = $ENV{DEBUG};
52 @ISA = qw(Exporter);
53 @EXPORT = qw(&checkauth &get_template_and_user &haspermission &get_user_subpermissions);
54 @EXPORT_OK = qw(&check_api_auth &get_session &check_cookie_auth &checkpw &checkpw_internal &checkpw_hash
55 &get_all_subpermissions &get_user_subpermissions
57 %EXPORT_TAGS = ( EditPermissions => [qw(get_all_subpermissions get_user_subpermissions)] );
58 $ldap = C4::Context->config('useldapserver') || 0;
59 $cas = C4::Context->preference('casAuthentication');
60 $shib = C4::Context->config('useshibboleth') || 0;
61 $caslogout = C4::Context->preference('casLogout');
62 require C4::Auth_with_cas; # no import
64 if ($ldap) {
65 require C4::Auth_with_ldap;
66 import C4::Auth_with_ldap qw(checkpw_ldap);
68 if ($shib) {
69 require C4::Auth_with_shibboleth;
70 import C4::Auth_with_shibboleth
71 qw(shib_ok checkpw_shib logout_shib login_shib_url get_login_shib);
73 # Check for good config
74 if ( shib_ok() ) {
76 # Get shibboleth login attribute
77 $shib_login = get_login_shib();
80 # Bad config, disable shibboleth
81 else {
82 $shib = 0;
85 if ($cas) {
86 import C4::Auth_with_cas qw(check_api_auth_cas checkpw_cas login_cas logout_cas login_cas_url);
91 =head1 NAME
93 C4::Auth - Authenticates Koha users
95 =head1 SYNOPSIS
97 use CGI qw ( -utf8 );
98 use C4::Auth;
99 use C4::Output;
101 my $query = new CGI;
103 my ($template, $borrowernumber, $cookie)
104 = get_template_and_user(
106 template_name => "opac-main.tt",
107 query => $query,
108 type => "opac",
109 authnotrequired => 0,
110 flagsrequired => { catalogue => '*', tools => 'import_patrons' },
114 output_html_with_http_headers $query, $cookie, $template->output;
116 =head1 DESCRIPTION
118 The main function of this module is to provide
119 authentification. However the get_template_and_user function has
120 been provided so that a users login information is passed along
121 automatically. This gets loaded into the template.
123 =head1 FUNCTIONS
125 =head2 get_template_and_user
127 my ($template, $borrowernumber, $cookie)
128 = get_template_and_user(
130 template_name => "opac-main.tt",
131 query => $query,
132 type => "opac",
133 authnotrequired => 0,
134 flagsrequired => { catalogue => '*', tools => 'import_patrons' },
138 This call passes the C<query>, C<flagsrequired> and C<authnotrequired>
139 to C<&checkauth> (in this module) to perform authentification.
140 See C<&checkauth> for an explanation of these parameters.
142 The C<template_name> is then used to find the correct template for
143 the page. The authenticated users details are loaded onto the
144 template in the HTML::Template LOOP variable C<USER_INFO>. Also the
145 C<sessionID> is passed to the template. This can be used in templates
146 if cookies are disabled. It needs to be put as and input to every
147 authenticated page.
149 More information on the C<gettemplate> sub can be found in the
150 Output.pm module.
152 =cut
154 sub get_template_and_user {
156 my $in = shift;
157 my ( $user, $cookie, $sessionID, $flags );
159 C4::Context->interface( $in->{type} );
161 my $safe_chars = 'a-zA-Z0-9_\-\/';
162 die "bad template path" unless $in->{'template_name'} =~ m/^[$safe_chars]+.tt?$/ig; #sanitize input
164 $in->{'authnotrequired'} ||= 0;
165 my $template = C4::Templates::gettemplate(
166 $in->{'template_name'},
167 $in->{'type'},
168 $in->{'query'},
169 $in->{'is_plugin'}
172 if ( $in->{'template_name'} !~ m/maintenance/ ) {
173 ( $user, $cookie, $sessionID, $flags ) = checkauth(
174 $in->{'query'},
175 $in->{'authnotrequired'},
176 $in->{'flagsrequired'},
177 $in->{'type'}
181 my $borrowernumber;
182 if ($user) {
183 require C4::Members;
185 # It's possible for $user to be the borrowernumber if they don't have a
186 # userid defined (and are logging in through some other method, such
187 # as SSL certs against an email address)
188 $borrowernumber = getborrowernumber($user) if defined($user);
189 if ( !defined($borrowernumber) && defined($user) ) {
190 my $borrower = C4::Members::GetMember( borrowernumber => $user );
191 if ($borrower) {
192 $borrowernumber = $user;
194 # A bit of a hack, but I don't know there's a nicer way
195 # to do it.
196 $user = $borrower->{firstname} . ' ' . $borrower->{surname};
200 # user info
201 $template->param( loggedinusername => $user );
202 $template->param( loggedinusernumber => $borrowernumber );
203 $template->param( sessionID => $sessionID );
205 if ( $in->{'type'} eq 'opac' ) {
206 require C4::VirtualShelves;
207 my ( $total, $pubshelves, $barshelves ) = C4::VirtualShelves::GetSomeShelfNames( $borrowernumber, 'MASTHEAD' );
208 $template->param(
209 pubshelves => $total->{pubtotal},
210 pubshelvesloop => $pubshelves,
211 barshelves => $total->{bartotal},
212 barshelvesloop => $barshelves,
216 my ($borr) = C4::Members::GetMemberDetails($borrowernumber);
217 my @bordat;
218 $bordat[0] = $borr;
219 $template->param( "USER_INFO" => \@bordat );
221 my $all_perms = get_all_subpermissions();
223 my @flagroots = qw(circulate catalogue parameters borrowers permissions reserveforothers borrow
224 editcatalogue updatecharges management tools editauthorities serials reports acquisition);
226 # We are going to use the $flags returned by checkauth
227 # to create the template's parameters that will indicate
228 # which menus the user can access.
229 if ( $flags && $flags->{superlibrarian} == 1 ) {
230 $template->param( CAN_user_circulate => 1 );
231 $template->param( CAN_user_catalogue => 1 );
232 $template->param( CAN_user_parameters => 1 );
233 $template->param( CAN_user_borrowers => 1 );
234 $template->param( CAN_user_permissions => 1 );
235 $template->param( CAN_user_reserveforothers => 1 );
236 $template->param( CAN_user_editcatalogue => 1 );
237 $template->param( CAN_user_updatecharges => 1 );
238 $template->param( CAN_user_acquisition => 1 );
239 $template->param( CAN_user_management => 1 );
240 $template->param( CAN_user_tools => 1 );
241 $template->param( CAN_user_editauthorities => 1 );
242 $template->param( CAN_user_serials => 1 );
243 $template->param( CAN_user_reports => 1 );
244 $template->param( CAN_user_staffaccess => 1 );
245 $template->param( CAN_user_plugins => 1 );
246 $template->param( CAN_user_coursereserves => 1 );
247 foreach my $module ( keys %$all_perms ) {
249 foreach my $subperm ( keys %{ $all_perms->{$module} } ) {
250 $template->param( "CAN_user_${module}_${subperm}" => 1 );
255 if ($flags) {
256 foreach my $module ( keys %$all_perms ) {
257 if ( defined($flags->{$module}) && $flags->{$module} == 1 ) {
258 foreach my $subperm ( keys %{ $all_perms->{$module} } ) {
259 $template->param( "CAN_user_${module}_${subperm}" => 1 );
261 } elsif ( ref( $flags->{$module} ) ) {
262 foreach my $subperm ( keys %{ $flags->{$module} } ) {
263 $template->param( "CAN_user_${module}_${subperm}" => 1 );
269 if ($flags) {
270 foreach my $module ( keys %$flags ) {
271 if ( $flags->{$module} == 1 or ref( $flags->{$module} ) ) {
272 $template->param( "CAN_user_$module" => 1 );
273 if ( $module eq "parameters" ) {
274 $template->param( CAN_user_management => 1 );
280 # Logged-in opac search history
281 # If the requested template is an opac one and opac search history is enabled
282 if ( $in->{type} eq 'opac' && C4::Context->preference('EnableOpacSearchHistory') ) {
283 my $dbh = C4::Context->dbh;
284 my $query = "SELECT COUNT(*) FROM search_history WHERE userid=?";
285 my $sth = $dbh->prepare($query);
286 $sth->execute($borrowernumber);
288 # If at least one search has already been performed
289 if ( $sth->fetchrow_array > 0 ) {
291 # We show the link in opac
292 $template->param( EnableOpacSearchHistory => 1 );
295 # And if there are searches performed when the user was not logged in,
296 # we add them to the logged-in search history
297 my @recentSearches = C4::Search::History::get_from_session( { cgi => $in->{'query'} } );
298 if (@recentSearches) {
299 my $dbh = C4::Context->dbh;
300 my $query = q{
301 INSERT INTO search_history(userid, sessionid, query_desc, query_cgi, type, total, time )
302 VALUES (?, ?, ?, ?, ?, ?, ?)
305 my $sth = $dbh->prepare($query);
306 $sth->execute( $borrowernumber,
307 $in->{query}->cookie("CGISESSID"),
308 $_->{query_desc},
309 $_->{query_cgi},
310 $_->{type} || 'biblio',
311 $_->{total},
312 $_->{time},
313 ) foreach @recentSearches;
315 # clear out the search history from the session now that
316 # we've saved it to the database
317 C4::Search::History::set_to_session( { cgi => $in->{'query'}, search_history => [] } );
319 } elsif ( $in->{type} eq 'intranet' and C4::Context->preference('EnableSearchHistory') ) {
320 $template->param( EnableSearchHistory => 1 );
323 else { # if this is an anonymous session, setup to display public lists...
325 # If shibboleth is enabled, and we're in an anonymous session, we should allow
326 # the user to attempt login via shibboleth.
327 if ($shib) {
328 $template->param( shibbolethAuthentication => $shib,
329 shibbolethLoginUrl => login_shib_url( $in->{'query'} ),
332 # If shibboleth is enabled and we have a shibboleth login attribute,
333 # but we are in an anonymous session, then we clearly have an invalid
334 # shibboleth koha account.
335 if ($shib_login) {
336 $template->param( invalidShibLogin => '1' );
340 $template->param( sessionID => $sessionID );
342 if ( $in->{'type'} eq 'opac' ){
343 require C4::VirtualShelves;
344 my ( $total, $pubshelves ) = C4::VirtualShelves::GetSomeShelfNames( undef, 'MASTHEAD' );
345 $template->param(
346 pubshelves => $total->{pubtotal},
347 pubshelvesloop => $pubshelves,
352 # Anonymous opac search history
353 # If opac search history is enabled and at least one search has already been performed
354 if ( C4::Context->preference('EnableOpacSearchHistory') ) {
355 my @recentSearches = C4::Search::History::get_from_session( { cgi => $in->{'query'} } );
356 if (@recentSearches) {
357 $template->param( EnableOpacSearchHistory => 1 );
361 if ( C4::Context->preference('dateformat') ) {
362 $template->param( dateformat => C4::Context->preference('dateformat') );
365 # these template parameters are set the same regardless of $in->{'type'}
367 # Set the using_https variable for templates
368 # FIXME Under Plack the CGI->https method always returns 'OFF'
369 my $https = $in->{query}->https();
370 my $using_https = ( defined $https and $https ne 'OFF' ) ? 1 : 0;
372 $template->param(
373 "BiblioDefaultView" . C4::Context->preference("BiblioDefaultView") => 1,
374 EnhancedMessagingPreferences => C4::Context->preference('EnhancedMessagingPreferences'),
375 GoogleJackets => C4::Context->preference("GoogleJackets"),
376 OpenLibraryCovers => C4::Context->preference("OpenLibraryCovers"),
377 KohaAdminEmailAddress => "" . C4::Context->preference("KohaAdminEmailAddress"),
378 LoginBranchcode => ( C4::Context->userenv ? C4::Context->userenv->{"branch"} : undef ),
379 LoginFirstname => ( C4::Context->userenv ? C4::Context->userenv->{"firstname"} : "Bel" ),
380 LoginSurname => C4::Context->userenv ? C4::Context->userenv->{"surname"} : "Inconnu",
381 emailaddress => C4::Context->userenv ? C4::Context->userenv->{"emailaddress"} : undef,
382 loggedinpersona => C4::Context->userenv ? C4::Context->userenv->{"persona"} : undef,
383 TagsEnabled => C4::Context->preference("TagsEnabled"),
384 hide_marc => C4::Context->preference("hide_marc"),
385 item_level_itypes => C4::Context->preference('item-level_itypes'),
386 patronimages => C4::Context->preference("patronimages"),
387 singleBranchMode => C4::Context->preference("singleBranchMode"),
388 XSLTDetailsDisplay => C4::Context->preference("XSLTDetailsDisplay"),
389 XSLTResultsDisplay => C4::Context->preference("XSLTResultsDisplay"),
390 using_https => $using_https,
391 noItemTypeImages => C4::Context->preference("noItemTypeImages"),
392 marcflavour => C4::Context->preference("marcflavour"),
393 persona => C4::Context->preference("persona"),
394 OPACBaseURL => C4::Context->preference('OPACBaseURL'),
396 if ( $in->{'type'} eq "intranet" ) {
397 $template->param(
398 AmazonCoverImages => C4::Context->preference("AmazonCoverImages"),
399 AutoLocation => C4::Context->preference("AutoLocation"),
400 "BiblioDefaultView" . C4::Context->preference("IntranetBiblioDefaultView") => 1,
401 CalendarFirstDayOfWeek => ( C4::Context->preference("CalendarFirstDayOfWeek") eq "Sunday" ) ? 0 : 1,
402 CircAutocompl => C4::Context->preference("CircAutocompl"),
403 FRBRizeEditions => C4::Context->preference("FRBRizeEditions"),
404 IndependentBranches => C4::Context->preference("IndependentBranches"),
405 IntranetNav => C4::Context->preference("IntranetNav"),
406 IntranetmainUserblock => C4::Context->preference("IntranetmainUserblock"),
407 LibraryName => C4::Context->preference("LibraryName"),
408 LoginBranchname => ( C4::Context->userenv ? C4::Context->userenv->{"branchname"} : undef ),
409 advancedMARCEditor => C4::Context->preference("advancedMARCEditor"),
410 canreservefromotherbranches => C4::Context->preference('canreservefromotherbranches'),
411 intranetcolorstylesheet => C4::Context->preference("intranetcolorstylesheet"),
412 IntranetFavicon => C4::Context->preference("IntranetFavicon"),
413 intranetreadinghistory => C4::Context->preference("intranetreadinghistory"),
414 intranetstylesheet => C4::Context->preference("intranetstylesheet"),
415 IntranetUserCSS => C4::Context->preference("IntranetUserCSS"),
416 IntranetUserJS => C4::Context->preference("IntranetUserJS"),
417 intranetbookbag => C4::Context->preference("intranetbookbag"),
418 suggestion => C4::Context->preference("suggestion"),
419 virtualshelves => C4::Context->preference("virtualshelves"),
420 StaffSerialIssueDisplayCount => C4::Context->preference("StaffSerialIssueDisplayCount"),
421 EasyAnalyticalRecords => C4::Context->preference('EasyAnalyticalRecords'),
422 LocalCoverImages => C4::Context->preference('LocalCoverImages'),
423 OPACLocalCoverImages => C4::Context->preference('OPACLocalCoverImages'),
424 AllowMultipleCovers => C4::Context->preference('AllowMultipleCovers'),
425 EnableBorrowerFiles => C4::Context->preference('EnableBorrowerFiles'),
426 UseKohaPlugins => C4::Context->preference('UseKohaPlugins'),
427 UseCourseReserves => C4::Context->preference("UseCourseReserves"),
428 useDischarge => C4::Context->preference('useDischarge'),
431 else {
432 warn "template type should be OPAC, here it is=[" . $in->{'type'} . "]" unless ( $in->{'type'} eq 'opac' );
434 #TODO : replace LibraryName syspref with 'system name', and remove this html processing
435 my $LibraryNameTitle = C4::Context->preference("LibraryName");
436 $LibraryNameTitle =~ s/<(?:\/?)(?:br|p)\s*(?:\/?)>/ /sgi;
437 $LibraryNameTitle =~ s/<(?:[^<>'"]|'(?:[^']*)'|"(?:[^"]*)")*>//sg;
439 # clean up the busc param in the session
440 # if the page is not opac-detail and not the "add to list" page
441 # and not the "edit comments" page
442 if ( C4::Context->preference("OpacBrowseResults")
443 && $in->{'template_name'} =~ /opac-(.+)\.(?:tt|tmpl)$/ ) {
444 my $pagename = $1;
445 unless ( $pagename =~ /^(?:MARC|ISBD)?detail$/
446 or $pagename =~ /^addbybiblionumber$/
447 or $pagename =~ /^review$/ ) {
448 my $sessionSearch = get_session( $sessionID || $in->{'query'}->cookie("CGISESSID") );
449 $sessionSearch->clear( ["busc"] ) if ( $sessionSearch->param("busc") );
453 # variables passed from CGI: opac_css_override and opac_search_limits.
454 my $opac_search_limit = $ENV{'OPAC_SEARCH_LIMIT'};
455 my $opac_limit_override = $ENV{'OPAC_LIMIT_OVERRIDE'};
456 my $opac_name = '';
457 if (
458 ( $opac_limit_override && $opac_search_limit && $opac_search_limit =~ /branch:(\w+)/ ) ||
459 ( $in->{'query'}->param('limit') && $in->{'query'}->param('limit') =~ /branch:(\w+)/ ) ||
460 ( $in->{'query'}->param('multibranchlimit') && $in->{'query'}->param('multibranchlimit') =~ /multibranchlimit-(\w+)/ )
462 $opac_name = $1; # opac_search_limit is a branch, so we use it.
463 } elsif ( $in->{'query'}->param('multibranchlimit') ) {
464 $opac_name = $in->{'query'}->param('multibranchlimit');
465 } elsif ( C4::Context->preference("SearchMyLibraryFirst") && C4::Context->userenv && C4::Context->userenv->{'branch'} ) {
466 $opac_name = C4::Context->userenv->{'branch'};
469 $template->param(
470 OpacAdditionalStylesheet => C4::Context->preference("OpacAdditionalStylesheet"),
471 AnonSuggestions => "" . C4::Context->preference("AnonSuggestions"),
472 AuthorisedValueImages => C4::Context->preference("AuthorisedValueImages"),
473 BranchesLoop => GetBranchesLoop($opac_name),
474 BranchCategoriesLoop => GetBranchCategories( 'searchdomain', 1, $opac_name ),
475 CalendarFirstDayOfWeek => ( C4::Context->preference("CalendarFirstDayOfWeek") eq "Sunday" ) ? 0 : 1,
476 LibraryName => "" . C4::Context->preference("LibraryName"),
477 LibraryNameTitle => "" . $LibraryNameTitle,
478 LoginBranchname => C4::Context->userenv ? C4::Context->userenv->{"branchname"} : "",
479 OPACAmazonCoverImages => C4::Context->preference("OPACAmazonCoverImages"),
480 OPACFRBRizeEditions => C4::Context->preference("OPACFRBRizeEditions"),
481 OpacHighlightedWords => C4::Context->preference("OpacHighlightedWords"),
482 OPACShelfBrowser => "" . C4::Context->preference("OPACShelfBrowser"),
483 OPACURLOpenInNewWindow => "" . C4::Context->preference("OPACURLOpenInNewWindow"),
484 OPACUserCSS => "" . C4::Context->preference("OPACUserCSS"),
485 OpacAuthorities => C4::Context->preference("OpacAuthorities"),
486 opac_css_override => $ENV{'OPAC_CSS_OVERRIDE'},
487 opac_search_limit => $opac_search_limit,
488 opac_limit_override => $opac_limit_override,
489 OpacBrowser => C4::Context->preference("OpacBrowser"),
490 OpacCloud => C4::Context->preference("OpacCloud"),
491 OpacKohaUrl => C4::Context->preference("OpacKohaUrl"),
492 OpacMainUserBlock => "" . C4::Context->preference("OpacMainUserBlock"),
493 OpacNav => "" . C4::Context->preference("OpacNav"),
494 OpacNavRight => "" . C4::Context->preference("OpacNavRight"),
495 OpacNavBottom => "" . C4::Context->preference("OpacNavBottom"),
496 OpacPasswordChange => C4::Context->preference("OpacPasswordChange"),
497 OPACPatronDetails => C4::Context->preference("OPACPatronDetails"),
498 OPACPrivacy => C4::Context->preference("OPACPrivacy"),
499 OPACFinesTab => C4::Context->preference("OPACFinesTab"),
500 OpacTopissue => C4::Context->preference("OpacTopissue"),
501 RequestOnOpac => C4::Context->preference("RequestOnOpac"),
502 'Version' => C4::Context->preference('Version'),
503 hidelostitems => C4::Context->preference("hidelostitems"),
504 mylibraryfirst => ( C4::Context->preference("SearchMyLibraryFirst") && C4::Context->userenv ) ? C4::Context->userenv->{'branch'} : '',
505 opaclayoutstylesheet => "" . C4::Context->preference("opaclayoutstylesheet"),
506 opacbookbag => "" . C4::Context->preference("opacbookbag"),
507 opaccredits => "" . C4::Context->preference("opaccredits"),
508 OpacFavicon => C4::Context->preference("OpacFavicon"),
509 opacheader => "" . C4::Context->preference("opacheader"),
510 opaclanguagesdisplay => "" . C4::Context->preference("opaclanguagesdisplay"),
511 opacreadinghistory => C4::Context->preference("opacreadinghistory"),
512 OPACUserJS => C4::Context->preference("OPACUserJS"),
513 opacuserlogin => "" . C4::Context->preference("opacuserlogin"),
514 ShowReviewer => C4::Context->preference("ShowReviewer"),
515 ShowReviewerPhoto => C4::Context->preference("ShowReviewerPhoto"),
516 suggestion => "" . C4::Context->preference("suggestion"),
517 virtualshelves => "" . C4::Context->preference("virtualshelves"),
518 OPACSerialIssueDisplayCount => C4::Context->preference("OPACSerialIssueDisplayCount"),
519 OPACXSLTDetailsDisplay => C4::Context->preference("OPACXSLTDetailsDisplay"),
520 OPACXSLTResultsDisplay => C4::Context->preference("OPACXSLTResultsDisplay"),
521 SyndeticsClientCode => C4::Context->preference("SyndeticsClientCode"),
522 SyndeticsEnabled => C4::Context->preference("SyndeticsEnabled"),
523 SyndeticsCoverImages => C4::Context->preference("SyndeticsCoverImages"),
524 SyndeticsTOC => C4::Context->preference("SyndeticsTOC"),
525 SyndeticsSummary => C4::Context->preference("SyndeticsSummary"),
526 SyndeticsEditions => C4::Context->preference("SyndeticsEditions"),
527 SyndeticsExcerpt => C4::Context->preference("SyndeticsExcerpt"),
528 SyndeticsReviews => C4::Context->preference("SyndeticsReviews"),
529 SyndeticsAuthorNotes => C4::Context->preference("SyndeticsAuthorNotes"),
530 SyndeticsAwards => C4::Context->preference("SyndeticsAwards"),
531 SyndeticsSeries => C4::Context->preference("SyndeticsSeries"),
532 SyndeticsCoverImageSize => C4::Context->preference("SyndeticsCoverImageSize"),
533 OPACLocalCoverImages => C4::Context->preference("OPACLocalCoverImages"),
534 PatronSelfRegistration => C4::Context->preference("PatronSelfRegistration"),
535 PatronSelfRegistrationDefaultCategory => C4::Context->preference("PatronSelfRegistrationDefaultCategory"),
536 useDischarge => C4::Context->preference('useDischarge'),
539 $template->param( OpacPublic => '1' ) if ( $user || C4::Context->preference("OpacPublic") );
542 # Check if we were asked using parameters to force a specific language
543 if ( defined $in->{'query'}->param('language') ) {
545 # Extract the language, let C4::Languages::getlanguage choose
546 # what to do
547 my $language = C4::Languages::getlanguage( $in->{'query'} );
548 my $languagecookie = C4::Templates::getlanguagecookie( $in->{'query'}, $language );
549 if ( ref $cookie eq 'ARRAY' ) {
550 push @{$cookie}, $languagecookie;
551 } else {
552 $cookie = [ $cookie, $languagecookie ];
556 return ( $template, $borrowernumber, $cookie, $flags );
559 =head2 checkauth
561 ($userid, $cookie, $sessionID) = &checkauth($query, $noauth, $flagsrequired, $type);
563 Verifies that the user is authorized to run this script. If
564 the user is authorized, a (userid, cookie, session-id, flags)
565 quadruple is returned. If the user is not authorized but does
566 not have the required privilege (see $flagsrequired below), it
567 displays an error page and exits. Otherwise, it displays the
568 login page and exits.
570 Note that C<&checkauth> will return if and only if the user
571 is authorized, so it should be called early on, before any
572 unfinished operations (e.g., if you've opened a file, then
573 C<&checkauth> won't close it for you).
575 C<$query> is the CGI object for the script calling C<&checkauth>.
577 The C<$noauth> argument is optional. If it is set, then no
578 authorization is required for the script.
580 C<&checkauth> fetches user and session information from C<$query> and
581 ensures that the user is authorized to run scripts that require
582 authorization.
584 The C<$flagsrequired> argument specifies the required privileges
585 the user must have if the username and password are correct.
586 It should be specified as a reference-to-hash; keys in the hash
587 should be the "flags" for the user, as specified in the Members
588 intranet module. Any key specified must correspond to a "flag"
589 in the userflags table. E.g., { circulate => 1 } would specify
590 that the user must have the "circulate" privilege in order to
591 proceed. To make sure that access control is correct, the
592 C<$flagsrequired> parameter must be specified correctly.
594 Koha also has a concept of sub-permissions, also known as
595 granular permissions. This makes the value of each key
596 in the C<flagsrequired> hash take on an additional
597 meaning, i.e.,
601 The user must have access to all subfunctions of the module
602 specified by the hash key.
606 The user must have access to at least one subfunction of the module
607 specified by the hash key.
609 specific permission, e.g., 'export_catalog'
611 The user must have access to the specific subfunction list, which
612 must correspond to a row in the permissions table.
614 The C<$type> argument specifies whether the template should be
615 retrieved from the opac or intranet directory tree. "opac" is
616 assumed if it is not specified; however, if C<$type> is specified,
617 "intranet" is assumed if it is not "opac".
619 If C<$query> does not have a valid session ID associated with it
620 (i.e., the user has not logged in) or if the session has expired,
621 C<&checkauth> presents the user with a login page (from the point of
622 view of the original script, C<&checkauth> does not return). Once the
623 user has authenticated, C<&checkauth> restarts the original script
624 (this time, C<&checkauth> returns).
626 The login page is provided using a HTML::Template, which is set in the
627 systempreferences table or at the top of this file. The variable C<$type>
628 selects which template to use, either the opac or the intranet
629 authentification template.
631 C<&checkauth> returns a user ID, a cookie, and a session ID. The
632 cookie should be sent back to the browser; it verifies that the user
633 has authenticated.
635 =cut
637 sub _version_check {
638 my $type = shift;
639 my $query = shift;
640 my $version;
642 # If version syspref is unavailable, it means Koha is being installed,
643 # and so we must redirect to OPAC maintenance page or to the WebInstaller
644 # also, if OpacMaintenance is ON, OPAC should redirect to maintenance
645 if ( C4::Context->preference('OpacMaintenance') && $type eq 'opac' ) {
646 warn "OPAC Install required, redirecting to maintenance";
647 print $query->redirect("/cgi-bin/koha/maintenance.pl");
648 safe_exit;
650 unless ( $version = C4::Context->preference('Version') ) { # assignment, not comparison
651 if ( $type ne 'opac' ) {
652 warn "Install required, redirecting to Installer";
653 print $query->redirect("/cgi-bin/koha/installer/install.pl");
654 } else {
655 warn "OPAC Install required, redirecting to maintenance";
656 print $query->redirect("/cgi-bin/koha/maintenance.pl");
658 safe_exit;
661 # check that database and koha version are the same
662 # there is no DB version, it's a fresh install,
663 # go to web installer
664 # there is a DB version, compare it to the code version
665 my $kohaversion = Koha::version();
667 # remove the 3 last . to have a Perl number
668 $kohaversion =~ s/(.*\..*)\.(.*)\.(.*)/$1$2$3/;
669 $debug and print STDERR "kohaversion : $kohaversion\n";
670 if ( $version < $kohaversion ) {
671 my $warning = "Database update needed, redirecting to %s. Database is $version and Koha is $kohaversion";
672 if ( $type ne 'opac' ) {
673 warn sprintf( $warning, 'Installer' );
674 print $query->redirect("/cgi-bin/koha/installer/install.pl?step=1&op=updatestructure");
675 } else {
676 warn sprintf( "OPAC: " . $warning, 'maintenance' );
677 print $query->redirect("/cgi-bin/koha/maintenance.pl");
679 safe_exit;
683 sub _session_log {
684 (@_) or return 0;
685 open my $fh, '>>', "/tmp/sessionlog" or warn "ERROR: Cannot append to /tmp/sessionlog";
686 printf $fh join( "\n", @_ );
687 close $fh;
690 sub _timeout_syspref {
691 my $timeout = C4::Context->preference('timeout') || 600;
693 # value in days, convert in seconds
694 if ( $timeout =~ /(\d+)[dD]/ ) {
695 $timeout = $1 * 86400;
697 return $timeout;
700 sub checkauth {
701 my $query = shift;
702 $debug and warn "Checking Auth";
704 # $authnotrequired will be set for scripts which will run without authentication
705 my $authnotrequired = shift;
706 my $flagsrequired = shift;
707 my $type = shift;
708 my $persona = shift;
709 $type = 'opac' unless $type;
711 my $dbh = C4::Context->dbh;
712 my $timeout = _timeout_syspref();
714 _version_check( $type, $query );
716 # state variables
717 my $loggedin = 0;
718 my %info;
719 my ( $userid, $cookie, $sessionID, $flags, $barshelves, $pubshelves );
720 my $logout = $query->param('logout.x');
722 my $anon_search_history;
724 # This parameter is the name of the CAS server we want to authenticate against,
725 # when using authentication against multiple CAS servers, as configured in Auth_cas_servers.yaml
726 my $casparam = $query->param('cas');
727 my $q_userid = $query->param('userid') // '';
729 # Basic authentication is incompatible with the use of Shibboleth,
730 # as Shibboleth may return REMOTE_USER as a Shibboleth attribute,
731 # and it may not be the attribute we want to use to match the koha login.
733 # Also, do not consider an empty REMOTE_USER.
735 # Finally, after those tests, we can assume (although if it would be better with
736 # a syspref) that if we get a REMOTE_USER, that's from basic authentication,
737 # and we can affect it to $userid.
738 if ( !$shib and defined( $ENV{'REMOTE_USER'} ) and $ENV{'REMOTE_USER'} ne '' and $userid = $ENV{'REMOTE_USER'} ) {
740 # Using Basic Authentication, no cookies required
741 $cookie = $query->cookie(
742 -name => 'CGISESSID',
743 -value => '',
744 -expires => '',
745 -HttpOnly => 1,
747 $loggedin = 1;
749 elsif ($persona) {
751 # we don't want to set a session because we are being called by a persona callback
753 elsif ( $sessionID = $query->cookie("CGISESSID") )
754 { # assignment, not comparison
755 my $session = get_session($sessionID);
756 C4::Context->_new_userenv($sessionID);
757 my ( $ip, $lasttime, $sessiontype );
758 my $s_userid = '';
759 if ($session) {
760 $s_userid = $session->param('id') // '';
761 C4::Context->set_userenv(
762 $session->param('number'), $s_userid,
763 $session->param('cardnumber'), $session->param('firstname'),
764 $session->param('surname'), $session->param('branch'),
765 $session->param('branchname'), $session->param('flags'),
766 $session->param('emailaddress'), $session->param('branchprinter'),
767 $session->param('persona'), $session->param('shibboleth')
769 C4::Context::set_shelves_userenv( 'bar', $session->param('barshelves') );
770 C4::Context::set_shelves_userenv( 'pub', $session->param('pubshelves') );
771 C4::Context::set_shelves_userenv( 'tot', $session->param('totshelves') );
772 $debug and printf STDERR "AUTH_SESSION: (%s)\t%s %s - %s\n", map { $session->param($_) } qw(cardnumber firstname surname branch);
773 $ip = $session->param('ip');
774 $lasttime = $session->param('lasttime');
775 $userid = $s_userid;
776 $sessiontype = $session->param('sessiontype') || '';
778 if ( ( $query->param('koha_login_context') && ( $q_userid ne $s_userid ) )
779 || ( $cas && $query->param('ticket') && !C4::Context->userenv->{'id'} ) || ( $shib && $shib_login && !$logout ) ) {
781 #if a user enters an id ne to the id in the current session, we need to log them in...
782 #first we need to clear the anonymous session...
783 $debug and warn "query id = $q_userid but session id = $s_userid";
784 $anon_search_history = $session->param('search_history');
785 $session->delete();
786 $session->flush;
787 C4::Context->_unset_userenv($sessionID);
788 $sessionID = undef;
789 $userid = undef;
791 elsif ($logout) {
793 # voluntary logout the user
794 # check wether the user was using their shibboleth session or a local one
795 my $shibSuccess = C4::Context->userenv->{'shibboleth'};
796 $session->delete();
797 $session->flush;
798 C4::Context->_unset_userenv($sessionID);
800 #_session_log(sprintf "%20s from %16s logged out at %30s (manually).\n", $userid,$ip,(strftime "%c",localtime));
801 $sessionID = undef;
802 $userid = undef;
804 if ($cas and $caslogout) {
805 logout_cas($query, $type);
808 # If we are in a shibboleth session (shibboleth is enabled, a shibboleth match attribute is set and matches koha matchpoint)
809 if ( $shib and $shib_login and $shibSuccess and $type eq 'opac' ) {
811 # (Note: $type eq 'opac' condition should be removed when shibboleth authentication for intranet will be implemented)
812 logout_shib($query);
815 elsif ( !$lasttime || ( $lasttime < time() - $timeout ) ) {
817 # timed logout
818 $info{'timed_out'} = 1;
819 if ($session) {
820 $session->delete();
821 $session->flush;
823 C4::Context->_unset_userenv($sessionID);
825 #_session_log(sprintf "%20s from %16s logged out at %30s (inactivity).\n", $userid,$ip,(strftime "%c",localtime));
826 $userid = undef;
827 $sessionID = undef;
829 elsif ( C4::Context->preference('SessionRestrictionByIP') && $ip ne $ENV{'REMOTE_ADDR'} ) {
831 # Different ip than originally logged in from
832 $info{'oldip'} = $ip;
833 $info{'newip'} = $ENV{'REMOTE_ADDR'};
834 $info{'different_ip'} = 1;
835 $session->delete();
836 $session->flush;
837 C4::Context->_unset_userenv($sessionID);
839 #_session_log(sprintf "%20s from %16s logged out at %30s (ip changed to %16s).\n", $userid,$ip,(strftime "%c",localtime), $info{'newip'});
840 $sessionID = undef;
841 $userid = undef;
843 else {
844 $cookie = $query->cookie(
845 -name => 'CGISESSID',
846 -value => $session->id,
847 -HttpOnly => 1
849 $session->param( 'lasttime', time() );
850 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...
851 $flags = haspermission( $userid, $flagsrequired );
852 if ($flags) {
853 $loggedin = 1;
854 } else {
855 $info{'nopermission'} = 1;
860 unless ( $userid || $sessionID ) {
862 #we initiate a session prior to checking for a username to allow for anonymous sessions...
863 my $session = get_session("") or die "Auth ERROR: Cannot get_session()";
865 # Save anonymous search history in new session so it can be retrieved
866 # by get_template_and_user to store it in user's search history after
867 # a successful login.
868 if ($anon_search_history) {
869 $session->param( 'search_history', $anon_search_history );
872 my $sessionID = $session->id;
873 C4::Context->_new_userenv($sessionID);
874 $cookie = $query->cookie(
875 -name => 'CGISESSID',
876 -value => $session->id,
877 -HttpOnly => 1
879 $userid = $q_userid;
880 my $pki_field = C4::Context->preference('AllowPKIAuth');
881 if ( !defined($pki_field) ) {
882 print STDERR "ERROR: Missing system preference AllowPKIAuth.\n";
883 $pki_field = 'None';
885 if ( ( $cas && $query->param('ticket') )
886 || $userid
887 || ( $shib && $shib_login )
888 || $pki_field ne 'None'
889 || $persona )
891 my $password = $query->param('password');
892 my $shibSuccess = 0;
894 my ( $return, $cardnumber );
896 # If shib is enabled and we have a shib login, does the login match a valid koha user
897 if ( $shib && $shib_login && $type eq 'opac' ) {
898 my $retuserid;
900 # Do not pass password here, else shib will not be checked in checkpw.
901 ( $return, $cardnumber, $retuserid ) = checkpw( $dbh, $userid, undef, $query );
902 $userid = $retuserid;
903 $shibSuccess = $return;
904 $info{'invalidShibLogin'} = 1 unless ($return);
907 # If shib login and match were successful, skip further login methods
908 unless ($shibSuccess) {
909 if ( $cas && $query->param('ticket') ) {
910 my $retuserid;
911 ( $return, $cardnumber, $retuserid ) =
912 checkpw( $dbh, $userid, $password, $query, $type );
913 $userid = $retuserid;
914 $info{'invalidCasLogin'} = 1 unless ($return);
917 elsif ($persona) {
918 my $value = $persona;
920 # If we're looking up the email, there's a chance that the person
921 # doesn't have a userid. So if there is none, we pass along the
922 # borrower number, and the bits of code that need to know the user
923 # ID will have to be smart enough to handle that.
924 require C4::Members;
925 my @users_info = C4::Members::GetBorrowersWithEmail($value);
926 if (@users_info) {
928 # First the userid, then the borrowernum
929 $value = $users_info[0][1] || $users_info[0][0];
931 else {
932 undef $value;
934 $return = $value ? 1 : 0;
935 $userid = $value;
938 elsif (
939 ( $pki_field eq 'Common Name' && $ENV{'SSL_CLIENT_S_DN_CN'} )
940 || ( $pki_field eq 'emailAddress'
941 && $ENV{'SSL_CLIENT_S_DN_Email'} )
944 my $value;
945 if ( $pki_field eq 'Common Name' ) {
946 $value = $ENV{'SSL_CLIENT_S_DN_CN'};
948 elsif ( $pki_field eq 'emailAddress' ) {
949 $value = $ENV{'SSL_CLIENT_S_DN_Email'};
951 # If we're looking up the email, there's a chance that the person
952 # doesn't have a userid. So if there is none, we pass along the
953 # borrower number, and the bits of code that need to know the user
954 # ID will have to be smart enough to handle that.
955 require C4::Members;
956 my @users_info = C4::Members::GetBorrowersWithEmail($value);
957 if (@users_info) {
959 # First the userid, then the borrowernum
960 $value = $users_info[0][1] || $users_info[0][0];
961 } else {
962 undef $value;
966 $return = $value ? 1 : 0;
967 $userid = $value;
970 else {
971 my $retuserid;
972 ( $return, $cardnumber, $retuserid ) =
973 checkpw( $dbh, $userid, $password, $query, $type );
974 $userid = $retuserid if ($retuserid);
975 $info{'invalid_username_or_password'} = 1 unless ($return);
979 # $return: 1 = valid user, 2 = superlibrarian
980 if ($return) {
982 #_session_log(sprintf "%20s from %16s logged in at %30s.\n", $userid,$ENV{'REMOTE_ADDR'},(strftime '%c', localtime));
983 if ( $flags = haspermission( $userid, $flagsrequired ) ) {
984 $loggedin = 1;
986 else {
987 $info{'nopermission'} = 1;
988 C4::Context->_unset_userenv($sessionID);
990 my ( $borrowernumber, $firstname, $surname, $userflags,
991 $branchcode, $branchname, $branchprinter, $emailaddress );
993 if ( $return == 1 ) {
994 my $select = "
995 SELECT borrowernumber, firstname, surname, flags, borrowers.branchcode,
996 branches.branchname as branchname,
997 branches.branchprinter as branchprinter,
998 email
999 FROM borrowers
1000 LEFT JOIN branches on borrowers.branchcode=branches.branchcode
1002 my $sth = $dbh->prepare("$select where userid=?");
1003 $sth->execute($userid);
1004 unless ( $sth->rows ) {
1005 $debug and print STDERR "AUTH_1: no rows for userid='$userid'\n";
1006 $sth = $dbh->prepare("$select where cardnumber=?");
1007 $sth->execute($cardnumber);
1009 unless ( $sth->rows ) {
1010 $debug and print STDERR "AUTH_2a: no rows for cardnumber='$cardnumber'\n";
1011 $sth->execute($userid);
1012 unless ( $sth->rows ) {
1013 $debug and print STDERR "AUTH_2b: no rows for userid='$userid' AS cardnumber\n";
1017 if ( $sth->rows ) {
1018 ( $borrowernumber, $firstname, $surname, $userflags,
1019 $branchcode, $branchname, $branchprinter, $emailaddress ) = $sth->fetchrow;
1020 $debug and print STDERR "AUTH_3 results: " .
1021 "$cardnumber,$borrowernumber,$userid,$firstname,$surname,$userflags,$branchcode,$emailaddress\n";
1022 } else {
1023 print STDERR "AUTH_3: no results for userid='$userid', cardnumber='$cardnumber'.\n";
1026 # launch a sequence to check if we have a ip for the branch, i
1027 # if we have one we replace the branchcode of the userenv by the branch bound in the ip.
1029 my $ip = $ENV{'REMOTE_ADDR'};
1031 # if they specify at login, use that
1032 if ( $query->param('branch') ) {
1033 $branchcode = $query->param('branch');
1034 $branchname = GetBranchName($branchcode);
1036 my $branches = GetBranches();
1037 if ( C4::Context->boolean_preference('IndependentBranches') && C4::Context->boolean_preference('Autolocation') ) {
1039 # we have to check they are coming from the right ip range
1040 my $domain = $branches->{$branchcode}->{'branchip'};
1041 if ( $ip !~ /^$domain/ ) {
1042 $loggedin = 0;
1043 $info{'wrongip'} = 1;
1047 my @branchesloop;
1048 foreach my $br ( keys %$branches ) {
1050 # now we work with the treatment of ip
1051 my $domain = $branches->{$br}->{'branchip'};
1052 if ( $domain && $ip =~ /^$domain/ ) {
1053 $branchcode = $branches->{$br}->{'branchcode'};
1055 # new op dev : add the branchprinter and branchname in the cookie
1056 $branchprinter = $branches->{$br}->{'branchprinter'};
1057 $branchname = $branches->{$br}->{'branchname'};
1060 $session->param( 'number', $borrowernumber );
1061 $session->param( 'id', $userid );
1062 $session->param( 'cardnumber', $cardnumber );
1063 $session->param( 'firstname', $firstname );
1064 $session->param( 'surname', $surname );
1065 $session->param( 'branch', $branchcode );
1066 $session->param( 'branchname', $branchname );
1067 $session->param( 'flags', $userflags );
1068 $session->param( 'emailaddress', $emailaddress );
1069 $session->param( 'ip', $session->remote_addr() );
1070 $session->param( 'lasttime', time() );
1071 $session->param( 'shibboleth', $shibSuccess );
1072 $debug and printf STDERR "AUTH_4: (%s)\t%s %s - %s\n", map { $session->param($_) } qw(cardnumber firstname surname branch);
1074 elsif ( $return == 2 ) {
1076 #We suppose the user is the superlibrarian
1077 $borrowernumber = 0;
1078 $session->param( 'number', 0 );
1079 $session->param( 'id', C4::Context->config('user') );
1080 $session->param( 'cardnumber', C4::Context->config('user') );
1081 $session->param( 'firstname', C4::Context->config('user') );
1082 $session->param( 'surname', C4::Context->config('user') );
1083 $session->param( 'branch', 'NO_LIBRARY_SET' );
1084 $session->param( 'branchname', 'NO_LIBRARY_SET' );
1085 $session->param( 'flags', 1 );
1086 $session->param( 'emailaddress', C4::Context->preference('KohaAdminEmailAddress') );
1087 $session->param( 'ip', $session->remote_addr() );
1088 $session->param( 'lasttime', time() );
1090 if ($persona) {
1091 $session->param( 'persona', 1 );
1093 C4::Context->set_userenv(
1094 $session->param('number'), $session->param('id'),
1095 $session->param('cardnumber'), $session->param('firstname'),
1096 $session->param('surname'), $session->param('branch'),
1097 $session->param('branchname'), $session->param('flags'),
1098 $session->param('emailaddress'), $session->param('branchprinter'),
1099 $session->param('persona'), $session->param('shibboleth')
1103 # $return: 0 = invalid user
1104 # reset to anonymous session
1105 else {
1106 $debug and warn "Login failed, resetting anonymous session...";
1107 if ($userid) {
1108 $info{'invalid_username_or_password'} = 1;
1109 C4::Context->_unset_userenv($sessionID);
1111 $session->param( 'lasttime', time() );
1112 $session->param( 'ip', $session->remote_addr() );
1113 $session->param( 'sessiontype', 'anon' );
1115 } # END if ( $userid = $query->param('userid') )
1116 elsif ( $type eq "opac" ) {
1118 # if we are here this is an anonymous session; add public lists to it and a few other items...
1119 # anonymous sessions are created only for the OPAC
1120 $debug and warn "Initiating an anonymous session...";
1122 # setting a couple of other session vars...
1123 $session->param( 'ip', $session->remote_addr() );
1124 $session->param( 'lasttime', time() );
1125 $session->param( 'sessiontype', 'anon' );
1127 } # END unless ($userid)
1129 # finished authentification, now respond
1130 if ( $loggedin || $authnotrequired )
1132 # successful login
1133 unless ($cookie) {
1134 $cookie = $query->cookie(
1135 -name => 'CGISESSID',
1136 -value => '',
1137 -HttpOnly => 1
1140 return ( $userid, $cookie, $sessionID, $flags );
1145 # AUTH rejected, show the login/password template, after checking the DB.
1149 # get the inputs from the incoming query
1150 my @inputs = ();
1151 foreach my $name ( param $query) {
1152 (next) if ( $name eq 'userid' || $name eq 'password' || $name eq 'ticket' );
1153 my $value = $query->param($name);
1154 push @inputs, { name => $name, value => $value };
1157 my $LibraryNameTitle = C4::Context->preference("LibraryName");
1158 $LibraryNameTitle =~ s/<(?:\/?)(?:br|p)\s*(?:\/?)>/ /sgi;
1159 $LibraryNameTitle =~ s/<(?:[^<>'"]|'(?:[^']*)'|"(?:[^"]*)")*>//sg;
1161 my $template_name = ( $type eq 'opac' ) ? 'opac-auth.tt' : 'auth.tt';
1162 my $template = C4::Templates::gettemplate( $template_name, $type, $query );
1163 $template->param(
1164 branchloop => GetBranchesLoop(),
1165 OpacAdditionalStylesheet => C4::Context->preference("OpacAdditionalStylesheet"),
1166 opaclayoutstylesheet => C4::Context->preference("opaclayoutstylesheet"),
1167 login => 1,
1168 INPUTS => \@inputs,
1169 casAuthentication => C4::Context->preference("casAuthentication"),
1170 shibbolethAuthentication => $shib,
1171 SessionRestrictionByIP => C4::Context->preference("SessionRestrictionByIP"),
1172 suggestion => C4::Context->preference("suggestion"),
1173 virtualshelves => C4::Context->preference("virtualshelves"),
1174 LibraryName => "" . C4::Context->preference("LibraryName"),
1175 LibraryNameTitle => "" . $LibraryNameTitle,
1176 opacuserlogin => C4::Context->preference("opacuserlogin"),
1177 OpacNav => C4::Context->preference("OpacNav"),
1178 OpacNavRight => C4::Context->preference("OpacNavRight"),
1179 OpacNavBottom => C4::Context->preference("OpacNavBottom"),
1180 opaccredits => C4::Context->preference("opaccredits"),
1181 OpacFavicon => C4::Context->preference("OpacFavicon"),
1182 opacreadinghistory => C4::Context->preference("opacreadinghistory"),
1183 opaclanguagesdisplay => C4::Context->preference("opaclanguagesdisplay"),
1184 OPACUserJS => C4::Context->preference("OPACUserJS"),
1185 opacbookbag => "" . C4::Context->preference("opacbookbag"),
1186 OpacCloud => C4::Context->preference("OpacCloud"),
1187 OpacTopissue => C4::Context->preference("OpacTopissue"),
1188 OpacAuthorities => C4::Context->preference("OpacAuthorities"),
1189 OpacBrowser => C4::Context->preference("OpacBrowser"),
1190 opacheader => C4::Context->preference("opacheader"),
1191 TagsEnabled => C4::Context->preference("TagsEnabled"),
1192 OPACUserCSS => C4::Context->preference("OPACUserCSS"),
1193 intranetcolorstylesheet => C4::Context->preference("intranetcolorstylesheet"),
1194 intranetstylesheet => C4::Context->preference("intranetstylesheet"),
1195 intranetbookbag => C4::Context->preference("intranetbookbag"),
1196 IntranetNav => C4::Context->preference("IntranetNav"),
1197 IntranetFavicon => C4::Context->preference("IntranetFavicon"),
1198 IntranetUserJS => C4::Context->preference("IntranetUserJS"),
1199 IndependentBranches => C4::Context->preference("IndependentBranches"),
1200 AutoLocation => C4::Context->preference("AutoLocation"),
1201 wrongip => $info{'wrongip'},
1202 PatronSelfRegistration => C4::Context->preference("PatronSelfRegistration"),
1203 PatronSelfRegistrationDefaultCategory => C4::Context->preference("PatronSelfRegistrationDefaultCategory"),
1204 persona => C4::Context->preference("Persona"),
1205 opac_css_override => $ENV{'OPAC_CSS_OVERRIDE'},
1208 $template->param( OpacPublic => C4::Context->preference("OpacPublic") );
1209 $template->param( loginprompt => 1 ) unless $info{'nopermission'};
1211 if ( $type eq 'opac' ) {
1212 require C4::VirtualShelves;
1213 my ( $total, $pubshelves ) = C4::VirtualShelves::GetSomeShelfNames( undef, 'MASTHEAD' );
1214 $template->param(
1215 pubshelves => $total->{pubtotal},
1216 pubshelvesloop => $pubshelves,
1220 if ($cas) {
1222 # Is authentication against multiple CAS servers enabled?
1223 if ( C4::Auth_with_cas::multipleAuth && !$casparam ) {
1224 my $casservers = C4::Auth_with_cas::getMultipleAuth();
1225 my @tmplservers;
1226 foreach my $key ( keys %$casservers ) {
1227 push @tmplservers, { name => $key, value => login_cas_url( $query, $key, $type ) . "?cas=$key" };
1229 $template->param(
1230 casServersLoop => \@tmplservers
1232 } else {
1233 $template->param(
1234 casServerUrl => login_cas_url($query, undef, $type),
1238 $template->param(
1239 invalidCasLogin => $info{'invalidCasLogin'}
1243 if ($shib) {
1244 $template->param(
1245 shibbolethAuthentication => $shib,
1246 shibbolethLoginUrl => login_shib_url($query),
1250 my $self_url = $query->url( -absolute => 1 );
1251 $template->param(
1252 url => $self_url,
1253 LibraryName => C4::Context->preference("LibraryName"),
1255 $template->param(%info);
1257 # $cookie = $query->cookie(CGISESSID => $session->id
1258 # );
1259 print $query->header(
1260 -type => 'text/html',
1261 -charset => 'utf-8',
1262 -cookie => $cookie
1264 $template->output;
1265 safe_exit;
1268 =head2 check_api_auth
1270 ($status, $cookie, $sessionId) = check_api_auth($query, $userflags);
1272 Given a CGI query containing the parameters 'userid' and 'password' and/or a session
1273 cookie, determine if the user has the privileges specified by C<$userflags>.
1275 C<check_api_auth> is is meant for authenticating users of web services, and
1276 consequently will always return and will not attempt to redirect the user
1277 agent.
1279 If a valid session cookie is already present, check_api_auth will return a status
1280 of "ok", the cookie, and the Koha session ID.
1282 If no session cookie is present, check_api_auth will check the 'userid' and 'password
1283 parameters and create a session cookie and Koha session if the supplied credentials
1284 are OK.
1286 Possible return values in C<$status> are:
1288 =over
1290 =item "ok" -- user authenticated; C<$cookie> and C<$sessionid> have valid values.
1292 =item "failed" -- credentials are not correct; C<$cookie> and C<$sessionid> are undef
1294 =item "maintenance" -- DB is in maintenance mode; no login possible at the moment
1296 =item "expired -- session cookie has expired; API user should resubmit userid and password
1298 =back
1300 =cut
1302 sub check_api_auth {
1303 my $query = shift;
1304 my $flagsrequired = shift;
1306 my $dbh = C4::Context->dbh;
1307 my $timeout = _timeout_syspref();
1309 unless ( C4::Context->preference('Version') ) {
1311 # database has not been installed yet
1312 return ( "maintenance", undef, undef );
1314 my $kohaversion = Koha::version();
1315 $kohaversion =~ s/(.*\..*)\.(.*)\.(.*)/$1$2$3/;
1316 if ( C4::Context->preference('Version') < $kohaversion ) {
1318 # database in need of version update; assume that
1319 # no API should be called while databsae is in
1320 # this condition.
1321 return ( "maintenance", undef, undef );
1324 # FIXME -- most of what follows is a copy-and-paste
1325 # of code from checkauth. There is an obvious need
1326 # for refactoring to separate the various parts of
1327 # the authentication code, but as of 2007-11-19 this
1328 # is deferred so as to not introduce bugs into the
1329 # regular authentication code for Koha 3.0.
1331 # see if we have a valid session cookie already
1332 # however, if a userid parameter is present (i.e., from
1333 # a form submission, assume that any current cookie
1334 # is to be ignored
1335 my $sessionID = undef;
1336 unless ( $query->param('userid') ) {
1337 $sessionID = $query->cookie("CGISESSID");
1339 if ( $sessionID && not( $cas && $query->param('PT') ) ) {
1340 my $session = get_session($sessionID);
1341 C4::Context->_new_userenv($sessionID);
1342 if ($session) {
1343 C4::Context->set_userenv(
1344 $session->param('number'), $session->param('id'),
1345 $session->param('cardnumber'), $session->param('firstname'),
1346 $session->param('surname'), $session->param('branch'),
1347 $session->param('branchname'), $session->param('flags'),
1348 $session->param('emailaddress'), $session->param('branchprinter')
1351 my $ip = $session->param('ip');
1352 my $lasttime = $session->param('lasttime');
1353 my $userid = $session->param('id');
1354 if ( $lasttime < time() - $timeout ) {
1356 # time out
1357 $session->delete();
1358 $session->flush;
1359 C4::Context->_unset_userenv($sessionID);
1360 $userid = undef;
1361 $sessionID = undef;
1362 return ( "expired", undef, undef );
1363 } elsif ( C4::Context->preference('SessionRestrictionByIP') && $ip ne $ENV{'REMOTE_ADDR'} ) {
1365 # IP address changed
1366 $session->delete();
1367 $session->flush;
1368 C4::Context->_unset_userenv($sessionID);
1369 $userid = undef;
1370 $sessionID = undef;
1371 return ( "expired", undef, undef );
1372 } else {
1373 my $cookie = $query->cookie(
1374 -name => 'CGISESSID',
1375 -value => $session->id,
1376 -HttpOnly => 1,
1378 $session->param( 'lasttime', time() );
1379 my $flags = haspermission( $userid, $flagsrequired );
1380 if ($flags) {
1381 return ( "ok", $cookie, $sessionID );
1382 } else {
1383 $session->delete();
1384 $session->flush;
1385 C4::Context->_unset_userenv($sessionID);
1386 $userid = undef;
1387 $sessionID = undef;
1388 return ( "failed", undef, undef );
1391 } else {
1392 return ( "expired", undef, undef );
1394 } else {
1396 # new login
1397 my $userid = $query->param('userid');
1398 my $password = $query->param('password');
1399 my ( $return, $cardnumber );
1401 # Proxy CAS auth
1402 if ( $cas && $query->param('PT') ) {
1403 my $retuserid;
1404 $debug and print STDERR "## check_api_auth - checking CAS\n";
1406 # In case of a CAS authentication, we use the ticket instead of the password
1407 my $PT = $query->param('PT');
1408 ( $return, $cardnumber, $userid ) = check_api_auth_cas( $dbh, $PT, $query ); # EXTERNAL AUTH
1409 } else {
1411 # User / password auth
1412 unless ( $userid and $password ) {
1414 # caller did something wrong, fail the authenticateion
1415 return ( "failed", undef, undef );
1417 ( $return, $cardnumber ) = checkpw( $dbh, $userid, $password, $query );
1420 if ( $return and haspermission( $userid, $flagsrequired ) ) {
1421 my $session = get_session("");
1422 return ( "failed", undef, undef ) unless $session;
1424 my $sessionID = $session->id;
1425 C4::Context->_new_userenv($sessionID);
1426 my $cookie = $query->cookie(
1427 -name => 'CGISESSID',
1428 -value => $sessionID,
1429 -HttpOnly => 1,
1431 if ( $return == 1 ) {
1432 my (
1433 $borrowernumber, $firstname, $surname,
1434 $userflags, $branchcode, $branchname,
1435 $branchprinter, $emailaddress
1437 my $sth =
1438 $dbh->prepare(
1439 "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=?"
1441 $sth->execute($userid);
1443 $borrowernumber, $firstname, $surname,
1444 $userflags, $branchcode, $branchname,
1445 $branchprinter, $emailaddress
1446 ) = $sth->fetchrow if ( $sth->rows );
1448 unless ( $sth->rows ) {
1449 my $sth = $dbh->prepare(
1450 "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=?"
1452 $sth->execute($cardnumber);
1454 $borrowernumber, $firstname, $surname,
1455 $userflags, $branchcode, $branchname,
1456 $branchprinter, $emailaddress
1457 ) = $sth->fetchrow if ( $sth->rows );
1459 unless ( $sth->rows ) {
1460 $sth->execute($userid);
1462 $borrowernumber, $firstname, $surname, $userflags,
1463 $branchcode, $branchname, $branchprinter, $emailaddress
1464 ) = $sth->fetchrow if ( $sth->rows );
1468 my $ip = $ENV{'REMOTE_ADDR'};
1470 # if they specify at login, use that
1471 if ( $query->param('branch') ) {
1472 $branchcode = $query->param('branch');
1473 $branchname = GetBranchName($branchcode);
1475 my $branches = GetBranches();
1476 my @branchesloop;
1477 foreach my $br ( keys %$branches ) {
1479 # now we work with the treatment of ip
1480 my $domain = $branches->{$br}->{'branchip'};
1481 if ( $domain && $ip =~ /^$domain/ ) {
1482 $branchcode = $branches->{$br}->{'branchcode'};
1484 # new op dev : add the branchprinter and branchname in the cookie
1485 $branchprinter = $branches->{$br}->{'branchprinter'};
1486 $branchname = $branches->{$br}->{'branchname'};
1489 $session->param( 'number', $borrowernumber );
1490 $session->param( 'id', $userid );
1491 $session->param( 'cardnumber', $cardnumber );
1492 $session->param( 'firstname', $firstname );
1493 $session->param( 'surname', $surname );
1494 $session->param( 'branch', $branchcode );
1495 $session->param( 'branchname', $branchname );
1496 $session->param( 'flags', $userflags );
1497 $session->param( 'emailaddress', $emailaddress );
1498 $session->param( 'ip', $session->remote_addr() );
1499 $session->param( 'lasttime', time() );
1500 } elsif ( $return == 2 ) {
1502 #We suppose the user is the superlibrarian
1503 $session->param( 'number', 0 );
1504 $session->param( 'id', C4::Context->config('user') );
1505 $session->param( 'cardnumber', C4::Context->config('user') );
1506 $session->param( 'firstname', C4::Context->config('user') );
1507 $session->param( 'surname', C4::Context->config('user') );
1508 $session->param( 'branch', 'NO_LIBRARY_SET' );
1509 $session->param( 'branchname', 'NO_LIBRARY_SET' );
1510 $session->param( 'flags', 1 );
1511 $session->param( 'emailaddress', C4::Context->preference('KohaAdminEmailAddress') );
1512 $session->param( 'ip', $session->remote_addr() );
1513 $session->param( 'lasttime', time() );
1515 C4::Context->set_userenv(
1516 $session->param('number'), $session->param('id'),
1517 $session->param('cardnumber'), $session->param('firstname'),
1518 $session->param('surname'), $session->param('branch'),
1519 $session->param('branchname'), $session->param('flags'),
1520 $session->param('emailaddress'), $session->param('branchprinter')
1522 return ( "ok", $cookie, $sessionID );
1523 } else {
1524 return ( "failed", undef, undef );
1529 =head2 check_cookie_auth
1531 ($status, $sessionId) = check_api_auth($cookie, $userflags);
1533 Given a CGISESSID cookie set during a previous login to Koha, determine
1534 if the user has the privileges specified by C<$userflags>.
1536 C<check_cookie_auth> is meant for authenticating special services
1537 such as tools/upload-file.pl that are invoked by other pages that
1538 have been authenticated in the usual way.
1540 Possible return values in C<$status> are:
1542 =over
1544 =item "ok" -- user authenticated; C<$sessionID> have valid values.
1546 =item "failed" -- credentials are not correct; C<$sessionid> are undef
1548 =item "maintenance" -- DB is in maintenance mode; no login possible at the moment
1550 =item "expired -- session cookie has expired; API user should resubmit userid and password
1552 =back
1554 =cut
1556 sub check_cookie_auth {
1557 my $cookie = shift;
1558 my $flagsrequired = shift;
1560 my $dbh = C4::Context->dbh;
1561 my $timeout = _timeout_syspref();
1563 unless ( C4::Context->preference('Version') ) {
1565 # database has not been installed yet
1566 return ( "maintenance", undef );
1568 my $kohaversion = Koha::version();
1569 $kohaversion =~ s/(.*\..*)\.(.*)\.(.*)/$1$2$3/;
1570 if ( C4::Context->preference('Version') < $kohaversion ) {
1572 # database in need of version update; assume that
1573 # no API should be called while databsae is in
1574 # this condition.
1575 return ( "maintenance", undef );
1578 # FIXME -- most of what follows is a copy-and-paste
1579 # of code from checkauth. There is an obvious need
1580 # for refactoring to separate the various parts of
1581 # the authentication code, but as of 2007-11-23 this
1582 # is deferred so as to not introduce bugs into the
1583 # regular authentication code for Koha 3.0.
1585 # see if we have a valid session cookie already
1586 # however, if a userid parameter is present (i.e., from
1587 # a form submission, assume that any current cookie
1588 # is to be ignored
1589 unless ( defined $cookie and $cookie ) {
1590 return ( "failed", undef );
1592 my $sessionID = $cookie;
1593 my $session = get_session($sessionID);
1594 C4::Context->_new_userenv($sessionID);
1595 if ($session) {
1596 C4::Context->set_userenv(
1597 $session->param('number'), $session->param('id'),
1598 $session->param('cardnumber'), $session->param('firstname'),
1599 $session->param('surname'), $session->param('branch'),
1600 $session->param('branchname'), $session->param('flags'),
1601 $session->param('emailaddress'), $session->param('branchprinter')
1604 my $ip = $session->param('ip');
1605 my $lasttime = $session->param('lasttime');
1606 my $userid = $session->param('id');
1607 if ( $lasttime < time() - $timeout ) {
1609 # time out
1610 $session->delete();
1611 $session->flush;
1612 C4::Context->_unset_userenv($sessionID);
1613 $userid = undef;
1614 $sessionID = undef;
1615 return ("expired", undef);
1616 } elsif ( C4::Context->preference('SessionRestrictionByIP') && $ip ne $ENV{'REMOTE_ADDR'} ) {
1618 # IP address changed
1619 $session->delete();
1620 $session->flush;
1621 C4::Context->_unset_userenv($sessionID);
1622 $userid = undef;
1623 $sessionID = undef;
1624 return ( "expired", undef );
1625 } else {
1626 $session->param( 'lasttime', time() );
1627 my $flags = haspermission( $userid, $flagsrequired );
1628 if ($flags) {
1629 return ( "ok", $sessionID );
1630 } else {
1631 $session->delete();
1632 $session->flush;
1633 C4::Context->_unset_userenv($sessionID);
1634 $userid = undef;
1635 $sessionID = undef;
1636 return ( "failed", undef );
1639 } else {
1640 return ( "expired", undef );
1644 =head2 get_session
1646 use CGI::Session;
1647 my $session = get_session($sessionID);
1649 Given a session ID, retrieve the CGI::Session object used to store
1650 the session's state. The session object can be used to store
1651 data that needs to be accessed by different scripts during a
1652 user's session.
1654 If the C<$sessionID> parameter is an empty string, a new session
1655 will be created.
1657 =cut
1659 sub get_session {
1660 my $sessionID = shift;
1661 my $storage_method = C4::Context->preference('SessionStorage');
1662 my $dbh = C4::Context->dbh;
1663 my $session;
1664 if ( $storage_method eq 'mysql' ) {
1665 $session = new CGI::Session( "driver:MySQL;serializer:yaml;id:md5", $sessionID, { Handle => $dbh } );
1667 elsif ( $storage_method eq 'Pg' ) {
1668 $session = new CGI::Session( "driver:PostgreSQL;serializer:yaml;id:md5", $sessionID, { Handle => $dbh } );
1670 elsif ( $storage_method eq 'memcached' && C4::Context->ismemcached ) {
1671 $session = new CGI::Session( "driver:memcached;serializer:yaml;id:md5", $sessionID, { Memcached => C4::Context->memcached } );
1673 else {
1674 # catch all defaults to tmp should work on all systems
1675 $session = new CGI::Session( "driver:File;serializer:yaml;id:md5", $sessionID, { Directory => '/tmp' } );
1677 return $session;
1680 sub checkpw {
1681 my ( $dbh, $userid, $password, $query, $type ) = @_;
1682 $type = 'opac' unless $type;
1683 if ($ldap) {
1684 $debug and print STDERR "## checkpw - checking LDAP\n";
1685 my ( $retval, $retcard, $retuserid ) = checkpw_ldap(@_); # EXTERNAL AUTH
1686 return 0 if $retval == -1; # Incorrect password for LDAP login attempt
1687 ($retval) and return ( $retval, $retcard, $retuserid );
1690 if ( $cas && $query && $query->param('ticket') ) {
1691 $debug and print STDERR "## checkpw - checking CAS\n";
1693 # In case of a CAS authentication, we use the ticket instead of the password
1694 my $ticket = $query->param('ticket');
1695 $query->delete('ticket'); # remove ticket to come back to original URL
1696 my ( $retval, $retcard, $retuserid ) = checkpw_cas( $dbh, $ticket, $query, $type ); # EXTERNAL AUTH
1697 ($retval) and return ( $retval, $retcard, $retuserid );
1698 return 0;
1701 # If we are in a shibboleth session (shibboleth is enabled, and a shibboleth match attribute is present)
1702 # Check for password to asertain whether we want to be testing against shibboleth or another method this
1703 # time around.
1704 if ( $shib && $shib_login && !$password ) {
1706 $debug and print STDERR "## checkpw - checking Shibboleth\n";
1708 # In case of a Shibboleth authentication, we expect a shibboleth user attribute
1709 # (defined under shibboleth mapping in koha-conf.xml) to contain the login of the
1710 # shibboleth-authenticated user
1712 # Then, we check if it matches a valid koha user
1713 if ($shib_login) {
1714 my ( $retval, $retcard, $retuserid ) = C4::Auth_with_shibboleth::checkpw_shib($shib_login); # EXTERNAL AUTH
1715 ($retval) and return ( $retval, $retcard, $retuserid );
1716 return 0;
1720 # INTERNAL AUTH
1721 return checkpw_internal(@_)
1724 sub checkpw_internal {
1725 my ( $dbh, $userid, $password ) = @_;
1727 $password = Encode::encode( 'UTF-8', $password )
1728 if Encode::is_utf8($password);
1730 if ( $userid && $userid eq C4::Context->config('user') ) {
1731 if ( $password && $password eq C4::Context->config('pass') ) {
1733 # Koha superuser account
1734 # C4::Context->set_userenv(0,0,C4::Context->config('user'),C4::Context->config('user'),C4::Context->config('user'),"",1);
1735 return 2;
1737 else {
1738 return 0;
1742 my $sth =
1743 $dbh->prepare(
1744 "select password,cardnumber,borrowernumber,userid,firstname,surname,borrowers.branchcode,branches.branchname,flags from borrowers join branches on borrowers.branchcode=branches.branchcode where userid=?"
1746 $sth->execute($userid);
1747 if ( $sth->rows ) {
1748 my ( $stored_hash, $cardnumber, $borrowernumber, $userid, $firstname,
1749 $surname, $branchcode, $branchname, $flags )
1750 = $sth->fetchrow;
1752 if ( checkpw_hash( $password, $stored_hash ) ) {
1754 C4::Context->set_userenv( "$borrowernumber", $userid, $cardnumber,
1755 $firstname, $surname, $branchcode, $branchname, $flags );
1756 return 1, $cardnumber, $userid;
1759 $sth =
1760 $dbh->prepare(
1761 "select password,cardnumber,borrowernumber,userid,firstname,surname,borrowers.branchcode,branches.branchname,flags from borrowers join branches on borrowers.branchcode=branches.branchcode where cardnumber=?"
1763 $sth->execute($userid);
1764 if ( $sth->rows ) {
1765 my ( $stored_hash, $cardnumber, $borrowernumber, $userid, $firstname,
1766 $surname, $branchcode, $branchname, $flags )
1767 = $sth->fetchrow;
1769 if ( checkpw_hash( $password, $stored_hash ) ) {
1771 C4::Context->set_userenv( $borrowernumber, $userid, $cardnumber,
1772 $firstname, $surname, $branchcode, $branchname, $flags );
1773 return 1, $cardnumber, $userid;
1776 if ( $userid && $userid eq 'demo'
1777 && "$password" eq 'demo'
1778 && C4::Context->config('demo') )
1781 # DEMO => the demo user is allowed to do everything (if demo set to 1 in koha.conf
1782 # some features won't be effective : modify systempref, modify MARC structure,
1783 return 2;
1785 return 0;
1788 sub checkpw_hash {
1789 my ( $password, $stored_hash ) = @_;
1791 return if $stored_hash eq '!';
1793 # check what encryption algorithm was implemented: Bcrypt - if the hash starts with '$2' it is Bcrypt else md5
1794 my $hash;
1795 if ( substr( $stored_hash, 0, 2 ) eq '$2' ) {
1796 $hash = hash_password( $password, $stored_hash );
1797 } else {
1798 $hash = md5_base64($password);
1800 return $hash eq $stored_hash;
1803 =head2 getuserflags
1805 my $authflags = getuserflags($flags, $userid, [$dbh]);
1807 Translates integer flags into permissions strings hash.
1809 C<$flags> is the integer userflags value ( borrowers.userflags )
1810 C<$userid> is the members.userid, used for building subpermissions
1811 C<$authflags> is a hashref of permissions
1813 =cut
1815 sub getuserflags {
1816 my $flags = shift;
1817 my $userid = shift;
1818 my $dbh = @_ ? shift : C4::Context->dbh;
1819 my $userflags;
1821 # I don't want to do this, but if someone logs in as the database
1822 # user, it would be preferable not to spam them to death with
1823 # numeric warnings. So, we make $flags numeric.
1824 no warnings 'numeric';
1825 $flags += 0;
1827 my $sth = $dbh->prepare("SELECT bit, flag, defaulton FROM userflags");
1828 $sth->execute;
1830 while ( my ( $bit, $flag, $defaulton ) = $sth->fetchrow ) {
1831 if ( ( $flags & ( 2**$bit ) ) || $defaulton ) {
1832 $userflags->{$flag} = 1;
1834 else {
1835 $userflags->{$flag} = 0;
1839 # get subpermissions and merge with top-level permissions
1840 my $user_subperms = get_user_subpermissions($userid);
1841 foreach my $module ( keys %$user_subperms ) {
1842 next if $userflags->{$module} == 1; # user already has permission for everything in this module
1843 $userflags->{$module} = $user_subperms->{$module};
1846 return $userflags;
1849 =head2 get_user_subpermissions
1851 $user_perm_hashref = get_user_subpermissions($userid);
1853 Given the userid (note, not the borrowernumber) of a staff user,
1854 return a hashref of hashrefs of the specific subpermissions
1855 accorded to the user. An example return is
1858 tools => {
1859 export_catalog => 1,
1860 import_patrons => 1,
1864 The top-level hash-key is a module or function code from
1865 userflags.flag, while the second-level key is a code
1866 from permissions.
1868 The results of this function do not give a complete picture
1869 of the functions that a staff user can access; it is also
1870 necessary to check borrowers.flags.
1872 =cut
1874 sub get_user_subpermissions {
1875 my $userid = shift;
1877 my $dbh = C4::Context->dbh;
1878 my $sth = $dbh->prepare( "SELECT flag, user_permissions.code
1879 FROM user_permissions
1880 JOIN permissions USING (module_bit, code)
1881 JOIN userflags ON (module_bit = bit)
1882 JOIN borrowers USING (borrowernumber)
1883 WHERE userid = ?" );
1884 $sth->execute($userid);
1886 my $user_perms = {};
1887 while ( my $perm = $sth->fetchrow_hashref ) {
1888 $user_perms->{ $perm->{'flag'} }->{ $perm->{'code'} } = 1;
1890 return $user_perms;
1893 =head2 get_all_subpermissions
1895 my $perm_hashref = get_all_subpermissions();
1897 Returns a hashref of hashrefs defining all specific
1898 permissions currently defined. The return value
1899 has the same structure as that of C<get_user_subpermissions>,
1900 except that the innermost hash value is the description
1901 of the subpermission.
1903 =cut
1905 sub get_all_subpermissions {
1906 my $dbh = C4::Context->dbh;
1907 my $sth = $dbh->prepare( "SELECT flag, code, description
1908 FROM permissions
1909 JOIN userflags ON (module_bit = bit)" );
1910 $sth->execute();
1912 my $all_perms = {};
1913 while ( my $perm = $sth->fetchrow_hashref ) {
1914 $all_perms->{ $perm->{'flag'} }->{ $perm->{'code'} } = $perm->{'description'};
1916 return $all_perms;
1919 =head2 haspermission
1921 $flags = ($userid, $flagsrequired);
1923 C<$userid> the userid of the member
1924 C<$flags> is a hashref of required flags like C<$borrower-&lt;{authflags}>
1926 Returns member's flags or 0 if a permission is not met.
1928 =cut
1930 sub haspermission {
1931 my ( $userid, $flagsrequired ) = @_;
1932 my $sth = C4::Context->dbh->prepare("SELECT flags FROM borrowers WHERE userid=?");
1933 $sth->execute($userid);
1934 my $row = $sth->fetchrow();
1935 my $flags = getuserflags( $row, $userid );
1936 if ( $userid eq C4::Context->config('user') ) {
1938 # Super User Account from /etc/koha.conf
1939 $flags->{'superlibrarian'} = 1;
1941 elsif ( $userid eq 'demo' && C4::Context->config('demo') ) {
1943 # Demo user that can do "anything" (demo=1 in /etc/koha.conf)
1944 $flags->{'superlibrarian'} = 1;
1947 return $flags if $flags->{superlibrarian};
1949 foreach my $module ( keys %$flagsrequired ) {
1950 my $subperm = $flagsrequired->{$module};
1951 if ( $subperm eq '*' ) {
1952 return 0 unless ( $flags->{$module} == 1 or ref( $flags->{$module} ) );
1953 } else {
1954 return 0 unless (
1955 ( defined $flags->{$module} and
1956 $flags->{$module} == 1 )
1958 ( ref( $flags->{$module} ) and
1959 exists $flags->{$module}->{$subperm} and
1960 $flags->{$module}->{$subperm} == 1 )
1964 return $flags;
1966 #FIXME - This fcn should return the failed permission so a suitable error msg can be delivered.
1969 sub getborrowernumber {
1970 my ($userid) = @_;
1971 my $userenv = C4::Context->userenv;
1972 if ( defined($userenv) && ref($userenv) eq 'HASH' && $userenv->{number} ) {
1973 return $userenv->{number};
1975 my $dbh = C4::Context->dbh;
1976 for my $field ( 'userid', 'cardnumber' ) {
1977 my $sth =
1978 $dbh->prepare("select borrowernumber from borrowers where $field=?");
1979 $sth->execute($userid);
1980 if ( $sth->rows ) {
1981 my ($bnumber) = $sth->fetchrow;
1982 return $bnumber;
1985 return 0;
1988 END { } # module clean-up code here (global destructor)
1990 __END__
1992 =head1 SEE ALSO
1994 CGI(3)
1996 C4::Output(3)
1998 Crypt::Eksblowfish::Bcrypt(3)
2000 Digest::MD5(3)
2002 =cut