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 /;
37 use Encode qw( encode is_utf8);
40 use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS $debug $ldap $cas $caslogout $shib $shib_login);
43 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
63 require C4::Auth_with_ldap;
64 import C4::Auth_with_ldap qw(checkpw_ldap);
67 require C4::Auth_with_shibboleth;
68 import C4::Auth_with_shibboleth
69 qw(shib_ok checkpw_shib logout_shib login_shib_url get_login_shib);
71 # Check for good config
73 # Get shibboleth login attribute
74 $shib_login = get_login_shib();
76 # Bad config, disable shibboleth
82 import C4::Auth_with_cas qw(check_api_auth_cas checkpw_cas login_cas logout_cas login_cas_url);
89 C4::Auth - Authenticates Koha users
99 my ($template, $borrowernumber, $cookie)
100 = get_template_and_user(
102 template_name => "opac-main.tt",
105 authnotrequired => 0,
106 flagsrequired => {borrow => 1, catalogue => '*', tools => 'import_patrons' },
110 output_html_with_http_headers $query, $cookie, $template->output;
114 The main function of this module is to provide
115 authentification. However the get_template_and_user function has
116 been provided so that a users login information is passed along
117 automatically. This gets loaded into the template.
121 =head2 get_template_and_user
123 my ($template, $borrowernumber, $cookie)
124 = get_template_and_user(
126 template_name => "opac-main.tt",
129 authnotrequired => 0,
130 flagsrequired => {borrow => 1, catalogue => '*', tools => 'import_patrons' },
134 This call passes the C<query>, C<flagsrequired> and C<authnotrequired>
135 to C<&checkauth> (in this module) to perform authentification.
136 See C<&checkauth> for an explanation of these parameters.
138 The C<template_name> is then used to find the correct template for
139 the page. The authenticated users details are loaded onto the
140 template in the HTML::Template LOOP variable C<USER_INFO>. Also the
141 C<sessionID> is passed to the template. This can be used in templates
142 if cookies are disabled. It needs to be put as and input to every
145 More information on the C<gettemplate> sub can be found in the
150 sub get_template_and_user {
153 my ( $user, $cookie, $sessionID, $flags );
155 C4::Context->interface($in->{type});
157 $in->{'authnotrequired'} ||= 0;
158 my $template = C4::Templates::gettemplate(
159 $in->{'template_name'},
165 if ( $in->{'template_name'} !~m/maintenance/ ) {
166 ( $user, $cookie, $sessionID, $flags ) = checkauth(
168 $in->{'authnotrequired'},
169 $in->{'flagsrequired'},
177 # It's possible for $user to be the borrowernumber if they don't have a
178 # userid defined (and are logging in through some other method, such
179 # as SSL certs against an email address)
180 $borrowernumber = getborrowernumber($user) if defined($user);
181 if (!defined($borrowernumber) && defined($user)) {
182 my $borrower = C4::Members::GetMember(borrowernumber => $user);
184 $borrowernumber = $user;
185 # A bit of a hack, but I don't know there's a nicer way
187 $user = $borrower->{firstname} . ' ' . $borrower->{surname};
192 $template->param( loggedinusername => $user );
193 $template->param( loggedinusernumber => $borrowernumber );
194 $template->param( sessionID => $sessionID );
196 my ($total, $pubshelves, $barshelves) = C4::VirtualShelves::GetSomeShelfNames($borrowernumber, 'MASTHEAD');
198 pubshelves => $total->{pubtotal},
199 pubshelvesloop => $pubshelves,
200 barshelves => $total->{bartotal},
201 barshelvesloop => $barshelves,
204 my ( $borr ) = C4::Members::GetMemberDetails( $borrowernumber );
207 $template->param( "USER_INFO" => \@bordat );
209 my $all_perms = get_all_subpermissions();
211 my @flagroots = qw(circulate catalogue parameters borrowers permissions reserveforothers borrow
212 editcatalogue updatecharges management tools editauthorities serials reports acquisition);
213 # We are going to use the $flags returned by checkauth
214 # to create the template's parameters that will indicate
215 # which menus the user can access.
216 if ( $flags && $flags->{superlibrarian}==1 ) {
217 $template->param( CAN_user_circulate => 1 );
218 $template->param( CAN_user_catalogue => 1 );
219 $template->param( CAN_user_parameters => 1 );
220 $template->param( CAN_user_borrowers => 1 );
221 $template->param( CAN_user_permissions => 1 );
222 $template->param( CAN_user_reserveforothers => 1 );
223 $template->param( CAN_user_borrow => 1 );
224 $template->param( CAN_user_editcatalogue => 1 );
225 $template->param( CAN_user_updatecharges => 1 );
226 $template->param( CAN_user_acquisition => 1 );
227 $template->param( CAN_user_management => 1 );
228 $template->param( CAN_user_tools => 1 );
229 $template->param( CAN_user_editauthorities => 1 );
230 $template->param( CAN_user_serials => 1 );
231 $template->param( CAN_user_reports => 1 );
232 $template->param( CAN_user_staffaccess => 1 );
233 $template->param( CAN_user_plugins => 1 );
234 $template->param( CAN_user_coursereserves => 1 );
235 foreach my $module (keys %$all_perms) {
236 foreach my $subperm (keys %{ $all_perms->{$module} }) {
237 $template->param( "CAN_user_${module}_${subperm}" => 1 );
243 foreach my $module (keys %$all_perms) {
244 if ( $flags->{$module} == 1) {
245 foreach my $subperm (keys %{ $all_perms->{$module} }) {
246 $template->param( "CAN_user_${module}_${subperm}" => 1 );
248 } elsif ( ref($flags->{$module}) ) {
249 foreach my $subperm (keys %{ $flags->{$module} } ) {
250 $template->param( "CAN_user_${module}_${subperm}" => 1 );
257 foreach my $module (keys %$flags) {
258 if ( $flags->{$module} == 1 or ref($flags->{$module}) ) {
259 $template->param( "CAN_user_$module" => 1 );
260 if ($module eq "parameters") {
261 $template->param( CAN_user_management => 1 );
266 # Logged-in opac search history
267 # If the requested template is an opac one and opac search history is enabled
268 if ($in->{type} eq 'opac' && C4::Context->preference('EnableOpacSearchHistory')) {
269 my $dbh = C4::Context->dbh;
270 my $query = "SELECT COUNT(*) FROM search_history WHERE userid=?";
271 my $sth = $dbh->prepare($query);
272 $sth->execute($borrowernumber);
274 # If at least one search has already been performed
275 if ($sth->fetchrow_array > 0) {
276 # We show the link in opac
277 $template->param( EnableOpacSearchHistory => 1 );
280 # And if there are searches performed when the user was not logged in,
281 # we add them to the logged-in search history
282 my @recentSearches = C4::Search::History::get_from_session({ cgi => $in->{'query'} });
283 if (@recentSearches) {
284 my $dbh = C4::Context->dbh;
286 INSERT INTO search_history(userid, sessionid, query_desc, query_cgi, type, total, time )
287 VALUES (?, ?, ?, ?, ?, ?, ?)
290 my $sth = $dbh->prepare($query);
291 $sth->execute( $borrowernumber,
292 $in->{query}->cookie("CGISESSID"),
295 $_->{type} || 'biblio',
298 ) foreach @recentSearches;
300 # clear out the search history from the session now that
301 # we've saved it to the database
302 C4::Search::History::set_to_session({ cgi => $in->{'query'}, search_history => [] });
304 } elsif ( $in->{type} eq 'intranet' and C4::Context->preference('EnableSearchHistory') ) {
305 $template->param( EnableSearchHistory => 1 );
308 else { # if this is an anonymous session, setup to display public lists...
310 # If shibboleth is enabled, and we're in an anonymous session, we should allow
311 # the user to attemp login via shibboleth.
313 $template->param( shibbolethAuthentication => $shib,
314 shibbolethLoginUrl => login_shib_url($in->{'query'}),
316 # If shibboleth is enabled and we have a shibboleth login attribute,
317 # but we are in an anonymous session, then we clearly have an invalid
318 # shibboleth koha account.
320 $template->param( invalidShibLogin => '1');
324 $template->param( sessionID => $sessionID );
326 my ($total, $pubshelves) = C4::VirtualShelves::GetSomeShelfNames(undef, 'MASTHEAD');
328 pubshelves => $total->{pubtotal},
329 pubshelvesloop => $pubshelves,
332 # Anonymous opac search history
333 # If opac search history is enabled and at least one search has already been performed
334 if (C4::Context->preference('EnableOpacSearchHistory')) {
335 my @recentSearches = C4::Search::History::get_from_session({ cgi => $in->{'query'} });
336 if (@recentSearches) {
337 $template->param(EnableOpacSearchHistory => 1);
341 if(C4::Context->preference('dateformat')){
342 $template->param(dateformat => C4::Context->preference('dateformat'))
345 # these template parameters are set the same regardless of $in->{'type'}
347 # Set the using_https variable for templates
348 # FIXME Under Plack the CGI->https method always returns 'OFF'
349 my $https = $in->{query}->https();
350 my $using_https = (defined $https and $https ne 'OFF') ? 1 : 0;
353 "BiblioDefaultView".C4::Context->preference("BiblioDefaultView") => 1,
354 EnhancedMessagingPreferences => C4::Context->preference('EnhancedMessagingPreferences'),
355 GoogleJackets => C4::Context->preference("GoogleJackets"),
356 OpenLibraryCovers => C4::Context->preference("OpenLibraryCovers"),
357 KohaAdminEmailAddress => "" . C4::Context->preference("KohaAdminEmailAddress"),
358 LoginBranchcode => (C4::Context->userenv?C4::Context->userenv->{"branch"}:undef),
359 LoginFirstname => (C4::Context->userenv?C4::Context->userenv->{"firstname"}:"Bel"),
360 LoginSurname => C4::Context->userenv?C4::Context->userenv->{"surname"}:"Inconnu",
361 emailaddress => C4::Context->userenv?C4::Context->userenv->{"emailaddress"}:undef,
362 loggedinpersona => C4::Context->userenv?C4::Context->userenv->{"persona"}:undef,
363 TagsEnabled => C4::Context->preference("TagsEnabled"),
364 hide_marc => C4::Context->preference("hide_marc"),
365 item_level_itypes => C4::Context->preference('item-level_itypes'),
366 patronimages => C4::Context->preference("patronimages"),
367 singleBranchMode => C4::Context->preference("singleBranchMode"),
368 XSLTDetailsDisplay => C4::Context->preference("XSLTDetailsDisplay"),
369 XSLTResultsDisplay => C4::Context->preference("XSLTResultsDisplay"),
370 using_https => $using_https,
371 noItemTypeImages => C4::Context->preference("noItemTypeImages"),
372 marcflavour => C4::Context->preference("marcflavour"),
373 persona => C4::Context->preference("persona"),
375 if ( $in->{'type'} eq "intranet" ) {
377 AmazonCoverImages => C4::Context->preference("AmazonCoverImages"),
378 AutoLocation => C4::Context->preference("AutoLocation"),
379 "BiblioDefaultView".C4::Context->preference("IntranetBiblioDefaultView") => 1,
380 CalendarFirstDayOfWeek => (C4::Context->preference("CalendarFirstDayOfWeek") eq "Sunday")?0:1,
381 CircAutocompl => C4::Context->preference("CircAutocompl"),
382 FRBRizeEditions => C4::Context->preference("FRBRizeEditions"),
383 IndependentBranches => C4::Context->preference("IndependentBranches"),
384 IntranetNav => C4::Context->preference("IntranetNav"),
385 IntranetmainUserblock => C4::Context->preference("IntranetmainUserblock"),
386 LibraryName => C4::Context->preference("LibraryName"),
387 LoginBranchname => (C4::Context->userenv?C4::Context->userenv->{"branchname"}:undef),
388 advancedMARCEditor => C4::Context->preference("advancedMARCEditor"),
389 canreservefromotherbranches => C4::Context->preference('canreservefromotherbranches'),
390 intranetcolorstylesheet => C4::Context->preference("intranetcolorstylesheet"),
391 IntranetFavicon => C4::Context->preference("IntranetFavicon"),
392 intranetreadinghistory => C4::Context->preference("intranetreadinghistory"),
393 intranetstylesheet => C4::Context->preference("intranetstylesheet"),
394 IntranetUserCSS => C4::Context->preference("IntranetUserCSS"),
395 intranetuserjs => C4::Context->preference("intranetuserjs"),
396 intranetbookbag => C4::Context->preference("intranetbookbag"),
397 suggestion => C4::Context->preference("suggestion"),
398 virtualshelves => C4::Context->preference("virtualshelves"),
399 StaffSerialIssueDisplayCount => C4::Context->preference("StaffSerialIssueDisplayCount"),
400 EasyAnalyticalRecords => C4::Context->preference('EasyAnalyticalRecords'),
401 LocalCoverImages => C4::Context->preference('LocalCoverImages'),
402 OPACLocalCoverImages => C4::Context->preference('OPACLocalCoverImages'),
403 AllowMultipleCovers => C4::Context->preference('AllowMultipleCovers'),
404 EnableBorrowerFiles => C4::Context->preference('EnableBorrowerFiles'),
405 UseKohaPlugins => C4::Context->preference('UseKohaPlugins'),
406 UseCourseReserves => C4::Context->preference("UseCourseReserves"),
410 warn "template type should be OPAC, here it is=[" . $in->{'type'} . "]" unless ( $in->{'type'} eq 'opac' );
411 #TODO : replace LibraryName syspref with 'system name', and remove this html processing
412 my $LibraryNameTitle = C4::Context->preference("LibraryName");
413 $LibraryNameTitle =~ s/<(?:\/?)(?:br|p)\s*(?:\/?)>/ /sgi;
414 $LibraryNameTitle =~ s/<(?:[^<>'"]|'(?:[^']*)'|"(?:[^"]*)")*>//sg;
415 # clean up the busc param in the session if the page is not opac-detail and not the "add to list" page
416 if ( C4::Context->preference("OpacBrowseResults")
417 && $in->{'template_name'} =~ /opac-(.+)\.(?:tt|tmpl)$/ ) {
419 unless ( $pagename =~ /^(?:MARC|ISBD)?detail$/
420 or $pagename =~ /^addbybiblionumber$/ ) {
421 my $sessionSearch = get_session($sessionID || $in->{'query'}->cookie("CGISESSID"));
422 $sessionSearch->clear(["busc"]) if ($sessionSearch->param("busc"));
425 # variables passed from CGI: opac_css_override and opac_search_limits.
426 my $opac_search_limit = $ENV{'OPAC_SEARCH_LIMIT'};
427 my $opac_limit_override = $ENV{'OPAC_LIMIT_OVERRIDE'};
430 ($opac_limit_override && $opac_search_limit && $opac_search_limit =~ /branch:(\w+)/) ||
431 ($in->{'query'}->param('limit') && $in->{'query'}->param('limit') =~ /branch:(\w+)/) ||
432 ($in->{'query'}->param('multibranchlimit') && $in->{'query'}->param('multibranchlimit') =~ /multibranchlimit-(\w+)/)
434 $opac_name = $1; # opac_search_limit is a branch, so we use it.
435 } elsif ( $in->{'query'}->param('multibranchlimit') ) {
436 $opac_name = $in->{'query'}->param('multibranchlimit');
437 } elsif (C4::Context->preference("SearchMyLibraryFirst") && C4::Context->userenv && C4::Context->userenv->{'branch'}) {
438 $opac_name = C4::Context->userenv->{'branch'};
440 # FIXME Under Plack the CGI->https method always returns 'OFF' ($using_https will be set to 0 in this case)
441 my $opac_base_url = C4::Context->preference("OPACBaseURL"); #FIXME uses $using_https below as well
442 if (!$opac_base_url){
443 $opac_base_url = $ENV{'SERVER_NAME'} . ($ENV{'SERVER_PORT'} eq ($using_https ? "443" : "80") ? '' : ":$ENV{'SERVER_PORT'}");
446 opaccolorstylesheet => C4::Context->preference("opaccolorstylesheet"),
447 AnonSuggestions => "" . C4::Context->preference("AnonSuggestions"),
448 AuthorisedValueImages => C4::Context->preference("AuthorisedValueImages"),
449 BranchesLoop => GetBranchesLoop($opac_name),
450 BranchCategoriesLoop => GetBranchCategories( 'searchdomain', 1, $opac_name ),
451 CalendarFirstDayOfWeek => (C4::Context->preference("CalendarFirstDayOfWeek") eq "Sunday")?0:1,
452 LibraryName => "" . C4::Context->preference("LibraryName"),
453 LibraryNameTitle => "" . $LibraryNameTitle,
454 LoginBranchname => C4::Context->userenv?C4::Context->userenv->{"branchname"}:"",
455 OPACAmazonCoverImages => C4::Context->preference("OPACAmazonCoverImages"),
456 OPACFRBRizeEditions => C4::Context->preference("OPACFRBRizeEditions"),
457 OpacHighlightedWords => C4::Context->preference("OpacHighlightedWords"),
458 OPACItemHolds => C4::Context->preference("OPACItemHolds"),
459 OPACShelfBrowser => "". C4::Context->preference("OPACShelfBrowser"),
460 OPACURLOpenInNewWindow => "" . C4::Context->preference("OPACURLOpenInNewWindow"),
461 OPACUserCSS => "". C4::Context->preference("OPACUserCSS"),
462 OPACViewOthersSuggestions => "" . C4::Context->preference("OPACViewOthersSuggestions"),
463 OpacAuthorities => C4::Context->preference("OpacAuthorities"),
464 OPACBaseURL => ($using_https ? "https://" : "http://") . $opac_base_url,
465 opac_css_override => $ENV{'OPAC_CSS_OVERRIDE'},
466 opac_search_limit => $opac_search_limit,
467 opac_limit_override => $opac_limit_override,
468 OpacBrowser => C4::Context->preference("OpacBrowser"),
469 OpacCloud => C4::Context->preference("OpacCloud"),
470 OpacKohaUrl => C4::Context->preference("OpacKohaUrl"),
471 OpacMainUserBlock => "" . C4::Context->preference("OpacMainUserBlock"),
472 OpacNav => "" . C4::Context->preference("OpacNav"),
473 OpacNavRight => "" . C4::Context->preference("OpacNavRight"),
474 OpacNavBottom => "" . C4::Context->preference("OpacNavBottom"),
475 OpacPasswordChange => C4::Context->preference("OpacPasswordChange"),
476 OPACPatronDetails => C4::Context->preference("OPACPatronDetails"),
477 OPACPrivacy => C4::Context->preference("OPACPrivacy"),
478 OPACFinesTab => C4::Context->preference("OPACFinesTab"),
479 OpacTopissue => C4::Context->preference("OpacTopissue"),
480 RequestOnOpac => C4::Context->preference("RequestOnOpac"),
481 'Version' => C4::Context->preference('Version'),
482 hidelostitems => C4::Context->preference("hidelostitems"),
483 mylibraryfirst => (C4::Context->preference("SearchMyLibraryFirst") && C4::Context->userenv) ? C4::Context->userenv->{'branch'} : '',
484 opaclayoutstylesheet => "" . C4::Context->preference("opaclayoutstylesheet"),
485 opacbookbag => "" . C4::Context->preference("opacbookbag"),
486 opaccredits => "" . C4::Context->preference("opaccredits"),
487 OpacFavicon => C4::Context->preference("OpacFavicon"),
488 opacheader => "" . C4::Context->preference("opacheader"),
489 opaclanguagesdisplay => "" . C4::Context->preference("opaclanguagesdisplay"),
490 opacreadinghistory => C4::Context->preference("opacreadinghistory"),
491 opacuserjs => C4::Context->preference("opacuserjs"),
492 opacuserlogin => "" . C4::Context->preference("opacuserlogin"),
493 ShowReviewer => C4::Context->preference("ShowReviewer"),
494 ShowReviewerPhoto => C4::Context->preference("ShowReviewerPhoto"),
495 suggestion => "" . C4::Context->preference("suggestion"),
496 virtualshelves => "" . C4::Context->preference("virtualshelves"),
497 OPACSerialIssueDisplayCount => C4::Context->preference("OPACSerialIssueDisplayCount"),
498 OPACXSLTDetailsDisplay => C4::Context->preference("OPACXSLTDetailsDisplay"),
499 OPACXSLTResultsDisplay => C4::Context->preference("OPACXSLTResultsDisplay"),
500 SyndeticsClientCode => C4::Context->preference("SyndeticsClientCode"),
501 SyndeticsEnabled => C4::Context->preference("SyndeticsEnabled"),
502 SyndeticsCoverImages => C4::Context->preference("SyndeticsCoverImages"),
503 SyndeticsTOC => C4::Context->preference("SyndeticsTOC"),
504 SyndeticsSummary => C4::Context->preference("SyndeticsSummary"),
505 SyndeticsEditions => C4::Context->preference("SyndeticsEditions"),
506 SyndeticsExcerpt => C4::Context->preference("SyndeticsExcerpt"),
507 SyndeticsReviews => C4::Context->preference("SyndeticsReviews"),
508 SyndeticsAuthorNotes => C4::Context->preference("SyndeticsAuthorNotes"),
509 SyndeticsAwards => C4::Context->preference("SyndeticsAwards"),
510 SyndeticsSeries => C4::Context->preference("SyndeticsSeries"),
511 SyndeticsCoverImageSize => C4::Context->preference("SyndeticsCoverImageSize"),
512 OPACLocalCoverImages => C4::Context->preference("OPACLocalCoverImages"),
513 PatronSelfRegistration => C4::Context->preference("PatronSelfRegistration"),
514 PatronSelfRegistrationDefaultCategory => C4::Context->preference("PatronSelfRegistrationDefaultCategory"),
517 $template->param(OpacPublic => '1') if ($user || C4::Context->preference("OpacPublic"));
520 # Check if we were asked using parameters to force a specific language
521 if ( defined $in->{'query'}->param('language') ) {
522 # Extract the language, let C4::Languages::getlanguage choose
524 my $language = C4::Languages::getlanguage($in->{'query'});
525 my $languagecookie = C4::Templates::getlanguagecookie($in->{'query'},$language);
526 if ( ref $cookie eq 'ARRAY' ) {
527 push @{ $cookie }, $languagecookie;
529 $cookie = [$cookie, $languagecookie];
533 return ( $template, $borrowernumber, $cookie, $flags);
538 ($userid, $cookie, $sessionID) = &checkauth($query, $noauth, $flagsrequired, $type);
540 Verifies that the user is authorized to run this script. If
541 the user is authorized, a (userid, cookie, session-id, flags)
542 quadruple is returned. If the user is not authorized but does
543 not have the required privilege (see $flagsrequired below), it
544 displays an error page and exits. Otherwise, it displays the
545 login page and exits.
547 Note that C<&checkauth> will return if and only if the user
548 is authorized, so it should be called early on, before any
549 unfinished operations (e.g., if you've opened a file, then
550 C<&checkauth> won't close it for you).
552 C<$query> is the CGI object for the script calling C<&checkauth>.
554 The C<$noauth> argument is optional. If it is set, then no
555 authorization is required for the script.
557 C<&checkauth> fetches user and session information from C<$query> and
558 ensures that the user is authorized to run scripts that require
561 The C<$flagsrequired> argument specifies the required privileges
562 the user must have if the username and password are correct.
563 It should be specified as a reference-to-hash; keys in the hash
564 should be the "flags" for the user, as specified in the Members
565 intranet module. Any key specified must correspond to a "flag"
566 in the userflags table. E.g., { circulate => 1 } would specify
567 that the user must have the "circulate" privilege in order to
568 proceed. To make sure that access control is correct, the
569 C<$flagsrequired> parameter must be specified correctly.
571 Koha also has a concept of sub-permissions, also known as
572 granular permissions. This makes the value of each key
573 in the C<flagsrequired> hash take on an additional
578 The user must have access to all subfunctions of the module
579 specified by the hash key.
583 The user must have access to at least one subfunction of the module
584 specified by the hash key.
586 specific permission, e.g., 'export_catalog'
588 The user must have access to the specific subfunction list, which
589 must correspond to a row in the permissions table.
591 The C<$type> argument specifies whether the template should be
592 retrieved from the opac or intranet directory tree. "opac" is
593 assumed if it is not specified; however, if C<$type> is specified,
594 "intranet" is assumed if it is not "opac".
596 If C<$query> does not have a valid session ID associated with it
597 (i.e., the user has not logged in) or if the session has expired,
598 C<&checkauth> presents the user with a login page (from the point of
599 view of the original script, C<&checkauth> does not return). Once the
600 user has authenticated, C<&checkauth> restarts the original script
601 (this time, C<&checkauth> returns).
603 The login page is provided using a HTML::Template, which is set in the
604 systempreferences table or at the top of this file. The variable C<$type>
605 selects which template to use, either the opac or the intranet
606 authentification template.
608 C<&checkauth> returns a user ID, a cookie, and a session ID. The
609 cookie should be sent back to the browser; it verifies that the user
618 # If Version syspref is unavailable, it means Koha is beeing installed,
619 # and so we must redirect to OPAC maintenance page or to the WebInstaller
620 # also, if OpacMaintenance is ON, OPAC should redirect to maintenance
621 if (C4::Context->preference('OpacMaintenance') && $type eq 'opac') {
622 warn "OPAC Install required, redirecting to maintenance";
623 print $query->redirect("/cgi-bin/koha/maintenance.pl");
626 unless ( $version = C4::Context->preference('Version') ) { # assignment, not comparison
627 if ( $type ne 'opac' ) {
628 warn "Install required, redirecting to Installer";
629 print $query->redirect("/cgi-bin/koha/installer/install.pl");
631 warn "OPAC Install required, redirecting to maintenance";
632 print $query->redirect("/cgi-bin/koha/maintenance.pl");
637 # check that database and koha version are the same
638 # there is no DB version, it's a fresh install,
639 # go to web installer
640 # there is a DB version, compare it to the code version
641 my $kohaversion=C4::Context::KOHAVERSION;
642 # remove the 3 last . to have a Perl number
643 $kohaversion =~ s/(.*\..*)\.(.*)\.(.*)/$1$2$3/;
644 $debug and print STDERR "kohaversion : $kohaversion\n";
645 if ($version < $kohaversion){
646 my $warning = "Database update needed, redirecting to %s. Database is $version and Koha is $kohaversion";
647 if ($type ne 'opac'){
648 warn sprintf($warning, 'Installer');
649 print $query->redirect("/cgi-bin/koha/installer/install.pl?step=3");
651 warn sprintf("OPAC: " . $warning, 'maintenance');
652 print $query->redirect("/cgi-bin/koha/maintenance.pl");
660 open my $fh, '>>', "/tmp/sessionlog" or warn "ERROR: Cannot append to /tmp/sessionlog";
661 printf $fh join("\n",@_);
665 sub _timeout_syspref {
666 my $timeout = C4::Context->preference('timeout') || 600;
667 # value in days, convert in seconds
668 if ($timeout =~ /(\d+)[dD]/) {
669 $timeout = $1 * 86400;
676 $debug and warn "Checking Auth";
677 # $authnotrequired will be set for scripts which will run without authentication
678 my $authnotrequired = shift;
679 my $flagsrequired = shift;
682 $type = 'opac' unless $type;
684 my $dbh = C4::Context->dbh;
685 my $timeout = _timeout_syspref();
687 _version_check($type,$query);
691 my ( $userid, $cookie, $sessionID, $flags, $barshelves, $pubshelves );
692 my $logout = $query->param('logout.x');
694 my $anon_search_history;
696 # This parameter is the name of the CAS server we want to authenticate against,
697 # when using authentication against multiple CAS servers, as configured in Auth_cas_servers.yaml
698 my $casparam = $query->param('cas');
699 my $q_userid = $query->param('userid') // '';
701 # Basic authentication is incompatible with the use of Shibboleth,
702 # as Shibboleth may return REMOTE_USER as a Shibboleth attribute,
703 # and it may not be the attribute we want to use to match the koha login.
705 # Also, do not consider an empty REMOTE_USER.
707 # Finally, after those tests, we can assume (although if it would be better with
708 # a syspref) that if we get a REMOTE_USER, that's from basic authentication,
709 # and we can affect it to $userid.
710 if ( !$shib and defined($ENV{'REMOTE_USER'}) and $ENV{'REMOTE_USER'} ne '' and $userid = $ENV{'REMOTE_USER'} ) {
712 # Using Basic Authentication, no cookies required
713 $cookie = $query->cookie(
714 -name => 'CGISESSID',
722 # we dont want to set a session because we are being called by a persona callback
724 elsif ( $sessionID = $query->cookie("CGISESSID") )
725 { # assignment, not comparison
726 my $session = get_session($sessionID);
727 C4::Context->_new_userenv($sessionID);
728 my ($ip, $lasttime, $sessiontype);
731 $s_userid = $session->param('id') // '';
732 C4::Context::set_userenv(
733 $session->param('number'), $s_userid,
734 $session->param('cardnumber'), $session->param('firstname'),
735 $session->param('surname'), $session->param('branch'),
736 $session->param('branchname'), $session->param('flags'),
737 $session->param('emailaddress'), $session->param('branchprinter'),
738 $session->param('persona'), $session->param('shibboleth')
740 C4::Context::set_shelves_userenv('bar',$session->param('barshelves'));
741 C4::Context::set_shelves_userenv('pub',$session->param('pubshelves'));
742 C4::Context::set_shelves_userenv('tot',$session->param('totshelves'));
743 $debug and printf STDERR "AUTH_SESSION: (%s)\t%s %s - %s\n", map {$session->param($_)} qw(cardnumber firstname surname branch) ;
744 $ip = $session->param('ip');
745 $lasttime = $session->param('lasttime');
747 $sessiontype = $session->param('sessiontype') || '';
749 if ( ( $query->param('koha_login_context') && ($q_userid ne $s_userid) )
750 || ( $cas && $query->param('ticket') ) || ( $shib && $shib_login && !$logout ) ) {
751 #if a user enters an id ne to the id in the current session, we need to log them in...
752 #first we need to clear the anonymous session...
753 $debug and warn "query id = $q_userid but session id = $s_userid";
754 $anon_search_history = $session->param('search_history');
757 C4::Context->_unset_userenv($sessionID);
762 # voluntary logout the user
763 # check wether the user was using their shibboleth session or a local one
764 my $shibSuccess = C4::Context->userenv->{'shibboleth'};
767 C4::Context->_unset_userenv($sessionID);
768 #_session_log(sprintf "%20s from %16s logged out at %30s (manually).\n", $userid,$ip,(strftime "%c",localtime));
772 if ($cas and $caslogout) {
776 # If we are in a shibboleth session (shibboleth is enabled, a shibboleth match attribute is set and matches koha matchpoint)
777 if ( $shib and $shib_login and $shibSuccess and $type eq 'opac') {
778 # (Note: $type eq 'opac' condition should be removed when shibboleth authentication for intranet will be implemented)
782 elsif ( !$lasttime || ($lasttime < time() - $timeout) ) {
784 $info{'timed_out'} = 1;
789 C4::Context->_unset_userenv($sessionID);
790 #_session_log(sprintf "%20s from %16s logged out at %30s (inactivity).\n", $userid,$ip,(strftime "%c",localtime));
794 elsif ( $ip ne $ENV{'REMOTE_ADDR'} ) {
795 # Different ip than originally logged in from
796 $info{'oldip'} = $ip;
797 $info{'newip'} = $ENV{'REMOTE_ADDR'};
798 $info{'different_ip'} = 1;
801 C4::Context->_unset_userenv($sessionID);
802 #_session_log(sprintf "%20s from %16s logged out at %30s (ip changed to %16s).\n", $userid,$ip,(strftime "%c",localtime), $info{'newip'});
807 $cookie = $query->cookie(
808 -name => 'CGISESSID',
809 -value => $session->id,
812 $session->param( 'lasttime', time() );
813 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...
814 $flags = haspermission($userid, $flagsrequired);
818 $info{'nopermission'} = 1;
823 unless ($userid || $sessionID) {
825 #we initiate a session prior to checking for a username to allow for anonymous sessions...
826 my $session = get_session("") or die "Auth ERROR: Cannot get_session()";
828 # Save anonymous search history in new session so it can be retrieved
829 # by get_template_and_user to store it in user's search history after
830 # a successful login.
831 if ($anon_search_history) {
832 $session->param('search_history', $anon_search_history);
835 my $sessionID = $session->id;
836 C4::Context->_new_userenv($sessionID);
837 $cookie = $query->cookie(
838 -name => 'CGISESSID',
839 -value => $session->id,
843 my $pki_field = C4::Context->preference('AllowPKIAuth');
844 if (! defined($pki_field) ) {
845 print STDERR "ERROR: Missing system preference AllowPKIAuth.\n";
848 if ( ( $cas && $query->param('ticket') )
850 || ( $shib && $shib_login )
851 || $pki_field ne 'None'
854 my $password = $query->param('password');
857 my ( $return, $cardnumber );
858 # If shib is enabled and we have a shib login, does the login match a valid koha user
859 if ( $shib && $shib_login && $type eq 'opac' ) {
861 # Do not pass password here, else shib will not be checked in checkpw.
862 ( $return, $cardnumber, $retuserid ) = checkpw( $dbh, $userid, undef, $query );
863 $userid = $retuserid;
864 $shibSuccess = $return;
865 $info{'invalidShibLogin'} = 1 unless ($return);
867 # If shib login and match were successfull, skip further login methods
868 unless ( $shibSuccess ) {
869 if ( $cas && $query->param('ticket') ) {
871 ( $return, $cardnumber, $retuserid ) =
872 checkpw( $dbh, $userid, $password, $query );
873 $userid = $retuserid;
874 $info{'invalidCasLogin'} = 1 unless ($return);
878 my $value = $persona;
880 # If we're looking up the email, there's a chance that the person
881 # doesn't have a userid. So if there is none, we pass along the
882 # borrower number, and the bits of code that need to know the user
883 # ID will have to be smart enough to handle that.
885 my @users_info = C4::Members::GetBorrowersWithEmail($value);
888 # First the userid, then the borrowernum
889 $value = $users_info[0][1] || $users_info[0][0];
894 $return = $value ? 1 : 0;
899 ( $pki_field eq 'Common Name' && $ENV{'SSL_CLIENT_S_DN_CN'} )
900 || ( $pki_field eq 'emailAddress'
901 && $ENV{'SSL_CLIENT_S_DN_Email'} )
905 if ( $pki_field eq 'Common Name' ) {
906 $value = $ENV{'SSL_CLIENT_S_DN_CN'};
908 elsif ( $pki_field eq 'emailAddress' ) {
909 $value = $ENV{'SSL_CLIENT_S_DN_Email'};
911 # If we're looking up the email, there's a chance that the person
912 # doesn't have a userid. So if there is none, we pass along the
913 # borrower number, and the bits of code that need to know the user
914 # ID will have to be smart enough to handle that.
916 my @users_info = C4::Members::GetBorrowersWithEmail($value);
919 # First the userid, then the borrowernum
920 $value = $users_info[0][1] || $users_info[0][0];
927 $return = $value ? 1 : 0;
933 ( $return, $cardnumber, $retuserid ) =
934 checkpw( $dbh, $userid, $password, $query );
935 $userid = $retuserid if ( $retuserid );
936 $info{'invalid_username_or_password'} = 1 unless ($return);
939 #_session_log(sprintf "%20s from %16s logged in at %30s.\n", $userid,$ENV{'REMOTE_ADDR'},(strftime '%c', localtime));
940 if ( $flags = haspermission( $userid, $flagsrequired ) ) {
944 $info{'nopermission'} = 1;
945 C4::Context->_unset_userenv($sessionID);
947 my ($borrowernumber, $firstname, $surname, $userflags,
948 $branchcode, $branchname, $branchprinter, $emailaddress);
950 if ( $return == 1 ) {
952 SELECT borrowernumber, firstname, surname, flags, borrowers.branchcode,
953 branches.branchname as branchname,
954 branches.branchprinter as branchprinter,
957 LEFT JOIN branches on borrowers.branchcode=branches.branchcode
959 my $sth = $dbh->prepare("$select where userid=?");
960 $sth->execute($userid);
961 unless ($sth->rows) {
962 $debug and print STDERR "AUTH_1: no rows for userid='$userid'\n";
963 $sth = $dbh->prepare("$select where cardnumber=?");
964 $sth->execute($cardnumber);
966 unless ($sth->rows) {
967 $debug and print STDERR "AUTH_2a: no rows for cardnumber='$cardnumber'\n";
968 $sth->execute($userid);
969 unless ($sth->rows) {
970 $debug and print STDERR "AUTH_2b: no rows for userid='$userid' AS cardnumber\n";
975 ($borrowernumber, $firstname, $surname, $userflags,
976 $branchcode, $branchname, $branchprinter, $emailaddress) = $sth->fetchrow;
977 $debug and print STDERR "AUTH_3 results: " .
978 "$cardnumber,$borrowernumber,$userid,$firstname,$surname,$userflags,$branchcode,$emailaddress\n";
980 print STDERR "AUTH_3: no results for userid='$userid', cardnumber='$cardnumber'.\n";
983 # launch a sequence to check if we have a ip for the branch, i
984 # if we have one we replace the branchcode of the userenv by the branch bound in the ip.
986 my $ip = $ENV{'REMOTE_ADDR'};
987 # if they specify at login, use that
988 if ($query->param('branch')) {
989 $branchcode = $query->param('branch');
990 $branchname = GetBranchName($branchcode);
992 my $branches = GetBranches();
993 if (C4::Context->boolean_preference('IndependentBranches') && C4::Context->boolean_preference('Autolocation')){
994 # we have to check they are coming from the right ip range
995 my $domain = $branches->{$branchcode}->{'branchip'};
996 if ($ip !~ /^$domain/){
998 $info{'wrongip'} = 1;
1003 foreach my $br ( keys %$branches ) {
1004 # now we work with the treatment of ip
1005 my $domain = $branches->{$br}->{'branchip'};
1006 if ( $domain && $ip =~ /^$domain/ ) {
1007 $branchcode = $branches->{$br}->{'branchcode'};
1009 # new op dev : add the branchprinter and branchname in the cookie
1010 $branchprinter = $branches->{$br}->{'branchprinter'};
1011 $branchname = $branches->{$br}->{'branchname'};
1014 $session->param('number',$borrowernumber);
1015 $session->param('id',$userid);
1016 $session->param('cardnumber',$cardnumber);
1017 $session->param('firstname',$firstname);
1018 $session->param('surname',$surname);
1019 $session->param('branch',$branchcode);
1020 $session->param('branchname',$branchname);
1021 $session->param('flags',$userflags);
1022 $session->param('emailaddress',$emailaddress);
1023 $session->param('ip',$session->remote_addr());
1024 $session->param('lasttime',time());
1025 $session->param('shibboleth',$shibSuccess);
1026 $debug and printf STDERR "AUTH_4: (%s)\t%s %s - %s\n", map {$session->param($_)} qw(cardnumber firstname surname branch) ;
1028 elsif ( $return == 2 ) {
1029 #We suppose the user is the superlibrarian
1030 $borrowernumber = 0;
1031 $session->param('number',0);
1032 $session->param('id',C4::Context->config('user'));
1033 $session->param('cardnumber',C4::Context->config('user'));
1034 $session->param('firstname',C4::Context->config('user'));
1035 $session->param('surname',C4::Context->config('user'));
1036 $session->param('branch','NO_LIBRARY_SET');
1037 $session->param('branchname','NO_LIBRARY_SET');
1038 $session->param('flags',1);
1039 $session->param('emailaddress', C4::Context->preference('KohaAdminEmailAddress'));
1040 $session->param('ip',$session->remote_addr());
1041 $session->param('lasttime',time());
1044 $session->param('persona',1);
1046 C4::Context::set_userenv(
1047 $session->param('number'), $session->param('id'),
1048 $session->param('cardnumber'), $session->param('firstname'),
1049 $session->param('surname'), $session->param('branch'),
1050 $session->param('branchname'), $session->param('flags'),
1051 $session->param('emailaddress'), $session->param('branchprinter'),
1052 $session->param('persona'), $session->param('shibboleth')
1058 $info{'invalid_username_or_password'} = 1;
1059 C4::Context->_unset_userenv($sessionID);
1061 $session->param('lasttime',time());
1062 $session->param('ip',$session->remote_addr());
1064 } # END if ( $userid = $query->param('userid') )
1065 elsif ($type eq "opac") {
1066 # if we are here this is an anonymous session; add public lists to it and a few other items...
1067 # anonymous sessions are created only for the OPAC
1068 $debug and warn "Initiating an anonymous session...";
1070 # setting a couple of other session vars...
1071 $session->param('ip',$session->remote_addr());
1072 $session->param('lasttime',time());
1073 $session->param('sessiontype','anon');
1075 } # END unless ($userid)
1077 # finished authentification, now respond
1078 if ( $loggedin || $authnotrequired )
1082 $cookie = $query->cookie(
1083 -name => 'CGISESSID',
1088 return ( $userid, $cookie, $sessionID, $flags );
1093 # AUTH rejected, show the login/password template, after checking the DB.
1097 # get the inputs from the incoming query
1099 foreach my $name ( param $query) {
1100 (next) if ( $name eq 'userid' || $name eq 'password' || $name eq 'ticket' );
1101 my $value = $query->param($name);
1102 push @inputs, { name => $name, value => $value };
1105 my $LibraryNameTitle = C4::Context->preference("LibraryName");
1106 $LibraryNameTitle =~ s/<(?:\/?)(?:br|p)\s*(?:\/?)>/ /sgi;
1107 $LibraryNameTitle =~ s/<(?:[^<>'"]|'(?:[^']*)'|"(?:[^"]*)")*>//sg;
1109 my $template_name = ( $type eq 'opac' ) ? 'opac-auth.tt' : 'auth.tt';
1110 my $template = C4::Templates::gettemplate($template_name, $type, $query );
1112 branchloop => GetBranchesLoop(),
1113 opaccolorstylesheet => C4::Context->preference("opaccolorstylesheet"),
1114 opaclayoutstylesheet => C4::Context->preference("opaclayoutstylesheet"),
1117 casAuthentication => C4::Context->preference("casAuthentication"),
1118 shibbolethAuthentication => $shib,
1119 suggestion => C4::Context->preference("suggestion"),
1120 virtualshelves => C4::Context->preference("virtualshelves"),
1121 LibraryName => "" . C4::Context->preference("LibraryName"),
1122 LibraryNameTitle => "" . $LibraryNameTitle,
1123 opacuserlogin => C4::Context->preference("opacuserlogin"),
1124 OpacNav => C4::Context->preference("OpacNav"),
1125 OpacNavRight => C4::Context->preference("OpacNavRight"),
1126 OpacNavBottom => C4::Context->preference("OpacNavBottom"),
1127 opaccredits => C4::Context->preference("opaccredits"),
1128 OpacFavicon => C4::Context->preference("OpacFavicon"),
1129 opacreadinghistory => C4::Context->preference("opacreadinghistory"),
1130 opaclanguagesdisplay => C4::Context->preference("opaclanguagesdisplay"),
1131 opacuserjs => C4::Context->preference("opacuserjs"),
1132 opacbookbag => "" . C4::Context->preference("opacbookbag"),
1133 OpacCloud => C4::Context->preference("OpacCloud"),
1134 OpacTopissue => C4::Context->preference("OpacTopissue"),
1135 OpacAuthorities => C4::Context->preference("OpacAuthorities"),
1136 OpacBrowser => C4::Context->preference("OpacBrowser"),
1137 opacheader => C4::Context->preference("opacheader"),
1138 TagsEnabled => C4::Context->preference("TagsEnabled"),
1139 OPACUserCSS => C4::Context->preference("OPACUserCSS"),
1140 intranetcolorstylesheet => C4::Context->preference("intranetcolorstylesheet"),
1141 intranetstylesheet => C4::Context->preference("intranetstylesheet"),
1142 intranetbookbag => C4::Context->preference("intranetbookbag"),
1143 IntranetNav => C4::Context->preference("IntranetNav"),
1144 IntranetFavicon => C4::Context->preference("IntranetFavicon"),
1145 intranetuserjs => C4::Context->preference("intranetuserjs"),
1146 IndependentBranches=> C4::Context->preference("IndependentBranches"),
1147 AutoLocation => C4::Context->preference("AutoLocation"),
1148 wrongip => $info{'wrongip'},
1149 PatronSelfRegistration => C4::Context->preference("PatronSelfRegistration"),
1150 PatronSelfRegistrationDefaultCategory => C4::Context->preference("PatronSelfRegistrationDefaultCategory"),
1151 persona => C4::Context->preference("Persona"),
1152 opac_css_override => $ENV{'OPAC_CSS_OVERRIDE'},
1155 $template->param( OpacPublic => C4::Context->preference("OpacPublic"));
1156 $template->param( loginprompt => 1 ) unless $info{'nopermission'};
1158 if($type eq 'opac'){
1159 my ($total, $pubshelves) = C4::VirtualShelves::GetSomeShelfNames(undef, 'MASTHEAD');
1161 pubshelves => $total->{pubtotal},
1162 pubshelvesloop => $pubshelves,
1168 # Is authentication against multiple CAS servers enabled?
1169 if (C4::Auth_with_cas::multipleAuth && !$casparam) {
1170 my $casservers = C4::Auth_with_cas::getMultipleAuth();
1172 foreach my $key (keys %$casservers) {
1173 push @tmplservers, {name => $key, value => login_cas_url($query, $key) . "?cas=$key" };
1176 casServersLoop => \@tmplservers
1180 casServerUrl => login_cas_url($query),
1185 invalidCasLogin => $info{'invalidCasLogin'}
1191 shibbolethAuthentication => $shib,
1192 shibbolethLoginUrl => login_shib_url($query),
1196 my $self_url = $query->url( -absolute => 1 );
1199 LibraryName => C4::Context->preference("LibraryName"),
1201 $template->param( %info );
1202 # $cookie = $query->cookie(CGISESSID => $session->id
1204 print $query->header(
1205 -type => 'text/html',
1206 -charset => 'utf-8',
1213 =head2 check_api_auth
1215 ($status, $cookie, $sessionId) = check_api_auth($query, $userflags);
1217 Given a CGI query containing the parameters 'userid' and 'password' and/or a session
1218 cookie, determine if the user has the privileges specified by C<$userflags>.
1220 C<check_api_auth> is is meant for authenticating users of web services, and
1221 consequently will always return and will not attempt to redirect the user
1224 If a valid session cookie is already present, check_api_auth will return a status
1225 of "ok", the cookie, and the Koha session ID.
1227 If no session cookie is present, check_api_auth will check the 'userid' and 'password
1228 parameters and create a session cookie and Koha session if the supplied credentials
1231 Possible return values in C<$status> are:
1235 =item "ok" -- user authenticated; C<$cookie> and C<$sessionid> have valid values.
1237 =item "failed" -- credentials are not correct; C<$cookie> and C<$sessionid> are undef
1239 =item "maintenance" -- DB is in maintenance mode; no login possible at the moment
1241 =item "expired -- session cookie has expired; API user should resubmit userid and password
1247 sub check_api_auth {
1249 my $flagsrequired = shift;
1251 my $dbh = C4::Context->dbh;
1252 my $timeout = _timeout_syspref();
1254 unless (C4::Context->preference('Version')) {
1255 # database has not been installed yet
1256 return ("maintenance", undef, undef);
1258 my $kohaversion=C4::Context::KOHAVERSION;
1259 $kohaversion =~ s/(.*\..*)\.(.*)\.(.*)/$1$2$3/;
1260 if (C4::Context->preference('Version') < $kohaversion) {
1261 # database in need of version update; assume that
1262 # no API should be called while databsae is in
1264 return ("maintenance", undef, undef);
1267 # FIXME -- most of what follows is a copy-and-paste
1268 # of code from checkauth. There is an obvious need
1269 # for refactoring to separate the various parts of
1270 # the authentication code, but as of 2007-11-19 this
1271 # is deferred so as to not introduce bugs into the
1272 # regular authentication code for Koha 3.0.
1274 # see if we have a valid session cookie already
1275 # however, if a userid parameter is present (i.e., from
1276 # a form submission, assume that any current cookie
1278 my $sessionID = undef;
1279 unless ($query->param('userid')) {
1280 $sessionID = $query->cookie("CGISESSID");
1282 if ($sessionID && not ($cas && $query->param('PT')) ) {
1283 my $session = get_session($sessionID);
1284 C4::Context->_new_userenv($sessionID);
1286 C4::Context::set_userenv(
1287 $session->param('number'), $session->param('id'),
1288 $session->param('cardnumber'), $session->param('firstname'),
1289 $session->param('surname'), $session->param('branch'),
1290 $session->param('branchname'), $session->param('flags'),
1291 $session->param('emailaddress'), $session->param('branchprinter')
1294 my $ip = $session->param('ip');
1295 my $lasttime = $session->param('lasttime');
1296 my $userid = $session->param('id');
1297 if ( $lasttime < time() - $timeout ) {
1301 C4::Context->_unset_userenv($sessionID);
1304 return ("expired", undef, undef);
1305 } elsif ( $ip ne $ENV{'REMOTE_ADDR'} ) {
1306 # IP address changed
1309 C4::Context->_unset_userenv($sessionID);
1312 return ("expired", undef, undef);
1314 my $cookie = $query->cookie(
1315 -name => 'CGISESSID',
1316 -value => $session->id,
1319 $session->param('lasttime',time());
1320 my $flags = haspermission($userid, $flagsrequired);
1322 return ("ok", $cookie, $sessionID);
1326 C4::Context->_unset_userenv($sessionID);
1329 return ("failed", undef, undef);
1333 return ("expired", undef, undef);
1337 my $userid = $query->param('userid');
1338 my $password = $query->param('password');
1339 my ($return, $cardnumber);
1342 if ($cas && $query->param('PT')) {
1344 $debug and print STDERR "## check_api_auth - checking CAS\n";
1345 # In case of a CAS authentication, we use the ticket instead of the password
1346 my $PT = $query->param('PT');
1347 ($return,$cardnumber,$userid) = check_api_auth_cas($dbh, $PT, $query); # EXTERNAL AUTH
1349 # User / password auth
1350 unless ($userid and $password) {
1351 # caller did something wrong, fail the authenticateion
1352 return ("failed", undef, undef);
1354 ( $return, $cardnumber ) = checkpw( $dbh, $userid, $password, $query );
1357 if ($return and haspermission( $userid, $flagsrequired)) {
1358 my $session = get_session("");
1359 return ("failed", undef, undef) unless $session;
1361 my $sessionID = $session->id;
1362 C4::Context->_new_userenv($sessionID);
1363 my $cookie = $query->cookie(
1364 -name => 'CGISESSID',
1365 -value => $sessionID,
1368 if ( $return == 1 ) {
1370 $borrowernumber, $firstname, $surname,
1371 $userflags, $branchcode, $branchname,
1372 $branchprinter, $emailaddress
1376 "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=?"
1378 $sth->execute($userid);
1380 $borrowernumber, $firstname, $surname,
1381 $userflags, $branchcode, $branchname,
1382 $branchprinter, $emailaddress
1383 ) = $sth->fetchrow if ( $sth->rows );
1385 unless ($sth->rows ) {
1386 my $sth = $dbh->prepare(
1387 "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=?"
1389 $sth->execute($cardnumber);
1391 $borrowernumber, $firstname, $surname,
1392 $userflags, $branchcode, $branchname,
1393 $branchprinter, $emailaddress
1394 ) = $sth->fetchrow if ( $sth->rows );
1396 unless ( $sth->rows ) {
1397 $sth->execute($userid);
1399 $borrowernumber, $firstname, $surname, $userflags,
1400 $branchcode, $branchname, $branchprinter, $emailaddress
1401 ) = $sth->fetchrow if ( $sth->rows );
1405 my $ip = $ENV{'REMOTE_ADDR'};
1406 # if they specify at login, use that
1407 if ($query->param('branch')) {
1408 $branchcode = $query->param('branch');
1409 $branchname = GetBranchName($branchcode);
1411 my $branches = GetBranches();
1413 foreach my $br ( keys %$branches ) {
1414 # now we work with the treatment of ip
1415 my $domain = $branches->{$br}->{'branchip'};
1416 if ( $domain && $ip =~ /^$domain/ ) {
1417 $branchcode = $branches->{$br}->{'branchcode'};
1419 # new op dev : add the branchprinter and branchname in the cookie
1420 $branchprinter = $branches->{$br}->{'branchprinter'};
1421 $branchname = $branches->{$br}->{'branchname'};
1424 $session->param('number',$borrowernumber);
1425 $session->param('id',$userid);
1426 $session->param('cardnumber',$cardnumber);
1427 $session->param('firstname',$firstname);
1428 $session->param('surname',$surname);
1429 $session->param('branch',$branchcode);
1430 $session->param('branchname',$branchname);
1431 $session->param('flags',$userflags);
1432 $session->param('emailaddress',$emailaddress);
1433 $session->param('ip',$session->remote_addr());
1434 $session->param('lasttime',time());
1435 } elsif ( $return == 2 ) {
1436 #We suppose the user is the superlibrarian
1437 $session->param('number',0);
1438 $session->param('id',C4::Context->config('user'));
1439 $session->param('cardnumber',C4::Context->config('user'));
1440 $session->param('firstname',C4::Context->config('user'));
1441 $session->param('surname',C4::Context->config('user'));
1442 $session->param('branch','NO_LIBRARY_SET');
1443 $session->param('branchname','NO_LIBRARY_SET');
1444 $session->param('flags',1);
1445 $session->param('emailaddress', C4::Context->preference('KohaAdminEmailAddress'));
1446 $session->param('ip',$session->remote_addr());
1447 $session->param('lasttime',time());
1449 C4::Context::set_userenv(
1450 $session->param('number'), $session->param('id'),
1451 $session->param('cardnumber'), $session->param('firstname'),
1452 $session->param('surname'), $session->param('branch'),
1453 $session->param('branchname'), $session->param('flags'),
1454 $session->param('emailaddress'), $session->param('branchprinter')
1456 return ("ok", $cookie, $sessionID);
1458 return ("failed", undef, undef);
1463 =head2 check_cookie_auth
1465 ($status, $sessionId) = check_api_auth($cookie, $userflags);
1467 Given a CGISESSID cookie set during a previous login to Koha, determine
1468 if the user has the privileges specified by C<$userflags>.
1470 C<check_cookie_auth> is meant for authenticating special services
1471 such as tools/upload-file.pl that are invoked by other pages that
1472 have been authenticated in the usual way.
1474 Possible return values in C<$status> are:
1478 =item "ok" -- user authenticated; C<$sessionID> have valid values.
1480 =item "failed" -- credentials are not correct; C<$sessionid> are undef
1482 =item "maintenance" -- DB is in maintenance mode; no login possible at the moment
1484 =item "expired -- session cookie has expired; API user should resubmit userid and password
1490 sub check_cookie_auth {
1492 my $flagsrequired = shift;
1494 my $dbh = C4::Context->dbh;
1495 my $timeout = _timeout_syspref();
1497 unless (C4::Context->preference('Version')) {
1498 # database has not been installed yet
1499 return ("maintenance", undef);
1501 my $kohaversion=C4::Context::KOHAVERSION;
1502 $kohaversion =~ s/(.*\..*)\.(.*)\.(.*)/$1$2$3/;
1503 if (C4::Context->preference('Version') < $kohaversion) {
1504 # database in need of version update; assume that
1505 # no API should be called while databsae is in
1507 return ("maintenance", undef);
1510 # FIXME -- most of what follows is a copy-and-paste
1511 # of code from checkauth. There is an obvious need
1512 # for refactoring to separate the various parts of
1513 # the authentication code, but as of 2007-11-23 this
1514 # is deferred so as to not introduce bugs into the
1515 # regular authentication code for Koha 3.0.
1517 # see if we have a valid session cookie already
1518 # however, if a userid parameter is present (i.e., from
1519 # a form submission, assume that any current cookie
1521 unless (defined $cookie and $cookie) {
1522 return ("failed", undef);
1524 my $sessionID = $cookie;
1525 my $session = get_session($sessionID);
1526 C4::Context->_new_userenv($sessionID);
1528 C4::Context::set_userenv(
1529 $session->param('number'), $session->param('id'),
1530 $session->param('cardnumber'), $session->param('firstname'),
1531 $session->param('surname'), $session->param('branch'),
1532 $session->param('branchname'), $session->param('flags'),
1533 $session->param('emailaddress'), $session->param('branchprinter')
1536 my $ip = $session->param('ip');
1537 my $lasttime = $session->param('lasttime');
1538 my $userid = $session->param('id');
1539 if ( $lasttime < time() - $timeout ) {
1543 C4::Context->_unset_userenv($sessionID);
1546 return ("expired", undef);
1547 } elsif ( $ip ne $ENV{'REMOTE_ADDR'} ) {
1548 # IP address changed
1551 C4::Context->_unset_userenv($sessionID);
1554 return ("expired", undef);
1556 $session->param('lasttime',time());
1557 my $flags = haspermission($userid, $flagsrequired);
1559 return ("ok", $sessionID);
1563 C4::Context->_unset_userenv($sessionID);
1566 return ("failed", undef);
1570 return ("expired", undef);
1577 my $session = get_session($sessionID);
1579 Given a session ID, retrieve the CGI::Session object used to store
1580 the session's state. The session object can be used to store
1581 data that needs to be accessed by different scripts during a
1584 If the C<$sessionID> parameter is an empty string, a new session
1590 my $sessionID = shift;
1591 my $storage_method = C4::Context->preference('SessionStorage');
1592 my $dbh = C4::Context->dbh;
1594 if ($storage_method eq 'mysql'){
1595 $session = new CGI::Session("driver:MySQL;serializer:yaml;id:md5", $sessionID, {Handle=>$dbh});
1597 elsif ($storage_method eq 'Pg') {
1598 $session = new CGI::Session("driver:PostgreSQL;serializer:yaml;id:md5", $sessionID, {Handle=>$dbh});
1600 elsif ($storage_method eq 'memcached' && C4::Context->ismemcached){
1601 $session = new CGI::Session("driver:memcached;serializer:yaml;id:md5", $sessionID, { Memcached => C4::Context->memcached } );
1604 # catch all defaults to tmp should work on all systems
1605 $session = new CGI::Session("driver:File;serializer:yaml;id:md5", $sessionID, {Directory=>'/tmp'});
1611 my ( $dbh, $userid, $password, $query ) = @_;
1613 $debug and print STDERR "## checkpw - checking LDAP\n";
1614 my ($retval,$retcard,$retuserid) = checkpw_ldap(@_); # EXTERNAL AUTH
1615 return 0 if $retval == -1; # Incorrect password for LDAP login attempt
1616 ($retval) and return ($retval,$retcard,$retuserid);
1619 if ($cas && $query && $query->param('ticket')) {
1620 $debug and print STDERR "## checkpw - checking CAS\n";
1621 # In case of a CAS authentication, we use the ticket instead of the password
1622 my $ticket = $query->param('ticket');
1623 $query->delete('ticket'); # remove ticket to come back to original URL
1624 my ($retval,$retcard,$retuserid) = checkpw_cas($dbh, $ticket, $query); # EXTERNAL AUTH
1625 ($retval) and return ($retval,$retcard,$retuserid);
1629 # If we are in a shibboleth session (shibboleth is enabled, and a shibboleth match attribute is present)
1630 # Check for password to asertain whether we want to be testing against shibboleth or another method this
1632 if ($shib && $shib_login && !$password) {
1634 $debug and print STDERR "## checkpw - checking Shibboleth\n";
1635 # In case of a Shibboleth authentication, we expect a shibboleth user attribute
1636 # (defined under shibboleth mapping in koha-conf.xml) to contain the login of the
1637 # shibboleth-authenticated user
1639 # Then, we check if it matches a valid koha user
1641 my ( $retval, $retcard, $retuserid ) = C4::Auth_with_shibboleth::checkpw_shib( $shib_login ); # EXTERNAL AUTH
1642 ($retval) and return ( $retval, $retcard, $retuserid );
1648 return checkpw_internal(@_)
1651 sub checkpw_internal {
1652 my ( $dbh, $userid, $password ) = @_;
1654 $password = Encode::encode( 'UTF-8', $password )
1655 if Encode::is_utf8($password);
1657 if ( $userid && $userid eq C4::Context->config('user') ) {
1658 if ( $password && $password eq C4::Context->config('pass') ) {
1659 # Koha superuser account
1660 # C4::Context->set_userenv(0,0,C4::Context->config('user'),C4::Context->config('user'),C4::Context->config('user'),"",1);
1670 "select password,cardnumber,borrowernumber,userid,firstname,surname,branchcode,flags from borrowers where userid=?"
1672 $sth->execute($userid);
1674 my ( $stored_hash, $cardnumber, $borrowernumber, $userid, $firstname,
1675 $surname, $branchcode, $flags )
1678 if ( checkpw_hash($password, $stored_hash) ) {
1680 C4::Context->set_userenv( "$borrowernumber", $userid, $cardnumber,
1681 $firstname, $surname, $branchcode, $flags );
1682 return 1, $cardnumber, $userid;
1687 "select password,cardnumber,borrowernumber,userid, firstname,surname,branchcode,flags from borrowers where cardnumber=?"
1689 $sth->execute($userid);
1691 my ( $stored_hash, $cardnumber, $borrowernumber, $userid, $firstname,
1692 $surname, $branchcode, $flags )
1695 if ( checkpw_hash($password, $stored_hash) ) {
1697 C4::Context->set_userenv( $borrowernumber, $userid, $cardnumber,
1698 $firstname, $surname, $branchcode, $flags );
1699 return 1, $cardnumber, $userid;
1702 if ( $userid && $userid eq 'demo'
1703 && "$password" eq 'demo'
1704 && C4::Context->config('demo') )
1707 # DEMO => the demo user is allowed to do everything (if demo set to 1 in koha.conf
1708 # some features won't be effective : modify systempref, modify MARC structure,
1715 my ( $password, $stored_hash ) = @_;
1717 return if $stored_hash eq '!';
1719 # check what encryption algorithm was implemented: Bcrypt - if the hash starts with '$2' it is Bcrypt else md5
1721 if ( substr($stored_hash,0,2) eq '$2') {
1722 $hash = hash_password($password, $stored_hash);
1724 $hash = md5_base64($password);
1726 return $hash eq $stored_hash;
1731 my $authflags = getuserflags($flags, $userid, [$dbh]);
1733 Translates integer flags into permissions strings hash.
1735 C<$flags> is the integer userflags value ( borrowers.userflags )
1736 C<$userid> is the members.userid, used for building subpermissions
1737 C<$authflags> is a hashref of permissions
1744 my $dbh = @_ ? shift : C4::Context->dbh;
1747 # I don't want to do this, but if someone logs in as the database
1748 # user, it would be preferable not to spam them to death with
1749 # numeric warnings. So, we make $flags numeric.
1750 no warnings 'numeric';
1753 my $sth = $dbh->prepare("SELECT bit, flag, defaulton FROM userflags");
1756 while ( my ( $bit, $flag, $defaulton ) = $sth->fetchrow ) {
1757 if ( ( $flags & ( 2**$bit ) ) || $defaulton ) {
1758 $userflags->{$flag} = 1;
1761 $userflags->{$flag} = 0;
1764 # get subpermissions and merge with top-level permissions
1765 my $user_subperms = get_user_subpermissions($userid);
1766 foreach my $module (keys %$user_subperms) {
1767 next if $userflags->{$module} == 1; # user already has permission for everything in this module
1768 $userflags->{$module} = $user_subperms->{$module};
1774 =head2 get_user_subpermissions
1776 $user_perm_hashref = get_user_subpermissions($userid);
1778 Given the userid (note, not the borrowernumber) of a staff user,
1779 return a hashref of hashrefs of the specific subpermissions
1780 accorded to the user. An example return is
1784 export_catalog => 1,
1785 import_patrons => 1,
1789 The top-level hash-key is a module or function code from
1790 userflags.flag, while the second-level key is a code
1793 The results of this function do not give a complete picture
1794 of the functions that a staff user can access; it is also
1795 necessary to check borrowers.flags.
1799 sub get_user_subpermissions {
1802 my $dbh = C4::Context->dbh;
1803 my $sth = $dbh->prepare("SELECT flag, user_permissions.code
1804 FROM user_permissions
1805 JOIN permissions USING (module_bit, code)
1806 JOIN userflags ON (module_bit = bit)
1807 JOIN borrowers USING (borrowernumber)
1809 $sth->execute($userid);
1811 my $user_perms = {};
1812 while (my $perm = $sth->fetchrow_hashref) {
1813 $user_perms->{$perm->{'flag'}}->{$perm->{'code'}} = 1;
1818 =head2 get_all_subpermissions
1820 my $perm_hashref = get_all_subpermissions();
1822 Returns a hashref of hashrefs defining all specific
1823 permissions currently defined. The return value
1824 has the same structure as that of C<get_user_subpermissions>,
1825 except that the innermost hash value is the description
1826 of the subpermission.
1830 sub get_all_subpermissions {
1831 my $dbh = C4::Context->dbh;
1832 my $sth = $dbh->prepare("SELECT flag, code, description
1834 JOIN userflags ON (module_bit = bit)");
1838 while (my $perm = $sth->fetchrow_hashref) {
1839 $all_perms->{$perm->{'flag'}}->{$perm->{'code'}} = $perm->{'description'};
1844 =head2 haspermission
1846 $flags = ($userid, $flagsrequired);
1848 C<$userid> the userid of the member
1849 C<$flags> is a hashref of required flags like C<$borrower-<{authflags}>
1851 Returns member's flags or 0 if a permission is not met.
1856 my ($userid, $flagsrequired) = @_;
1857 my $sth = C4::Context->dbh->prepare("SELECT flags FROM borrowers WHERE userid=?");
1858 $sth->execute($userid);
1859 my $row = $sth->fetchrow();
1860 my $flags = getuserflags($row, $userid);
1861 if ( $userid eq C4::Context->config('user') ) {
1862 # Super User Account from /etc/koha.conf
1863 $flags->{'superlibrarian'} = 1;
1865 elsif ( $userid eq 'demo' && C4::Context->config('demo') ) {
1866 # Demo user that can do "anything" (demo=1 in /etc/koha.conf)
1867 $flags->{'superlibrarian'} = 1;
1870 return $flags if $flags->{superlibrarian};
1872 foreach my $module ( keys %$flagsrequired ) {
1873 my $subperm = $flagsrequired->{$module};
1874 if ($subperm eq '*') {
1875 return 0 unless ( $flags->{$module} == 1 or ref($flags->{$module}) );
1877 return 0 unless ( $flags->{$module} == 1 or
1878 ( ref($flags->{$module}) and
1879 exists $flags->{$module}->{$subperm} and
1880 $flags->{$module}->{$subperm} == 1
1886 #FIXME - This fcn should return the failed permission so a suitable error msg can be delivered.
1890 sub getborrowernumber {
1892 my $userenv = C4::Context->userenv;
1893 if ( defined( $userenv ) && ref( $userenv ) eq 'HASH' && $userenv->{number} ) {
1894 return $userenv->{number};
1896 my $dbh = C4::Context->dbh;
1897 for my $field ( 'userid', 'cardnumber' ) {
1899 $dbh->prepare("select borrowernumber from borrowers where $field=?");
1900 $sth->execute($userid);
1902 my ($bnumber) = $sth->fetchrow;
1909 END { } # module clean-up code here (global destructor)
1919 Crypt::Eksblowfish::Bcrypt(3)