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 }
44 if ( psgi_env ) { die 'psgi:exit' }
47 $VERSION = 3.07.00.049; # set version for version checking
51 @EXPORT = qw(&checkauth &get_template_and_user &haspermission &get_user_subpermissions);
52 @EXPORT_OK = qw(&check_api_auth &get_session &check_cookie_auth &checkpw &checkpw_internal &checkpw_hash
53 &get_all_subpermissions &get_user_subpermissions
55 %EXPORT_TAGS = ( EditPermissions => [qw(get_all_subpermissions get_user_subpermissions)] );
56 $ldap = C4::Context->config('useldapserver') || 0;
57 $cas = C4::Context->preference('casAuthentication');
58 $shib = C4::Context->preference('shibbolethAuthentication');
59 $caslogout = C4::Context->preference('casLogout');
60 require C4::Auth_with_cas; # no import
61 require C4::Auth_with_Shibboleth;
63 require C4::Auth_with_ldap;
64 import C4::Auth_with_ldap qw(checkpw_ldap);
67 import C4::Auth_with_Shibboleth qw(checkpw_shib logout_shib login_shib_url get_login_shib);
69 $shib_login = get_login_shib();
72 import C4::Auth_with_cas qw(check_api_auth_cas checkpw_cas login_cas logout_cas login_cas_url);
79 C4::Auth - Authenticates Koha users
89 my ($template, $borrowernumber, $cookie)
90 = get_template_and_user(
92 template_name => "opac-main.tt",
96 flagsrequired => {borrow => 1, catalogue => '*', tools => 'import_patrons' },
100 output_html_with_http_headers $query, $cookie, $template->output;
104 The main function of this module is to provide
105 authentification. However the get_template_and_user function has
106 been provided so that a users login information is passed along
107 automatically. This gets loaded into the template.
111 =head2 get_template_and_user
113 my ($template, $borrowernumber, $cookie)
114 = get_template_and_user(
116 template_name => "opac-main.tt",
119 authnotrequired => 0,
120 flagsrequired => {borrow => 1, catalogue => '*', tools => 'import_patrons' },
124 This call passes the C<query>, C<flagsrequired> and C<authnotrequired>
125 to C<&checkauth> (in this module) to perform authentification.
126 See C<&checkauth> for an explanation of these parameters.
128 The C<template_name> is then used to find the correct template for
129 the page. The authenticated users details are loaded onto the
130 template in the HTML::Template LOOP variable C<USER_INFO>. Also the
131 C<sessionID> is passed to the template. This can be used in templates
132 if cookies are disabled. It needs to be put as and input to every
135 More information on the C<gettemplate> sub can be found in the
140 sub get_template_and_user {
143 my ( $user, $cookie, $sessionID, $flags );
145 C4::Context->interface($in->{type});
147 $in->{'authnotrequired'} ||= 0;
148 my $template = C4::Templates::gettemplate(
149 $in->{'template_name'},
155 if ( $in->{'template_name'} !~m/maintenance/ ) {
156 ( $user, $cookie, $sessionID, $flags ) = checkauth(
158 $in->{'authnotrequired'},
159 $in->{'flagsrequired'},
167 # It's possible for $user to be the borrowernumber if they don't have a
168 # userid defined (and are logging in through some other method, such
169 # as SSL certs against an email address)
170 $borrowernumber = getborrowernumber($user) if defined($user);
171 if (!defined($borrowernumber) && defined($user)) {
172 my $borrower = C4::Members::GetMember(borrowernumber => $user);
174 $borrowernumber = $user;
175 # A bit of a hack, but I don't know there's a nicer way
177 $user = $borrower->{firstname} . ' ' . $borrower->{surname};
182 $template->param( loggedinusername => $user );
183 $template->param( sessionID => $sessionID );
185 my ($total, $pubshelves, $barshelves) = C4::VirtualShelves::GetSomeShelfNames($borrowernumber, 'MASTHEAD');
187 pubshelves => $total->{pubtotal},
188 pubshelvesloop => $pubshelves,
189 barshelves => $total->{bartotal},
190 barshelvesloop => $barshelves,
193 my ( $borr ) = C4::Members::GetMemberDetails( $borrowernumber );
196 $template->param( "USER_INFO" => \@bordat );
198 my $all_perms = get_all_subpermissions();
200 my @flagroots = qw(circulate catalogue parameters borrowers permissions reserveforothers borrow
201 editcatalogue updatecharges management tools editauthorities serials reports acquisition);
202 # We are going to use the $flags returned by checkauth
203 # to create the template's parameters that will indicate
204 # which menus the user can access.
205 if ( $flags && $flags->{superlibrarian}==1 ) {
206 $template->param( CAN_user_circulate => 1 );
207 $template->param( CAN_user_catalogue => 1 );
208 $template->param( CAN_user_parameters => 1 );
209 $template->param( CAN_user_borrowers => 1 );
210 $template->param( CAN_user_permissions => 1 );
211 $template->param( CAN_user_reserveforothers => 1 );
212 $template->param( CAN_user_borrow => 1 );
213 $template->param( CAN_user_editcatalogue => 1 );
214 $template->param( CAN_user_updatecharges => 1 );
215 $template->param( CAN_user_acquisition => 1 );
216 $template->param( CAN_user_management => 1 );
217 $template->param( CAN_user_tools => 1 );
218 $template->param( CAN_user_editauthorities => 1 );
219 $template->param( CAN_user_serials => 1 );
220 $template->param( CAN_user_reports => 1 );
221 $template->param( CAN_user_staffaccess => 1 );
222 $template->param( CAN_user_plugins => 1 );
223 $template->param( CAN_user_coursereserves => 1 );
224 foreach my $module (keys %$all_perms) {
225 foreach my $subperm (keys %{ $all_perms->{$module} }) {
226 $template->param( "CAN_user_${module}_${subperm}" => 1 );
232 foreach my $module (keys %$all_perms) {
233 if ( $flags->{$module} == 1) {
234 foreach my $subperm (keys %{ $all_perms->{$module} }) {
235 $template->param( "CAN_user_${module}_${subperm}" => 1 );
237 } elsif ( ref($flags->{$module}) ) {
238 foreach my $subperm (keys %{ $flags->{$module} } ) {
239 $template->param( "CAN_user_${module}_${subperm}" => 1 );
246 foreach my $module (keys %$flags) {
247 if ( $flags->{$module} == 1 or ref($flags->{$module}) ) {
248 $template->param( "CAN_user_$module" => 1 );
249 if ($module eq "parameters") {
250 $template->param( CAN_user_management => 1 );
255 # Logged-in opac search history
256 # If the requested template is an opac one and opac search history is enabled
257 if ($in->{type} eq 'opac' && C4::Context->preference('EnableOpacSearchHistory')) {
258 my $dbh = C4::Context->dbh;
259 my $query = "SELECT COUNT(*) FROM search_history WHERE userid=?";
260 my $sth = $dbh->prepare($query);
261 $sth->execute($borrowernumber);
263 # If at least one search has already been performed
264 if ($sth->fetchrow_array > 0) {
265 # We show the link in opac
266 $template->param( EnableOpacSearchHistory => 1 );
269 # And if there are searches performed when the user was not logged in,
270 # we add them to the logged-in search history
271 my @recentSearches = C4::Search::History::get_from_session({ cgi => $in->{'query'} });
272 if (@recentSearches) {
273 my $dbh = C4::Context->dbh;
275 INSERT INTO search_history(userid, sessionid, query_desc, query_cgi, type, total, time )
276 VALUES (?, ?, ?, ?, ?, ?, ?)
279 my $sth = $dbh->prepare($query);
280 $sth->execute( $borrowernumber,
281 $in->{query}->cookie("CGISESSID"),
284 $_->{type} || 'biblio',
287 ) foreach @recentSearches;
289 # clear out the search history from the session now that
290 # we've saved it to the database
291 C4::Search::History::set_to_session({ cgi => $in->{'query'}, search_history => [] });
293 } elsif ( $in->{type} eq 'intranet' and C4::Context->preference('EnableSearchHistory') ) {
294 $template->param( EnableSearchHistory => 1 );
297 else { # if this is an anonymous session, setup to display public lists...
299 $template->param( sessionID => $sessionID );
301 my ($total, $pubshelves) = C4::VirtualShelves::GetSomeShelfNames(undef, 'MASTHEAD');
303 pubshelves => $total->{pubtotal},
304 pubshelvesloop => $pubshelves,
307 # Anonymous opac search history
308 # If opac search history is enabled and at least one search has already been performed
309 if (C4::Context->preference('EnableOpacSearchHistory')) {
310 my @recentSearches = C4::Search::History::get_from_session({ cgi => $in->{'query'} });
311 if (@recentSearches) {
312 $template->param(EnableOpacSearchHistory => 1);
316 if(C4::Context->preference('dateformat')){
317 $template->param(dateformat => C4::Context->preference('dateformat'))
320 # these template parameters are set the same regardless of $in->{'type'}
322 # Set the using_https variable for templates
323 # FIXME Under Plack the CGI->https method always returns 'OFF'
324 my $https = $in->{query}->https();
325 my $using_https = (defined $https and $https ne 'OFF') ? 1 : 0;
328 "BiblioDefaultView".C4::Context->preference("BiblioDefaultView") => 1,
329 EnhancedMessagingPreferences => C4::Context->preference('EnhancedMessagingPreferences'),
330 GoogleJackets => C4::Context->preference("GoogleJackets"),
331 OpenLibraryCovers => C4::Context->preference("OpenLibraryCovers"),
332 KohaAdminEmailAddress => "" . C4::Context->preference("KohaAdminEmailAddress"),
333 LoginBranchcode => (C4::Context->userenv?C4::Context->userenv->{"branch"}:undef),
334 LoginFirstname => (C4::Context->userenv?C4::Context->userenv->{"firstname"}:"Bel"),
335 LoginSurname => C4::Context->userenv?C4::Context->userenv->{"surname"}:"Inconnu",
336 emailaddress => C4::Context->userenv?C4::Context->userenv->{"emailaddress"}:undef,
337 loggedinpersona => C4::Context->userenv?C4::Context->userenv->{"persona"}:undef,
338 TagsEnabled => C4::Context->preference("TagsEnabled"),
339 hide_marc => C4::Context->preference("hide_marc"),
340 item_level_itypes => C4::Context->preference('item-level_itypes'),
341 patronimages => C4::Context->preference("patronimages"),
342 singleBranchMode => C4::Context->preference("singleBranchMode"),
343 XSLTDetailsDisplay => C4::Context->preference("XSLTDetailsDisplay"),
344 XSLTResultsDisplay => C4::Context->preference("XSLTResultsDisplay"),
345 using_https => $using_https,
346 noItemTypeImages => C4::Context->preference("noItemTypeImages"),
347 marcflavour => C4::Context->preference("marcflavour"),
348 persona => C4::Context->preference("persona"),
350 if ( $in->{'type'} eq "intranet" ) {
352 AmazonCoverImages => C4::Context->preference("AmazonCoverImages"),
353 AutoLocation => C4::Context->preference("AutoLocation"),
354 "BiblioDefaultView".C4::Context->preference("IntranetBiblioDefaultView") => 1,
355 CalendarFirstDayOfWeek => (C4::Context->preference("CalendarFirstDayOfWeek") eq "Sunday")?0:1,
356 CircAutocompl => C4::Context->preference("CircAutocompl"),
357 FRBRizeEditions => C4::Context->preference("FRBRizeEditions"),
358 IndependentBranches => C4::Context->preference("IndependentBranches"),
359 IntranetNav => C4::Context->preference("IntranetNav"),
360 IntranetmainUserblock => C4::Context->preference("IntranetmainUserblock"),
361 LibraryName => C4::Context->preference("LibraryName"),
362 LoginBranchname => (C4::Context->userenv?C4::Context->userenv->{"branchname"}:undef),
363 advancedMARCEditor => C4::Context->preference("advancedMARCEditor"),
364 canreservefromotherbranches => C4::Context->preference('canreservefromotherbranches'),
365 intranetcolorstylesheet => C4::Context->preference("intranetcolorstylesheet"),
366 IntranetFavicon => C4::Context->preference("IntranetFavicon"),
367 intranetreadinghistory => C4::Context->preference("intranetreadinghistory"),
368 intranetstylesheet => C4::Context->preference("intranetstylesheet"),
369 IntranetUserCSS => C4::Context->preference("IntranetUserCSS"),
370 intranetuserjs => C4::Context->preference("intranetuserjs"),
371 intranetbookbag => C4::Context->preference("intranetbookbag"),
372 suggestion => C4::Context->preference("suggestion"),
373 virtualshelves => C4::Context->preference("virtualshelves"),
374 StaffSerialIssueDisplayCount => C4::Context->preference("StaffSerialIssueDisplayCount"),
375 EasyAnalyticalRecords => C4::Context->preference('EasyAnalyticalRecords'),
376 LocalCoverImages => C4::Context->preference('LocalCoverImages'),
377 OPACLocalCoverImages => C4::Context->preference('OPACLocalCoverImages'),
378 AllowMultipleCovers => C4::Context->preference('AllowMultipleCovers'),
379 EnableBorrowerFiles => C4::Context->preference('EnableBorrowerFiles'),
380 UseKohaPlugins => C4::Context->preference('UseKohaPlugins'),
381 UseCourseReserves => C4::Context->preference("UseCourseReserves"),
385 warn "template type should be OPAC, here it is=[" . $in->{'type'} . "]" unless ( $in->{'type'} eq 'opac' );
386 #TODO : replace LibraryName syspref with 'system name', and remove this html processing
387 my $LibraryNameTitle = C4::Context->preference("LibraryName");
388 $LibraryNameTitle =~ s/<(?:\/?)(?:br|p)\s*(?:\/?)>/ /sgi;
389 $LibraryNameTitle =~ s/<(?:[^<>'"]|'(?:[^']*)'|"(?:[^"]*)")*>//sg;
390 # clean up the busc param in the session if the page is not opac-detail and not the "add to list" page
391 if ( C4::Context->preference("OpacBrowseResults")
392 && $in->{'template_name'} =~ /opac-(.+)\.(?:tt|tmpl)$/ ) {
394 unless ( $pagename =~ /^(?:MARC|ISBD)?detail$/
395 or $pagename =~ /^addbybiblionumber$/ ) {
396 my $sessionSearch = get_session($sessionID || $in->{'query'}->cookie("CGISESSID"));
397 $sessionSearch->clear(["busc"]) if ($sessionSearch->param("busc"));
400 # variables passed from CGI: opac_css_override and opac_search_limits.
401 my $opac_search_limit = $ENV{'OPAC_SEARCH_LIMIT'};
402 my $opac_limit_override = $ENV{'OPAC_LIMIT_OVERRIDE'};
405 ($opac_limit_override && $opac_search_limit && $opac_search_limit =~ /branch:(\w+)/) ||
406 ($in->{'query'}->param('limit') && $in->{'query'}->param('limit') =~ /branch:(\w+)/) ||
407 ($in->{'query'}->param('multibranchlimit') && $in->{'query'}->param('multibranchlimit') =~ /multibranchlimit-(\w+)/)
409 $opac_name = $1; # opac_search_limit is a branch, so we use it.
410 } elsif ( $in->{'query'}->param('multibranchlimit') ) {
411 $opac_name = $in->{'query'}->param('multibranchlimit');
412 } elsif (C4::Context->preference("SearchMyLibraryFirst") && C4::Context->userenv && C4::Context->userenv->{'branch'}) {
413 $opac_name = C4::Context->userenv->{'branch'};
415 # FIXME Under Plack the CGI->https method always returns 'OFF' ($using_https will be set to 0 in this case)
416 my $opac_base_url = C4::Context->preference("OPACBaseURL"); #FIXME uses $using_https below as well
417 if (!$opac_base_url){
418 $opac_base_url = $ENV{'SERVER_NAME'} . ($ENV{'SERVER_PORT'} eq ($using_https ? "443" : "80") ? '' : ":$ENV{'SERVER_PORT'}");
421 opaccolorstylesheet => C4::Context->preference("opaccolorstylesheet"),
422 AnonSuggestions => "" . C4::Context->preference("AnonSuggestions"),
423 AuthorisedValueImages => C4::Context->preference("AuthorisedValueImages"),
424 BranchesLoop => GetBranchesLoop($opac_name),
425 BranchCategoriesLoop => GetBranchCategories( 'searchdomain', 1, $opac_name ),
426 CalendarFirstDayOfWeek => (C4::Context->preference("CalendarFirstDayOfWeek") eq "Sunday")?0:1,
427 LibraryName => "" . C4::Context->preference("LibraryName"),
428 LibraryNameTitle => "" . $LibraryNameTitle,
429 LoginBranchname => C4::Context->userenv?C4::Context->userenv->{"branchname"}:"",
430 OPACAmazonCoverImages => C4::Context->preference("OPACAmazonCoverImages"),
431 OPACFRBRizeEditions => C4::Context->preference("OPACFRBRizeEditions"),
432 OpacHighlightedWords => C4::Context->preference("OpacHighlightedWords"),
433 OPACItemHolds => C4::Context->preference("OPACItemHolds"),
434 OPACShelfBrowser => "". C4::Context->preference("OPACShelfBrowser"),
435 OPACURLOpenInNewWindow => "" . C4::Context->preference("OPACURLOpenInNewWindow"),
436 OPACUserCSS => "". C4::Context->preference("OPACUserCSS"),
437 OPACMobileUserCSS => "". C4::Context->preference("OPACMobileUserCSS"),
438 OPACViewOthersSuggestions => "" . C4::Context->preference("OPACViewOthersSuggestions"),
439 OpacAuthorities => C4::Context->preference("OpacAuthorities"),
440 OPACBaseURL => ($using_https ? "https://" : "http://") . $opac_base_url,
441 opac_css_override => $ENV{'OPAC_CSS_OVERRIDE'},
442 opac_search_limit => $opac_search_limit,
443 opac_limit_override => $opac_limit_override,
444 OpacBrowser => C4::Context->preference("OpacBrowser"),
445 OpacCloud => C4::Context->preference("OpacCloud"),
446 OpacKohaUrl => C4::Context->preference("OpacKohaUrl"),
447 OpacMainUserBlock => "" . C4::Context->preference("OpacMainUserBlock"),
448 OpacMainUserBlockMobile => "" . C4::Context->preference("OpacMainUserBlockMobile"),
449 OpacShowLibrariesPulldownMobile => C4::Context->preference("OpacShowLibrariesPulldownMobile"),
450 OpacNav => "" . C4::Context->preference("OpacNav"),
451 OpacNavRight => "" . C4::Context->preference("OpacNavRight"),
452 OpacNavBottom => "" . C4::Context->preference("OpacNavBottom"),
453 OpacPasswordChange => C4::Context->preference("OpacPasswordChange"),
454 OPACPatronDetails => C4::Context->preference("OPACPatronDetails"),
455 OPACPrivacy => C4::Context->preference("OPACPrivacy"),
456 OPACFinesTab => C4::Context->preference("OPACFinesTab"),
457 OpacTopissue => C4::Context->preference("OpacTopissue"),
458 RequestOnOpac => C4::Context->preference("RequestOnOpac"),
459 'Version' => C4::Context->preference('Version'),
460 hidelostitems => C4::Context->preference("hidelostitems"),
461 mylibraryfirst => (C4::Context->preference("SearchMyLibraryFirst") && C4::Context->userenv) ? C4::Context->userenv->{'branch'} : '',
462 opaclayoutstylesheet => "" . C4::Context->preference("opaclayoutstylesheet"),
463 opacbookbag => "" . C4::Context->preference("opacbookbag"),
464 opaccredits => "" . C4::Context->preference("opaccredits"),
465 OpacFavicon => C4::Context->preference("OpacFavicon"),
466 opacheader => "" . C4::Context->preference("opacheader"),
467 opaclanguagesdisplay => "" . C4::Context->preference("opaclanguagesdisplay"),
468 opacreadinghistory => C4::Context->preference("opacreadinghistory"),
469 opacuserjs => C4::Context->preference("opacuserjs"),
470 opacuserlogin => "" . C4::Context->preference("opacuserlogin"),
471 ShowReviewer => C4::Context->preference("ShowReviewer"),
472 ShowReviewerPhoto => C4::Context->preference("ShowReviewerPhoto"),
473 suggestion => "" . C4::Context->preference("suggestion"),
474 virtualshelves => "" . C4::Context->preference("virtualshelves"),
475 OPACSerialIssueDisplayCount => C4::Context->preference("OPACSerialIssueDisplayCount"),
476 OPACXSLTDetailsDisplay => C4::Context->preference("OPACXSLTDetailsDisplay"),
477 OPACXSLTResultsDisplay => C4::Context->preference("OPACXSLTResultsDisplay"),
478 SyndeticsClientCode => C4::Context->preference("SyndeticsClientCode"),
479 SyndeticsEnabled => C4::Context->preference("SyndeticsEnabled"),
480 SyndeticsCoverImages => C4::Context->preference("SyndeticsCoverImages"),
481 SyndeticsTOC => C4::Context->preference("SyndeticsTOC"),
482 SyndeticsSummary => C4::Context->preference("SyndeticsSummary"),
483 SyndeticsEditions => C4::Context->preference("SyndeticsEditions"),
484 SyndeticsExcerpt => C4::Context->preference("SyndeticsExcerpt"),
485 SyndeticsReviews => C4::Context->preference("SyndeticsReviews"),
486 SyndeticsAuthorNotes => C4::Context->preference("SyndeticsAuthorNotes"),
487 SyndeticsAwards => C4::Context->preference("SyndeticsAwards"),
488 SyndeticsSeries => C4::Context->preference("SyndeticsSeries"),
489 SyndeticsCoverImageSize => C4::Context->preference("SyndeticsCoverImageSize"),
490 OPACLocalCoverImages => C4::Context->preference("OPACLocalCoverImages"),
491 PatronSelfRegistration => C4::Context->preference("PatronSelfRegistration"),
492 PatronSelfRegistrationDefaultCategory => C4::Context->preference("PatronSelfRegistrationDefaultCategory"),
495 $template->param(OpacPublic => '1') if ($user || C4::Context->preference("OpacPublic"));
498 # Check if we were asked using parameters to force a specific language
499 if ( defined $in->{'query'}->param('language') ) {
500 # Extract the language, let C4::Languages::getlanguage choose
502 my $language = C4::Languages::getlanguage($in->{'query'});
503 my $languagecookie = C4::Templates::getlanguagecookie($in->{'query'},$language);
504 if ( ref $cookie eq 'ARRAY' ) {
505 push @{ $cookie }, $languagecookie;
507 $cookie = [$cookie, $languagecookie];
511 return ( $template, $borrowernumber, $cookie, $flags);
516 ($userid, $cookie, $sessionID) = &checkauth($query, $noauth, $flagsrequired, $type);
518 Verifies that the user is authorized to run this script. If
519 the user is authorized, a (userid, cookie, session-id, flags)
520 quadruple is returned. If the user is not authorized but does
521 not have the required privilege (see $flagsrequired below), it
522 displays an error page and exits. Otherwise, it displays the
523 login page and exits.
525 Note that C<&checkauth> will return if and only if the user
526 is authorized, so it should be called early on, before any
527 unfinished operations (e.g., if you've opened a file, then
528 C<&checkauth> won't close it for you).
530 C<$query> is the CGI object for the script calling C<&checkauth>.
532 The C<$noauth> argument is optional. If it is set, then no
533 authorization is required for the script.
535 C<&checkauth> fetches user and session information from C<$query> and
536 ensures that the user is authorized to run scripts that require
539 The C<$flagsrequired> argument specifies the required privileges
540 the user must have if the username and password are correct.
541 It should be specified as a reference-to-hash; keys in the hash
542 should be the "flags" for the user, as specified in the Members
543 intranet module. Any key specified must correspond to a "flag"
544 in the userflags table. E.g., { circulate => 1 } would specify
545 that the user must have the "circulate" privilege in order to
546 proceed. To make sure that access control is correct, the
547 C<$flagsrequired> parameter must be specified correctly.
549 Koha also has a concept of sub-permissions, also known as
550 granular permissions. This makes the value of each key
551 in the C<flagsrequired> hash take on an additional
556 The user must have access to all subfunctions of the module
557 specified by the hash key.
561 The user must have access to at least one subfunction of the module
562 specified by the hash key.
564 specific permission, e.g., 'export_catalog'
566 The user must have access to the specific subfunction list, which
567 must correspond to a row in the permissions table.
569 The C<$type> argument specifies whether the template should be
570 retrieved from the opac or intranet directory tree. "opac" is
571 assumed if it is not specified; however, if C<$type> is specified,
572 "intranet" is assumed if it is not "opac".
574 If C<$query> does not have a valid session ID associated with it
575 (i.e., the user has not logged in) or if the session has expired,
576 C<&checkauth> presents the user with a login page (from the point of
577 view of the original script, C<&checkauth> does not return). Once the
578 user has authenticated, C<&checkauth> restarts the original script
579 (this time, C<&checkauth> returns).
581 The login page is provided using a HTML::Template, which is set in the
582 systempreferences table or at the top of this file. The variable C<$type>
583 selects which template to use, either the opac or the intranet
584 authentification template.
586 C<&checkauth> returns a user ID, a cookie, and a session ID. The
587 cookie should be sent back to the browser; it verifies that the user
596 # If Version syspref is unavailable, it means Koha is beeing installed,
597 # and so we must redirect to OPAC maintenance page or to the WebInstaller
598 # also, if OpacMaintenance is ON, OPAC should redirect to maintenance
599 if (C4::Context->preference('OpacMaintenance') && $type eq 'opac') {
600 warn "OPAC Install required, redirecting to maintenance";
601 print $query->redirect("/cgi-bin/koha/maintenance.pl");
604 unless ( $version = C4::Context->preference('Version') ) { # assignment, not comparison
605 if ( $type ne 'opac' ) {
606 warn "Install required, redirecting to Installer";
607 print $query->redirect("/cgi-bin/koha/installer/install.pl");
609 warn "OPAC Install required, redirecting to maintenance";
610 print $query->redirect("/cgi-bin/koha/maintenance.pl");
615 # check that database and koha version are the same
616 # there is no DB version, it's a fresh install,
617 # go to web installer
618 # there is a DB version, compare it to the code version
619 my $kohaversion=C4::Context::KOHAVERSION;
620 # remove the 3 last . to have a Perl number
621 $kohaversion =~ s/(.*\..*)\.(.*)\.(.*)/$1$2$3/;
622 $debug and print STDERR "kohaversion : $kohaversion\n";
623 if ($version < $kohaversion){
624 my $warning = "Database update needed, redirecting to %s. Database is $version and Koha is $kohaversion";
625 if ($type ne 'opac'){
626 warn sprintf($warning, 'Installer');
627 print $query->redirect("/cgi-bin/koha/installer/install.pl?step=3");
629 warn sprintf("OPAC: " . $warning, 'maintenance');
630 print $query->redirect("/cgi-bin/koha/maintenance.pl");
638 open my $fh, '>>', "/tmp/sessionlog" or warn "ERROR: Cannot append to /tmp/sessionlog";
639 printf $fh join("\n",@_);
643 sub _timeout_syspref {
644 my $timeout = C4::Context->preference('timeout') || 600;
645 # value in days, convert in seconds
646 if ($timeout =~ /(\d+)[dD]/) {
647 $timeout = $1 * 86400;
654 $debug and warn "Checking Auth";
655 # $authnotrequired will be set for scripts which will run without authentication
656 my $authnotrequired = shift;
657 my $flagsrequired = shift;
660 $type = 'opac' unless $type;
662 my $dbh = C4::Context->dbh;
663 my $timeout = _timeout_syspref();
665 _version_check($type,$query);
669 my ( $userid, $cookie, $sessionID, $flags, $barshelves, $pubshelves );
670 my $logout = $query->param('logout.x');
672 my $anon_search_history;
674 # This parameter is the name of the CAS server we want to authenticate against,
675 # when using authentication against multiple CAS servers, as configured in Auth_cas_servers.yaml
676 my $casparam = $query->param('cas');
677 my $q_userid = $query->param('userid') // '';
679 # Basic authentication is incompatible with the use of Shibboleth,
680 # as Shibboleth may return REMOTE_USER as a Shibboleth attribute,
681 # and it may not be the attribute we want to use to match the koha login.
683 # Also, do not consider an empty REMOTE_USER.
685 # Finally, after those tests, we can assume (although if it would be better with
686 # a syspref) that if we get a REMOTE_USER, that's from basic authentication,
687 # and we can affect it to $userid.
688 if ( !$shib and $ENV{'REMOTE_USER'} ne '' and $userid = $ENV{'REMOTE_USER'} ) {
690 # Using Basic Authentication, no cookies required
691 $cookie = $query->cookie(
692 -name => 'CGISESSID',
700 # we dont want to set a session because we are being called by a persona callback
702 elsif ( $sessionID = $query->cookie("CGISESSID") )
703 { # assignment, not comparison
704 my $session = get_session($sessionID);
705 C4::Context->_new_userenv($sessionID);
706 my ($ip, $lasttime, $sessiontype);
709 $s_userid = $session->param('id') // '';
710 C4::Context::set_userenv(
711 $session->param('number'), $s_userid,
712 $session->param('cardnumber'), $session->param('firstname'),
713 $session->param('surname'), $session->param('branch'),
714 $session->param('branchname'), $session->param('flags'),
715 $session->param('emailaddress'), $session->param('branchprinter'),
716 $session->param('persona')
718 C4::Context::set_shelves_userenv('bar',$session->param('barshelves'));
719 C4::Context::set_shelves_userenv('pub',$session->param('pubshelves'));
720 C4::Context::set_shelves_userenv('tot',$session->param('totshelves'));
721 $debug and printf STDERR "AUTH_SESSION: (%s)\t%s %s - %s\n", map {$session->param($_)} qw(cardnumber firstname surname branch) ;
722 $ip = $session->param('ip');
723 $lasttime = $session->param('lasttime');
725 $sessiontype = $session->param('sessiontype') || '';
727 if ( ( $query->param('koha_login_context') && ($q_userid ne $s_userid) )
728 || ( $cas && $query->param('ticket') ) ) {
729 #if a user enters an id ne to the id in the current session, we need to log them in...
730 #first we need to clear the anonymous session...
731 $debug and warn "query id = $q_userid but session id = $s_userid";
732 $anon_search_history = $session->param('search_history');
735 C4::Context->_unset_userenv($sessionID);
740 # voluntary logout the user
743 C4::Context->_unset_userenv($sessionID);
744 #_session_log(sprintf "%20s from %16s logged out at %30s (manually).\n", $userid,$ip,(strftime "%c",localtime));
748 if ($cas and $caslogout) {
752 # If we are in a shibboleth session (shibboleth is enabled, and a shibboleth username is set)
753 if ( $shib and $shib_login and $type eq 'opac') {
754 # (Note: $type eq 'opac' condition should be removed when shibboleth authentication for intranet will be implemented)
758 elsif ( !$lasttime || ($lasttime < time() - $timeout) ) {
760 $info{'timed_out'} = 1;
765 C4::Context->_unset_userenv($sessionID);
766 #_session_log(sprintf "%20s from %16s logged out at %30s (inactivity).\n", $userid,$ip,(strftime "%c",localtime));
770 elsif ( $ip ne $ENV{'REMOTE_ADDR'} ) {
771 # Different ip than originally logged in from
772 $info{'oldip'} = $ip;
773 $info{'newip'} = $ENV{'REMOTE_ADDR'};
774 $info{'different_ip'} = 1;
777 C4::Context->_unset_userenv($sessionID);
778 #_session_log(sprintf "%20s from %16s logged out at %30s (ip changed to %16s).\n", $userid,$ip,(strftime "%c",localtime), $info{'newip'});
783 $cookie = $query->cookie(
784 -name => 'CGISESSID',
785 -value => $session->id,
788 $session->param( 'lasttime', time() );
789 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...
790 $flags = haspermission($userid, $flagsrequired);
794 $info{'nopermission'} = 1;
799 unless ($userid || $sessionID) {
801 #we initiate a session prior to checking for a username to allow for anonymous sessions...
802 my $session = get_session("") or die "Auth ERROR: Cannot get_session()";
804 # Save anonymous search history in new session so it can be retrieved
805 # by get_template_and_user to store it in user's search history after
806 # a successful login.
807 if ($anon_search_history) {
808 $session->param('search_history', $anon_search_history);
811 my $sessionID = $session->id;
812 C4::Context->_new_userenv($sessionID);
813 $cookie = $query->cookie(
814 -name => 'CGISESSID',
815 -value => $session->id,
819 my $pki_field = C4::Context->preference('AllowPKIAuth');
820 if (! defined($pki_field) ) {
821 print STDERR "ERROR: Missing system preference AllowPKIAuth.\n";
824 if ( ( $cas && $query->param('ticket') )
827 || $pki_field ne 'None'
830 my $password = $query->param('password');
832 my ( $return, $cardnumber );
833 if ($shib && $shib_login && $type eq 'opac' && !$password) {
835 ( $return, $cardnumber, $retuserid ) = checkpw( $dbh, $userid, $password, $query );
836 $userid = $retuserid;
837 $info{'invalidShibLogin'} = 1 unless ($return);
839 } elsif ( $cas && $query->param('ticket') ) {
841 ( $return, $cardnumber, $retuserid ) =
842 checkpw( $dbh, $userid, $password, $query );
843 $userid = $retuserid;
844 $info{'invalidCasLogin'} = 1 unless ($return);
848 my $value = $persona;
850 # If we're looking up the email, there's a chance that the person
851 # doesn't have a userid. So if there is none, we pass along the
852 # borrower number, and the bits of code that need to know the user
853 # ID will have to be smart enough to handle that.
855 my @users_info = C4::Members::GetBorrowersWithEmail($value);
858 # First the userid, then the borrowernum
859 $value = $users_info[0][1] || $users_info[0][0];
864 $return = $value ? 1 : 0;
869 ( $pki_field eq 'Common Name' && $ENV{'SSL_CLIENT_S_DN_CN'} )
870 || ( $pki_field eq 'emailAddress'
871 && $ENV{'SSL_CLIENT_S_DN_Email'} )
875 if ( $pki_field eq 'Common Name' ) {
876 $value = $ENV{'SSL_CLIENT_S_DN_CN'};
878 elsif ( $pki_field eq 'emailAddress' ) {
879 $value = $ENV{'SSL_CLIENT_S_DN_Email'};
881 # If we're looking up the email, there's a chance that the person
882 # doesn't have a userid. So if there is none, we pass along the
883 # borrower number, and the bits of code that need to know the user
884 # ID will have to be smart enough to handle that.
886 my @users_info = C4::Members::GetBorrowersWithEmail($value);
889 # First the userid, then the borrowernum
890 $value = $users_info[0][1] || $users_info[0][0];
897 $return = $value ? 1 : 0;
903 ( $return, $cardnumber, $retuserid ) =
904 checkpw( $dbh, $userid, $password, $query );
905 $userid = $retuserid if ( $retuserid );
908 #_session_log(sprintf "%20s from %16s logged in at %30s.\n", $userid,$ENV{'REMOTE_ADDR'},(strftime '%c', localtime));
909 if ( $flags = haspermission( $userid, $flagsrequired ) ) {
913 $info{'nopermission'} = 1;
914 C4::Context->_unset_userenv($sessionID);
916 my ($borrowernumber, $firstname, $surname, $userflags,
917 $branchcode, $branchname, $branchprinter, $emailaddress);
919 if ( $return == 1 ) {
921 SELECT borrowernumber, firstname, surname, flags, borrowers.branchcode,
922 branches.branchname as branchname,
923 branches.branchprinter as branchprinter,
926 LEFT JOIN branches on borrowers.branchcode=branches.branchcode
928 my $sth = $dbh->prepare("$select where userid=?");
929 $sth->execute($userid);
930 unless ($sth->rows) {
931 $debug and print STDERR "AUTH_1: no rows for userid='$userid'\n";
932 $sth = $dbh->prepare("$select where cardnumber=?");
933 $sth->execute($cardnumber);
935 unless ($sth->rows) {
936 $debug and print STDERR "AUTH_2a: no rows for cardnumber='$cardnumber'\n";
937 $sth->execute($userid);
938 unless ($sth->rows) {
939 $debug and print STDERR "AUTH_2b: no rows for userid='$userid' AS cardnumber\n";
944 ($borrowernumber, $firstname, $surname, $userflags,
945 $branchcode, $branchname, $branchprinter, $emailaddress) = $sth->fetchrow;
946 $debug and print STDERR "AUTH_3 results: " .
947 "$cardnumber,$borrowernumber,$userid,$firstname,$surname,$userflags,$branchcode,$emailaddress\n";
949 print STDERR "AUTH_3: no results for userid='$userid', cardnumber='$cardnumber'.\n";
952 # launch a sequence to check if we have a ip for the branch, i
953 # if we have one we replace the branchcode of the userenv by the branch bound in the ip.
955 my $ip = $ENV{'REMOTE_ADDR'};
956 # if they specify at login, use that
957 if ($query->param('branch')) {
958 $branchcode = $query->param('branch');
959 $branchname = GetBranchName($branchcode);
961 my $branches = GetBranches();
962 if (C4::Context->boolean_preference('IndependentBranches') && C4::Context->boolean_preference('Autolocation')){
963 # we have to check they are coming from the right ip range
964 my $domain = $branches->{$branchcode}->{'branchip'};
965 if ($ip !~ /^$domain/){
967 $info{'wrongip'} = 1;
972 foreach my $br ( keys %$branches ) {
973 # now we work with the treatment of ip
974 my $domain = $branches->{$br}->{'branchip'};
975 if ( $domain && $ip =~ /^$domain/ ) {
976 $branchcode = $branches->{$br}->{'branchcode'};
978 # new op dev : add the branchprinter and branchname in the cookie
979 $branchprinter = $branches->{$br}->{'branchprinter'};
980 $branchname = $branches->{$br}->{'branchname'};
983 $session->param('number',$borrowernumber);
984 $session->param('id',$userid);
985 $session->param('cardnumber',$cardnumber);
986 $session->param('firstname',$firstname);
987 $session->param('surname',$surname);
988 $session->param('branch',$branchcode);
989 $session->param('branchname',$branchname);
990 $session->param('flags',$userflags);
991 $session->param('emailaddress',$emailaddress);
992 $session->param('ip',$session->remote_addr());
993 $session->param('lasttime',time());
994 $debug and printf STDERR "AUTH_4: (%s)\t%s %s - %s\n", map {$session->param($_)} qw(cardnumber firstname surname branch) ;
996 elsif ( $return == 2 ) {
997 #We suppose the user is the superlibrarian
999 $session->param('number',0);
1000 $session->param('id',C4::Context->config('user'));
1001 $session->param('cardnumber',C4::Context->config('user'));
1002 $session->param('firstname',C4::Context->config('user'));
1003 $session->param('surname',C4::Context->config('user'));
1004 $session->param('branch','NO_LIBRARY_SET');
1005 $session->param('branchname','NO_LIBRARY_SET');
1006 $session->param('flags',1);
1007 $session->param('emailaddress', C4::Context->preference('KohaAdminEmailAddress'));
1008 $session->param('ip',$session->remote_addr());
1009 $session->param('lasttime',time());
1012 $session->param('persona',1);
1014 C4::Context::set_userenv(
1015 $session->param('number'), $session->param('id'),
1016 $session->param('cardnumber'), $session->param('firstname'),
1017 $session->param('surname'), $session->param('branch'),
1018 $session->param('branchname'), $session->param('flags'),
1019 $session->param('emailaddress'), $session->param('branchprinter'),
1020 $session->param('persona')
1026 $info{'invalid_username_or_password'} = 1;
1027 C4::Context->_unset_userenv($sessionID);
1029 $session->param('lasttime',time());
1030 $session->param('ip',$session->remote_addr());
1032 } # END if ( $userid = $query->param('userid') )
1033 elsif ($type eq "opac") {
1034 # if we are here this is an anonymous session; add public lists to it and a few other items...
1035 # anonymous sessions are created only for the OPAC
1036 $debug and warn "Initiating an anonymous session...";
1038 # setting a couple of other session vars...
1039 $session->param('ip',$session->remote_addr());
1040 $session->param('lasttime',time());
1041 $session->param('sessiontype','anon');
1043 } # END unless ($userid)
1045 # finished authentification, now respond
1046 if ( $loggedin || $authnotrequired )
1050 $cookie = $query->cookie(
1051 -name => 'CGISESSID',
1056 return ( $userid, $cookie, $sessionID, $flags );
1061 # AUTH rejected, show the login/password template, after checking the DB.
1065 # get the inputs from the incoming query
1067 foreach my $name ( param $query) {
1068 (next) if ( $name eq 'userid' || $name eq 'password' || $name eq 'ticket' );
1069 my $value = $query->param($name);
1070 push @inputs, { name => $name, value => $value };
1073 my $LibraryNameTitle = C4::Context->preference("LibraryName");
1074 $LibraryNameTitle =~ s/<(?:\/?)(?:br|p)\s*(?:\/?)>/ /sgi;
1075 $LibraryNameTitle =~ s/<(?:[^<>'"]|'(?:[^']*)'|"(?:[^"]*)")*>//sg;
1077 my $template_name = ( $type eq 'opac' ) ? 'opac-auth.tt' : 'auth.tt';
1078 my $template = C4::Templates::gettemplate($template_name, $type, $query );
1080 branchloop => GetBranchesLoop(),
1081 opaccolorstylesheet => C4::Context->preference("opaccolorstylesheet"),
1082 opaclayoutstylesheet => C4::Context->preference("opaclayoutstylesheet"),
1085 casAuthentication => C4::Context->preference("casAuthentication"),
1086 shibbolethAuthentication => C4::Context->preference("shibbolethAuthentication"),
1087 suggestion => C4::Context->preference("suggestion"),
1088 virtualshelves => C4::Context->preference("virtualshelves"),
1089 LibraryName => "" . C4::Context->preference("LibraryName"),
1090 LibraryNameTitle => "" . $LibraryNameTitle,
1091 opacuserlogin => C4::Context->preference("opacuserlogin"),
1092 OpacNav => C4::Context->preference("OpacNav"),
1093 OpacNavRight => C4::Context->preference("OpacNavRight"),
1094 OpacNavBottom => C4::Context->preference("OpacNavBottom"),
1095 opaccredits => C4::Context->preference("opaccredits"),
1096 OpacFavicon => C4::Context->preference("OpacFavicon"),
1097 opacreadinghistory => C4::Context->preference("opacreadinghistory"),
1098 opaclanguagesdisplay => C4::Context->preference("opaclanguagesdisplay"),
1099 opacuserjs => C4::Context->preference("opacuserjs"),
1100 opacbookbag => "" . C4::Context->preference("opacbookbag"),
1101 OpacCloud => C4::Context->preference("OpacCloud"),
1102 OpacTopissue => C4::Context->preference("OpacTopissue"),
1103 OpacAuthorities => C4::Context->preference("OpacAuthorities"),
1104 OpacBrowser => C4::Context->preference("OpacBrowser"),
1105 opacheader => C4::Context->preference("opacheader"),
1106 TagsEnabled => C4::Context->preference("TagsEnabled"),
1107 OPACUserCSS => C4::Context->preference("OPACUserCSS"),
1108 intranetcolorstylesheet => C4::Context->preference("intranetcolorstylesheet"),
1109 intranetstylesheet => C4::Context->preference("intranetstylesheet"),
1110 intranetbookbag => C4::Context->preference("intranetbookbag"),
1111 IntranetNav => C4::Context->preference("IntranetNav"),
1112 IntranetFavicon => C4::Context->preference("IntranetFavicon"),
1113 intranetuserjs => C4::Context->preference("intranetuserjs"),
1114 IndependentBranches=> C4::Context->preference("IndependentBranches"),
1115 AutoLocation => C4::Context->preference("AutoLocation"),
1116 wrongip => $info{'wrongip'},
1117 PatronSelfRegistration => C4::Context->preference("PatronSelfRegistration"),
1118 PatronSelfRegistrationDefaultCategory => C4::Context->preference("PatronSelfRegistrationDefaultCategory"),
1119 persona => C4::Context->preference("Persona"),
1120 opac_css_override => $ENV{'OPAC_CSS_OVERRIDE'},
1123 $template->param( OpacPublic => C4::Context->preference("OpacPublic"));
1124 $template->param( loginprompt => 1 ) unless $info{'nopermission'};
1126 if($type eq 'opac'){
1127 my ($total, $pubshelves) = C4::VirtualShelves::GetSomeShelfNames(undef, 'MASTHEAD');
1129 pubshelves => $total->{pubtotal},
1130 pubshelvesloop => $pubshelves,
1136 # Is authentication against multiple CAS servers enabled?
1137 if (C4::Auth_with_cas::multipleAuth && !$casparam) {
1138 my $casservers = C4::Auth_with_cas::getMultipleAuth();
1140 foreach my $key (keys %$casservers) {
1141 push @tmplservers, {name => $key, value => login_cas_url($query, $key) . "?cas=$key" };
1144 casServersLoop => \@tmplservers
1148 casServerUrl => login_cas_url($query),
1153 invalidCasLogin => $info{'invalidCasLogin'}
1159 shibbolethLoginUrl => login_shib_url($query),
1163 my $self_url = $query->url( -absolute => 1 );
1166 LibraryName => C4::Context->preference("LibraryName"),
1168 $template->param( %info );
1169 # $cookie = $query->cookie(CGISESSID => $session->id
1171 print $query->header(
1172 -type => 'text/html',
1173 -charset => 'utf-8',
1180 =head2 check_api_auth
1182 ($status, $cookie, $sessionId) = check_api_auth($query, $userflags);
1184 Given a CGI query containing the parameters 'userid' and 'password' and/or a session
1185 cookie, determine if the user has the privileges specified by C<$userflags>.
1187 C<check_api_auth> is is meant for authenticating users of web services, and
1188 consequently will always return and will not attempt to redirect the user
1191 If a valid session cookie is already present, check_api_auth will return a status
1192 of "ok", the cookie, and the Koha session ID.
1194 If no session cookie is present, check_api_auth will check the 'userid' and 'password
1195 parameters and create a session cookie and Koha session if the supplied credentials
1198 Possible return values in C<$status> are:
1202 =item "ok" -- user authenticated; C<$cookie> and C<$sessionid> have valid values.
1204 =item "failed" -- credentials are not correct; C<$cookie> and C<$sessionid> are undef
1206 =item "maintenance" -- DB is in maintenance mode; no login possible at the moment
1208 =item "expired -- session cookie has expired; API user should resubmit userid and password
1214 sub check_api_auth {
1216 my $flagsrequired = shift;
1218 my $dbh = C4::Context->dbh;
1219 my $timeout = _timeout_syspref();
1221 unless (C4::Context->preference('Version')) {
1222 # database has not been installed yet
1223 return ("maintenance", undef, undef);
1225 my $kohaversion=C4::Context::KOHAVERSION;
1226 $kohaversion =~ s/(.*\..*)\.(.*)\.(.*)/$1$2$3/;
1227 if (C4::Context->preference('Version') < $kohaversion) {
1228 # database in need of version update; assume that
1229 # no API should be called while databsae is in
1231 return ("maintenance", undef, undef);
1234 # FIXME -- most of what follows is a copy-and-paste
1235 # of code from checkauth. There is an obvious need
1236 # for refactoring to separate the various parts of
1237 # the authentication code, but as of 2007-11-19 this
1238 # is deferred so as to not introduce bugs into the
1239 # regular authentication code for Koha 3.0.
1241 # see if we have a valid session cookie already
1242 # however, if a userid parameter is present (i.e., from
1243 # a form submission, assume that any current cookie
1245 my $sessionID = undef;
1246 unless ($query->param('userid')) {
1247 $sessionID = $query->cookie("CGISESSID");
1249 if ($sessionID && not ($cas && $query->param('PT')) ) {
1250 my $session = get_session($sessionID);
1251 C4::Context->_new_userenv($sessionID);
1253 C4::Context::set_userenv(
1254 $session->param('number'), $session->param('id'),
1255 $session->param('cardnumber'), $session->param('firstname'),
1256 $session->param('surname'), $session->param('branch'),
1257 $session->param('branchname'), $session->param('flags'),
1258 $session->param('emailaddress'), $session->param('branchprinter')
1261 my $ip = $session->param('ip');
1262 my $lasttime = $session->param('lasttime');
1263 my $userid = $session->param('id');
1264 if ( $lasttime < time() - $timeout ) {
1268 C4::Context->_unset_userenv($sessionID);
1271 return ("expired", undef, undef);
1272 } elsif ( $ip ne $ENV{'REMOTE_ADDR'} ) {
1273 # IP address changed
1276 C4::Context->_unset_userenv($sessionID);
1279 return ("expired", undef, undef);
1281 my $cookie = $query->cookie(
1282 -name => 'CGISESSID',
1283 -value => $session->id,
1286 $session->param('lasttime',time());
1287 my $flags = haspermission($userid, $flagsrequired);
1289 return ("ok", $cookie, $sessionID);
1293 C4::Context->_unset_userenv($sessionID);
1296 return ("failed", undef, undef);
1300 return ("expired", undef, undef);
1304 my $userid = $query->param('userid');
1305 my $password = $query->param('password');
1306 my ($return, $cardnumber);
1309 if ($cas && $query->param('PT')) {
1311 $debug and print STDERR "## check_api_auth - checking CAS\n";
1312 # In case of a CAS authentication, we use the ticket instead of the password
1313 my $PT = $query->param('PT');
1314 ($return,$cardnumber,$userid) = check_api_auth_cas($dbh, $PT, $query); # EXTERNAL AUTH
1316 # User / password auth
1317 unless ($userid and $password) {
1318 # caller did something wrong, fail the authenticateion
1319 return ("failed", undef, undef);
1321 ( $return, $cardnumber ) = checkpw( $dbh, $userid, $password, $query );
1324 if ($return and haspermission( $userid, $flagsrequired)) {
1325 my $session = get_session("");
1326 return ("failed", undef, undef) unless $session;
1328 my $sessionID = $session->id;
1329 C4::Context->_new_userenv($sessionID);
1330 my $cookie = $query->cookie(
1331 -name => 'CGISESSID',
1332 -value => $sessionID,
1335 if ( $return == 1 ) {
1337 $borrowernumber, $firstname, $surname,
1338 $userflags, $branchcode, $branchname,
1339 $branchprinter, $emailaddress
1343 "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=?"
1345 $sth->execute($userid);
1347 $borrowernumber, $firstname, $surname,
1348 $userflags, $branchcode, $branchname,
1349 $branchprinter, $emailaddress
1350 ) = $sth->fetchrow if ( $sth->rows );
1352 unless ($sth->rows ) {
1353 my $sth = $dbh->prepare(
1354 "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=?"
1356 $sth->execute($cardnumber);
1358 $borrowernumber, $firstname, $surname,
1359 $userflags, $branchcode, $branchname,
1360 $branchprinter, $emailaddress
1361 ) = $sth->fetchrow if ( $sth->rows );
1363 unless ( $sth->rows ) {
1364 $sth->execute($userid);
1366 $borrowernumber, $firstname, $surname, $userflags,
1367 $branchcode, $branchname, $branchprinter, $emailaddress
1368 ) = $sth->fetchrow if ( $sth->rows );
1372 my $ip = $ENV{'REMOTE_ADDR'};
1373 # if they specify at login, use that
1374 if ($query->param('branch')) {
1375 $branchcode = $query->param('branch');
1376 $branchname = GetBranchName($branchcode);
1378 my $branches = GetBranches();
1380 foreach my $br ( keys %$branches ) {
1381 # now we work with the treatment of ip
1382 my $domain = $branches->{$br}->{'branchip'};
1383 if ( $domain && $ip =~ /^$domain/ ) {
1384 $branchcode = $branches->{$br}->{'branchcode'};
1386 # new op dev : add the branchprinter and branchname in the cookie
1387 $branchprinter = $branches->{$br}->{'branchprinter'};
1388 $branchname = $branches->{$br}->{'branchname'};
1391 $session->param('number',$borrowernumber);
1392 $session->param('id',$userid);
1393 $session->param('cardnumber',$cardnumber);
1394 $session->param('firstname',$firstname);
1395 $session->param('surname',$surname);
1396 $session->param('branch',$branchcode);
1397 $session->param('branchname',$branchname);
1398 $session->param('flags',$userflags);
1399 $session->param('emailaddress',$emailaddress);
1400 $session->param('ip',$session->remote_addr());
1401 $session->param('lasttime',time());
1402 } elsif ( $return == 2 ) {
1403 #We suppose the user is the superlibrarian
1404 $session->param('number',0);
1405 $session->param('id',C4::Context->config('user'));
1406 $session->param('cardnumber',C4::Context->config('user'));
1407 $session->param('firstname',C4::Context->config('user'));
1408 $session->param('surname',C4::Context->config('user'));
1409 $session->param('branch','NO_LIBRARY_SET');
1410 $session->param('branchname','NO_LIBRARY_SET');
1411 $session->param('flags',1);
1412 $session->param('emailaddress', C4::Context->preference('KohaAdminEmailAddress'));
1413 $session->param('ip',$session->remote_addr());
1414 $session->param('lasttime',time());
1416 C4::Context::set_userenv(
1417 $session->param('number'), $session->param('id'),
1418 $session->param('cardnumber'), $session->param('firstname'),
1419 $session->param('surname'), $session->param('branch'),
1420 $session->param('branchname'), $session->param('flags'),
1421 $session->param('emailaddress'), $session->param('branchprinter')
1423 return ("ok", $cookie, $sessionID);
1425 return ("failed", undef, undef);
1430 =head2 check_cookie_auth
1432 ($status, $sessionId) = check_api_auth($cookie, $userflags);
1434 Given a CGISESSID cookie set during a previous login to Koha, determine
1435 if the user has the privileges specified by C<$userflags>.
1437 C<check_cookie_auth> is meant for authenticating special services
1438 such as tools/upload-file.pl that are invoked by other pages that
1439 have been authenticated in the usual way.
1441 Possible return values in C<$status> are:
1445 =item "ok" -- user authenticated; C<$sessionID> have valid values.
1447 =item "failed" -- credentials are not correct; C<$sessionid> are undef
1449 =item "maintenance" -- DB is in maintenance mode; no login possible at the moment
1451 =item "expired -- session cookie has expired; API user should resubmit userid and password
1457 sub check_cookie_auth {
1459 my $flagsrequired = shift;
1461 my $dbh = C4::Context->dbh;
1462 my $timeout = _timeout_syspref();
1464 unless (C4::Context->preference('Version')) {
1465 # database has not been installed yet
1466 return ("maintenance", undef);
1468 my $kohaversion=C4::Context::KOHAVERSION;
1469 $kohaversion =~ s/(.*\..*)\.(.*)\.(.*)/$1$2$3/;
1470 if (C4::Context->preference('Version') < $kohaversion) {
1471 # database in need of version update; assume that
1472 # no API should be called while databsae is in
1474 return ("maintenance", undef);
1477 # FIXME -- most of what follows is a copy-and-paste
1478 # of code from checkauth. There is an obvious need
1479 # for refactoring to separate the various parts of
1480 # the authentication code, but as of 2007-11-23 this
1481 # is deferred so as to not introduce bugs into the
1482 # regular authentication code for Koha 3.0.
1484 # see if we have a valid session cookie already
1485 # however, if a userid parameter is present (i.e., from
1486 # a form submission, assume that any current cookie
1488 unless (defined $cookie and $cookie) {
1489 return ("failed", undef);
1491 my $sessionID = $cookie;
1492 my $session = get_session($sessionID);
1493 C4::Context->_new_userenv($sessionID);
1495 C4::Context::set_userenv(
1496 $session->param('number'), $session->param('id'),
1497 $session->param('cardnumber'), $session->param('firstname'),
1498 $session->param('surname'), $session->param('branch'),
1499 $session->param('branchname'), $session->param('flags'),
1500 $session->param('emailaddress'), $session->param('branchprinter')
1503 my $ip = $session->param('ip');
1504 my $lasttime = $session->param('lasttime');
1505 my $userid = $session->param('id');
1506 if ( $lasttime < time() - $timeout ) {
1510 C4::Context->_unset_userenv($sessionID);
1513 return ("expired", undef);
1514 } elsif ( $ip ne $ENV{'REMOTE_ADDR'} ) {
1515 # IP address changed
1518 C4::Context->_unset_userenv($sessionID);
1521 return ("expired", undef);
1523 $session->param('lasttime',time());
1524 my $flags = haspermission($userid, $flagsrequired);
1526 return ("ok", $sessionID);
1530 C4::Context->_unset_userenv($sessionID);
1533 return ("failed", undef);
1537 return ("expired", undef);
1544 my $session = get_session($sessionID);
1546 Given a session ID, retrieve the CGI::Session object used to store
1547 the session's state. The session object can be used to store
1548 data that needs to be accessed by different scripts during a
1551 If the C<$sessionID> parameter is an empty string, a new session
1557 my $sessionID = shift;
1558 my $storage_method = C4::Context->preference('SessionStorage');
1559 my $dbh = C4::Context->dbh;
1561 if ($storage_method eq 'mysql'){
1562 $session = new CGI::Session("driver:MySQL;serializer:yaml;id:md5", $sessionID, {Handle=>$dbh});
1564 elsif ($storage_method eq 'Pg') {
1565 $session = new CGI::Session("driver:PostgreSQL;serializer:yaml;id:md5", $sessionID, {Handle=>$dbh});
1567 elsif ($storage_method eq 'memcached' && C4::Context->ismemcached){
1568 $session = new CGI::Session("driver:memcached;serializer:yaml;id:md5", $sessionID, { Memcached => C4::Context->memcached } );
1571 # catch all defaults to tmp should work on all systems
1572 $session = new CGI::Session("driver:File;serializer:yaml;id:md5", $sessionID, {Directory=>'/tmp'});
1578 my ( $dbh, $userid, $password, $query ) = @_;
1581 $debug and print STDERR "## checkpw - checking LDAP\n";
1582 my ($retval,$retcard,$retuserid) = checkpw_ldap(@_); # EXTERNAL AUTH
1583 return 0 if $retval == -1; # Incorrect password for LDAP login attempt
1584 ($retval) and return ($retval,$retcard,$retuserid);
1587 if ($cas && $query && $query->param('ticket')) {
1588 $debug and print STDERR "## checkpw - checking CAS\n";
1589 # In case of a CAS authentication, we use the ticket instead of the password
1590 my $ticket = $query->param('ticket');
1591 $query->delete('ticket'); # remove ticket to come back to original URL
1592 my ($retval,$retcard,$retuserid) = checkpw_cas($dbh, $ticket, $query); # EXTERNAL AUTH
1593 ($retval) and return ($retval,$retcard,$retuserid);
1597 # If we are in a shibboleth session (shibboleth is enabled and no password has been provided)
1598 if ($shib && !$password) {
1600 $debug and print STDERR "## checkpw - checking Shibboleth\n";
1601 # In case of a Shibboleth authentication, we expect a shibboleth user attribute
1602 # (defined in the shibbolethLoginAttribute) tto contain the login of the
1603 # shibboleth-authenticated user
1605 # Shibboleth attributes are mapped into http environmement variables,
1606 # so we're getting the login of the user this way
1607 my $attributename = C4::Context->preference('shibbolethLoginAttribute');
1608 my $attributevalue = $ENV{$attributename};
1610 # Then, we check if it matches a valid koha user
1612 my ( $retval, $retcard, $retuserid ) = C4::Auth_with_Shibboleth::checkpw_shib( $dbh, $shib_login ); # EXTERNAL AUTH
1613 ($retval) and return ( $retval, $retcard, $retuserid );
1619 return checkpw_internal(@_)
1622 sub checkpw_internal {
1623 my ( $dbh, $userid, $password ) = @_;
1625 if ( $userid && $userid eq C4::Context->config('user') ) {
1626 if ( $password && $password eq C4::Context->config('pass') ) {
1627 # Koha superuser account
1628 # C4::Context->set_userenv(0,0,C4::Context->config('user'),C4::Context->config('user'),C4::Context->config('user'),"",1);
1638 "select password,cardnumber,borrowernumber,userid,firstname,surname,branchcode,flags from borrowers where userid=?"
1640 $sth->execute($userid);
1642 my ( $stored_hash, $cardnumber, $borrowernumber, $userid, $firstname,
1643 $surname, $branchcode, $flags )
1646 if ( checkpw_hash($password, $stored_hash) ) {
1648 C4::Context->set_userenv( "$borrowernumber", $userid, $cardnumber,
1649 $firstname, $surname, $branchcode, $flags );
1650 return 1, $cardnumber, $userid;
1655 "select password,cardnumber,borrowernumber,userid, firstname,surname,branchcode,flags from borrowers where cardnumber=?"
1657 $sth->execute($userid);
1659 my ( $stored_hash, $cardnumber, $borrowernumber, $userid, $firstname,
1660 $surname, $branchcode, $flags )
1663 if ( checkpw_hash($password, $stored_hash) ) {
1665 C4::Context->set_userenv( $borrowernumber, $userid, $cardnumber,
1666 $firstname, $surname, $branchcode, $flags );
1667 return 1, $cardnumber, $userid;
1670 if ( $userid && $userid eq 'demo'
1671 && "$password" eq 'demo'
1672 && C4::Context->config('demo') )
1675 # DEMO => the demo user is allowed to do everything (if demo set to 1 in koha.conf
1676 # some features won't be effective : modify systempref, modify MARC structure,
1683 my ( $password, $stored_hash ) = @_;
1685 return if $stored_hash eq '!';
1687 # check what encryption algorithm was implemented: Bcrypt - if the hash starts with '$2' it is Bcrypt else md5
1689 if ( substr($stored_hash,0,2) eq '$2') {
1690 $hash = hash_password($password, $stored_hash);
1692 $hash = md5_base64($password);
1694 return $hash eq $stored_hash;
1699 my $authflags = getuserflags($flags, $userid, [$dbh]);
1701 Translates integer flags into permissions strings hash.
1703 C<$flags> is the integer userflags value ( borrowers.userflags )
1704 C<$userid> is the members.userid, used for building subpermissions
1705 C<$authflags> is a hashref of permissions
1712 my $dbh = @_ ? shift : C4::Context->dbh;
1715 # I don't want to do this, but if someone logs in as the database
1716 # user, it would be preferable not to spam them to death with
1717 # numeric warnings. So, we make $flags numeric.
1718 no warnings 'numeric';
1721 my $sth = $dbh->prepare("SELECT bit, flag, defaulton FROM userflags");
1724 while ( my ( $bit, $flag, $defaulton ) = $sth->fetchrow ) {
1725 if ( ( $flags & ( 2**$bit ) ) || $defaulton ) {
1726 $userflags->{$flag} = 1;
1729 $userflags->{$flag} = 0;
1732 # get subpermissions and merge with top-level permissions
1733 my $user_subperms = get_user_subpermissions($userid);
1734 foreach my $module (keys %$user_subperms) {
1735 next if $userflags->{$module} == 1; # user already has permission for everything in this module
1736 $userflags->{$module} = $user_subperms->{$module};
1742 =head2 get_user_subpermissions
1744 $user_perm_hashref = get_user_subpermissions($userid);
1746 Given the userid (note, not the borrowernumber) of a staff user,
1747 return a hashref of hashrefs of the specific subpermissions
1748 accorded to the user. An example return is
1752 export_catalog => 1,
1753 import_patrons => 1,
1757 The top-level hash-key is a module or function code from
1758 userflags.flag, while the second-level key is a code
1761 The results of this function do not give a complete picture
1762 of the functions that a staff user can access; it is also
1763 necessary to check borrowers.flags.
1767 sub get_user_subpermissions {
1770 my $dbh = C4::Context->dbh;
1771 my $sth = $dbh->prepare("SELECT flag, user_permissions.code
1772 FROM user_permissions
1773 JOIN permissions USING (module_bit, code)
1774 JOIN userflags ON (module_bit = bit)
1775 JOIN borrowers USING (borrowernumber)
1777 $sth->execute($userid);
1779 my $user_perms = {};
1780 while (my $perm = $sth->fetchrow_hashref) {
1781 $user_perms->{$perm->{'flag'}}->{$perm->{'code'}} = 1;
1786 =head2 get_all_subpermissions
1788 my $perm_hashref = get_all_subpermissions();
1790 Returns a hashref of hashrefs defining all specific
1791 permissions currently defined. The return value
1792 has the same structure as that of C<get_user_subpermissions>,
1793 except that the innermost hash value is the description
1794 of the subpermission.
1798 sub get_all_subpermissions {
1799 my $dbh = C4::Context->dbh;
1800 my $sth = $dbh->prepare("SELECT flag, code, description
1802 JOIN userflags ON (module_bit = bit)");
1806 while (my $perm = $sth->fetchrow_hashref) {
1807 $all_perms->{$perm->{'flag'}}->{$perm->{'code'}} = $perm->{'description'};
1812 =head2 haspermission
1814 $flags = ($userid, $flagsrequired);
1816 C<$userid> the userid of the member
1817 C<$flags> is a hashref of required flags like C<$borrower-<{authflags}>
1819 Returns member's flags or 0 if a permission is not met.
1824 my ($userid, $flagsrequired) = @_;
1825 my $sth = C4::Context->dbh->prepare("SELECT flags FROM borrowers WHERE userid=?");
1826 $sth->execute($userid);
1827 my $row = $sth->fetchrow();
1828 my $flags = getuserflags($row, $userid);
1829 if ( $userid eq C4::Context->config('user') ) {
1830 # Super User Account from /etc/koha.conf
1831 $flags->{'superlibrarian'} = 1;
1833 elsif ( $userid eq 'demo' && C4::Context->config('demo') ) {
1834 # Demo user that can do "anything" (demo=1 in /etc/koha.conf)
1835 $flags->{'superlibrarian'} = 1;
1838 return $flags if $flags->{superlibrarian};
1840 foreach my $module ( keys %$flagsrequired ) {
1841 my $subperm = $flagsrequired->{$module};
1842 if ($subperm eq '*') {
1843 return 0 unless ( $flags->{$module} == 1 or ref($flags->{$module}) );
1845 return 0 unless ( $flags->{$module} == 1 or
1846 ( ref($flags->{$module}) and
1847 exists $flags->{$module}->{$subperm} and
1848 $flags->{$module}->{$subperm} == 1
1854 #FIXME - This fcn should return the failed permission so a suitable error msg can be delivered.
1858 sub getborrowernumber {
1860 my $userenv = C4::Context->userenv;
1861 if ( defined( $userenv ) && ref( $userenv ) eq 'HASH' && $userenv->{number} ) {
1862 return $userenv->{number};
1864 my $dbh = C4::Context->dbh;
1865 for my $field ( 'userid', 'cardnumber' ) {
1867 $dbh->prepare("select borrowernumber from borrowers where $field=?");
1868 $sth->execute($userid);
1870 my ($bnumber) = $sth->fetchrow;
1877 END { } # module clean-up code here (global destructor)
1887 Crypt::Eksblowfish::Bcrypt(3)