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 under the
8 # terms of the GNU General Public License as published by the Free Software
9 # Foundation; either version 2 of the License, or (at your option) any later
12 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
13 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14 # A PARTICULAR PURPOSE. See the GNU General Public License for more details.
16 # You should have received a copy of the GNU General Public License along
17 # with Koha; if not, write to the Free Software Foundation, Inc.,
18 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
22 use Digest
::MD5
qw(md5_base64);
23 use JSON qw
/encode_json/;
29 use C4
::Templates
; # to get the template
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 /;
39 use vars
qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS $debug $ldap $cas $caslogout $shib $shib_login);
42 sub psgi_env { any { /^psgi\./ } keys %ENV }
45 if (psgi_env) { die 'psgi:exit' }
48 $VERSION = 3.07.00.049; # set version for version checking
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
64 require C4
::Auth_with_ldap
;
65 import C4
::Auth_with_ldap
qw(checkpw_ldap);
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
75 # Get shibboleth login attribute
76 $shib_login = get_login_shib
();
79 # Bad config, disable shibboleth
85 import C4
::Auth_with_cas
qw(check_api_auth_cas checkpw_cas login_cas logout_cas login_cas_url);
92 C4::Auth - Authenticates Koha users
102 my ($template, $borrowernumber, $cookie)
103 = get_template_and_user(
105 template_name => "opac-main.tt",
108 authnotrequired => 0,
109 flagsrequired => {borrow => 1, catalogue => '*', tools => 'import_patrons' },
113 output_html_with_http_headers $query, $cookie, $template->output;
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.
124 =head2 get_template_and_user
126 my ($template, $borrowernumber, $cookie)
127 = get_template_and_user(
129 template_name => "opac-main.tt",
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
148 More information on the C<gettemplate> sub can be found in the
153 sub get_template_and_user
{
156 my ( $user, $cookie, $sessionID, $flags );
158 C4
::Context
->interface( $in->{type
} );
160 $in->{'authnotrequired'} ||= 0;
161 my $template = C4
::Templates
::gettemplate
(
162 $in->{'template_name'},
168 if ( $in->{'template_name'} !~ m/maintenance/ ) {
169 ( $user, $cookie, $sessionID, $flags ) = checkauth
(
171 $in->{'authnotrequired'},
172 $in->{'flagsrequired'},
181 # It's possible for $user to be the borrowernumber if they don't have a
182 # userid defined (and are logging in through some other method, such
183 # as SSL certs against an email address)
184 $borrowernumber = getborrowernumber
($user) if defined($user);
185 if ( !defined($borrowernumber) && defined($user) ) {
186 my $borrower = C4
::Members
::GetMember
( borrowernumber
=> $user );
188 $borrowernumber = $user;
190 # A bit of a hack, but I don't know there's a nicer way
192 $user = $borrower->{firstname
} . ' ' . $borrower->{surname
};
197 $template->param( loggedinusername
=> $user );
198 $template->param( loggedinusernumber
=> $borrowernumber );
199 $template->param( sessionID
=> $sessionID );
201 my ( $total, $pubshelves, $barshelves ) = C4
::VirtualShelves
::GetSomeShelfNames
( $borrowernumber, 'MASTHEAD' );
203 pubshelves
=> $total->{pubtotal
},
204 pubshelvesloop
=> $pubshelves,
205 barshelves
=> $total->{bartotal
},
206 barshelvesloop
=> $barshelves,
209 my ($borr) = C4
::Members
::GetMemberDetails
($borrowernumber);
212 $template->param( "USER_INFO" => \
@bordat );
214 my $all_perms = get_all_subpermissions
();
216 my @flagroots = qw(circulate catalogue parameters borrowers permissions reserveforothers borrow
217 editcatalogue updatecharges management tools editauthorities serials reports acquisition);
219 # We are going to use the $flags returned by checkauth
220 # to create the template's parameters that will indicate
221 # which menus the user can access.
222 if ( $flags && $flags->{superlibrarian
} == 1 ) {
223 $template->param( CAN_user_circulate
=> 1 );
224 $template->param( CAN_user_catalogue
=> 1 );
225 $template->param( CAN_user_parameters
=> 1 );
226 $template->param( CAN_user_borrowers
=> 1 );
227 $template->param( CAN_user_permissions
=> 1 );
228 $template->param( CAN_user_reserveforothers
=> 1 );
229 $template->param( CAN_user_borrow
=> 1 );
230 $template->param( CAN_user_editcatalogue
=> 1 );
231 $template->param( CAN_user_updatecharges
=> 1 );
232 $template->param( CAN_user_acquisition
=> 1 );
233 $template->param( CAN_user_management
=> 1 );
234 $template->param( CAN_user_tools
=> 1 );
235 $template->param( CAN_user_editauthorities
=> 1 );
236 $template->param( CAN_user_serials
=> 1 );
237 $template->param( CAN_user_reports
=> 1 );
238 $template->param( CAN_user_staffaccess
=> 1 );
239 $template->param( CAN_user_plugins
=> 1 );
240 $template->param( CAN_user_coursereserves
=> 1 );
241 foreach my $module ( keys %$all_perms ) {
243 foreach my $subperm ( keys %{ $all_perms->{$module} } ) {
244 $template->param( "CAN_user_${module}_${subperm}" => 1 );
250 foreach my $module ( keys %$all_perms ) {
251 if ( $flags->{$module} == 1 ) {
252 foreach my $subperm ( keys %{ $all_perms->{$module} } ) {
253 $template->param( "CAN_user_${module}_${subperm}" => 1 );
255 } elsif ( ref( $flags->{$module} ) ) {
256 foreach my $subperm ( keys %{ $flags->{$module} } ) {
257 $template->param( "CAN_user_${module}_${subperm}" => 1 );
264 foreach my $module ( keys %$flags ) {
265 if ( $flags->{$module} == 1 or ref( $flags->{$module} ) ) {
266 $template->param( "CAN_user_$module" => 1 );
267 if ( $module eq "parameters" ) {
268 $template->param( CAN_user_management
=> 1 );
274 # Logged-in opac search history
275 # If the requested template is an opac one and opac search history is enabled
276 if ( $in->{type
} eq 'opac' && C4
::Context
->preference('EnableOpacSearchHistory') ) {
277 my $dbh = C4
::Context
->dbh;
278 my $query = "SELECT COUNT(*) FROM search_history WHERE userid=?";
279 my $sth = $dbh->prepare($query);
280 $sth->execute($borrowernumber);
282 # If at least one search has already been performed
283 if ( $sth->fetchrow_array > 0 ) {
285 # We show the link in opac
286 $template->param( EnableOpacSearchHistory
=> 1 );
289 # And if there are searches performed when the user was not logged in,
290 # we add them to the logged-in search history
291 my @recentSearches = C4
::Search
::History
::get_from_session
( { cgi
=> $in->{'query'} } );
292 if (@recentSearches) {
293 my $dbh = C4
::Context
->dbh;
295 INSERT INTO search_history(userid, sessionid, query_desc, query_cgi, type, total, time )
296 VALUES (?, ?, ?, ?, ?, ?, ?)
299 my $sth = $dbh->prepare($query);
300 $sth->execute( $borrowernumber,
301 $in->{query
}->cookie("CGISESSID"),
304 $_->{type
} || 'biblio',
307 ) foreach @recentSearches;
309 # clear out the search history from the session now that
310 # we've saved it to the database
311 C4
::Search
::History
::set_to_session
( { cgi
=> $in->{'query'}, search_history
=> [] } );
313 } elsif ( $in->{type
} eq 'intranet' and C4
::Context
->preference('EnableSearchHistory') ) {
314 $template->param( EnableSearchHistory
=> 1 );
317 else { # if this is an anonymous session, setup to display public lists...
319 # If shibboleth is enabled, and we're in an anonymous session, we should allow
320 # the user to attemp login via shibboleth.
322 $template->param( shibbolethAuthentication
=> $shib,
323 shibbolethLoginUrl
=> login_shib_url
( $in->{'query'} ),
326 # If shibboleth is enabled and we have a shibboleth login attribute,
327 # but we are in an anonymous session, then we clearly have an invalid
328 # shibboleth koha account.
330 $template->param( invalidShibLogin
=> '1' );
334 $template->param( sessionID
=> $sessionID );
336 my ( $total, $pubshelves ) = C4
::VirtualShelves
::GetSomeShelfNames
( undef, 'MASTHEAD' );
338 pubshelves
=> $total->{pubtotal
},
339 pubshelvesloop
=> $pubshelves,
343 # Anonymous opac search history
344 # If opac search history is enabled and at least one search has already been performed
345 if ( C4
::Context
->preference('EnableOpacSearchHistory') ) {
346 my @recentSearches = C4
::Search
::History
::get_from_session
( { cgi
=> $in->{'query'} } );
347 if (@recentSearches) {
348 $template->param( EnableOpacSearchHistory
=> 1 );
352 if ( C4
::Context
->preference('dateformat') ) {
353 $template->param( dateformat
=> C4
::Context
->preference('dateformat') );
356 # these template parameters are set the same regardless of $in->{'type'}
358 # Set the using_https variable for templates
359 # FIXME Under Plack the CGI->https method always returns 'OFF'
360 my $https = $in->{query
}->https();
361 my $using_https = ( defined $https and $https ne 'OFF' ) ?
1 : 0;
364 "BiblioDefaultView" . C4
::Context
->preference("BiblioDefaultView") => 1,
365 EnhancedMessagingPreferences
=> C4
::Context
->preference('EnhancedMessagingPreferences'),
366 GoogleJackets
=> C4
::Context
->preference("GoogleJackets"),
367 OpenLibraryCovers
=> C4
::Context
->preference("OpenLibraryCovers"),
368 KohaAdminEmailAddress
=> "" . C4
::Context
->preference("KohaAdminEmailAddress"),
369 LoginBranchcode
=> ( C4
::Context
->userenv ? C4
::Context
->userenv->{"branch"} : undef ),
370 LoginFirstname
=> ( C4
::Context
->userenv ? C4
::Context
->userenv->{"firstname"} : "Bel" ),
371 LoginSurname
=> C4
::Context
->userenv ? C4
::Context
->userenv->{"surname"} : "Inconnu",
372 emailaddress
=> C4
::Context
->userenv ? C4
::Context
->userenv->{"emailaddress"} : undef,
373 loggedinpersona
=> C4
::Context
->userenv ? C4
::Context
->userenv->{"persona"} : undef,
374 TagsEnabled
=> C4
::Context
->preference("TagsEnabled"),
375 hide_marc
=> C4
::Context
->preference("hide_marc"),
376 item_level_itypes
=> C4
::Context
->preference('item-level_itypes'),
377 patronimages
=> C4
::Context
->preference("patronimages"),
378 singleBranchMode
=> C4
::Context
->preference("singleBranchMode"),
379 XSLTDetailsDisplay
=> C4
::Context
->preference("XSLTDetailsDisplay"),
380 XSLTResultsDisplay
=> C4
::Context
->preference("XSLTResultsDisplay"),
381 using_https
=> $using_https,
382 noItemTypeImages
=> C4
::Context
->preference("noItemTypeImages"),
383 marcflavour
=> C4
::Context
->preference("marcflavour"),
384 persona
=> C4
::Context
->preference("persona"),
386 if ( $in->{'type'} eq "intranet" ) {
388 AmazonCoverImages
=> C4
::Context
->preference("AmazonCoverImages"),
389 AutoLocation
=> C4
::Context
->preference("AutoLocation"),
390 "BiblioDefaultView" . C4
::Context
->preference("IntranetBiblioDefaultView") => 1,
391 CalendarFirstDayOfWeek
=> ( C4
::Context
->preference("CalendarFirstDayOfWeek") eq "Sunday" ) ?
0 : 1,
392 CircAutocompl
=> C4
::Context
->preference("CircAutocompl"),
393 FRBRizeEditions
=> C4
::Context
->preference("FRBRizeEditions"),
394 IndependentBranches
=> C4
::Context
->preference("IndependentBranches"),
395 IntranetNav
=> C4
::Context
->preference("IntranetNav"),
396 IntranetmainUserblock
=> C4
::Context
->preference("IntranetmainUserblock"),
397 LibraryName
=> C4
::Context
->preference("LibraryName"),
398 LoginBranchname
=> ( C4
::Context
->userenv ? C4
::Context
->userenv->{"branchname"} : undef ),
399 advancedMARCEditor
=> C4
::Context
->preference("advancedMARCEditor"),
400 canreservefromotherbranches
=> C4
::Context
->preference('canreservefromotherbranches'),
401 intranetcolorstylesheet
=> C4
::Context
->preference("intranetcolorstylesheet"),
402 IntranetFavicon
=> C4
::Context
->preference("IntranetFavicon"),
403 intranetreadinghistory
=> C4
::Context
->preference("intranetreadinghistory"),
404 intranetstylesheet
=> C4
::Context
->preference("intranetstylesheet"),
405 IntranetUserCSS
=> C4
::Context
->preference("IntranetUserCSS"),
406 intranetuserjs
=> C4
::Context
->preference("intranetuserjs"),
407 intranetbookbag
=> C4
::Context
->preference("intranetbookbag"),
408 suggestion
=> C4
::Context
->preference("suggestion"),
409 virtualshelves
=> C4
::Context
->preference("virtualshelves"),
410 StaffSerialIssueDisplayCount
=> C4
::Context
->preference("StaffSerialIssueDisplayCount"),
411 EasyAnalyticalRecords
=> C4
::Context
->preference('EasyAnalyticalRecords'),
412 LocalCoverImages
=> C4
::Context
->preference('LocalCoverImages'),
413 OPACLocalCoverImages
=> C4
::Context
->preference('OPACLocalCoverImages'),
414 AllowMultipleCovers
=> C4
::Context
->preference('AllowMultipleCovers'),
415 EnableBorrowerFiles
=> C4
::Context
->preference('EnableBorrowerFiles'),
416 UseKohaPlugins
=> C4
::Context
->preference('UseKohaPlugins'),
417 UseCourseReserves
=> C4
::Context
->preference("UseCourseReserves"),
421 warn "template type should be OPAC, here it is=[" . $in->{'type'} . "]" unless ( $in->{'type'} eq 'opac' );
423 #TODO : replace LibraryName syspref with 'system name', and remove this html processing
424 my $LibraryNameTitle = C4
::Context
->preference("LibraryName");
425 $LibraryNameTitle =~ s/<(?:\/?)(?:br|p)\s*(?:\/?
)>/ /sgi;
426 $LibraryNameTitle =~ s/<(?:[^<>'"]|'(?:[^']*)'|"(?:[^"]*)")*>//sg;
428 # clean up the busc param in the session if the page is not opac-detail and not the "add to list" page
429 if ( C4
::Context
->preference("OpacBrowseResults")
430 && $in->{'template_name'} =~ /opac-(.+)\.(?:tt|tmpl)$/ ) {
432 unless ( $pagename =~ /^(?:MARC|ISBD)?detail$/
433 or $pagename =~ /^addbybiblionumber$/ ) {
434 my $sessionSearch = get_session
( $sessionID || $in->{'query'}->cookie("CGISESSID") );
435 $sessionSearch->clear( ["busc"] ) if ( $sessionSearch->param("busc") );
439 # variables passed from CGI: opac_css_override and opac_search_limits.
440 my $opac_search_limit = $ENV{'OPAC_SEARCH_LIMIT'};
441 my $opac_limit_override = $ENV{'OPAC_LIMIT_OVERRIDE'};
444 ( $opac_limit_override && $opac_search_limit && $opac_search_limit =~ /branch:(\w+)/ ) ||
445 ( $in->{'query'}->param('limit') && $in->{'query'}->param('limit') =~ /branch:(\w+)/ ) ||
446 ( $in->{'query'}->param('multibranchlimit') && $in->{'query'}->param('multibranchlimit') =~ /multibranchlimit-(\w+)/ )
448 $opac_name = $1; # opac_search_limit is a branch, so we use it.
449 } elsif ( $in->{'query'}->param('multibranchlimit') ) {
450 $opac_name = $in->{'query'}->param('multibranchlimit');
451 } elsif ( C4
::Context
->preference("SearchMyLibraryFirst") && C4
::Context
->userenv && C4
::Context
->userenv->{'branch'} ) {
452 $opac_name = C4
::Context
->userenv->{'branch'};
455 # FIXME Under Plack the CGI->https method always returns 'OFF' ($using_https will be set to 0 in this case)
456 my $opac_base_url = C4
::Context
->preference("OPACBaseURL"); #FIXME uses $using_https below as well
457 if ( !$opac_base_url ) {
458 $opac_base_url = $ENV{'SERVER_NAME'} . ( $ENV{'SERVER_PORT'} eq ( $using_https ?
"443" : "80" ) ?
'' : ":$ENV{'SERVER_PORT'}" );
461 opaccolorstylesheet
=> C4
::Context
->preference("opaccolorstylesheet"),
462 AnonSuggestions
=> "" . C4
::Context
->preference("AnonSuggestions"),
463 AuthorisedValueImages
=> C4
::Context
->preference("AuthorisedValueImages"),
464 BranchesLoop
=> GetBranchesLoop
($opac_name),
465 BranchCategoriesLoop
=> GetBranchCategories
( 'searchdomain', 1, $opac_name ),
466 CalendarFirstDayOfWeek
=> ( C4
::Context
->preference("CalendarFirstDayOfWeek") eq "Sunday" ) ?
0 : 1,
467 LibraryName
=> "" . C4
::Context
->preference("LibraryName"),
468 LibraryNameTitle
=> "" . $LibraryNameTitle,
469 LoginBranchname
=> C4
::Context
->userenv ? C4
::Context
->userenv->{"branchname"} : "",
470 OPACAmazonCoverImages
=> C4
::Context
->preference("OPACAmazonCoverImages"),
471 OPACFRBRizeEditions
=> C4
::Context
->preference("OPACFRBRizeEditions"),
472 OpacHighlightedWords
=> C4
::Context
->preference("OpacHighlightedWords"),
473 OPACItemHolds
=> C4
::Context
->preference("OPACItemHolds"),
474 OPACShelfBrowser
=> "" . C4
::Context
->preference("OPACShelfBrowser"),
475 OPACURLOpenInNewWindow
=> "" . C4
::Context
->preference("OPACURLOpenInNewWindow"),
476 OPACUserCSS
=> "" . C4
::Context
->preference("OPACUserCSS"),
477 OPACViewOthersSuggestions
=> "" . C4
::Context
->preference("OPACViewOthersSuggestions"),
478 OpacAuthorities
=> C4
::Context
->preference("OpacAuthorities"),
479 OPACBaseURL
=> ( $using_https ?
"https://" : "http://" ) . $opac_base_url,
480 opac_css_override
=> $ENV{'OPAC_CSS_OVERRIDE'},
481 opac_search_limit
=> $opac_search_limit,
482 opac_limit_override
=> $opac_limit_override,
483 OpacBrowser
=> C4
::Context
->preference("OpacBrowser"),
484 OpacCloud
=> C4
::Context
->preference("OpacCloud"),
485 OpacKohaUrl
=> C4
::Context
->preference("OpacKohaUrl"),
486 OpacMainUserBlock
=> "" . C4
::Context
->preference("OpacMainUserBlock"),
487 OpacNav
=> "" . C4
::Context
->preference("OpacNav"),
488 OpacNavRight
=> "" . C4
::Context
->preference("OpacNavRight"),
489 OpacNavBottom
=> "" . C4
::Context
->preference("OpacNavBottom"),
490 OpacPasswordChange
=> C4
::Context
->preference("OpacPasswordChange"),
491 OPACPatronDetails
=> C4
::Context
->preference("OPACPatronDetails"),
492 OPACPrivacy
=> C4
::Context
->preference("OPACPrivacy"),
493 OPACFinesTab
=> C4
::Context
->preference("OPACFinesTab"),
494 OpacTopissue
=> C4
::Context
->preference("OpacTopissue"),
495 RequestOnOpac
=> C4
::Context
->preference("RequestOnOpac"),
496 'Version' => C4
::Context
->preference('Version'),
497 hidelostitems
=> C4
::Context
->preference("hidelostitems"),
498 mylibraryfirst
=> ( C4
::Context
->preference("SearchMyLibraryFirst") && C4
::Context
->userenv ) ? C4
::Context
->userenv->{'branch'} : '',
499 opaclayoutstylesheet
=> "" . C4
::Context
->preference("opaclayoutstylesheet"),
500 opacbookbag
=> "" . C4
::Context
->preference("opacbookbag"),
501 opaccredits
=> "" . C4
::Context
->preference("opaccredits"),
502 OpacFavicon
=> C4
::Context
->preference("OpacFavicon"),
503 opacheader
=> "" . C4
::Context
->preference("opacheader"),
504 opaclanguagesdisplay
=> "" . C4
::Context
->preference("opaclanguagesdisplay"),
505 opacreadinghistory
=> C4
::Context
->preference("opacreadinghistory"),
506 opacuserjs
=> C4
::Context
->preference("opacuserjs"),
507 opacuserlogin
=> "" . C4
::Context
->preference("opacuserlogin"),
508 ShowReviewer
=> C4
::Context
->preference("ShowReviewer"),
509 ShowReviewerPhoto
=> C4
::Context
->preference("ShowReviewerPhoto"),
510 suggestion
=> "" . C4
::Context
->preference("suggestion"),
511 virtualshelves
=> "" . C4
::Context
->preference("virtualshelves"),
512 OPACSerialIssueDisplayCount
=> C4
::Context
->preference("OPACSerialIssueDisplayCount"),
513 OPACXSLTDetailsDisplay
=> C4
::Context
->preference("OPACXSLTDetailsDisplay"),
514 OPACXSLTResultsDisplay
=> C4
::Context
->preference("OPACXSLTResultsDisplay"),
515 SyndeticsClientCode
=> C4
::Context
->preference("SyndeticsClientCode"),
516 SyndeticsEnabled
=> C4
::Context
->preference("SyndeticsEnabled"),
517 SyndeticsCoverImages
=> C4
::Context
->preference("SyndeticsCoverImages"),
518 SyndeticsTOC
=> C4
::Context
->preference("SyndeticsTOC"),
519 SyndeticsSummary
=> C4
::Context
->preference("SyndeticsSummary"),
520 SyndeticsEditions
=> C4
::Context
->preference("SyndeticsEditions"),
521 SyndeticsExcerpt
=> C4
::Context
->preference("SyndeticsExcerpt"),
522 SyndeticsReviews
=> C4
::Context
->preference("SyndeticsReviews"),
523 SyndeticsAuthorNotes
=> C4
::Context
->preference("SyndeticsAuthorNotes"),
524 SyndeticsAwards
=> C4
::Context
->preference("SyndeticsAwards"),
525 SyndeticsSeries
=> C4
::Context
->preference("SyndeticsSeries"),
526 SyndeticsCoverImageSize
=> C4
::Context
->preference("SyndeticsCoverImageSize"),
527 OPACLocalCoverImages
=> C4
::Context
->preference("OPACLocalCoverImages"),
528 PatronSelfRegistration
=> C4
::Context
->preference("PatronSelfRegistration"),
529 PatronSelfRegistrationDefaultCategory
=> C4
::Context
->preference("PatronSelfRegistrationDefaultCategory"),
532 $template->param( OpacPublic
=> '1' ) if ( $user || C4
::Context
->preference("OpacPublic") );
535 # Check if we were asked using parameters to force a specific language
536 if ( defined $in->{'query'}->param('language') ) {
538 # Extract the language, let C4::Languages::getlanguage choose
540 my $language = C4
::Languages
::getlanguage
( $in->{'query'} );
541 my $languagecookie = C4
::Templates
::getlanguagecookie
( $in->{'query'}, $language );
542 if ( ref $cookie eq 'ARRAY' ) {
543 push @
{$cookie}, $languagecookie;
545 $cookie = [ $cookie, $languagecookie ];
549 return ( $template, $borrowernumber, $cookie, $flags );
554 ($userid, $cookie, $sessionID) = &checkauth($query, $noauth, $flagsrequired, $type);
556 Verifies that the user is authorized to run this script. If
557 the user is authorized, a (userid, cookie, session-id, flags)
558 quadruple is returned. If the user is not authorized but does
559 not have the required privilege (see $flagsrequired below), it
560 displays an error page and exits. Otherwise, it displays the
561 login page and exits.
563 Note that C<&checkauth> will return if and only if the user
564 is authorized, so it should be called early on, before any
565 unfinished operations (e.g., if you've opened a file, then
566 C<&checkauth> won't close it for you).
568 C<$query> is the CGI object for the script calling C<&checkauth>.
570 The C<$noauth> argument is optional. If it is set, then no
571 authorization is required for the script.
573 C<&checkauth> fetches user and session information from C<$query> and
574 ensures that the user is authorized to run scripts that require
577 The C<$flagsrequired> argument specifies the required privileges
578 the user must have if the username and password are correct.
579 It should be specified as a reference-to-hash; keys in the hash
580 should be the "flags" for the user, as specified in the Members
581 intranet module. Any key specified must correspond to a "flag"
582 in the userflags table. E.g., { circulate => 1 } would specify
583 that the user must have the "circulate" privilege in order to
584 proceed. To make sure that access control is correct, the
585 C<$flagsrequired> parameter must be specified correctly.
587 Koha also has a concept of sub-permissions, also known as
588 granular permissions. This makes the value of each key
589 in the C<flagsrequired> hash take on an additional
594 The user must have access to all subfunctions of the module
595 specified by the hash key.
599 The user must have access to at least one subfunction of the module
600 specified by the hash key.
602 specific permission, e.g., 'export_catalog'
604 The user must have access to the specific subfunction list, which
605 must correspond to a row in the permissions table.
607 The C<$type> argument specifies whether the template should be
608 retrieved from the opac or intranet directory tree. "opac" is
609 assumed if it is not specified; however, if C<$type> is specified,
610 "intranet" is assumed if it is not "opac".
612 If C<$query> does not have a valid session ID associated with it
613 (i.e., the user has not logged in) or if the session has expired,
614 C<&checkauth> presents the user with a login page (from the point of
615 view of the original script, C<&checkauth> does not return). Once the
616 user has authenticated, C<&checkauth> restarts the original script
617 (this time, C<&checkauth> returns).
619 The login page is provided using a HTML::Template, which is set in the
620 systempreferences table or at the top of this file. The variable C<$type>
621 selects which template to use, either the opac or the intranet
622 authentification template.
624 C<&checkauth> returns a user ID, a cookie, and a session ID. The
625 cookie should be sent back to the browser; it verifies that the user
635 # If Version syspref is unavailable, it means Koha is beeing installed,
636 # and so we must redirect to OPAC maintenance page or to the WebInstaller
637 # also, if OpacMaintenance is ON, OPAC should redirect to maintenance
638 if ( C4
::Context
->preference('OpacMaintenance') && $type eq 'opac' ) {
639 warn "OPAC Install required, redirecting to maintenance";
640 print $query->redirect("/cgi-bin/koha/maintenance.pl");
643 unless ( $version = C4
::Context
->preference('Version') ) { # assignment, not comparison
644 if ( $type ne 'opac' ) {
645 warn "Install required, redirecting to Installer";
646 print $query->redirect("/cgi-bin/koha/installer/install.pl");
648 warn "OPAC Install required, redirecting to maintenance";
649 print $query->redirect("/cgi-bin/koha/maintenance.pl");
654 # check that database and koha version are the same
655 # there is no DB version, it's a fresh install,
656 # go to web installer
657 # there is a DB version, compare it to the code version
658 my $kohaversion = C4
::Context
::KOHAVERSION
;
660 # remove the 3 last . to have a Perl number
661 $kohaversion =~ s/(.*\..*)\.(.*)\.(.*)/$1$2$3/;
662 $debug and print STDERR
"kohaversion : $kohaversion\n";
663 if ( $version < $kohaversion ) {
664 my $warning = "Database update needed, redirecting to %s. Database is $version and Koha is $kohaversion";
665 if ( $type ne 'opac' ) {
666 warn sprintf( $warning, 'Installer' );
667 print $query->redirect("/cgi-bin/koha/installer/install.pl?step=3");
669 warn sprintf( "OPAC: " . $warning, 'maintenance' );
670 print $query->redirect("/cgi-bin/koha/maintenance.pl");
678 open my $fh, '>>', "/tmp/sessionlog" or warn "ERROR: Cannot append to /tmp/sessionlog";
679 printf $fh join( "\n", @_ );
683 sub _timeout_syspref
{
684 my $timeout = C4
::Context
->preference('timeout') || 600;
686 # value in days, convert in seconds
687 if ( $timeout =~ /(\d+)[dD]/ ) {
688 $timeout = $1 * 86400;
695 $debug and warn "Checking Auth";
697 # $authnotrequired will be set for scripts which will run without authentication
698 my $authnotrequired = shift;
699 my $flagsrequired = shift;
702 $type = 'opac' unless $type;
704 my $dbh = C4
::Context
->dbh;
705 my $timeout = _timeout_syspref
();
707 _version_check
( $type, $query );
712 my ( $userid, $cookie, $sessionID, $flags, $barshelves, $pubshelves );
713 my $logout = $query->param('logout.x');
715 my $anon_search_history;
717 # This parameter is the name of the CAS server we want to authenticate against,
718 # when using authentication against multiple CAS servers, as configured in Auth_cas_servers.yaml
719 my $casparam = $query->param('cas');
720 my $q_userid = $query->param('userid') // '';
722 # Basic authentication is incompatible with the use of Shibboleth,
723 # as Shibboleth may return REMOTE_USER as a Shibboleth attribute,
724 # and it may not be the attribute we want to use to match the koha login.
726 # Also, do not consider an empty REMOTE_USER.
728 # Finally, after those tests, we can assume (although if it would be better with
729 # a syspref) that if we get a REMOTE_USER, that's from basic authentication,
730 # and we can affect it to $userid.
731 if ( !$shib and defined( $ENV{'REMOTE_USER'} ) and $ENV{'REMOTE_USER'} ne '' and $userid = $ENV{'REMOTE_USER'} ) {
733 # Using Basic Authentication, no cookies required
734 $cookie = $query->cookie(
735 -name
=> 'CGISESSID',
744 # we dont want to set a session because we are being called by a persona callback
746 elsif ( $sessionID = $query->cookie("CGISESSID") )
747 { # assignment, not comparison
748 my $session = get_session
($sessionID);
749 C4
::Context
->_new_userenv($sessionID);
750 my ( $ip, $lasttime, $sessiontype );
753 $s_userid = $session->param('id') // '';
754 C4
::Context
::set_userenv
(
755 $session->param('number'), $s_userid,
756 $session->param('cardnumber'), $session->param('firstname'),
757 $session->param('surname'), $session->param('branch'),
758 $session->param('branchname'), $session->param('flags'),
759 $session->param('emailaddress'), $session->param('branchprinter'),
760 $session->param('persona'), $session->param('shibboleth')
762 C4
::Context
::set_shelves_userenv
( 'bar', $session->param('barshelves') );
763 C4
::Context
::set_shelves_userenv
( 'pub', $session->param('pubshelves') );
764 C4
::Context
::set_shelves_userenv
( 'tot', $session->param('totshelves') );
765 $debug and printf STDERR
"AUTH_SESSION: (%s)\t%s %s - %s\n", map { $session->param($_) } qw(cardnumber firstname surname branch);
766 $ip = $session->param('ip');
767 $lasttime = $session->param('lasttime');
769 $sessiontype = $session->param('sessiontype') || '';
771 if ( ( $query->param('koha_login_context') && ( $q_userid ne $s_userid ) )
772 || ( $cas && $query->param('ticket') ) || ( $shib && $shib_login && !$logout ) ) {
774 #if a user enters an id ne to the id in the current session, we need to log them in...
775 #first we need to clear the anonymous session...
776 $debug and warn "query id = $q_userid but session id = $s_userid";
777 $anon_search_history = $session->param('search_history');
780 C4
::Context
->_unset_userenv($sessionID);
786 # voluntary logout the user
787 # check wether the user was using their shibboleth session or a local one
788 my $shibSuccess = C4
::Context
->userenv->{'shibboleth'};
791 C4
::Context
->_unset_userenv($sessionID);
793 #_session_log(sprintf "%20s from %16s logged out at %30s (manually).\n", $userid,$ip,(strftime "%c",localtime));
797 if ( $cas and $caslogout ) {
801 # If we are in a shibboleth session (shibboleth is enabled, a shibboleth match attribute is set and matches koha matchpoint)
802 if ( $shib and $shib_login and $shibSuccess and $type eq 'opac' ) {
804 # (Note: $type eq 'opac' condition should be removed when shibboleth authentication for intranet will be implemented)
808 elsif ( !$lasttime || ( $lasttime < time() - $timeout ) ) {
811 $info{'timed_out'} = 1;
816 C4
::Context
->_unset_userenv($sessionID);
818 #_session_log(sprintf "%20s from %16s logged out at %30s (inactivity).\n", $userid,$ip,(strftime "%c",localtime));
822 elsif ( C4
::Context
->preference('SessionRestrictionByIP') && $ip ne $ENV{'REMOTE_ADDR'} ) {
824 # Different ip than originally logged in from
825 $info{'oldip'} = $ip;
826 $info{'newip'} = $ENV{'REMOTE_ADDR'};
827 $info{'different_ip'} = 1;
830 C4
::Context
->_unset_userenv($sessionID);
832 #_session_log(sprintf "%20s from %16s logged out at %30s (ip changed to %16s).\n", $userid,$ip,(strftime "%c",localtime), $info{'newip'});
837 $cookie = $query->cookie(
838 -name
=> 'CGISESSID',
839 -value
=> $session->id,
842 $session->param( 'lasttime', time() );
843 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...
844 $flags = haspermission
( $userid, $flagsrequired );
848 $info{'nopermission'} = 1;
853 unless ( $userid || $sessionID ) {
855 #we initiate a session prior to checking for a username to allow for anonymous sessions...
856 my $session = get_session
("") or die "Auth ERROR: Cannot get_session()";
858 # Save anonymous search history in new session so it can be retrieved
859 # by get_template_and_user to store it in user's search history after
860 # a successful login.
861 if ($anon_search_history) {
862 $session->param( 'search_history', $anon_search_history );
865 my $sessionID = $session->id;
866 C4
::Context
->_new_userenv($sessionID);
867 $cookie = $query->cookie(
868 -name
=> 'CGISESSID',
869 -value
=> $session->id,
873 my $pki_field = C4
::Context
->preference('AllowPKIAuth');
874 if ( !defined($pki_field) ) {
875 print STDERR
"ERROR: Missing system preference AllowPKIAuth.\n";
878 if ( ( $cas && $query->param('ticket') )
880 || ( $shib && $shib_login )
881 || $pki_field ne 'None'
884 my $password = $query->param('password');
887 my ( $return, $cardnumber );
889 # If shib is enabled and we have a shib login, does the login match a valid koha user
890 if ( $shib && $shib_login && $type eq 'opac' ) {
893 # Do not pass password here, else shib will not be checked in checkpw.
894 ( $return, $cardnumber, $retuserid ) = checkpw
( $dbh, $userid, undef, $query );
895 $userid = $retuserid;
896 $shibSuccess = $return;
897 $info{'invalidShibLogin'} = 1 unless ($return);
900 # If shib login and match were successfull, skip further login methods
901 unless ($shibSuccess) {
902 if ( $cas && $query->param('ticket') ) {
904 ( $return, $cardnumber, $retuserid ) =
905 checkpw
( $dbh, $userid, $password, $query );
906 $userid = $retuserid;
907 $info{'invalidCasLogin'} = 1 unless ($return);
911 my $value = $persona;
913 # If we're looking up the email, there's a chance that the person
914 # doesn't have a userid. So if there is none, we pass along the
915 # borrower number, and the bits of code that need to know the user
916 # ID will have to be smart enough to handle that.
918 my @users_info = C4
::Members
::GetBorrowersWithEmail
($value);
921 # First the userid, then the borrowernum
922 $value = $users_info[0][1] || $users_info[0][0];
927 $return = $value ?
1 : 0;
932 ( $pki_field eq 'Common Name' && $ENV{'SSL_CLIENT_S_DN_CN'} )
933 || ( $pki_field eq 'emailAddress'
934 && $ENV{'SSL_CLIENT_S_DN_Email'} )
938 if ( $pki_field eq 'Common Name' ) {
939 $value = $ENV{'SSL_CLIENT_S_DN_CN'};
941 elsif ( $pki_field eq 'emailAddress' ) {
942 $value = $ENV{'SSL_CLIENT_S_DN_Email'};
944 # If we're looking up the email, there's a chance that the person
945 # doesn't have a userid. So if there is none, we pass along the
946 # borrower number, and the bits of code that need to know the user
947 # ID will have to be smart enough to handle that.
949 my @users_info = C4
::Members
::GetBorrowersWithEmail
($value);
952 # First the userid, then the borrowernum
953 $value = $users_info[0][1] || $users_info[0][0];
959 $return = $value ?
1 : 0;
965 ( $return, $cardnumber, $retuserid ) =
966 checkpw
( $dbh, $userid, $password, $query );
967 $userid = $retuserid if ($retuserid);
968 $info{'invalid_username_or_password'} = 1 unless ($return);
972 # $return: 1 = valid user, 2 = superlibrarian
975 #_session_log(sprintf "%20s from %16s logged in at %30s.\n", $userid,$ENV{'REMOTE_ADDR'},(strftime '%c', localtime));
976 if ( $flags = haspermission
( $userid, $flagsrequired ) ) {
980 $info{'nopermission'} = 1;
981 C4
::Context
->_unset_userenv($sessionID);
983 my ( $borrowernumber, $firstname, $surname, $userflags,
984 $branchcode, $branchname, $branchprinter, $emailaddress );
986 if ( $return == 1 ) {
988 SELECT borrowernumber, firstname, surname, flags, borrowers.branchcode,
989 branches.branchname as branchname,
990 branches.branchprinter as branchprinter,
993 LEFT JOIN branches on borrowers.branchcode=branches.branchcode
995 my $sth = $dbh->prepare("$select where userid=?");
996 $sth->execute($userid);
997 unless ( $sth->rows ) {
998 $debug and print STDERR
"AUTH_1: no rows for userid='$userid'\n";
999 $sth = $dbh->prepare("$select where cardnumber=?");
1000 $sth->execute($cardnumber);
1002 unless ( $sth->rows ) {
1003 $debug and print STDERR
"AUTH_2a: no rows for cardnumber='$cardnumber'\n";
1004 $sth->execute($userid);
1005 unless ( $sth->rows ) {
1006 $debug and print STDERR
"AUTH_2b: no rows for userid='$userid' AS cardnumber\n";
1011 ( $borrowernumber, $firstname, $surname, $userflags,
1012 $branchcode, $branchname, $branchprinter, $emailaddress ) = $sth->fetchrow;
1013 $debug and print STDERR
"AUTH_3 results: " .
1014 "$cardnumber,$borrowernumber,$userid,$firstname,$surname,$userflags,$branchcode,$emailaddress\n";
1016 print STDERR
"AUTH_3: no results for userid='$userid', cardnumber='$cardnumber'.\n";
1019 # launch a sequence to check if we have a ip for the branch, i
1020 # if we have one we replace the branchcode of the userenv by the branch bound in the ip.
1022 my $ip = $ENV{'REMOTE_ADDR'};
1024 # if they specify at login, use that
1025 if ( $query->param('branch') ) {
1026 $branchcode = $query->param('branch');
1027 $branchname = GetBranchName
($branchcode);
1029 my $branches = GetBranches
();
1030 if ( C4
::Context
->boolean_preference('IndependentBranches') && C4
::Context
->boolean_preference('Autolocation') ) {
1032 # we have to check they are coming from the right ip range
1033 my $domain = $branches->{$branchcode}->{'branchip'};
1034 if ( $ip !~ /^$domain/ ) {
1036 $info{'wrongip'} = 1;
1041 foreach my $br ( keys %$branches ) {
1043 # now we work with the treatment of ip
1044 my $domain = $branches->{$br}->{'branchip'};
1045 if ( $domain && $ip =~ /^$domain/ ) {
1046 $branchcode = $branches->{$br}->{'branchcode'};
1048 # new op dev : add the branchprinter and branchname in the cookie
1049 $branchprinter = $branches->{$br}->{'branchprinter'};
1050 $branchname = $branches->{$br}->{'branchname'};
1053 $session->param( 'number', $borrowernumber );
1054 $session->param( 'id', $userid );
1055 $session->param( 'cardnumber', $cardnumber );
1056 $session->param( 'firstname', $firstname );
1057 $session->param( 'surname', $surname );
1058 $session->param( 'branch', $branchcode );
1059 $session->param( 'branchname', $branchname );
1060 $session->param( 'flags', $userflags );
1061 $session->param( 'emailaddress', $emailaddress );
1062 $session->param( 'ip', $session->remote_addr() );
1063 $session->param( 'lasttime', time() );
1064 $session->param( 'shibboleth', $shibSuccess );
1065 $debug and printf STDERR
"AUTH_4: (%s)\t%s %s - %s\n", map { $session->param($_) } qw(cardnumber firstname surname branch);
1067 elsif ( $return == 2 ) {
1069 #We suppose the user is the superlibrarian
1070 $borrowernumber = 0;
1071 $session->param( 'number', 0 );
1072 $session->param( 'id', C4
::Context
->config('user') );
1073 $session->param( 'cardnumber', C4
::Context
->config('user') );
1074 $session->param( 'firstname', C4
::Context
->config('user') );
1075 $session->param( 'surname', C4
::Context
->config('user') );
1076 $session->param( 'branch', 'NO_LIBRARY_SET' );
1077 $session->param( 'branchname', 'NO_LIBRARY_SET' );
1078 $session->param( 'flags', 1 );
1079 $session->param( 'emailaddress', C4
::Context
->preference('KohaAdminEmailAddress') );
1080 $session->param( 'ip', $session->remote_addr() );
1081 $session->param( 'lasttime', time() );
1084 $session->param( 'persona', 1 );
1086 C4
::Context
::set_userenv
(
1087 $session->param('number'), $session->param('id'),
1088 $session->param('cardnumber'), $session->param('firstname'),
1089 $session->param('surname'), $session->param('branch'),
1090 $session->param('branchname'), $session->param('flags'),
1091 $session->param('emailaddress'), $session->param('branchprinter'),
1092 $session->param('persona'), $session->param('shibboleth')
1096 # $return: 0 = invalid user
1097 # reset to anonymous session
1099 $debug and warn "Login failed, resetting anonymous session...";
1101 $info{'invalid_username_or_password'} = 1;
1102 C4
::Context
->_unset_userenv($sessionID);
1104 $session->param( 'lasttime', time() );
1105 $session->param( 'ip', $session->remote_addr() );
1106 $session->param( 'sessiontype', 'anon' );
1108 } # END if ( $userid = $query->param('userid') )
1109 elsif ( $type eq "opac" ) {
1111 # if we are here this is an anonymous session; add public lists to it and a few other items...
1112 # anonymous sessions are created only for the OPAC
1113 $debug and warn "Initiating an anonymous session...";
1115 # setting a couple of other session vars...
1116 $session->param( 'ip', $session->remote_addr() );
1117 $session->param( 'lasttime', time() );
1118 $session->param( 'sessiontype', 'anon' );
1120 } # END unless ($userid)
1122 # finished authentification, now respond
1123 if ( $loggedin || $authnotrequired )
1127 $cookie = $query->cookie(
1128 -name
=> 'CGISESSID',
1133 return ( $userid, $cookie, $sessionID, $flags );
1138 # AUTH rejected, show the login/password template, after checking the DB.
1142 # get the inputs from the incoming query
1144 foreach my $name ( param
$query) {
1145 (next) if ( $name eq 'userid' || $name eq 'password' || $name eq 'ticket' );
1146 my $value = $query->param($name);
1147 push @inputs, { name
=> $name, value
=> $value };
1150 my $LibraryNameTitle = C4
::Context
->preference("LibraryName");
1151 $LibraryNameTitle =~ s/<(?:\/?)(?:br|p)\s*(?:\/?
)>/ /sgi;
1152 $LibraryNameTitle =~ s/<(?:[^<>'"]|'(?:[^']*)'|"(?:[^"]*)")*>//sg;
1154 my $template_name = ( $type eq 'opac' ) ?
'opac-auth.tt' : 'auth.tt';
1155 my $template = C4
::Templates
::gettemplate
( $template_name, $type, $query );
1157 branchloop
=> GetBranchesLoop
(),
1158 opaccolorstylesheet
=> C4
::Context
->preference("opaccolorstylesheet"),
1159 opaclayoutstylesheet
=> C4
::Context
->preference("opaclayoutstylesheet"),
1162 casAuthentication
=> C4
::Context
->preference("casAuthentication"),
1163 shibbolethAuthentication
=> $shib,
1164 SessionRestrictionByIP
=> C4
::Context
->preference("SessionRestrictionByIP"),
1165 suggestion
=> C4
::Context
->preference("suggestion"),
1166 virtualshelves
=> C4
::Context
->preference("virtualshelves"),
1167 LibraryName
=> "" . C4
::Context
->preference("LibraryName"),
1168 LibraryNameTitle
=> "" . $LibraryNameTitle,
1169 opacuserlogin
=> C4
::Context
->preference("opacuserlogin"),
1170 OpacNav
=> C4
::Context
->preference("OpacNav"),
1171 OpacNavRight
=> C4
::Context
->preference("OpacNavRight"),
1172 OpacNavBottom
=> C4
::Context
->preference("OpacNavBottom"),
1173 opaccredits
=> C4
::Context
->preference("opaccredits"),
1174 OpacFavicon
=> C4
::Context
->preference("OpacFavicon"),
1175 opacreadinghistory
=> C4
::Context
->preference("opacreadinghistory"),
1176 opaclanguagesdisplay
=> C4
::Context
->preference("opaclanguagesdisplay"),
1177 opacuserjs
=> C4
::Context
->preference("opacuserjs"),
1178 opacbookbag
=> "" . C4
::Context
->preference("opacbookbag"),
1179 OpacCloud
=> C4
::Context
->preference("OpacCloud"),
1180 OpacTopissue
=> C4
::Context
->preference("OpacTopissue"),
1181 OpacAuthorities
=> C4
::Context
->preference("OpacAuthorities"),
1182 OpacBrowser
=> C4
::Context
->preference("OpacBrowser"),
1183 opacheader
=> C4
::Context
->preference("opacheader"),
1184 TagsEnabled
=> C4
::Context
->preference("TagsEnabled"),
1185 OPACUserCSS
=> C4
::Context
->preference("OPACUserCSS"),
1186 intranetcolorstylesheet
=> C4
::Context
->preference("intranetcolorstylesheet"),
1187 intranetstylesheet
=> C4
::Context
->preference("intranetstylesheet"),
1188 intranetbookbag
=> C4
::Context
->preference("intranetbookbag"),
1189 IntranetNav
=> C4
::Context
->preference("IntranetNav"),
1190 IntranetFavicon
=> C4
::Context
->preference("IntranetFavicon"),
1191 intranetuserjs
=> C4
::Context
->preference("intranetuserjs"),
1192 IndependentBranches
=> C4
::Context
->preference("IndependentBranches"),
1193 AutoLocation
=> C4
::Context
->preference("AutoLocation"),
1194 wrongip
=> $info{'wrongip'},
1195 PatronSelfRegistration
=> C4
::Context
->preference("PatronSelfRegistration"),
1196 PatronSelfRegistrationDefaultCategory
=> C4
::Context
->preference("PatronSelfRegistrationDefaultCategory"),
1197 persona
=> C4
::Context
->preference("Persona"),
1198 opac_css_override
=> $ENV{'OPAC_CSS_OVERRIDE'},
1201 $template->param( OpacPublic
=> C4
::Context
->preference("OpacPublic") );
1202 $template->param( loginprompt
=> 1 ) unless $info{'nopermission'};
1204 if ( $type eq 'opac' ) {
1205 my ( $total, $pubshelves ) = C4
::VirtualShelves
::GetSomeShelfNames
( undef, 'MASTHEAD' );
1207 pubshelves
=> $total->{pubtotal
},
1208 pubshelvesloop
=> $pubshelves,
1214 # Is authentication against multiple CAS servers enabled?
1215 if ( C4
::Auth_with_cas
::multipleAuth
&& !$casparam ) {
1216 my $casservers = C4
::Auth_with_cas
::getMultipleAuth
();
1218 foreach my $key ( keys %$casservers ) {
1219 push @tmplservers, { name
=> $key, value
=> login_cas_url
( $query, $key ) . "?cas=$key" };
1222 casServersLoop
=> \
@tmplservers
1226 casServerUrl
=> login_cas_url
($query),
1231 invalidCasLogin
=> $info{'invalidCasLogin'}
1237 shibbolethAuthentication
=> $shib,
1238 shibbolethLoginUrl
=> login_shib_url
($query),
1242 my $self_url = $query->url( -absolute
=> 1 );
1245 LibraryName
=> C4
::Context
->preference("LibraryName"),
1247 $template->param(%info);
1249 # $cookie = $query->cookie(CGISESSID => $session->id
1251 print $query->header(
1252 -type
=> 'text/html',
1253 -charset
=> 'utf-8',
1260 =head2 check_api_auth
1262 ($status, $cookie, $sessionId) = check_api_auth($query, $userflags);
1264 Given a CGI query containing the parameters 'userid' and 'password' and/or a session
1265 cookie, determine if the user has the privileges specified by C<$userflags>.
1267 C<check_api_auth> is is meant for authenticating users of web services, and
1268 consequently will always return and will not attempt to redirect the user
1271 If a valid session cookie is already present, check_api_auth will return a status
1272 of "ok", the cookie, and the Koha session ID.
1274 If no session cookie is present, check_api_auth will check the 'userid' and 'password
1275 parameters and create a session cookie and Koha session if the supplied credentials
1278 Possible return values in C<$status> are:
1282 =item "ok" -- user authenticated; C<$cookie> and C<$sessionid> have valid values.
1284 =item "failed" -- credentials are not correct; C<$cookie> and C<$sessionid> are undef
1286 =item "maintenance" -- DB is in maintenance mode; no login possible at the moment
1288 =item "expired -- session cookie has expired; API user should resubmit userid and password
1294 sub check_api_auth
{
1296 my $flagsrequired = shift;
1298 my $dbh = C4
::Context
->dbh;
1299 my $timeout = _timeout_syspref
();
1301 unless ( C4
::Context
->preference('Version') ) {
1303 # database has not been installed yet
1304 return ( "maintenance", undef, undef );
1306 my $kohaversion = C4
::Context
::KOHAVERSION
;
1307 $kohaversion =~ s/(.*\..*)\.(.*)\.(.*)/$1$2$3/;
1308 if ( C4
::Context
->preference('Version') < $kohaversion ) {
1310 # database in need of version update; assume that
1311 # no API should be called while databsae is in
1313 return ( "maintenance", undef, undef );
1316 # FIXME -- most of what follows is a copy-and-paste
1317 # of code from checkauth. There is an obvious need
1318 # for refactoring to separate the various parts of
1319 # the authentication code, but as of 2007-11-19 this
1320 # is deferred so as to not introduce bugs into the
1321 # regular authentication code for Koha 3.0.
1323 # see if we have a valid session cookie already
1324 # however, if a userid parameter is present (i.e., from
1325 # a form submission, assume that any current cookie
1327 my $sessionID = undef;
1328 unless ( $query->param('userid') ) {
1329 $sessionID = $query->cookie("CGISESSID");
1331 if ( $sessionID && not( $cas && $query->param('PT') ) ) {
1332 my $session = get_session
($sessionID);
1333 C4
::Context
->_new_userenv($sessionID);
1335 C4
::Context
::set_userenv
(
1336 $session->param('number'), $session->param('id'),
1337 $session->param('cardnumber'), $session->param('firstname'),
1338 $session->param('surname'), $session->param('branch'),
1339 $session->param('branchname'), $session->param('flags'),
1340 $session->param('emailaddress'), $session->param('branchprinter')
1343 my $ip = $session->param('ip');
1344 my $lasttime = $session->param('lasttime');
1345 my $userid = $session->param('id');
1346 if ( $lasttime < time() - $timeout ) {
1351 C4
::Context
->_unset_userenv($sessionID);
1354 return ( "expired", undef, undef );
1355 } elsif ( C4
::Context
->preference('SessionRestrictionByIP') && $ip ne $ENV{'REMOTE_ADDR'} ) {
1357 # IP address changed
1360 C4
::Context
->_unset_userenv($sessionID);
1363 return ( "expired", undef, undef );
1365 my $cookie = $query->cookie(
1366 -name
=> 'CGISESSID',
1367 -value
=> $session->id,
1370 $session->param( 'lasttime', time() );
1371 my $flags = haspermission
( $userid, $flagsrequired );
1373 return ( "ok", $cookie, $sessionID );
1377 C4
::Context
->_unset_userenv($sessionID);
1380 return ( "failed", undef, undef );
1384 return ( "expired", undef, undef );
1389 my $userid = $query->param('userid');
1390 my $password = $query->param('password');
1391 my ( $return, $cardnumber );
1394 if ( $cas && $query->param('PT') ) {
1396 $debug and print STDERR
"## check_api_auth - checking CAS\n";
1398 # In case of a CAS authentication, we use the ticket instead of the password
1399 my $PT = $query->param('PT');
1400 ( $return, $cardnumber, $userid ) = check_api_auth_cas
( $dbh, $PT, $query ); # EXTERNAL AUTH
1403 # User / password auth
1404 unless ( $userid and $password ) {
1406 # caller did something wrong, fail the authenticateion
1407 return ( "failed", undef, undef );
1409 ( $return, $cardnumber ) = checkpw
( $dbh, $userid, $password, $query );
1412 if ( $return and haspermission
( $userid, $flagsrequired ) ) {
1413 my $session = get_session
("");
1414 return ( "failed", undef, undef ) unless $session;
1416 my $sessionID = $session->id;
1417 C4
::Context
->_new_userenv($sessionID);
1418 my $cookie = $query->cookie(
1419 -name
=> 'CGISESSID',
1420 -value
=> $sessionID,
1423 if ( $return == 1 ) {
1425 $borrowernumber, $firstname, $surname,
1426 $userflags, $branchcode, $branchname,
1427 $branchprinter, $emailaddress
1431 "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=?"
1433 $sth->execute($userid);
1435 $borrowernumber, $firstname, $surname,
1436 $userflags, $branchcode, $branchname,
1437 $branchprinter, $emailaddress
1438 ) = $sth->fetchrow if ( $sth->rows );
1440 unless ( $sth->rows ) {
1441 my $sth = $dbh->prepare(
1442 "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=?"
1444 $sth->execute($cardnumber);
1446 $borrowernumber, $firstname, $surname,
1447 $userflags, $branchcode, $branchname,
1448 $branchprinter, $emailaddress
1449 ) = $sth->fetchrow if ( $sth->rows );
1451 unless ( $sth->rows ) {
1452 $sth->execute($userid);
1454 $borrowernumber, $firstname, $surname, $userflags,
1455 $branchcode, $branchname, $branchprinter, $emailaddress
1456 ) = $sth->fetchrow if ( $sth->rows );
1460 my $ip = $ENV{'REMOTE_ADDR'};
1462 # if they specify at login, use that
1463 if ( $query->param('branch') ) {
1464 $branchcode = $query->param('branch');
1465 $branchname = GetBranchName
($branchcode);
1467 my $branches = GetBranches
();
1469 foreach my $br ( keys %$branches ) {
1471 # now we work with the treatment of ip
1472 my $domain = $branches->{$br}->{'branchip'};
1473 if ( $domain && $ip =~ /^$domain/ ) {
1474 $branchcode = $branches->{$br}->{'branchcode'};
1476 # new op dev : add the branchprinter and branchname in the cookie
1477 $branchprinter = $branches->{$br}->{'branchprinter'};
1478 $branchname = $branches->{$br}->{'branchname'};
1481 $session->param( 'number', $borrowernumber );
1482 $session->param( 'id', $userid );
1483 $session->param( 'cardnumber', $cardnumber );
1484 $session->param( 'firstname', $firstname );
1485 $session->param( 'surname', $surname );
1486 $session->param( 'branch', $branchcode );
1487 $session->param( 'branchname', $branchname );
1488 $session->param( 'flags', $userflags );
1489 $session->param( 'emailaddress', $emailaddress );
1490 $session->param( 'ip', $session->remote_addr() );
1491 $session->param( 'lasttime', time() );
1492 } elsif ( $return == 2 ) {
1494 #We suppose the user is the superlibrarian
1495 $session->param( 'number', 0 );
1496 $session->param( 'id', C4
::Context
->config('user') );
1497 $session->param( 'cardnumber', C4
::Context
->config('user') );
1498 $session->param( 'firstname', C4
::Context
->config('user') );
1499 $session->param( 'surname', C4
::Context
->config('user') );
1500 $session->param( 'branch', 'NO_LIBRARY_SET' );
1501 $session->param( 'branchname', 'NO_LIBRARY_SET' );
1502 $session->param( 'flags', 1 );
1503 $session->param( 'emailaddress', C4
::Context
->preference('KohaAdminEmailAddress') );
1504 $session->param( 'ip', $session->remote_addr() );
1505 $session->param( 'lasttime', time() );
1507 C4
::Context
::set_userenv
(
1508 $session->param('number'), $session->param('id'),
1509 $session->param('cardnumber'), $session->param('firstname'),
1510 $session->param('surname'), $session->param('branch'),
1511 $session->param('branchname'), $session->param('flags'),
1512 $session->param('emailaddress'), $session->param('branchprinter')
1514 return ( "ok", $cookie, $sessionID );
1516 return ( "failed", undef, undef );
1521 =head2 check_cookie_auth
1523 ($status, $sessionId) = check_api_auth($cookie, $userflags);
1525 Given a CGISESSID cookie set during a previous login to Koha, determine
1526 if the user has the privileges specified by C<$userflags>.
1528 C<check_cookie_auth> is meant for authenticating special services
1529 such as tools/upload-file.pl that are invoked by other pages that
1530 have been authenticated in the usual way.
1532 Possible return values in C<$status> are:
1536 =item "ok" -- user authenticated; C<$sessionID> have valid values.
1538 =item "failed" -- credentials are not correct; C<$sessionid> are undef
1540 =item "maintenance" -- DB is in maintenance mode; no login possible at the moment
1542 =item "expired -- session cookie has expired; API user should resubmit userid and password
1548 sub check_cookie_auth
{
1550 my $flagsrequired = shift;
1552 my $dbh = C4
::Context
->dbh;
1553 my $timeout = _timeout_syspref
();
1555 unless ( C4
::Context
->preference('Version') ) {
1557 # database has not been installed yet
1558 return ( "maintenance", undef );
1560 my $kohaversion = C4
::Context
::KOHAVERSION
;
1561 $kohaversion =~ s/(.*\..*)\.(.*)\.(.*)/$1$2$3/;
1562 if ( C4
::Context
->preference('Version') < $kohaversion ) {
1564 # database in need of version update; assume that
1565 # no API should be called while databsae is in
1567 return ( "maintenance", undef );
1570 # FIXME -- most of what follows is a copy-and-paste
1571 # of code from checkauth. There is an obvious need
1572 # for refactoring to separate the various parts of
1573 # the authentication code, but as of 2007-11-23 this
1574 # is deferred so as to not introduce bugs into the
1575 # regular authentication code for Koha 3.0.
1577 # see if we have a valid session cookie already
1578 # however, if a userid parameter is present (i.e., from
1579 # a form submission, assume that any current cookie
1581 unless ( defined $cookie and $cookie ) {
1582 return ( "failed", undef );
1584 my $sessionID = $cookie;
1585 my $session = get_session
($sessionID);
1586 C4
::Context
->_new_userenv($sessionID);
1588 C4
::Context
::set_userenv
(
1589 $session->param('number'), $session->param('id'),
1590 $session->param('cardnumber'), $session->param('firstname'),
1591 $session->param('surname'), $session->param('branch'),
1592 $session->param('branchname'), $session->param('flags'),
1593 $session->param('emailaddress'), $session->param('branchprinter')
1596 my $ip = $session->param('ip');
1597 my $lasttime = $session->param('lasttime');
1598 my $userid = $session->param('id');
1599 if ( $lasttime < time() - $timeout ) {
1604 C4
::Context
->_unset_userenv($sessionID);
1607 return ("expired", undef);
1608 } elsif ( C4
::Context
->preference('SessionRestrictionByIP') && $ip ne $ENV{'REMOTE_ADDR'} ) {
1610 # IP address changed
1613 C4
::Context
->_unset_userenv($sessionID);
1616 return ( "expired", undef );
1618 $session->param( 'lasttime', time() );
1619 my $flags = haspermission
( $userid, $flagsrequired );
1621 return ( "ok", $sessionID );
1625 C4
::Context
->_unset_userenv($sessionID);
1628 return ( "failed", undef );
1632 return ( "expired", undef );
1639 my $session = get_session($sessionID);
1641 Given a session ID, retrieve the CGI::Session object used to store
1642 the session's state. The session object can be used to store
1643 data that needs to be accessed by different scripts during a
1646 If the C<$sessionID> parameter is an empty string, a new session
1652 my $sessionID = shift;
1653 my $storage_method = C4
::Context
->preference('SessionStorage');
1654 my $dbh = C4
::Context
->dbh;
1656 if ( $storage_method eq 'mysql' ) {
1657 $session = new CGI
::Session
( "driver:MySQL;serializer:yaml;id:md5", $sessionID, { Handle
=> $dbh } );
1659 elsif ( $storage_method eq 'Pg' ) {
1660 $session = new CGI
::Session
( "driver:PostgreSQL;serializer:yaml;id:md5", $sessionID, { Handle
=> $dbh } );
1662 elsif ( $storage_method eq 'memcached' && C4
::Context
->ismemcached ) {
1663 $session = new CGI
::Session
( "driver:memcached;serializer:yaml;id:md5", $sessionID, { Memcached
=> C4
::Context
->memcached } );
1666 # catch all defaults to tmp should work on all systems
1667 $session = new CGI
::Session
( "driver:File;serializer:yaml;id:md5", $sessionID, { Directory
=> '/tmp' } );
1673 my ( $dbh, $userid, $password, $query ) = @_;
1675 $debug and print STDERR
"## checkpw - checking LDAP\n";
1676 my ( $retval, $retcard, $retuserid ) = checkpw_ldap
(@_); # EXTERNAL AUTH
1677 return 0 if $retval == -1; # Incorrect password for LDAP login attempt
1678 ($retval) and return ( $retval, $retcard, $retuserid );
1681 if ( $cas && $query && $query->param('ticket') ) {
1682 $debug and print STDERR
"## checkpw - checking CAS\n";
1684 # In case of a CAS authentication, we use the ticket instead of the password
1685 my $ticket = $query->param('ticket');
1686 $query->delete('ticket'); # remove ticket to come back to original URL
1687 my ( $retval, $retcard, $retuserid ) = checkpw_cas
( $dbh, $ticket, $query ); # EXTERNAL AUTH
1688 ($retval) and return ( $retval, $retcard, $retuserid );
1692 # If we are in a shibboleth session (shibboleth is enabled, and a shibboleth match attribute is present)
1693 # Check for password to asertain whether we want to be testing against shibboleth or another method this
1695 if ( $shib && $shib_login && !$password ) {
1697 $debug and print STDERR
"## checkpw - checking Shibboleth\n";
1699 # In case of a Shibboleth authentication, we expect a shibboleth user attribute
1700 # (defined under shibboleth mapping in koha-conf.xml) to contain the login of the
1701 # shibboleth-authenticated user
1703 # Then, we check if it matches a valid koha user
1705 my ( $retval, $retcard, $retuserid ) = C4
::Auth_with_shibboleth
::checkpw_shib
($shib_login); # EXTERNAL AUTH
1706 ($retval) and return ( $retval, $retcard, $retuserid );
1712 return checkpw_internal
(@_)
1715 sub checkpw_internal
{
1716 my ( $dbh, $userid, $password ) = @_;
1718 if ( $userid && $userid eq C4
::Context
->config('user') ) {
1719 if ( $password && $password eq C4
::Context
->config('pass') ) {
1721 # Koha superuser account
1722 # C4::Context->set_userenv(0,0,C4::Context->config('user'),C4::Context->config('user'),C4::Context->config('user'),"",1);
1732 "select password,cardnumber,borrowernumber,userid,firstname,surname,branchcode,flags from borrowers where userid=?"
1734 $sth->execute($userid);
1736 my ( $stored_hash, $cardnumber, $borrowernumber, $userid, $firstname,
1737 $surname, $branchcode, $flags )
1740 if ( checkpw_hash
( $password, $stored_hash ) ) {
1742 C4
::Context
->set_userenv( "$borrowernumber", $userid, $cardnumber,
1743 $firstname, $surname, $branchcode, $flags );
1744 return 1, $cardnumber, $userid;
1749 "select password,cardnumber,borrowernumber,userid, firstname,surname,branchcode,flags from borrowers where cardnumber=?"
1751 $sth->execute($userid);
1753 my ( $stored_hash, $cardnumber, $borrowernumber, $userid, $firstname,
1754 $surname, $branchcode, $flags )
1757 if ( checkpw_hash
( $password, $stored_hash ) ) {
1759 C4
::Context
->set_userenv( $borrowernumber, $userid, $cardnumber,
1760 $firstname, $surname, $branchcode, $flags );
1761 return 1, $cardnumber, $userid;
1764 if ( $userid && $userid eq 'demo'
1765 && "$password" eq 'demo'
1766 && C4
::Context
->config('demo') )
1769 # DEMO => the demo user is allowed to do everything (if demo set to 1 in koha.conf
1770 # some features won't be effective : modify systempref, modify MARC structure,
1777 my ( $password, $stored_hash ) = @_;
1779 return if $stored_hash eq '!';
1781 # check what encryption algorithm was implemented: Bcrypt - if the hash starts with '$2' it is Bcrypt else md5
1783 if ( substr( $stored_hash, 0, 2 ) eq '$2' ) {
1784 $hash = hash_password
( $password, $stored_hash );
1786 $hash = md5_base64
($password);
1788 return $hash eq $stored_hash;
1793 my $authflags = getuserflags($flags, $userid, [$dbh]);
1795 Translates integer flags into permissions strings hash.
1797 C<$flags> is the integer userflags value ( borrowers.userflags )
1798 C<$userid> is the members.userid, used for building subpermissions
1799 C<$authflags> is a hashref of permissions
1806 my $dbh = @_ ?
shift : C4
::Context
->dbh;
1809 # I don't want to do this, but if someone logs in as the database
1810 # user, it would be preferable not to spam them to death with
1811 # numeric warnings. So, we make $flags numeric.
1812 no warnings
'numeric';
1815 my $sth = $dbh->prepare("SELECT bit, flag, defaulton FROM userflags");
1818 while ( my ( $bit, $flag, $defaulton ) = $sth->fetchrow ) {
1819 if ( ( $flags & ( 2**$bit ) ) || $defaulton ) {
1820 $userflags->{$flag} = 1;
1823 $userflags->{$flag} = 0;
1827 # get subpermissions and merge with top-level permissions
1828 my $user_subperms = get_user_subpermissions
($userid);
1829 foreach my $module ( keys %$user_subperms ) {
1830 next if $userflags->{$module} == 1; # user already has permission for everything in this module
1831 $userflags->{$module} = $user_subperms->{$module};
1837 =head2 get_user_subpermissions
1839 $user_perm_hashref = get_user_subpermissions($userid);
1841 Given the userid (note, not the borrowernumber) of a staff user,
1842 return a hashref of hashrefs of the specific subpermissions
1843 accorded to the user. An example return is
1847 export_catalog => 1,
1848 import_patrons => 1,
1852 The top-level hash-key is a module or function code from
1853 userflags.flag, while the second-level key is a code
1856 The results of this function do not give a complete picture
1857 of the functions that a staff user can access; it is also
1858 necessary to check borrowers.flags.
1862 sub get_user_subpermissions
{
1865 my $dbh = C4
::Context
->dbh;
1866 my $sth = $dbh->prepare( "SELECT flag, user_permissions.code
1867 FROM user_permissions
1868 JOIN permissions USING (module_bit, code)
1869 JOIN userflags ON (module_bit = bit)
1870 JOIN borrowers USING (borrowernumber)
1871 WHERE userid = ?" );
1872 $sth->execute($userid);
1874 my $user_perms = {};
1875 while ( my $perm = $sth->fetchrow_hashref ) {
1876 $user_perms->{ $perm->{'flag'} }->{ $perm->{'code'} } = 1;
1881 =head2 get_all_subpermissions
1883 my $perm_hashref = get_all_subpermissions();
1885 Returns a hashref of hashrefs defining all specific
1886 permissions currently defined. The return value
1887 has the same structure as that of C<get_user_subpermissions>,
1888 except that the innermost hash value is the description
1889 of the subpermission.
1893 sub get_all_subpermissions
{
1894 my $dbh = C4
::Context
->dbh;
1895 my $sth = $dbh->prepare( "SELECT flag, code, description
1897 JOIN userflags ON (module_bit = bit)" );
1901 while ( my $perm = $sth->fetchrow_hashref ) {
1902 $all_perms->{ $perm->{'flag'} }->{ $perm->{'code'} } = $perm->{'description'};
1907 =head2 haspermission
1909 $flags = ($userid, $flagsrequired);
1911 C<$userid> the userid of the member
1912 C<$flags> is a hashref of required flags like C<$borrower-<{authflags}>
1914 Returns member's flags or 0 if a permission is not met.
1919 my ( $userid, $flagsrequired ) = @_;
1920 my $sth = C4
::Context
->dbh->prepare("SELECT flags FROM borrowers WHERE userid=?");
1921 $sth->execute($userid);
1922 my $row = $sth->fetchrow();
1923 my $flags = getuserflags
( $row, $userid );
1924 if ( $userid eq C4
::Context
->config('user') ) {
1926 # Super User Account from /etc/koha.conf
1927 $flags->{'superlibrarian'} = 1;
1929 elsif ( $userid eq 'demo' && C4
::Context
->config('demo') ) {
1931 # Demo user that can do "anything" (demo=1 in /etc/koha.conf)
1932 $flags->{'superlibrarian'} = 1;
1935 return $flags if $flags->{superlibrarian
};
1937 foreach my $module ( keys %$flagsrequired ) {
1938 my $subperm = $flagsrequired->{$module};
1939 if ( $subperm eq '*' ) {
1940 return 0 unless ( $flags->{$module} == 1 or ref( $flags->{$module} ) );
1942 return 0 unless ( $flags->{$module} == 1 or
1943 ( ref( $flags->{$module} ) and
1944 exists $flags->{$module}->{$subperm} and
1945 $flags->{$module}->{$subperm} == 1
1952 #FIXME - This fcn should return the failed permission so a suitable error msg can be delivered.
1955 sub getborrowernumber
{
1957 my $userenv = C4
::Context
->userenv;
1958 if ( defined($userenv) && ref($userenv) eq 'HASH' && $userenv->{number
} ) {
1959 return $userenv->{number
};
1961 my $dbh = C4
::Context
->dbh;
1962 for my $field ( 'userid', 'cardnumber' ) {
1964 $dbh->prepare("select borrowernumber from borrowers where $field=?");
1965 $sth->execute($userid);
1967 my ($bnumber) = $sth->fetchrow;
1974 END { } # module clean-up code here (global destructor)
1984 Crypt::Eksblowfish::Bcrypt(3)