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);
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 $caslogout = C4::Context->preference('casLogout');
59 require C4::Auth_with_cas; # no import
61 require C4::Auth_with_ldap;
62 import C4::Auth_with_ldap qw(checkpw_ldap);
65 import C4::Auth_with_cas qw(check_api_auth_cas checkpw_cas login_cas logout_cas login_cas_url);
72 C4::Auth - Authenticates Koha users
82 my ($template, $borrowernumber, $cookie)
83 = get_template_and_user(
85 template_name => "opac-main.tmpl",
89 flagsrequired => {borrow => 1, catalogue => '*', tools => 'import_patrons' },
93 output_html_with_http_headers $query, $cookie, $template->output;
97 The main function of this module is to provide
98 authentification. However the get_template_and_user function has
99 been provided so that a users login information is passed along
100 automatically. This gets loaded into the template.
104 =head2 get_template_and_user
106 my ($template, $borrowernumber, $cookie)
107 = get_template_and_user(
109 template_name => "opac-main.tmpl",
112 authnotrequired => 0,
113 flagsrequired => {borrow => 1, catalogue => '*', tools => 'import_patrons' },
117 This call passes the C<query>, C<flagsrequired> and C<authnotrequired>
118 to C<&checkauth> (in this module) to perform authentification.
119 See C<&checkauth> for an explanation of these parameters.
121 The C<template_name> is then used to find the correct template for
122 the page. The authenticated users details are loaded onto the
123 template in the HTML::Template LOOP variable C<USER_INFO>. Also the
124 C<sessionID> is passed to the template. This can be used in templates
125 if cookies are disabled. It needs to be put as and input to every
128 More information on the C<gettemplate> sub can be found in the
133 sub get_template_and_user {
136 my ( $user, $cookie, $sessionID, $flags );
138 C4::Context->interface($in->{type});
140 # Sanitize template path to avoid path traversal
141 $in->{template_name} =~ s|^/||;
142 $in->{template_name} =~ s|\.\.||g;
144 $in->{'authnotrequired'} ||= 0;
145 my $template = C4::Templates::gettemplate(
146 $in->{'template_name'},
152 if ( $in->{'template_name'} !~m/maintenance/ ) {
153 ( $user, $cookie, $sessionID, $flags ) = checkauth(
155 $in->{'authnotrequired'},
156 $in->{'flagsrequired'},
164 # It's possible for $user to be the borrowernumber if they don't have a
165 # userid defined (and are logging in through some other method, such
166 # as SSL certs against an email address)
167 $borrowernumber = getborrowernumber($user) if defined($user);
168 if (!defined($borrowernumber) && defined($user)) {
169 my $borrower = C4::Members::GetMember(borrowernumber => $user);
171 $borrowernumber = $user;
172 # A bit of a hack, but I don't know there's a nicer way
174 $user = $borrower->{firstname} . ' ' . $borrower->{surname};
179 $template->param( loggedinusername => $user );
180 $template->param( sessionID => $sessionID );
182 my ($total, $pubshelves, $barshelves) = C4::VirtualShelves::GetSomeShelfNames($borrowernumber, 'MASTHEAD');
184 pubshelves => $total->{pubtotal},
185 pubshelvesloop => $pubshelves,
186 barshelves => $total->{bartotal},
187 barshelvesloop => $barshelves,
190 my ( $borr ) = C4::Members::GetMemberDetails( $borrowernumber );
193 $template->param( "USER_INFO" => \@bordat );
195 my $all_perms = get_all_subpermissions();
197 my @flagroots = qw(circulate catalogue parameters borrowers permissions reserveforothers borrow
198 editcatalogue updatecharges management tools editauthorities serials reports acquisition);
199 # We are going to use the $flags returned by checkauth
200 # to create the template's parameters that will indicate
201 # which menus the user can access.
202 if ( $flags && $flags->{superlibrarian}==1 ) {
203 $template->param( CAN_user_circulate => 1 );
204 $template->param( CAN_user_catalogue => 1 );
205 $template->param( CAN_user_parameters => 1 );
206 $template->param( CAN_user_borrowers => 1 );
207 $template->param( CAN_user_permissions => 1 );
208 $template->param( CAN_user_reserveforothers => 1 );
209 $template->param( CAN_user_borrow => 1 );
210 $template->param( CAN_user_editcatalogue => 1 );
211 $template->param( CAN_user_updatecharges => 1 );
212 $template->param( CAN_user_acquisition => 1 );
213 $template->param( CAN_user_management => 1 );
214 $template->param( CAN_user_tools => 1 );
215 $template->param( CAN_user_editauthorities => 1 );
216 $template->param( CAN_user_serials => 1 );
217 $template->param( CAN_user_reports => 1 );
218 $template->param( CAN_user_staffaccess => 1 );
219 $template->param( CAN_user_plugins => 1 );
220 $template->param( CAN_user_coursereserves => 1 );
221 foreach my $module (keys %$all_perms) {
222 foreach my $subperm (keys %{ $all_perms->{$module} }) {
223 $template->param( "CAN_user_${module}_${subperm}" => 1 );
229 foreach my $module (keys %$all_perms) {
230 if ( $flags->{$module} == 1) {
231 foreach my $subperm (keys %{ $all_perms->{$module} }) {
232 $template->param( "CAN_user_${module}_${subperm}" => 1 );
234 } elsif ( ref($flags->{$module}) ) {
235 foreach my $subperm (keys %{ $flags->{$module} } ) {
236 $template->param( "CAN_user_${module}_${subperm}" => 1 );
243 foreach my $module (keys %$flags) {
244 if ( $flags->{$module} == 1 or ref($flags->{$module}) ) {
245 $template->param( "CAN_user_$module" => 1 );
246 if ($module eq "parameters") {
247 $template->param( CAN_user_management => 1 );
252 # Logged-in opac search history
253 # If the requested template is an opac one and opac search history is enabled
254 if ($in->{type} eq 'opac' && C4::Context->preference('EnableOpacSearchHistory')) {
255 my $dbh = C4::Context->dbh;
256 my $query = "SELECT COUNT(*) FROM search_history WHERE userid=?";
257 my $sth = $dbh->prepare($query);
258 $sth->execute($borrowernumber);
260 # If at least one search has already been performed
261 if ($sth->fetchrow_array > 0) {
262 # We show the link in opac
263 $template->param( EnableOpacSearchHistory => 1 );
266 # And if there are searches performed when the user was not logged in,
267 # we add them to the logged-in search history
268 my @recentSearches = C4::Search::History::get_from_session({ cgi => $in->{'query'} });
269 if (@recentSearches) {
270 my $dbh = C4::Context->dbh;
272 INSERT INTO search_history(userid, sessionid, query_desc, query_cgi, type, total, time )
273 VALUES (?, ?, ?, ?, ?, ?, ?)
276 my $sth = $dbh->prepare($query);
277 $sth->execute( $borrowernumber,
278 $in->{query}->cookie("CGISESSID"),
281 $_->{type} || 'biblio',
284 ) foreach @recentSearches;
286 # clear out the search history from the session now that
287 # we've saved it to the database
288 C4::Search::History::set_to_session({ cgi => $in->{'query'}, search_history => [] });
290 } elsif ( $in->{type} eq 'intranet' and C4::Context->preference('EnableSearchHistory') ) {
291 $template->param( EnableSearchHistory => 1 );
294 else { # if this is an anonymous session, setup to display public lists...
296 $template->param( sessionID => $sessionID );
298 my ($total, $pubshelves) = C4::VirtualShelves::GetSomeShelfNames(undef, 'MASTHEAD');
300 pubshelves => $total->{pubtotal},
301 pubshelvesloop => $pubshelves,
304 # Anonymous opac search history
305 # If opac search history is enabled and at least one search has already been performed
306 if (C4::Context->preference('EnableOpacSearchHistory')) {
307 my @recentSearches = C4::Search::History::get_from_session({ cgi => $in->{'query'} });
308 if (@recentSearches) {
309 $template->param(EnableOpacSearchHistory => 1);
313 if ( C4::Context->preference('dateformat') ) {
314 $template->param( dateformat => C4::Context->preference('dateformat') );
317 # these template parameters are set the same regardless of $in->{'type'}
319 # Set the using_https variable for templates
320 # FIXME Under Plack the CGI->https method always returns 'OFF'
321 my $https = $in->{query}->https();
322 my $using_https = (defined $https and $https ne 'OFF') ? 1 : 0;
325 "BiblioDefaultView".C4::Context->preference("BiblioDefaultView") => 1,
326 EnhancedMessagingPreferences => C4::Context->preference('EnhancedMessagingPreferences'),
327 GoogleJackets => C4::Context->preference("GoogleJackets"),
328 OpenLibraryCovers => C4::Context->preference("OpenLibraryCovers"),
329 KohaAdminEmailAddress => "" . C4::Context->preference("KohaAdminEmailAddress"),
330 LoginBranchcode => (C4::Context->userenv?C4::Context->userenv->{"branch"}:undef),
331 LoginFirstname => (C4::Context->userenv?C4::Context->userenv->{"firstname"}:"Bel"),
332 LoginSurname => C4::Context->userenv?C4::Context->userenv->{"surname"}:"Inconnu",
333 emailaddress => C4::Context->userenv?C4::Context->userenv->{"emailaddress"}:undef,
334 loggedinpersona => C4::Context->userenv?C4::Context->userenv->{"persona"}:undef,
335 TagsEnabled => C4::Context->preference("TagsEnabled"),
336 hide_marc => C4::Context->preference("hide_marc"),
337 item_level_itypes => C4::Context->preference('item-level_itypes'),
338 patronimages => C4::Context->preference("patronimages"),
339 singleBranchMode => C4::Context->preference("singleBranchMode"),
340 XSLTDetailsDisplay => C4::Context->preference("XSLTDetailsDisplay"),
341 XSLTResultsDisplay => C4::Context->preference("XSLTResultsDisplay"),
342 using_https => $using_https,
343 noItemTypeImages => C4::Context->preference("noItemTypeImages"),
344 marcflavour => C4::Context->preference("marcflavour"),
345 persona => C4::Context->preference("persona"),
347 if ( $in->{'type'} eq "intranet" ) {
349 AmazonCoverImages => C4::Context->preference("AmazonCoverImages"),
350 AutoLocation => C4::Context->preference("AutoLocation"),
351 "BiblioDefaultView".C4::Context->preference("IntranetBiblioDefaultView") => 1,
352 CalendarFirstDayOfWeek => (C4::Context->preference("CalendarFirstDayOfWeek") eq "Sunday")?0:1,
353 CircAutocompl => C4::Context->preference("CircAutocompl"),
354 FRBRizeEditions => C4::Context->preference("FRBRizeEditions"),
355 IndependentBranches => C4::Context->preference("IndependentBranches"),
356 IntranetNav => C4::Context->preference("IntranetNav"),
357 IntranetmainUserblock => C4::Context->preference("IntranetmainUserblock"),
358 LibraryName => C4::Context->preference("LibraryName"),
359 LoginBranchname => (C4::Context->userenv?C4::Context->userenv->{"branchname"}:undef),
360 advancedMARCEditor => C4::Context->preference("advancedMARCEditor"),
361 canreservefromotherbranches => C4::Context->preference('canreservefromotherbranches'),
362 intranetcolorstylesheet => C4::Context->preference("intranetcolorstylesheet"),
363 IntranetFavicon => C4::Context->preference("IntranetFavicon"),
364 intranetreadinghistory => C4::Context->preference("intranetreadinghistory"),
365 intranetstylesheet => C4::Context->preference("intranetstylesheet"),
366 IntranetUserCSS => C4::Context->preference("IntranetUserCSS"),
367 intranetuserjs => C4::Context->preference("intranetuserjs"),
368 intranetbookbag => C4::Context->preference("intranetbookbag"),
369 suggestion => C4::Context->preference("suggestion"),
370 virtualshelves => C4::Context->preference("virtualshelves"),
371 StaffSerialIssueDisplayCount => C4::Context->preference("StaffSerialIssueDisplayCount"),
372 EasyAnalyticalRecords => C4::Context->preference('EasyAnalyticalRecords'),
373 LocalCoverImages => C4::Context->preference('LocalCoverImages'),
374 OPACLocalCoverImages => C4::Context->preference('OPACLocalCoverImages'),
375 AllowMultipleCovers => C4::Context->preference('AllowMultipleCovers'),
376 EnableBorrowerFiles => C4::Context->preference('EnableBorrowerFiles'),
377 UseKohaPlugins => C4::Context->preference('UseKohaPlugins'),
378 UseCourseReserves => C4::Context->preference("UseCourseReserves"),
382 warn "template type should be OPAC, here it is=[" . $in->{'type'} . "]" unless ( $in->{'type'} eq 'opac' );
383 #TODO : replace LibraryName syspref with 'system name', and remove this html processing
384 my $LibraryNameTitle = C4::Context->preference("LibraryName");
385 $LibraryNameTitle =~ s/<(?:\/?)(?:br|p)\s*(?:\/?)>/ /sgi;
386 $LibraryNameTitle =~ s/<(?:[^<>'"]|'(?:[^']*)'|"(?:[^"]*)")*>//sg;
387 # clean up the busc param in the session if the page is not opac-detail and not the "add to list" page
388 if ( C4::Context->preference("OpacBrowseResults")
389 && $in->{'template_name'} =~ /opac-(.+)\.(?:tt|tmpl)$/ ) {
391 unless ( $pagename =~ /^(?:MARC|ISBD)?detail$/
392 or $pagename =~ /^addbybiblionumber$/ ) {
393 my $sessionSearch = get_session($sessionID || $in->{'query'}->cookie("CGISESSID"));
394 $sessionSearch->clear(["busc"]) if ($sessionSearch->param("busc"));
397 # variables passed from CGI: opac_css_override and opac_search_limits.
398 my $opac_search_limit = $ENV{'OPAC_SEARCH_LIMIT'};
399 my $opac_limit_override = $ENV{'OPAC_LIMIT_OVERRIDE'};
402 ($opac_limit_override && $opac_search_limit && $opac_search_limit =~ /branch:(\w+)/) ||
403 ($in->{'query'}->param('limit') && $in->{'query'}->param('limit') =~ /branch:(\w+)/) ||
404 ($in->{'query'}->param('multibranchlimit') && $in->{'query'}->param('multibranchlimit') =~ /multibranchlimit-(\w+)/)
406 $opac_name = $1; # opac_search_limit is a branch, so we use it.
407 } elsif ( $in->{'query'}->param('multibranchlimit') ) {
408 $opac_name = $in->{'query'}->param('multibranchlimit');
409 } elsif (C4::Context->preference("SearchMyLibraryFirst") && C4::Context->userenv && C4::Context->userenv->{'branch'}) {
410 $opac_name = C4::Context->userenv->{'branch'};
413 opaccolorstylesheet => C4::Context->preference("opaccolorstylesheet"),
414 AnonSuggestions => "" . C4::Context->preference("AnonSuggestions"),
415 AuthorisedValueImages => C4::Context->preference("AuthorisedValueImages"),
416 BranchesLoop => GetBranchesLoop($opac_name),
417 BranchCategoriesLoop => GetBranchCategories( 'searchdomain', 1, $opac_name ),
418 CalendarFirstDayOfWeek => (C4::Context->preference("CalendarFirstDayOfWeek") eq "Sunday")?0:1,
419 LibraryName => "" . C4::Context->preference("LibraryName"),
420 LibraryNameTitle => "" . $LibraryNameTitle,
421 LoginBranchname => C4::Context->userenv?C4::Context->userenv->{"branchname"}:"",
422 OPACAmazonCoverImages => C4::Context->preference("OPACAmazonCoverImages"),
423 OPACFRBRizeEditions => C4::Context->preference("OPACFRBRizeEditions"),
424 OpacHighlightedWords => C4::Context->preference("OpacHighlightedWords"),
425 OPACItemHolds => C4::Context->preference("OPACItemHolds"),
426 OPACShelfBrowser => "". C4::Context->preference("OPACShelfBrowser"),
427 OPACURLOpenInNewWindow => "" . C4::Context->preference("OPACURLOpenInNewWindow"),
428 OPACUserCSS => "". C4::Context->preference("OPACUserCSS"),
429 OPACMobileUserCSS => "". C4::Context->preference("OPACMobileUserCSS"),
430 OPACViewOthersSuggestions => "" . C4::Context->preference("OPACViewOthersSuggestions"),
431 OpacAuthorities => C4::Context->preference("OpacAuthorities"),
432 OPACBaseURL => ($in->{'query'}->https() ? "https://" : "http://") . $ENV{'SERVER_NAME'} .
433 ($ENV{'SERVER_PORT'} eq ($in->{'query'}->https() ? "443" : "80") ? '' : ":$ENV{'SERVER_PORT'}"),
434 opac_css_override => $ENV{'OPAC_CSS_OVERRIDE'},
435 opac_search_limit => $opac_search_limit,
436 opac_limit_override => $opac_limit_override,
437 OpacBrowser => C4::Context->preference("OpacBrowser"),
438 OpacCloud => C4::Context->preference("OpacCloud"),
439 OpacKohaUrl => C4::Context->preference("OpacKohaUrl"),
440 OpacMainUserBlock => "" . C4::Context->preference("OpacMainUserBlock"),
441 OpacMainUserBlockMobile => "" . C4::Context->preference("OpacMainUserBlockMobile"),
442 OpacShowFiltersPulldownMobile => C4::Context->preference("OpacShowFiltersPulldownMobile"),
443 OpacShowLibrariesPulldownMobile => C4::Context->preference("OpacShowLibrariesPulldownMobile"),
444 OpacNav => "" . C4::Context->preference("OpacNav"),
445 OpacNavRight => "" . C4::Context->preference("OpacNavRight"),
446 OpacNavBottom => "" . C4::Context->preference("OpacNavBottom"),
447 OpacPasswordChange => C4::Context->preference("OpacPasswordChange"),
448 OPACPatronDetails => C4::Context->preference("OPACPatronDetails"),
449 OPACPrivacy => C4::Context->preference("OPACPrivacy"),
450 OPACFinesTab => C4::Context->preference("OPACFinesTab"),
451 OpacTopissue => C4::Context->preference("OpacTopissue"),
452 RequestOnOpac => C4::Context->preference("RequestOnOpac"),
453 'Version' => C4::Context->preference('Version'),
454 hidelostitems => C4::Context->preference("hidelostitems"),
455 mylibraryfirst => (C4::Context->preference("SearchMyLibraryFirst") && C4::Context->userenv) ? C4::Context->userenv->{'branch'} : '',
456 opaclayoutstylesheet => "" . C4::Context->preference("opaclayoutstylesheet"),
457 opacbookbag => "" . C4::Context->preference("opacbookbag"),
458 opaccredits => "" . C4::Context->preference("opaccredits"),
459 OpacFavicon => C4::Context->preference("OpacFavicon"),
460 opacheader => "" . C4::Context->preference("opacheader"),
461 opaclanguagesdisplay => "" . C4::Context->preference("opaclanguagesdisplay"),
462 opacreadinghistory => C4::Context->preference("opacreadinghistory"),
463 opacsmallimage => "" . C4::Context->preference("opacsmallimage"),
464 opacuserjs => C4::Context->preference("opacuserjs"),
465 opacuserlogin => "" . C4::Context->preference("opacuserlogin"),
466 ShowReviewer => C4::Context->preference("ShowReviewer"),
467 ShowReviewerPhoto => C4::Context->preference("ShowReviewerPhoto"),
468 suggestion => "" . C4::Context->preference("suggestion"),
469 virtualshelves => "" . C4::Context->preference("virtualshelves"),
470 OPACSerialIssueDisplayCount => C4::Context->preference("OPACSerialIssueDisplayCount"),
471 OPACXSLTDetailsDisplay => C4::Context->preference("OPACXSLTDetailsDisplay"),
472 OPACXSLTResultsDisplay => C4::Context->preference("OPACXSLTResultsDisplay"),
473 SyndeticsClientCode => C4::Context->preference("SyndeticsClientCode"),
474 SyndeticsEnabled => C4::Context->preference("SyndeticsEnabled"),
475 SyndeticsCoverImages => C4::Context->preference("SyndeticsCoverImages"),
476 SyndeticsTOC => C4::Context->preference("SyndeticsTOC"),
477 SyndeticsSummary => C4::Context->preference("SyndeticsSummary"),
478 SyndeticsEditions => C4::Context->preference("SyndeticsEditions"),
479 SyndeticsExcerpt => C4::Context->preference("SyndeticsExcerpt"),
480 SyndeticsReviews => C4::Context->preference("SyndeticsReviews"),
481 SyndeticsAuthorNotes => C4::Context->preference("SyndeticsAuthorNotes"),
482 SyndeticsAwards => C4::Context->preference("SyndeticsAwards"),
483 SyndeticsSeries => C4::Context->preference("SyndeticsSeries"),
484 SyndeticsCoverImageSize => C4::Context->preference("SyndeticsCoverImageSize"),
485 OPACLocalCoverImages => C4::Context->preference("OPACLocalCoverImages"),
486 PatronSelfRegistration => C4::Context->preference("PatronSelfRegistration"),
487 PatronSelfRegistrationDefaultCategory => C4::Context->preference("PatronSelfRegistrationDefaultCategory"),
490 $template->param(OpacPublic => '1') if ($user || C4::Context->preference("OpacPublic"));
493 # Check if we were asked using parameters to force a specific language
494 if ( defined $in->{'query'}->param('language') ) {
495 # Extract the language, let C4::Languages::getlanguage choose
497 my $language = C4::Languages::getlanguage($in->{'query'});
498 my $languagecookie = C4::Templates::getlanguagecookie($in->{'query'},$language);
499 if ( ref $cookie eq 'ARRAY' ) {
500 push @{ $cookie }, $languagecookie;
502 $cookie = [$cookie, $languagecookie];
506 return ( $template, $borrowernumber, $cookie, $flags);
511 ($userid, $cookie, $sessionID) = &checkauth($query, $noauth, $flagsrequired, $type);
513 Verifies that the user is authorized to run this script. If
514 the user is authorized, a (userid, cookie, session-id, flags)
515 quadruple is returned. If the user is not authorized but does
516 not have the required privilege (see $flagsrequired below), it
517 displays an error page and exits. Otherwise, it displays the
518 login page and exits.
520 Note that C<&checkauth> will return if and only if the user
521 is authorized, so it should be called early on, before any
522 unfinished operations (e.g., if you've opened a file, then
523 C<&checkauth> won't close it for you).
525 C<$query> is the CGI object for the script calling C<&checkauth>.
527 The C<$noauth> argument is optional. If it is set, then no
528 authorization is required for the script.
530 C<&checkauth> fetches user and session information from C<$query> and
531 ensures that the user is authorized to run scripts that require
534 The C<$flagsrequired> argument specifies the required privileges
535 the user must have if the username and password are correct.
536 It should be specified as a reference-to-hash; keys in the hash
537 should be the "flags" for the user, as specified in the Members
538 intranet module. Any key specified must correspond to a "flag"
539 in the userflags table. E.g., { circulate => 1 } would specify
540 that the user must have the "circulate" privilege in order to
541 proceed. To make sure that access control is correct, the
542 C<$flagsrequired> parameter must be specified correctly.
544 Koha also has a concept of sub-permissions, also known as
545 granular permissions. This makes the value of each key
546 in the C<flagsrequired> hash take on an additional
551 The user must have access to all subfunctions of the module
552 specified by the hash key.
556 The user must have access to at least one subfunction of the module
557 specified by the hash key.
559 specific permission, e.g., 'export_catalog'
561 The user must have access to the specific subfunction list, which
562 must correspond to a row in the permissions table.
564 The C<$type> argument specifies whether the template should be
565 retrieved from the opac or intranet directory tree. "opac" is
566 assumed if it is not specified; however, if C<$type> is specified,
567 "intranet" is assumed if it is not "opac".
569 If C<$query> does not have a valid session ID associated with it
570 (i.e., the user has not logged in) or if the session has expired,
571 C<&checkauth> presents the user with a login page (from the point of
572 view of the original script, C<&checkauth> does not return). Once the
573 user has authenticated, C<&checkauth> restarts the original script
574 (this time, C<&checkauth> returns).
576 The login page is provided using a HTML::Template, which is set in the
577 systempreferences table or at the top of this file. The variable C<$type>
578 selects which template to use, either the opac or the intranet
579 authentification template.
581 C<&checkauth> returns a user ID, a cookie, and a session ID. The
582 cookie should be sent back to the browser; it verifies that the user
591 # If Version syspref is unavailable, it means Koha is beeing installed,
592 # and so we must redirect to OPAC maintenance page or to the WebInstaller
593 # also, if OpacMaintenance is ON, OPAC should redirect to maintenance
594 if (C4::Context->preference('OpacMaintenance') && $type eq 'opac') {
595 warn "OPAC Install required, redirecting to maintenance";
596 print $query->redirect("/cgi-bin/koha/maintenance.pl");
599 unless ( $version = C4::Context->preference('Version') ) { # assignment, not comparison
600 if ( $type ne 'opac' ) {
601 warn "Install required, redirecting to Installer";
602 print $query->redirect("/cgi-bin/koha/installer/install.pl");
604 warn "OPAC Install required, redirecting to maintenance";
605 print $query->redirect("/cgi-bin/koha/maintenance.pl");
610 # check that database and koha version are the same
611 # there is no DB version, it's a fresh install,
612 # go to web installer
613 # there is a DB version, compare it to the code version
614 my $kohaversion=C4::Context::KOHAVERSION;
615 # remove the 3 last . to have a Perl number
616 $kohaversion =~ s/(.*\..*)\.(.*)\.(.*)/$1$2$3/;
617 $debug and print STDERR "kohaversion : $kohaversion\n";
618 if ($version < $kohaversion){
619 my $warning = "Database update needed, redirecting to %s. Database is $version and Koha is $kohaversion";
620 if ($type ne 'opac'){
621 warn sprintf($warning, 'Installer');
622 print $query->redirect("/cgi-bin/koha/installer/install.pl?step=3");
624 warn sprintf("OPAC: " . $warning, 'maintenance');
625 print $query->redirect("/cgi-bin/koha/maintenance.pl");
633 open my $fh, '>>', "/tmp/sessionlog" or warn "ERROR: Cannot append to /tmp/sessionlog";
634 printf $fh join("\n",@_);
638 sub _timeout_syspref {
639 my $timeout = C4::Context->preference('timeout') || 600;
640 # value in days, convert in seconds
641 if ($timeout =~ /(\d+)[dD]/) {
642 $timeout = $1 * 86400;
649 $debug and warn "Checking Auth";
650 # $authnotrequired will be set for scripts which will run without authentication
651 my $authnotrequired = shift;
652 my $flagsrequired = shift;
655 $type = 'opac' unless $type;
657 my $dbh = C4::Context->dbh;
658 my $timeout = _timeout_syspref();
660 _version_check($type,$query);
664 my ( $userid, $cookie, $sessionID, $flags, $barshelves, $pubshelves );
665 my $logout = $query->param('logout.x');
667 my $anon_search_history;
669 # This parameter is the name of the CAS server we want to authenticate against,
670 # when using authentication against multiple CAS servers, as configured in Auth_cas_servers.yaml
671 my $casparam = $query->param('cas');
672 my $q_userid = $query->param('userid') // '';
674 if ( $userid = $ENV{'REMOTE_USER'} ) {
675 # Using Basic Authentication, no cookies required
676 $cookie = $query->cookie(
677 -name => 'CGISESSID',
685 # we dont want to set a session because we are being called by a persona callback
687 elsif ( $sessionID = $query->cookie("CGISESSID") )
688 { # assignment, not comparison
689 my $session = get_session($sessionID);
690 C4::Context->_new_userenv($sessionID);
691 my ($ip, $lasttime, $sessiontype);
694 $s_userid = $session->param('id') // '';
695 C4::Context::set_userenv(
696 $session->param('number'), $s_userid,
697 $session->param('cardnumber'), $session->param('firstname'),
698 $session->param('surname'), $session->param('branch'),
699 $session->param('branchname'), $session->param('flags'),
700 $session->param('emailaddress'), $session->param('branchprinter'),
701 $session->param('persona')
703 C4::Context::set_shelves_userenv('bar',$session->param('barshelves'));
704 C4::Context::set_shelves_userenv('pub',$session->param('pubshelves'));
705 C4::Context::set_shelves_userenv('tot',$session->param('totshelves'));
706 $debug and printf STDERR "AUTH_SESSION: (%s)\t%s %s - %s\n", map {$session->param($_)} qw(cardnumber firstname surname branch) ;
707 $ip = $session->param('ip');
708 $lasttime = $session->param('lasttime');
710 $sessiontype = $session->param('sessiontype') || '';
712 if ( ( $query->param('koha_login_context') && ($q_userid ne $s_userid) )
713 || ( $cas && $query->param('ticket') ) ) {
714 #if a user enters an id ne to the id in the current session, we need to log them in...
715 #first we need to clear the anonymous session...
716 $debug and warn "query id = $q_userid but session id = $s_userid";
717 $anon_search_history = $session->param('search_history');
720 C4::Context->_unset_userenv($sessionID);
725 # voluntary logout the user
728 C4::Context->_unset_userenv($sessionID);
729 #_session_log(sprintf "%20s from %16s logged out at %30s (manually).\n", $userid,$ip,(strftime "%c",localtime));
733 if ($cas and $caslogout) {
737 elsif ( !$lasttime || ($lasttime < time() - $timeout) ) {
739 $info{'timed_out'} = 1;
744 C4::Context->_unset_userenv($sessionID);
745 #_session_log(sprintf "%20s from %16s logged out at %30s (inactivity).\n", $userid,$ip,(strftime "%c",localtime));
749 elsif ( $ip ne $ENV{'REMOTE_ADDR'} ) {
750 # Different ip than originally logged in from
751 $info{'oldip'} = $ip;
752 $info{'newip'} = $ENV{'REMOTE_ADDR'};
753 $info{'different_ip'} = 1;
756 C4::Context->_unset_userenv($sessionID);
757 #_session_log(sprintf "%20s from %16s logged out at %30s (ip changed to %16s).\n", $userid,$ip,(strftime "%c",localtime), $info{'newip'});
762 $cookie = $query->cookie(
763 -name => 'CGISESSID',
764 -value => $session->id,
767 $session->param( 'lasttime', time() );
768 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...
769 $flags = haspermission($userid, $flagsrequired);
773 $info{'nopermission'} = 1;
778 unless ($userid || $sessionID) {
780 #we initiate a session prior to checking for a username to allow for anonymous sessions...
781 my $session = get_session("") or die "Auth ERROR: Cannot get_session()";
783 # Save anonymous search history in new session so it can be retrieved
784 # by get_template_and_user to store it in user's search history after
785 # a successful login.
786 if ($anon_search_history) {
787 $session->param('search_history', $anon_search_history);
790 my $sessionID = $session->id;
791 C4::Context->_new_userenv($sessionID);
792 $cookie = $query->cookie(
793 -name => 'CGISESSID',
794 -value => $session->id,
798 my $pki_field = C4::Context->preference('AllowPKIAuth');
799 if (! defined($pki_field) ) {
800 print STDERR "ERROR: Missing system preference AllowPKIAuth.\n";
803 if ( ( $cas && $query->param('ticket') )
805 || $pki_field ne 'None'
808 my $password = $query->param('password');
810 my ( $return, $cardnumber );
811 if ( $cas && $query->param('ticket') ) {
813 ( $return, $cardnumber, $retuserid ) =
814 checkpw( $dbh, $userid, $password, $query );
815 $userid = $retuserid;
816 $info{'invalidCasLogin'} = 1 unless ($return);
820 my $value = $persona;
822 # If we're looking up the email, there's a chance that the person
823 # doesn't have a userid. So if there is none, we pass along the
824 # borrower number, and the bits of code that need to know the user
825 # ID will have to be smart enough to handle that.
827 my @users_info = C4::Members::GetBorrowersWithEmail($value);
830 # First the userid, then the borrowernum
831 $value = $users_info[0][1] || $users_info[0][0];
836 $return = $value ? 1 : 0;
841 ( $pki_field eq 'Common Name' && $ENV{'SSL_CLIENT_S_DN_CN'} )
842 || ( $pki_field eq 'emailAddress'
843 && $ENV{'SSL_CLIENT_S_DN_Email'} )
847 if ( $pki_field eq 'Common Name' ) {
848 $value = $ENV{'SSL_CLIENT_S_DN_CN'};
850 elsif ( $pki_field eq 'emailAddress' ) {
851 $value = $ENV{'SSL_CLIENT_S_DN_Email'};
853 # If we're looking up the email, there's a chance that the person
854 # doesn't have a userid. So if there is none, we pass along the
855 # borrower number, and the bits of code that need to know the user
856 # ID will have to be smart enough to handle that.
858 my @users_info = C4::Members::GetBorrowersWithEmail($value);
861 # First the userid, then the borrowernum
862 $value = $users_info[0][1] || $users_info[0][0];
869 $return = $value ? 1 : 0;
875 ( $return, $cardnumber, $retuserid ) =
876 checkpw( $dbh, $userid, $password, $query );
877 $userid = $retuserid if ( $retuserid );
880 #_session_log(sprintf "%20s from %16s logged in at %30s.\n", $userid,$ENV{'REMOTE_ADDR'},(strftime '%c', localtime));
881 if ( $flags = haspermission( $userid, $flagsrequired ) ) {
885 $info{'nopermission'} = 1;
886 C4::Context->_unset_userenv($sessionID);
888 my ($borrowernumber, $firstname, $surname, $userflags,
889 $branchcode, $branchname, $branchprinter, $emailaddress);
891 if ( $return == 1 ) {
893 SELECT borrowernumber, firstname, surname, flags, borrowers.branchcode,
894 branches.branchname as branchname,
895 branches.branchprinter as branchprinter,
898 LEFT JOIN branches on borrowers.branchcode=branches.branchcode
900 my $sth = $dbh->prepare("$select where userid=?");
901 $sth->execute($userid);
902 unless ($sth->rows) {
903 $debug and print STDERR "AUTH_1: no rows for userid='$userid'\n";
904 $sth = $dbh->prepare("$select where cardnumber=?");
905 $sth->execute($cardnumber);
907 unless ($sth->rows) {
908 $debug and print STDERR "AUTH_2a: no rows for cardnumber='$cardnumber'\n";
909 $sth->execute($userid);
910 unless ($sth->rows) {
911 $debug and print STDERR "AUTH_2b: no rows for userid='$userid' AS cardnumber\n";
916 ($borrowernumber, $firstname, $surname, $userflags,
917 $branchcode, $branchname, $branchprinter, $emailaddress) = $sth->fetchrow;
918 $debug and print STDERR "AUTH_3 results: " .
919 "$cardnumber,$borrowernumber,$userid,$firstname,$surname,$userflags,$branchcode,$emailaddress\n";
921 print STDERR "AUTH_3: no results for userid='$userid', cardnumber='$cardnumber'.\n";
924 # launch a sequence to check if we have a ip for the branch, i
925 # if we have one we replace the branchcode of the userenv by the branch bound in the ip.
927 my $ip = $ENV{'REMOTE_ADDR'};
928 # if they specify at login, use that
929 if ($query->param('branch')) {
930 $branchcode = $query->param('branch');
931 $branchname = GetBranchName($branchcode);
933 my $branches = GetBranches();
934 if (C4::Context->boolean_preference('IndependentBranches') && C4::Context->boolean_preference('Autolocation')){
935 # we have to check they are coming from the right ip range
936 my $domain = $branches->{$branchcode}->{'branchip'};
937 if ($ip !~ /^$domain/){
939 $info{'wrongip'} = 1;
944 foreach my $br ( keys %$branches ) {
945 # now we work with the treatment of ip
946 my $domain = $branches->{$br}->{'branchip'};
947 if ( $domain && $ip =~ /^$domain/ ) {
948 $branchcode = $branches->{$br}->{'branchcode'};
950 # new op dev : add the branchprinter and branchname in the cookie
951 $branchprinter = $branches->{$br}->{'branchprinter'};
952 $branchname = $branches->{$br}->{'branchname'};
955 $session->param('number',$borrowernumber);
956 $session->param('id',$userid);
957 $session->param('cardnumber',$cardnumber);
958 $session->param('firstname',$firstname);
959 $session->param('surname',$surname);
960 $session->param('branch',$branchcode);
961 $session->param('branchname',$branchname);
962 $session->param('flags',$userflags);
963 $session->param('emailaddress',$emailaddress);
964 $session->param('ip',$session->remote_addr());
965 $session->param('lasttime',time());
966 $debug and printf STDERR "AUTH_4: (%s)\t%s %s - %s\n", map {$session->param($_)} qw(cardnumber firstname surname branch) ;
968 elsif ( $return == 2 ) {
969 #We suppose the user is the superlibrarian
971 $session->param('number',0);
972 $session->param('id',C4::Context->config('user'));
973 $session->param('cardnumber',C4::Context->config('user'));
974 $session->param('firstname',C4::Context->config('user'));
975 $session->param('surname',C4::Context->config('user'));
976 $session->param('branch','NO_LIBRARY_SET');
977 $session->param('branchname','NO_LIBRARY_SET');
978 $session->param('flags',1);
979 $session->param('emailaddress', C4::Context->preference('KohaAdminEmailAddress'));
980 $session->param('ip',$session->remote_addr());
981 $session->param('lasttime',time());
984 $session->param('persona',1);
986 C4::Context::set_userenv(
987 $session->param('number'), $session->param('id'),
988 $session->param('cardnumber'), $session->param('firstname'),
989 $session->param('surname'), $session->param('branch'),
990 $session->param('branchname'), $session->param('flags'),
991 $session->param('emailaddress'), $session->param('branchprinter'),
992 $session->param('persona')
997 $debug and warn "Login failed, resetting anonymous session...";
999 $info{'invalid_username_or_password'} = 1;
1000 C4::Context->_unset_userenv($sessionID);
1002 $session->param('lasttime',time());
1003 $session->param('ip',$session->remote_addr());
1004 $session->param('sessiontype','anon');
1006 } # END if ( $userid = $query->param('userid') )
1007 elsif ($type eq "opac") {
1008 # if we are here this is an anonymous session; add public lists to it and a few other items...
1009 # anonymous sessions are created only for the OPAC
1010 $debug and warn "Initiating an anonymous session...";
1012 # setting a couple of other session vars...
1013 $session->param('ip',$session->remote_addr());
1014 $session->param('lasttime',time());
1015 $session->param('sessiontype','anon');
1017 } # END unless ($userid)
1019 # finished authentification, now respond
1020 if ( $loggedin || $authnotrequired )
1024 $cookie = $query->cookie(
1025 -name => 'CGISESSID',
1030 return ( $userid, $cookie, $sessionID, $flags );
1035 # AUTH rejected, show the login/password template, after checking the DB.
1039 # get the inputs from the incoming query
1041 foreach my $name ( param $query) {
1042 (next) if ( $name eq 'userid' || $name eq 'password' || $name eq 'ticket' );
1043 my $value = $query->param($name);
1044 push @inputs, { name => $name, value => $value };
1047 my $LibraryNameTitle = C4::Context->preference("LibraryName");
1048 $LibraryNameTitle =~ s/<(?:\/?)(?:br|p)\s*(?:\/?)>/ /sgi;
1049 $LibraryNameTitle =~ s/<(?:[^<>'"]|'(?:[^']*)'|"(?:[^"]*)")*>//sg;
1051 my $template_name = ( $type eq 'opac' ) ? 'opac-auth.tmpl' : 'auth.tmpl';
1052 my $template = C4::Templates::gettemplate($template_name, $type, $query );
1054 branchloop => GetBranchesLoop(),
1055 opaccolorstylesheet => C4::Context->preference("opaccolorstylesheet"),
1056 opaclayoutstylesheet => C4::Context->preference("opaclayoutstylesheet"),
1059 casAuthentication => C4::Context->preference("casAuthentication"),
1060 suggestion => C4::Context->preference("suggestion"),
1061 virtualshelves => C4::Context->preference("virtualshelves"),
1062 LibraryName => "" . C4::Context->preference("LibraryName"),
1063 LibraryNameTitle => "" . $LibraryNameTitle,
1064 opacuserlogin => C4::Context->preference("opacuserlogin"),
1065 OpacNav => C4::Context->preference("OpacNav"),
1066 OpacNavRight => C4::Context->preference("OpacNavRight"),
1067 OpacNavBottom => C4::Context->preference("OpacNavBottom"),
1068 opaccredits => C4::Context->preference("opaccredits"),
1069 OpacFavicon => C4::Context->preference("OpacFavicon"),
1070 opacreadinghistory => C4::Context->preference("opacreadinghistory"),
1071 opacsmallimage => C4::Context->preference("opacsmallimage"),
1072 opaclanguagesdisplay => C4::Context->preference("opaclanguagesdisplay"),
1073 opacuserjs => C4::Context->preference("opacuserjs"),
1074 opacbookbag => "" . C4::Context->preference("opacbookbag"),
1075 OpacCloud => C4::Context->preference("OpacCloud"),
1076 OpacTopissue => C4::Context->preference("OpacTopissue"),
1077 OpacAuthorities => C4::Context->preference("OpacAuthorities"),
1078 OpacBrowser => C4::Context->preference("OpacBrowser"),
1079 opacheader => C4::Context->preference("opacheader"),
1080 TagsEnabled => C4::Context->preference("TagsEnabled"),
1081 OPACUserCSS => C4::Context->preference("OPACUserCSS"),
1082 intranetcolorstylesheet => C4::Context->preference("intranetcolorstylesheet"),
1083 intranetstylesheet => C4::Context->preference("intranetstylesheet"),
1084 intranetbookbag => C4::Context->preference("intranetbookbag"),
1085 IntranetNav => C4::Context->preference("IntranetNav"),
1086 IntranetFavicon => C4::Context->preference("IntranetFavicon"),
1087 intranetuserjs => C4::Context->preference("intranetuserjs"),
1088 IndependentBranches=> C4::Context->preference("IndependentBranches"),
1089 AutoLocation => C4::Context->preference("AutoLocation"),
1090 wrongip => $info{'wrongip'},
1091 PatronSelfRegistration => C4::Context->preference("PatronSelfRegistration"),
1092 PatronSelfRegistrationDefaultCategory => C4::Context->preference("PatronSelfRegistrationDefaultCategory"),
1093 persona => C4::Context->preference("Persona"),
1094 opac_css_override => $ENV{'OPAC_CSS_OVERRIDE'},
1097 $template->param( OpacPublic => C4::Context->preference("OpacPublic"));
1098 $template->param( loginprompt => 1 ) unless $info{'nopermission'};
1100 if($type eq 'opac'){
1101 my ($total, $pubshelves) = C4::VirtualShelves::GetSomeShelfNames(undef, 'MASTHEAD');
1103 pubshelves => $total->{pubtotal},
1104 pubshelvesloop => $pubshelves,
1110 # Is authentication against multiple CAS servers enabled?
1111 if (C4::Auth_with_cas::multipleAuth && !$casparam) {
1112 my $casservers = C4::Auth_with_cas::getMultipleAuth();
1114 foreach my $key (keys %$casservers) {
1115 push @tmplservers, {name => $key, value => login_cas_url($query, $key) . "?cas=$key" };
1118 casServersLoop => \@tmplservers
1122 casServerUrl => login_cas_url($query),
1127 invalidCasLogin => $info{'invalidCasLogin'}
1131 my $self_url = $query->url( -absolute => 1 );
1134 LibraryName => C4::Context->preference("LibraryName"),
1136 $template->param( %info );
1137 # $cookie = $query->cookie(CGISESSID => $session->id
1139 print $query->header(
1140 -type => 'text/html',
1141 -charset => 'utf-8',
1148 =head2 check_api_auth
1150 ($status, $cookie, $sessionId) = check_api_auth($query, $userflags);
1152 Given a CGI query containing the parameters 'userid' and 'password' and/or a session
1153 cookie, determine if the user has the privileges specified by C<$userflags>.
1155 C<check_api_auth> is is meant for authenticating users of web services, and
1156 consequently will always return and will not attempt to redirect the user
1159 If a valid session cookie is already present, check_api_auth will return a status
1160 of "ok", the cookie, and the Koha session ID.
1162 If no session cookie is present, check_api_auth will check the 'userid' and 'password
1163 parameters and create a session cookie and Koha session if the supplied credentials
1166 Possible return values in C<$status> are:
1170 =item "ok" -- user authenticated; C<$cookie> and C<$sessionid> have valid values.
1172 =item "failed" -- credentials are not correct; C<$cookie> and C<$sessionid> are undef
1174 =item "maintenance" -- DB is in maintenance mode; no login possible at the moment
1176 =item "expired -- session cookie has expired; API user should resubmit userid and password
1182 sub check_api_auth {
1184 my $flagsrequired = shift;
1186 my $dbh = C4::Context->dbh;
1187 my $timeout = _timeout_syspref();
1189 unless (C4::Context->preference('Version')) {
1190 # database has not been installed yet
1191 return ("maintenance", undef, undef);
1193 my $kohaversion=C4::Context::KOHAVERSION;
1194 $kohaversion =~ s/(.*\..*)\.(.*)\.(.*)/$1$2$3/;
1195 if (C4::Context->preference('Version') < $kohaversion) {
1196 # database in need of version update; assume that
1197 # no API should be called while databsae is in
1199 return ("maintenance", undef, undef);
1202 # FIXME -- most of what follows is a copy-and-paste
1203 # of code from checkauth. There is an obvious need
1204 # for refactoring to separate the various parts of
1205 # the authentication code, but as of 2007-11-19 this
1206 # is deferred so as to not introduce bugs into the
1207 # regular authentication code for Koha 3.0.
1209 # see if we have a valid session cookie already
1210 # however, if a userid parameter is present (i.e., from
1211 # a form submission, assume that any current cookie
1213 my $sessionID = undef;
1214 unless ($query->param('userid')) {
1215 $sessionID = $query->cookie("CGISESSID");
1217 if ($sessionID && not ($cas && $query->param('PT')) ) {
1218 my $session = get_session($sessionID);
1219 C4::Context->_new_userenv($sessionID);
1221 C4::Context::set_userenv(
1222 $session->param('number'), $session->param('id'),
1223 $session->param('cardnumber'), $session->param('firstname'),
1224 $session->param('surname'), $session->param('branch'),
1225 $session->param('branchname'), $session->param('flags'),
1226 $session->param('emailaddress'), $session->param('branchprinter')
1229 my $ip = $session->param('ip');
1230 my $lasttime = $session->param('lasttime');
1231 my $userid = $session->param('id');
1232 if ( $lasttime < time() - $timeout ) {
1236 C4::Context->_unset_userenv($sessionID);
1239 return ("expired", undef, undef);
1240 } elsif ( $ip ne $ENV{'REMOTE_ADDR'} ) {
1241 # IP address changed
1244 C4::Context->_unset_userenv($sessionID);
1247 return ("expired", undef, undef);
1249 my $cookie = $query->cookie(
1250 -name => 'CGISESSID',
1251 -value => $session->id,
1254 $session->param('lasttime',time());
1255 my $flags = haspermission($userid, $flagsrequired);
1257 return ("ok", $cookie, $sessionID);
1261 C4::Context->_unset_userenv($sessionID);
1264 return ("failed", undef, undef);
1268 return ("expired", undef, undef);
1272 my $userid = $query->param('userid');
1273 my $password = $query->param('password');
1274 my ($return, $cardnumber);
1277 if ($cas && $query->param('PT')) {
1279 $debug and print STDERR "## check_api_auth - checking CAS\n";
1280 # In case of a CAS authentication, we use the ticket instead of the password
1281 my $PT = $query->param('PT');
1282 ($return,$cardnumber,$userid) = check_api_auth_cas($dbh, $PT, $query); # EXTERNAL AUTH
1284 # User / password auth
1285 unless ($userid and $password) {
1286 # caller did something wrong, fail the authenticateion
1287 return ("failed", undef, undef);
1289 ( $return, $cardnumber ) = checkpw( $dbh, $userid, $password, $query );
1292 if ($return and haspermission( $userid, $flagsrequired)) {
1293 my $session = get_session("");
1294 return ("failed", undef, undef) unless $session;
1296 my $sessionID = $session->id;
1297 C4::Context->_new_userenv($sessionID);
1298 my $cookie = $query->cookie(
1299 -name => 'CGISESSID',
1300 -value => $sessionID,
1303 if ( $return == 1 ) {
1305 $borrowernumber, $firstname, $surname,
1306 $userflags, $branchcode, $branchname,
1307 $branchprinter, $emailaddress
1311 "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=?"
1313 $sth->execute($userid);
1315 $borrowernumber, $firstname, $surname,
1316 $userflags, $branchcode, $branchname,
1317 $branchprinter, $emailaddress
1318 ) = $sth->fetchrow if ( $sth->rows );
1320 unless ($sth->rows ) {
1321 my $sth = $dbh->prepare(
1322 "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=?"
1324 $sth->execute($cardnumber);
1326 $borrowernumber, $firstname, $surname,
1327 $userflags, $branchcode, $branchname,
1328 $branchprinter, $emailaddress
1329 ) = $sth->fetchrow if ( $sth->rows );
1331 unless ( $sth->rows ) {
1332 $sth->execute($userid);
1334 $borrowernumber, $firstname, $surname, $userflags,
1335 $branchcode, $branchname, $branchprinter, $emailaddress
1336 ) = $sth->fetchrow if ( $sth->rows );
1340 my $ip = $ENV{'REMOTE_ADDR'};
1341 # if they specify at login, use that
1342 if ($query->param('branch')) {
1343 $branchcode = $query->param('branch');
1344 $branchname = GetBranchName($branchcode);
1346 my $branches = GetBranches();
1348 foreach my $br ( keys %$branches ) {
1349 # now we work with the treatment of ip
1350 my $domain = $branches->{$br}->{'branchip'};
1351 if ( $domain && $ip =~ /^$domain/ ) {
1352 $branchcode = $branches->{$br}->{'branchcode'};
1354 # new op dev : add the branchprinter and branchname in the cookie
1355 $branchprinter = $branches->{$br}->{'branchprinter'};
1356 $branchname = $branches->{$br}->{'branchname'};
1359 $session->param('number',$borrowernumber);
1360 $session->param('id',$userid);
1361 $session->param('cardnumber',$cardnumber);
1362 $session->param('firstname',$firstname);
1363 $session->param('surname',$surname);
1364 $session->param('branch',$branchcode);
1365 $session->param('branchname',$branchname);
1366 $session->param('flags',$userflags);
1367 $session->param('emailaddress',$emailaddress);
1368 $session->param('ip',$session->remote_addr());
1369 $session->param('lasttime',time());
1370 } elsif ( $return == 2 ) {
1371 #We suppose the user is the superlibrarian
1372 $session->param('number',0);
1373 $session->param('id',C4::Context->config('user'));
1374 $session->param('cardnumber',C4::Context->config('user'));
1375 $session->param('firstname',C4::Context->config('user'));
1376 $session->param('surname',C4::Context->config('user'));
1377 $session->param('branch','NO_LIBRARY_SET');
1378 $session->param('branchname','NO_LIBRARY_SET');
1379 $session->param('flags',1);
1380 $session->param('emailaddress', C4::Context->preference('KohaAdminEmailAddress'));
1381 $session->param('ip',$session->remote_addr());
1382 $session->param('lasttime',time());
1384 C4::Context::set_userenv(
1385 $session->param('number'), $session->param('id'),
1386 $session->param('cardnumber'), $session->param('firstname'),
1387 $session->param('surname'), $session->param('branch'),
1388 $session->param('branchname'), $session->param('flags'),
1389 $session->param('emailaddress'), $session->param('branchprinter')
1391 return ("ok", $cookie, $sessionID);
1393 return ("failed", undef, undef);
1398 =head2 check_cookie_auth
1400 ($status, $sessionId) = check_api_auth($cookie, $userflags);
1402 Given a CGISESSID cookie set during a previous login to Koha, determine
1403 if the user has the privileges specified by C<$userflags>.
1405 C<check_cookie_auth> is meant for authenticating special services
1406 such as tools/upload-file.pl that are invoked by other pages that
1407 have been authenticated in the usual way.
1409 Possible return values in C<$status> are:
1413 =item "ok" -- user authenticated; C<$sessionID> have valid values.
1415 =item "failed" -- credentials are not correct; C<$sessionid> are undef
1417 =item "maintenance" -- DB is in maintenance mode; no login possible at the moment
1419 =item "expired -- session cookie has expired; API user should resubmit userid and password
1425 sub check_cookie_auth {
1427 my $flagsrequired = shift;
1429 my $dbh = C4::Context->dbh;
1430 my $timeout = _timeout_syspref();
1432 unless (C4::Context->preference('Version')) {
1433 # database has not been installed yet
1434 return ("maintenance", undef);
1436 my $kohaversion=C4::Context::KOHAVERSION;
1437 $kohaversion =~ s/(.*\..*)\.(.*)\.(.*)/$1$2$3/;
1438 if (C4::Context->preference('Version') < $kohaversion) {
1439 # database in need of version update; assume that
1440 # no API should be called while databsae is in
1442 return ("maintenance", undef);
1445 # FIXME -- most of what follows is a copy-and-paste
1446 # of code from checkauth. There is an obvious need
1447 # for refactoring to separate the various parts of
1448 # the authentication code, but as of 2007-11-23 this
1449 # is deferred so as to not introduce bugs into the
1450 # regular authentication code for Koha 3.0.
1452 # see if we have a valid session cookie already
1453 # however, if a userid parameter is present (i.e., from
1454 # a form submission, assume that any current cookie
1456 unless (defined $cookie and $cookie) {
1457 return ("failed", undef);
1459 my $sessionID = $cookie;
1460 my $session = get_session($sessionID);
1461 C4::Context->_new_userenv($sessionID);
1463 C4::Context::set_userenv(
1464 $session->param('number'), $session->param('id'),
1465 $session->param('cardnumber'), $session->param('firstname'),
1466 $session->param('surname'), $session->param('branch'),
1467 $session->param('branchname'), $session->param('flags'),
1468 $session->param('emailaddress'), $session->param('branchprinter')
1471 my $ip = $session->param('ip');
1472 my $lasttime = $session->param('lasttime');
1473 my $userid = $session->param('id');
1474 if ( $lasttime < time() - $timeout ) {
1478 C4::Context->_unset_userenv($sessionID);
1481 return ("expired", undef);
1482 } elsif ( $ip ne $ENV{'REMOTE_ADDR'} ) {
1483 # IP address changed
1486 C4::Context->_unset_userenv($sessionID);
1489 return ("expired", undef);
1491 $session->param('lasttime',time());
1492 my $flags = haspermission($userid, $flagsrequired);
1494 return ("ok", $sessionID);
1498 C4::Context->_unset_userenv($sessionID);
1501 return ("failed", undef);
1505 return ("expired", undef);
1512 my $session = get_session($sessionID);
1514 Given a session ID, retrieve the CGI::Session object used to store
1515 the session's state. The session object can be used to store
1516 data that needs to be accessed by different scripts during a
1519 If the C<$sessionID> parameter is an empty string, a new session
1525 my $sessionID = shift;
1526 my $storage_method = C4::Context->preference('SessionStorage');
1527 my $dbh = C4::Context->dbh;
1529 if ($storage_method eq 'mysql'){
1530 $session = new CGI::Session("driver:MySQL;serializer:yaml;id:md5", $sessionID, {Handle=>$dbh});
1532 elsif ($storage_method eq 'Pg') {
1533 $session = new CGI::Session("driver:PostgreSQL;serializer:yaml;id:md5", $sessionID, {Handle=>$dbh});
1535 elsif ($storage_method eq 'memcached' && C4::Context->ismemcached){
1536 $session = new CGI::Session("driver:memcached;serializer:yaml;id:md5", $sessionID, { Memcached => C4::Context->memcached } );
1539 # catch all defaults to tmp should work on all systems
1540 $session = new CGI::Session("driver:File;serializer:yaml;id:md5", $sessionID, {Directory=>'/tmp'});
1546 my ( $dbh, $userid, $password, $query ) = @_;
1549 $debug and print STDERR "## checkpw - checking LDAP\n";
1550 my ($retval,$retcard,$retuserid) = checkpw_ldap(@_); # EXTERNAL AUTH
1551 ($retval) and return ($retval,$retcard,$retuserid);
1554 if ($cas && $query && $query->param('ticket')) {
1555 $debug and print STDERR "## checkpw - checking CAS\n";
1556 # In case of a CAS authentication, we use the ticket instead of the password
1557 my $ticket = $query->param('ticket');
1558 $query->delete('ticket'); # remove ticket to come back to original URL
1559 my ($retval,$retcard,$retuserid) = checkpw_cas($dbh, $ticket, $query); # EXTERNAL AUTH
1560 ($retval) and return ($retval,$retcard,$retuserid);
1564 return checkpw_internal(@_)
1567 sub checkpw_internal {
1568 my ( $dbh, $userid, $password ) = @_;
1570 if ( $userid && $userid eq C4::Context->config('user') ) {
1571 if ( $password && $password eq C4::Context->config('pass') ) {
1572 # Koha superuser account
1573 # C4::Context->set_userenv(0,0,C4::Context->config('user'),C4::Context->config('user'),C4::Context->config('user'),"",1);
1583 "select password,cardnumber,borrowernumber,userid,firstname,surname,branchcode,flags from borrowers where userid=?"
1585 $sth->execute($userid);
1587 my ( $stored_hash, $cardnumber, $borrowernumber, $userid, $firstname,
1588 $surname, $branchcode, $flags )
1591 if ( checkpw_hash($password, $stored_hash) ) {
1593 C4::Context->set_userenv( "$borrowernumber", $userid, $cardnumber,
1594 $firstname, $surname, $branchcode, $flags );
1595 return 1, $cardnumber, $userid;
1600 "select password,cardnumber,borrowernumber,userid, firstname,surname,branchcode,flags from borrowers where cardnumber=?"
1602 $sth->execute($userid);
1604 my ( $stored_hash, $cardnumber, $borrowernumber, $userid, $firstname,
1605 $surname, $branchcode, $flags )
1608 if ( checkpw_hash($password, $stored_hash) ) {
1610 C4::Context->set_userenv( $borrowernumber, $userid, $cardnumber,
1611 $firstname, $surname, $branchcode, $flags );
1612 return 1, $cardnumber, $userid;
1615 if ( $userid && $userid eq 'demo'
1616 && "$password" eq 'demo'
1617 && C4::Context->config('demo') )
1620 # DEMO => the demo user is allowed to do everything (if demo set to 1 in koha.conf
1621 # some features won't be effective : modify systempref, modify MARC structure,
1628 my ( $password, $stored_hash ) = @_;
1630 return if $stored_hash eq '!';
1632 # check what encryption algorithm was implemented: Bcrypt - if the hash starts with '$2' it is Bcrypt else md5
1634 if ( substr($stored_hash,0,2) eq '$2') {
1635 $hash = hash_password($password, $stored_hash);
1637 $hash = md5_base64($password);
1639 return $hash eq $stored_hash;
1644 my $authflags = getuserflags($flags, $userid, [$dbh]);
1646 Translates integer flags into permissions strings hash.
1648 C<$flags> is the integer userflags value ( borrowers.userflags )
1649 C<$userid> is the members.userid, used for building subpermissions
1650 C<$authflags> is a hashref of permissions
1657 my $dbh = @_ ? shift : C4::Context->dbh;
1660 # I don't want to do this, but if someone logs in as the database
1661 # user, it would be preferable not to spam them to death with
1662 # numeric warnings. So, we make $flags numeric.
1663 no warnings 'numeric';
1666 my $sth = $dbh->prepare("SELECT bit, flag, defaulton FROM userflags");
1669 while ( my ( $bit, $flag, $defaulton ) = $sth->fetchrow ) {
1670 if ( ( $flags & ( 2**$bit ) ) || $defaulton ) {
1671 $userflags->{$flag} = 1;
1674 $userflags->{$flag} = 0;
1677 # get subpermissions and merge with top-level permissions
1678 my $user_subperms = get_user_subpermissions($userid);
1679 foreach my $module (keys %$user_subperms) {
1680 next if $userflags->{$module} == 1; # user already has permission for everything in this module
1681 $userflags->{$module} = $user_subperms->{$module};
1687 =head2 get_user_subpermissions
1689 $user_perm_hashref = get_user_subpermissions($userid);
1691 Given the userid (note, not the borrowernumber) of a staff user,
1692 return a hashref of hashrefs of the specific subpermissions
1693 accorded to the user. An example return is
1697 export_catalog => 1,
1698 import_patrons => 1,
1702 The top-level hash-key is a module or function code from
1703 userflags.flag, while the second-level key is a code
1706 The results of this function do not give a complete picture
1707 of the functions that a staff user can access; it is also
1708 necessary to check borrowers.flags.
1712 sub get_user_subpermissions {
1715 my $dbh = C4::Context->dbh;
1716 my $sth = $dbh->prepare("SELECT flag, user_permissions.code
1717 FROM user_permissions
1718 JOIN permissions USING (module_bit, code)
1719 JOIN userflags ON (module_bit = bit)
1720 JOIN borrowers USING (borrowernumber)
1722 $sth->execute($userid);
1724 my $user_perms = {};
1725 while (my $perm = $sth->fetchrow_hashref) {
1726 $user_perms->{$perm->{'flag'}}->{$perm->{'code'}} = 1;
1731 =head2 get_all_subpermissions
1733 my $perm_hashref = get_all_subpermissions();
1735 Returns a hashref of hashrefs defining all specific
1736 permissions currently defined. The return value
1737 has the same structure as that of C<get_user_subpermissions>,
1738 except that the innermost hash value is the description
1739 of the subpermission.
1743 sub get_all_subpermissions {
1744 my $dbh = C4::Context->dbh;
1745 my $sth = $dbh->prepare("SELECT flag, code, description
1747 JOIN userflags ON (module_bit = bit)");
1751 while (my $perm = $sth->fetchrow_hashref) {
1752 $all_perms->{$perm->{'flag'}}->{$perm->{'code'}} = $perm->{'description'};
1757 =head2 haspermission
1759 $flags = ($userid, $flagsrequired);
1761 C<$userid> the userid of the member
1762 C<$flags> is a hashref of required flags like C<$borrower-<{authflags}>
1764 Returns member's flags or 0 if a permission is not met.
1769 my ($userid, $flagsrequired) = @_;
1770 my $sth = C4::Context->dbh->prepare("SELECT flags FROM borrowers WHERE userid=?");
1771 $sth->execute($userid);
1772 my $row = $sth->fetchrow();
1773 my $flags = getuserflags($row, $userid);
1774 if ( $userid eq C4::Context->config('user') ) {
1775 # Super User Account from /etc/koha.conf
1776 $flags->{'superlibrarian'} = 1;
1778 elsif ( $userid eq 'demo' && C4::Context->config('demo') ) {
1779 # Demo user that can do "anything" (demo=1 in /etc/koha.conf)
1780 $flags->{'superlibrarian'} = 1;
1783 return $flags if $flags->{superlibrarian};
1785 foreach my $module ( keys %$flagsrequired ) {
1786 my $subperm = $flagsrequired->{$module};
1787 if ($subperm eq '*') {
1788 return 0 unless ( $flags->{$module} == 1 or ref($flags->{$module}) );
1790 return 0 unless ( $flags->{$module} == 1 or
1791 ( ref($flags->{$module}) and
1792 exists $flags->{$module}->{$subperm} and
1793 $flags->{$module}->{$subperm} == 1
1799 #FIXME - This fcn should return the failed permission so a suitable error msg can be delivered.
1803 sub getborrowernumber {
1805 my $userenv = C4::Context->userenv;
1806 if ( defined( $userenv ) && ref( $userenv ) eq 'HASH' && $userenv->{number} ) {
1807 return $userenv->{number};
1809 my $dbh = C4::Context->dbh;
1810 for my $field ( 'userid', 'cardnumber' ) {
1812 $dbh->prepare("select borrowernumber from borrowers where $field=?");
1813 $sth->execute($userid);
1815 my ($bnumber) = $sth->fetchrow;
1822 END { } # module clean-up code here (global destructor)
1832 Crypt::Eksblowfish::Bcrypt(3)