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
30 use C4::Branch; # GetBranches
31 use C4::Search::History;
32 use C4::VirtualShelves;
33 use Koha::AuthUtils qw(hash_password);
34 use POSIX qw/strftime/;
35 use List::MoreUtils qw/ any /;
38 use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS $debug $ldap $cas $caslogout);
41 sub psgi_env { any { /^psgi\./ } keys %ENV }
43 if ( psgi_env ) { die 'psgi:exit' }
46 $VERSION = 3.07.00.049; # set version for version checking
50 @EXPORT = qw(&checkauth &get_template_and_user &haspermission &get_user_subpermissions);
51 @EXPORT_OK = qw(&check_api_auth &get_session &check_cookie_auth &checkpw &checkpw_internal &checkpw_hash
52 &get_all_subpermissions &get_user_subpermissions
54 %EXPORT_TAGS = ( EditPermissions => [qw(get_all_subpermissions get_user_subpermissions)] );
55 $ldap = C4::Context->config('useldapserver') || 0;
56 $cas = C4::Context->preference('casAuthentication');
57 $caslogout = C4::Context->preference('casLogout');
58 require C4::Auth_with_cas; # no import
60 require C4::Auth_with_ldap;
61 import C4::Auth_with_ldap qw(checkpw_ldap);
64 import C4::Auth_with_cas qw(check_api_auth_cas checkpw_cas login_cas logout_cas login_cas_url);
71 C4::Auth - Authenticates Koha users
81 my ($template, $borrowernumber, $cookie)
82 = get_template_and_user(
84 template_name => "opac-main.tmpl",
88 flagsrequired => {borrow => 1, catalogue => '*', tools => 'import_patrons' },
92 output_html_with_http_headers $query, $cookie, $template->output;
96 The main function of this module is to provide
97 authentification. However the get_template_and_user function has
98 been provided so that a users login information is passed along
99 automatically. This gets loaded into the template.
103 =head2 get_template_and_user
105 my ($template, $borrowernumber, $cookie)
106 = get_template_and_user(
108 template_name => "opac-main.tmpl",
111 authnotrequired => 1,
112 flagsrequired => {borrow => 1, catalogue => '*', tools => 'import_patrons' },
116 This call passes the C<query>, C<flagsrequired> and C<authnotrequired>
117 to C<&checkauth> (in this module) to perform authentification.
118 See C<&checkauth> for an explanation of these parameters.
120 The C<template_name> is then used to find the correct template for
121 the page. The authenticated users details are loaded onto the
122 template in the HTML::Template LOOP variable C<USER_INFO>. Also the
123 C<sessionID> is passed to the template. This can be used in templates
124 if cookies are disabled. It needs to be put as and input to every
127 More information on the C<gettemplate> sub can be found in the
132 sub get_template_and_user {
135 my ( $user, $cookie, $sessionID, $flags );
137 my $template = C4::Templates::gettemplate(
138 $in->{'template_name'},
144 if ( $in->{'template_name'} !~m/maintenance/ ) {
145 ( $user, $cookie, $sessionID, $flags ) = checkauth(
147 $in->{'authnotrequired'},
148 $in->{'flagsrequired'},
156 # It's possible for $user to be the borrowernumber if they don't have a
157 # userid defined (and are logging in through some other method, such
158 # as SSL certs against an email address)
159 $borrowernumber = getborrowernumber($user) if defined($user);
160 if (!defined($borrowernumber) && defined($user)) {
161 my $borrower = C4::Members::GetMember(borrowernumber => $user);
163 $borrowernumber = $user;
164 # A bit of a hack, but I don't know there's a nicer way
166 $user = $borrower->{firstname} . ' ' . $borrower->{surname};
171 $template->param( loggedinusername => $user );
172 $template->param( sessionID => $sessionID );
174 my ($total, $pubshelves, $barshelves) = C4::VirtualShelves::GetSomeShelfNames($borrowernumber, 'MASTHEAD');
176 pubshelves => $total->{pubtotal},
177 pubshelvesloop => $pubshelves,
178 barshelves => $total->{bartotal},
179 barshelvesloop => $barshelves,
182 my ( $borr ) = C4::Members::GetMemberDetails( $borrowernumber );
185 $template->param( "USER_INFO" => \@bordat );
187 my $all_perms = get_all_subpermissions();
189 my @flagroots = qw(circulate catalogue parameters borrowers permissions reserveforothers borrow
190 editcatalogue updatecharges management tools editauthorities serials reports acquisition);
191 # We are going to use the $flags returned by checkauth
192 # to create the template's parameters that will indicate
193 # which menus the user can access.
194 if ( $flags && $flags->{superlibrarian}==1 ) {
195 $template->param( CAN_user_circulate => 1 );
196 $template->param( CAN_user_catalogue => 1 );
197 $template->param( CAN_user_parameters => 1 );
198 $template->param( CAN_user_borrowers => 1 );
199 $template->param( CAN_user_permissions => 1 );
200 $template->param( CAN_user_reserveforothers => 1 );
201 $template->param( CAN_user_borrow => 1 );
202 $template->param( CAN_user_editcatalogue => 1 );
203 $template->param( CAN_user_updatecharges => 1 );
204 $template->param( CAN_user_acquisition => 1 );
205 $template->param( CAN_user_management => 1 );
206 $template->param( CAN_user_tools => 1 );
207 $template->param( CAN_user_editauthorities => 1 );
208 $template->param( CAN_user_serials => 1 );
209 $template->param( CAN_user_reports => 1 );
210 $template->param( CAN_user_staffaccess => 1 );
211 $template->param( CAN_user_plugins => 1 );
212 $template->param( CAN_user_coursereserves => 1 );
213 foreach my $module (keys %$all_perms) {
214 foreach my $subperm (keys %{ $all_perms->{$module} }) {
215 $template->param( "CAN_user_${module}_${subperm}" => 1 );
221 foreach my $module (keys %$all_perms) {
222 if ( $flags->{$module} == 1) {
223 foreach my $subperm (keys %{ $all_perms->{$module} }) {
224 $template->param( "CAN_user_${module}_${subperm}" => 1 );
226 } elsif ( ref($flags->{$module}) ) {
227 foreach my $subperm (keys %{ $flags->{$module} } ) {
228 $template->param( "CAN_user_${module}_${subperm}" => 1 );
235 foreach my $module (keys %$flags) {
236 if ( $flags->{$module} == 1 or ref($flags->{$module}) ) {
237 $template->param( "CAN_user_$module" => 1 );
238 if ($module eq "parameters") {
239 $template->param( CAN_user_management => 1 );
244 # Logged-in opac search history
245 # If the requested template is an opac one and opac search history is enabled
246 if ($in->{type} eq 'opac' && C4::Context->preference('EnableOpacSearchHistory')) {
247 my $dbh = C4::Context->dbh;
248 my $query = "SELECT COUNT(*) FROM search_history WHERE userid=?";
249 my $sth = $dbh->prepare($query);
250 $sth->execute($borrowernumber);
252 # If at least one search has already been performed
253 if ($sth->fetchrow_array > 0) {
254 # We show the link in opac
255 $template->param( EnableOpacSearchHistory => 1 );
258 # And if there are searches performed when the user was not logged in,
259 # we add them to the logged-in search history
260 my @recentSearches = C4::Search::History::get_from_session({ cgi => $in->{'query'} });
261 if (@recentSearches) {
262 my $dbh = C4::Context->dbh;
264 INSERT INTO search_history(userid, sessionid, query_desc, query_cgi, type, total, time )
265 VALUES (?, ?, ?, ?, ?, ?, ?)
268 my $sth = $dbh->prepare($query);
269 $sth->execute( $borrowernumber,
270 $in->{query}->cookie("CGISESSID"),
273 $_->{type} || 'biblio',
276 ) foreach @recentSearches;
278 # clear out the search history from the session now that
279 # we've saved it to the database
280 C4::Search::History::set_to_session({ cgi => $in->{'query'}, search_history => [] });
282 } elsif ( $in->{type} eq 'intranet' and C4::Context->preference('EnableSearchHistory') ) {
283 $template->param( EnableSearchHistory => 1 );
286 else { # if this is an anonymous session, setup to display public lists...
288 $template->param( sessionID => $sessionID );
290 my ($total, $pubshelves) = C4::VirtualShelves::GetSomeShelfNames(undef, 'MASTHEAD');
292 pubshelves => $total->{pubtotal},
293 pubshelvesloop => $pubshelves,
296 # Anonymous opac search history
297 # If opac search history is enabled and at least one search has already been performed
298 if (C4::Context->preference('EnableOpacSearchHistory')) {
299 my @recentSearches = C4::Search::History::get_from_session({ cgi => $in->{'query'} });
300 if (@recentSearches) {
301 $template->param(EnableOpacSearchHistory => 1);
305 if(C4::Context->preference('dateformat')){
306 $template->param(dateformat => C4::Context->preference('dateformat'))
309 # these template parameters are set the same regardless of $in->{'type'}
311 # Set the using_https variable for templates
312 # FIXME Under Plack the CGI->https method always returns 'OFF'
313 my $https = $in->{query}->https();
314 my $using_https = (defined $https and $https ne 'OFF') ? 1 : 0;
317 "BiblioDefaultView".C4::Context->preference("BiblioDefaultView") => 1,
318 EnhancedMessagingPreferences => C4::Context->preference('EnhancedMessagingPreferences'),
319 GoogleJackets => C4::Context->preference("GoogleJackets"),
320 OpenLibraryCovers => C4::Context->preference("OpenLibraryCovers"),
321 KohaAdminEmailAddress => "" . C4::Context->preference("KohaAdminEmailAddress"),
322 LoginBranchcode => (C4::Context->userenv?C4::Context->userenv->{"branch"}:undef),
323 LoginFirstname => (C4::Context->userenv?C4::Context->userenv->{"firstname"}:"Bel"),
324 LoginSurname => C4::Context->userenv?C4::Context->userenv->{"surname"}:"Inconnu",
325 emailaddress => C4::Context->userenv?C4::Context->userenv->{"emailaddress"}:undef,
326 loggedinpersona => C4::Context->userenv?C4::Context->userenv->{"persona"}:undef,
327 TagsEnabled => C4::Context->preference("TagsEnabled"),
328 hide_marc => C4::Context->preference("hide_marc"),
329 item_level_itypes => C4::Context->preference('item-level_itypes'),
330 patronimages => C4::Context->preference("patronimages"),
331 singleBranchMode => C4::Context->preference("singleBranchMode"),
332 XSLTDetailsDisplay => C4::Context->preference("XSLTDetailsDisplay"),
333 XSLTResultsDisplay => C4::Context->preference("XSLTResultsDisplay"),
334 using_https => $using_https,
335 noItemTypeImages => C4::Context->preference("noItemTypeImages"),
336 marcflavour => C4::Context->preference("marcflavour"),
337 persona => C4::Context->preference("persona"),
339 if ( $in->{'type'} eq "intranet" ) {
341 AmazonCoverImages => C4::Context->preference("AmazonCoverImages"),
342 AutoLocation => C4::Context->preference("AutoLocation"),
343 "BiblioDefaultView".C4::Context->preference("IntranetBiblioDefaultView") => 1,
344 CalendarFirstDayOfWeek => (C4::Context->preference("CalendarFirstDayOfWeek") eq "Sunday")?0:1,
345 CircAutocompl => C4::Context->preference("CircAutocompl"),
346 FRBRizeEditions => C4::Context->preference("FRBRizeEditions"),
347 IndependentBranches => C4::Context->preference("IndependentBranches"),
348 IntranetNav => C4::Context->preference("IntranetNav"),
349 IntranetmainUserblock => C4::Context->preference("IntranetmainUserblock"),
350 LibraryName => C4::Context->preference("LibraryName"),
351 LoginBranchname => (C4::Context->userenv?C4::Context->userenv->{"branchname"}:undef),
352 advancedMARCEditor => C4::Context->preference("advancedMARCEditor"),
353 canreservefromotherbranches => C4::Context->preference('canreservefromotherbranches'),
354 intranetcolorstylesheet => C4::Context->preference("intranetcolorstylesheet"),
355 IntranetFavicon => C4::Context->preference("IntranetFavicon"),
356 intranetreadinghistory => C4::Context->preference("intranetreadinghistory"),
357 intranetstylesheet => C4::Context->preference("intranetstylesheet"),
358 IntranetUserCSS => C4::Context->preference("IntranetUserCSS"),
359 intranetuserjs => C4::Context->preference("intranetuserjs"),
360 intranetbookbag => C4::Context->preference("intranetbookbag"),
361 suggestion => C4::Context->preference("suggestion"),
362 virtualshelves => C4::Context->preference("virtualshelves"),
363 StaffSerialIssueDisplayCount => C4::Context->preference("StaffSerialIssueDisplayCount"),
364 EasyAnalyticalRecords => C4::Context->preference('EasyAnalyticalRecords'),
365 LocalCoverImages => C4::Context->preference('LocalCoverImages'),
366 OPACLocalCoverImages => C4::Context->preference('OPACLocalCoverImages'),
367 AllowMultipleCovers => C4::Context->preference('AllowMultipleCovers'),
368 EnableBorrowerFiles => C4::Context->preference('EnableBorrowerFiles'),
369 UseKohaPlugins => C4::Context->preference('UseKohaPlugins'),
370 UseCourseReserves => C4::Context->preference("UseCourseReserves"),
374 warn "template type should be OPAC, here it is=[" . $in->{'type'} . "]" unless ( $in->{'type'} eq 'opac' );
375 #TODO : replace LibraryName syspref with 'system name', and remove this html processing
376 my $LibraryNameTitle = C4::Context->preference("LibraryName");
377 $LibraryNameTitle =~ s/<(?:\/?)(?:br|p)\s*(?:\/?)>/ /sgi;
378 $LibraryNameTitle =~ s/<(?:[^<>'"]|'(?:[^']*)'|"(?:[^"]*)")*>//sg;
379 # clean up the busc param in the session if the page is not opac-detail and not the "add to list" page
380 if ( C4::Context->preference("OpacBrowseResults")
381 && $in->{'template_name'} =~ /opac-(.+)\.(?:tt|tmpl)$/ ) {
383 unless ( $pagename =~ /^(?:MARC|ISBD)?detail$/
384 or $pagename =~ /^addbybiblionumber$/ ) {
385 my $sessionSearch = get_session($sessionID || $in->{'query'}->cookie("CGISESSID"));
386 $sessionSearch->clear(["busc"]) if ($sessionSearch->param("busc"));
389 # variables passed from CGI: opac_css_override and opac_search_limits.
390 my $opac_search_limit = $ENV{'OPAC_SEARCH_LIMIT'};
391 my $opac_limit_override = $ENV{'OPAC_LIMIT_OVERRIDE'};
393 if (($opac_search_limit && $opac_search_limit =~ /branch:(\w+)/ && $opac_limit_override) || ($in->{'query'}->param('limit') && $in->{'query'}->param('limit') =~ /branch:(\w+)/)){
394 $opac_name = $1; # opac_search_limit is a branch, so we use it.
395 } elsif ( $in->{'query'}->param('multibranchlimit') ) {
396 $opac_name = $in->{'query'}->param('multibranchlimit');
397 } elsif (C4::Context->preference("SearchMyLibraryFirst") && C4::Context->userenv && C4::Context->userenv->{'branch'}) {
398 $opac_name = C4::Context->userenv->{'branch'};
401 opaccolorstylesheet => C4::Context->preference("opaccolorstylesheet"),
402 AnonSuggestions => "" . C4::Context->preference("AnonSuggestions"),
403 AuthorisedValueImages => C4::Context->preference("AuthorisedValueImages"),
404 BranchesLoop => GetBranchesLoop($opac_name),
405 BranchCategoriesLoop => GetBranchCategories( 'searchdomain', 1, $opac_name ),
406 CalendarFirstDayOfWeek => (C4::Context->preference("CalendarFirstDayOfWeek") eq "Sunday")?0:1,
407 LibraryName => "" . C4::Context->preference("LibraryName"),
408 LibraryNameTitle => "" . $LibraryNameTitle,
409 LoginBranchname => C4::Context->userenv?C4::Context->userenv->{"branchname"}:"",
410 OPACAmazonCoverImages => C4::Context->preference("OPACAmazonCoverImages"),
411 OPACFRBRizeEditions => C4::Context->preference("OPACFRBRizeEditions"),
412 OpacHighlightedWords => C4::Context->preference("OpacHighlightedWords"),
413 OPACItemHolds => C4::Context->preference("OPACItemHolds"),
414 OPACShelfBrowser => "". C4::Context->preference("OPACShelfBrowser"),
415 OPACURLOpenInNewWindow => "" . C4::Context->preference("OPACURLOpenInNewWindow"),
416 OPACUserCSS => "". C4::Context->preference("OPACUserCSS"),
417 OPACMobileUserCSS => "". C4::Context->preference("OPACMobileUserCSS"),
418 OPACViewOthersSuggestions => "" . C4::Context->preference("OPACViewOthersSuggestions"),
419 OpacAuthorities => C4::Context->preference("OpacAuthorities"),
420 OPACBaseURL => ($in->{'query'}->https() ? "https://" : "http://") . $ENV{'SERVER_NAME'} .
421 ($ENV{'SERVER_PORT'} eq ($in->{'query'}->https() ? "443" : "80") ? '' : ":$ENV{'SERVER_PORT'}"),
422 opac_css_override => $ENV{'OPAC_CSS_OVERRIDE'},
423 opac_search_limit => $opac_search_limit,
424 opac_limit_override => $opac_limit_override,
425 OpacBrowser => C4::Context->preference("OpacBrowser"),
426 OpacCloud => C4::Context->preference("OpacCloud"),
427 OpacKohaUrl => C4::Context->preference("OpacKohaUrl"),
428 OpacMainUserBlock => "" . C4::Context->preference("OpacMainUserBlock"),
429 OpacMainUserBlockMobile => "" . C4::Context->preference("OpacMainUserBlockMobile"),
430 OpacShowFiltersPulldownMobile => C4::Context->preference("OpacShowFiltersPulldownMobile"),
431 OpacShowLibrariesPulldownMobile => C4::Context->preference("OpacShowLibrariesPulldownMobile"),
432 OpacNav => "" . C4::Context->preference("OpacNav"),
433 OpacNavRight => "" . C4::Context->preference("OpacNavRight"),
434 OpacNavBottom => "" . C4::Context->preference("OpacNavBottom"),
435 OpacPasswordChange => C4::Context->preference("OpacPasswordChange"),
436 OPACPatronDetails => C4::Context->preference("OPACPatronDetails"),
437 OPACPrivacy => C4::Context->preference("OPACPrivacy"),
438 OPACFinesTab => C4::Context->preference("OPACFinesTab"),
439 OpacTopissue => C4::Context->preference("OpacTopissue"),
440 RequestOnOpac => C4::Context->preference("RequestOnOpac"),
441 'Version' => C4::Context->preference('Version'),
442 hidelostitems => C4::Context->preference("hidelostitems"),
443 mylibraryfirst => (C4::Context->preference("SearchMyLibraryFirst") && C4::Context->userenv) ? C4::Context->userenv->{'branch'} : '',
444 opaclayoutstylesheet => "" . C4::Context->preference("opaclayoutstylesheet"),
445 opacbookbag => "" . C4::Context->preference("opacbookbag"),
446 opaccredits => "" . C4::Context->preference("opaccredits"),
447 OpacFavicon => C4::Context->preference("OpacFavicon"),
448 opacheader => "" . C4::Context->preference("opacheader"),
449 opaclanguagesdisplay => "" . C4::Context->preference("opaclanguagesdisplay"),
450 opacreadinghistory => C4::Context->preference("opacreadinghistory"),
451 opacsmallimage => "" . C4::Context->preference("opacsmallimage"),
452 opacuserjs => C4::Context->preference("opacuserjs"),
453 opacuserlogin => "" . C4::Context->preference("opacuserlogin"),
454 ShowReviewer => C4::Context->preference("ShowReviewer"),
455 ShowReviewerPhoto => C4::Context->preference("ShowReviewerPhoto"),
456 suggestion => "" . C4::Context->preference("suggestion"),
457 virtualshelves => "" . C4::Context->preference("virtualshelves"),
458 OPACSerialIssueDisplayCount => C4::Context->preference("OPACSerialIssueDisplayCount"),
459 OPACXSLTDetailsDisplay => C4::Context->preference("OPACXSLTDetailsDisplay"),
460 OPACXSLTResultsDisplay => C4::Context->preference("OPACXSLTResultsDisplay"),
461 SyndeticsClientCode => C4::Context->preference("SyndeticsClientCode"),
462 SyndeticsEnabled => C4::Context->preference("SyndeticsEnabled"),
463 SyndeticsCoverImages => C4::Context->preference("SyndeticsCoverImages"),
464 SyndeticsTOC => C4::Context->preference("SyndeticsTOC"),
465 SyndeticsSummary => C4::Context->preference("SyndeticsSummary"),
466 SyndeticsEditions => C4::Context->preference("SyndeticsEditions"),
467 SyndeticsExcerpt => C4::Context->preference("SyndeticsExcerpt"),
468 SyndeticsReviews => C4::Context->preference("SyndeticsReviews"),
469 SyndeticsAuthorNotes => C4::Context->preference("SyndeticsAuthorNotes"),
470 SyndeticsAwards => C4::Context->preference("SyndeticsAwards"),
471 SyndeticsSeries => C4::Context->preference("SyndeticsSeries"),
472 SyndeticsCoverImageSize => C4::Context->preference("SyndeticsCoverImageSize"),
473 OPACLocalCoverImages => C4::Context->preference("OPACLocalCoverImages"),
474 PatronSelfRegistration => C4::Context->preference("PatronSelfRegistration"),
475 PatronSelfRegistrationDefaultCategory => C4::Context->preference("PatronSelfRegistrationDefaultCategory"),
478 $template->param(OpacPublic => '1') if ($user || C4::Context->preference("OpacPublic"));
481 # Check if we were asked using parameters to force a specific language
482 if ( defined $in->{'query'}->param('language') ) {
483 # Extract the language, let C4::Templates::getlanguage choose
485 my $language = C4::Templates::getlanguage($in->{'query'},$in->{'type'});
486 my $languagecookie = C4::Templates::getlanguagecookie($in->{'query'},$language);
487 if ( ref $cookie eq 'ARRAY' ) {
488 push @{ $cookie }, $languagecookie;
490 $cookie = [$cookie, $languagecookie];
494 return ( $template, $borrowernumber, $cookie, $flags);
499 ($userid, $cookie, $sessionID) = &checkauth($query, $noauth, $flagsrequired, $type);
501 Verifies that the user is authorized to run this script. If
502 the user is authorized, a (userid, cookie, session-id, flags)
503 quadruple is returned. If the user is not authorized but does
504 not have the required privilege (see $flagsrequired below), it
505 displays an error page and exits. Otherwise, it displays the
506 login page and exits.
508 Note that C<&checkauth> will return if and only if the user
509 is authorized, so it should be called early on, before any
510 unfinished operations (e.g., if you've opened a file, then
511 C<&checkauth> won't close it for you).
513 C<$query> is the CGI object for the script calling C<&checkauth>.
515 The C<$noauth> argument is optional. If it is set, then no
516 authorization is required for the script.
518 C<&checkauth> fetches user and session information from C<$query> and
519 ensures that the user is authorized to run scripts that require
522 The C<$flagsrequired> argument specifies the required privileges
523 the user must have if the username and password are correct.
524 It should be specified as a reference-to-hash; keys in the hash
525 should be the "flags" for the user, as specified in the Members
526 intranet module. Any key specified must correspond to a "flag"
527 in the userflags table. E.g., { circulate => 1 } would specify
528 that the user must have the "circulate" privilege in order to
529 proceed. To make sure that access control is correct, the
530 C<$flagsrequired> parameter must be specified correctly.
532 Koha also has a concept of sub-permissions, also known as
533 granular permissions. This makes the value of each key
534 in the C<flagsrequired> hash take on an additional
539 The user must have access to all subfunctions of the module
540 specified by the hash key.
544 The user must have access to at least one subfunction of the module
545 specified by the hash key.
547 specific permission, e.g., 'export_catalog'
549 The user must have access to the specific subfunction list, which
550 must correspond to a row in the permissions table.
552 The C<$type> argument specifies whether the template should be
553 retrieved from the opac or intranet directory tree. "opac" is
554 assumed if it is not specified; however, if C<$type> is specified,
555 "intranet" is assumed if it is not "opac".
557 If C<$query> does not have a valid session ID associated with it
558 (i.e., the user has not logged in) or if the session has expired,
559 C<&checkauth> presents the user with a login page (from the point of
560 view of the original script, C<&checkauth> does not return). Once the
561 user has authenticated, C<&checkauth> restarts the original script
562 (this time, C<&checkauth> returns).
564 The login page is provided using a HTML::Template, which is set in the
565 systempreferences table or at the top of this file. The variable C<$type>
566 selects which template to use, either the opac or the intranet
567 authentification template.
569 C<&checkauth> returns a user ID, a cookie, and a session ID. The
570 cookie should be sent back to the browser; it verifies that the user
579 # If Version syspref is unavailable, it means Koha is beeing installed,
580 # and so we must redirect to OPAC maintenance page or to the WebInstaller
581 # also, if OpacMaintenance is ON, OPAC should redirect to maintenance
582 if (C4::Context->preference('OpacMaintenance') && $type eq 'opac') {
583 warn "OPAC Install required, redirecting to maintenance";
584 print $query->redirect("/cgi-bin/koha/maintenance.pl");
587 unless ( $version = C4::Context->preference('Version') ) { # assignment, not comparison
588 if ( $type ne 'opac' ) {
589 warn "Install required, redirecting to Installer";
590 print $query->redirect("/cgi-bin/koha/installer/install.pl");
592 warn "OPAC Install required, redirecting to maintenance";
593 print $query->redirect("/cgi-bin/koha/maintenance.pl");
598 # check that database and koha version are the same
599 # there is no DB version, it's a fresh install,
600 # go to web installer
601 # there is a DB version, compare it to the code version
602 my $kohaversion=C4::Context::KOHAVERSION;
603 # remove the 3 last . to have a Perl number
604 $kohaversion =~ s/(.*\..*)\.(.*)\.(.*)/$1$2$3/;
605 $debug and print STDERR "kohaversion : $kohaversion\n";
606 if ($version < $kohaversion){
607 my $warning = "Database update needed, redirecting to %s. Database is $version and Koha is $kohaversion";
608 if ($type ne 'opac'){
609 warn sprintf($warning, 'Installer');
610 print $query->redirect("/cgi-bin/koha/installer/install.pl?step=3");
612 warn sprintf("OPAC: " . $warning, 'maintenance');
613 print $query->redirect("/cgi-bin/koha/maintenance.pl");
621 open my $fh, '>>', "/tmp/sessionlog" or warn "ERROR: Cannot append to /tmp/sessionlog";
622 printf $fh join("\n",@_);
626 sub _timeout_syspref {
627 my $timeout = C4::Context->preference('timeout') || 600;
628 # value in days, convert in seconds
629 if ($timeout =~ /(\d+)[dD]/) {
630 $timeout = $1 * 86400;
637 $debug and warn "Checking Auth";
638 # $authnotrequired will be set for scripts which will run without authentication
639 my $authnotrequired = shift;
640 my $flagsrequired = shift;
643 $type = 'opac' unless $type;
645 my $dbh = C4::Context->dbh;
646 my $timeout = _timeout_syspref();
648 _version_check($type,$query);
652 my ( $userid, $cookie, $sessionID, $flags, $barshelves, $pubshelves );
653 my $logout = $query->param('logout.x');
655 my $anon_search_history;
657 # This parameter is the name of the CAS server we want to authenticate against,
658 # when using authentication against multiple CAS servers, as configured in Auth_cas_servers.yaml
659 my $casparam = $query->param('cas');
660 my $q_userid = $query->param('userid') // '';
662 if ( $userid = $ENV{'REMOTE_USER'} ) {
663 # Using Basic Authentication, no cookies required
664 $cookie = $query->cookie(
665 -name => 'CGISESSID',
673 # we dont want to set a session because we are being called by a persona callback
675 elsif ( $sessionID = $query->cookie("CGISESSID") )
676 { # assignment, not comparison
677 my $session = get_session($sessionID);
678 C4::Context->_new_userenv($sessionID);
679 my ($ip, $lasttime, $sessiontype);
682 $s_userid = $session->param('id') // '';
683 C4::Context::set_userenv(
684 $session->param('number'), $s_userid,
685 $session->param('cardnumber'), $session->param('firstname'),
686 $session->param('surname'), $session->param('branch'),
687 $session->param('branchname'), $session->param('flags'),
688 $session->param('emailaddress'), $session->param('branchprinter'),
689 $session->param('persona')
691 C4::Context::set_shelves_userenv('bar',$session->param('barshelves'));
692 C4::Context::set_shelves_userenv('pub',$session->param('pubshelves'));
693 C4::Context::set_shelves_userenv('tot',$session->param('totshelves'));
694 $debug and printf STDERR "AUTH_SESSION: (%s)\t%s %s - %s\n", map {$session->param($_)} qw(cardnumber firstname surname branch) ;
695 $ip = $session->param('ip');
696 $lasttime = $session->param('lasttime');
698 $sessiontype = $session->param('sessiontype') || '';
700 if ( ( $query->param('koha_login_context') && ($q_userid ne $s_userid) )
701 || ( $cas && $query->param('ticket') ) ) {
702 #if a user enters an id ne to the id in the current session, we need to log them in...
703 #first we need to clear the anonymous session...
704 $debug and warn "query id = $q_userid but session id = $s_userid";
705 $anon_search_history = $session->param('search_history');
708 C4::Context->_unset_userenv($sessionID);
713 # voluntary logout the user
716 C4::Context->_unset_userenv($sessionID);
717 #_session_log(sprintf "%20s from %16s logged out at %30s (manually).\n", $userid,$ip,(strftime "%c",localtime));
721 if ($cas and $caslogout) {
725 elsif ( !$lasttime || ($lasttime < time() - $timeout) ) {
727 $info{'timed_out'} = 1;
732 C4::Context->_unset_userenv($sessionID);
733 #_session_log(sprintf "%20s from %16s logged out at %30s (inactivity).\n", $userid,$ip,(strftime "%c",localtime));
737 elsif ( $ip ne $ENV{'REMOTE_ADDR'} ) {
738 # Different ip than originally logged in from
739 $info{'oldip'} = $ip;
740 $info{'newip'} = $ENV{'REMOTE_ADDR'};
741 $info{'different_ip'} = 1;
744 C4::Context->_unset_userenv($sessionID);
745 #_session_log(sprintf "%20s from %16s logged out at %30s (ip changed to %16s).\n", $userid,$ip,(strftime "%c",localtime), $info{'newip'});
750 $cookie = $query->cookie(
751 -name => 'CGISESSID',
752 -value => $session->id,
755 $session->param( 'lasttime', time() );
756 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...
757 $flags = haspermission($userid, $flagsrequired);
761 $info{'nopermission'} = 1;
766 unless ($userid || $sessionID) {
768 #we initiate a session prior to checking for a username to allow for anonymous sessions...
769 my $session = get_session("") or die "Auth ERROR: Cannot get_session()";
771 # Save anonymous search history in new session so it can be retrieved
772 # by get_template_and_user to store it in user's search history after
773 # a successful login.
774 if ($anon_search_history) {
775 $session->param('search_history', $anon_search_history);
778 my $sessionID = $session->id;
779 C4::Context->_new_userenv($sessionID);
780 $cookie = $query->cookie(
781 -name => 'CGISESSID',
782 -value => $session->id,
786 my $pki_field = C4::Context->preference('AllowPKIAuth');
787 if (! defined($pki_field) ) {
788 print STDERR "ERROR: Missing system preference AllowPKIAuth.\n";
791 if ( ( $cas && $query->param('ticket') )
793 || $pki_field ne 'None'
796 my $password = $query->param('password');
798 my ( $return, $cardnumber );
799 if ( $cas && $query->param('ticket') ) {
801 ( $return, $cardnumber, $retuserid ) =
802 checkpw( $dbh, $userid, $password, $query );
803 $userid = $retuserid;
804 $info{'invalidCasLogin'} = 1 unless ($return);
808 my $value = $persona;
810 # If we're looking up the email, there's a chance that the person
811 # doesn't have a userid. So if there is none, we pass along the
812 # borrower number, and the bits of code that need to know the user
813 # ID will have to be smart enough to handle that.
815 my @users_info = C4::Members::GetBorrowersWithEmail($value);
818 # First the userid, then the borrowernum
819 $value = $users_info[0][1] || $users_info[0][0];
824 $return = $value ? 1 : 0;
829 ( $pki_field eq 'Common Name' && $ENV{'SSL_CLIENT_S_DN_CN'} )
830 || ( $pki_field eq 'emailAddress'
831 && $ENV{'SSL_CLIENT_S_DN_Email'} )
835 if ( $pki_field eq 'Common Name' ) {
836 $value = $ENV{'SSL_CLIENT_S_DN_CN'};
838 elsif ( $pki_field eq 'emailAddress' ) {
839 $value = $ENV{'SSL_CLIENT_S_DN_Email'};
841 # If we're looking up the email, there's a chance that the person
842 # doesn't have a userid. So if there is none, we pass along the
843 # borrower number, and the bits of code that need to know the user
844 # ID will have to be smart enough to handle that.
846 my @users_info = C4::Members::GetBorrowersWithEmail($value);
849 # First the userid, then the borrowernum
850 $value = $users_info[0][1] || $users_info[0][0];
857 $return = $value ? 1 : 0;
863 ( $return, $cardnumber, $retuserid ) =
864 checkpw( $dbh, $userid, $password, $query );
865 $userid = $retuserid if ( $retuserid );
868 #_session_log(sprintf "%20s from %16s logged in at %30s.\n", $userid,$ENV{'REMOTE_ADDR'},(strftime '%c', localtime));
869 if ( $flags = haspermission( $userid, $flagsrequired ) ) {
873 $info{'nopermission'} = 1;
874 C4::Context->_unset_userenv($sessionID);
876 my ($borrowernumber, $firstname, $surname, $userflags,
877 $branchcode, $branchname, $branchprinter, $emailaddress);
879 if ( $return == 1 ) {
881 SELECT borrowernumber, firstname, surname, flags, borrowers.branchcode,
882 branches.branchname as branchname,
883 branches.branchprinter as branchprinter,
886 LEFT JOIN branches on borrowers.branchcode=branches.branchcode
888 my $sth = $dbh->prepare("$select where userid=?");
889 $sth->execute($userid);
890 unless ($sth->rows) {
891 $debug and print STDERR "AUTH_1: no rows for userid='$userid'\n";
892 $sth = $dbh->prepare("$select where cardnumber=?");
893 $sth->execute($cardnumber);
895 unless ($sth->rows) {
896 $debug and print STDERR "AUTH_2a: no rows for cardnumber='$cardnumber'\n";
897 $sth->execute($userid);
898 unless ($sth->rows) {
899 $debug and print STDERR "AUTH_2b: no rows for userid='$userid' AS cardnumber\n";
904 ($borrowernumber, $firstname, $surname, $userflags,
905 $branchcode, $branchname, $branchprinter, $emailaddress) = $sth->fetchrow;
906 $debug and print STDERR "AUTH_3 results: " .
907 "$cardnumber,$borrowernumber,$userid,$firstname,$surname,$userflags,$branchcode,$emailaddress\n";
909 print STDERR "AUTH_3: no results for userid='$userid', cardnumber='$cardnumber'.\n";
912 # launch a sequence to check if we have a ip for the branch, i
913 # if we have one we replace the branchcode of the userenv by the branch bound in the ip.
915 my $ip = $ENV{'REMOTE_ADDR'};
916 # if they specify at login, use that
917 if ($query->param('branch')) {
918 $branchcode = $query->param('branch');
919 $branchname = GetBranchName($branchcode);
921 my $branches = GetBranches();
922 if (C4::Context->boolean_preference('IndependentBranches') && C4::Context->boolean_preference('Autolocation')){
923 # we have to check they are coming from the right ip range
924 my $domain = $branches->{$branchcode}->{'branchip'};
925 if ($ip !~ /^$domain/){
927 $info{'wrongip'} = 1;
932 foreach my $br ( keys %$branches ) {
933 # now we work with the treatment of ip
934 my $domain = $branches->{$br}->{'branchip'};
935 if ( $domain && $ip =~ /^$domain/ ) {
936 $branchcode = $branches->{$br}->{'branchcode'};
938 # new op dev : add the branchprinter and branchname in the cookie
939 $branchprinter = $branches->{$br}->{'branchprinter'};
940 $branchname = $branches->{$br}->{'branchname'};
943 $session->param('number',$borrowernumber);
944 $session->param('id',$userid);
945 $session->param('cardnumber',$cardnumber);
946 $session->param('firstname',$firstname);
947 $session->param('surname',$surname);
948 $session->param('branch',$branchcode);
949 $session->param('branchname',$branchname);
950 $session->param('flags',$userflags);
951 $session->param('emailaddress',$emailaddress);
952 $session->param('ip',$session->remote_addr());
953 $session->param('lasttime',time());
954 $debug and printf STDERR "AUTH_4: (%s)\t%s %s - %s\n", map {$session->param($_)} qw(cardnumber firstname surname branch) ;
956 elsif ( $return == 2 ) {
957 #We suppose the user is the superlibrarian
959 $session->param('number',0);
960 $session->param('id',C4::Context->config('user'));
961 $session->param('cardnumber',C4::Context->config('user'));
962 $session->param('firstname',C4::Context->config('user'));
963 $session->param('surname',C4::Context->config('user'));
964 $session->param('branch','NO_LIBRARY_SET');
965 $session->param('branchname','NO_LIBRARY_SET');
966 $session->param('flags',1);
967 $session->param('emailaddress', C4::Context->preference('KohaAdminEmailAddress'));
968 $session->param('ip',$session->remote_addr());
969 $session->param('lasttime',time());
972 $session->param('persona',1);
974 C4::Context::set_userenv(
975 $session->param('number'), $session->param('id'),
976 $session->param('cardnumber'), $session->param('firstname'),
977 $session->param('surname'), $session->param('branch'),
978 $session->param('branchname'), $session->param('flags'),
979 $session->param('emailaddress'), $session->param('branchprinter'),
980 $session->param('persona')
986 $info{'invalid_username_or_password'} = 1;
987 C4::Context->_unset_userenv($sessionID);
989 $session->param('lasttime',time());
990 $session->param('ip',$session->remote_addr());
992 } # END if ( $userid = $query->param('userid') )
993 elsif ($type eq "opac") {
994 # if we are here this is an anonymous session; add public lists to it and a few other items...
995 # anonymous sessions are created only for the OPAC
996 $debug and warn "Initiating an anonymous session...";
998 # setting a couple of other session vars...
999 $session->param('ip',$session->remote_addr());
1000 $session->param('lasttime',time());
1001 $session->param('sessiontype','anon');
1003 } # END unless ($userid)
1005 # finished authentification, now respond
1006 if ( $loggedin || $authnotrequired )
1010 $cookie = $query->cookie(
1011 -name => 'CGISESSID',
1016 return ( $userid, $cookie, $sessionID, $flags );
1021 # AUTH rejected, show the login/password template, after checking the DB.
1025 # get the inputs from the incoming query
1027 foreach my $name ( param $query) {
1028 (next) if ( $name eq 'userid' || $name eq 'password' || $name eq 'ticket' );
1029 my $value = $query->param($name);
1030 push @inputs, { name => $name, value => $value };
1033 my $LibraryNameTitle = C4::Context->preference("LibraryName");
1034 $LibraryNameTitle =~ s/<(?:\/?)(?:br|p)\s*(?:\/?)>/ /sgi;
1035 $LibraryNameTitle =~ s/<(?:[^<>'"]|'(?:[^']*)'|"(?:[^"]*)")*>//sg;
1037 my $template_name = ( $type eq 'opac' ) ? 'opac-auth.tmpl' : 'auth.tmpl';
1038 my $template = C4::Templates::gettemplate($template_name, $type, $query );
1040 branchloop => GetBranchesLoop(),
1041 opaccolorstylesheet => C4::Context->preference("opaccolorstylesheet"),
1042 opaclayoutstylesheet => C4::Context->preference("opaclayoutstylesheet"),
1045 casAuthentication => C4::Context->preference("casAuthentication"),
1046 suggestion => C4::Context->preference("suggestion"),
1047 virtualshelves => C4::Context->preference("virtualshelves"),
1048 LibraryName => "" . C4::Context->preference("LibraryName"),
1049 LibraryNameTitle => "" . $LibraryNameTitle,
1050 opacuserlogin => C4::Context->preference("opacuserlogin"),
1051 OpacNav => C4::Context->preference("OpacNav"),
1052 OpacNavRight => C4::Context->preference("OpacNavRight"),
1053 OpacNavBottom => C4::Context->preference("OpacNavBottom"),
1054 opaccredits => C4::Context->preference("opaccredits"),
1055 OpacFavicon => C4::Context->preference("OpacFavicon"),
1056 opacreadinghistory => C4::Context->preference("opacreadinghistory"),
1057 opacsmallimage => C4::Context->preference("opacsmallimage"),
1058 opaclanguagesdisplay => C4::Context->preference("opaclanguagesdisplay"),
1059 opacuserjs => C4::Context->preference("opacuserjs"),
1060 opacbookbag => "" . C4::Context->preference("opacbookbag"),
1061 OpacCloud => C4::Context->preference("OpacCloud"),
1062 OpacTopissue => C4::Context->preference("OpacTopissue"),
1063 OpacAuthorities => C4::Context->preference("OpacAuthorities"),
1064 OpacBrowser => C4::Context->preference("OpacBrowser"),
1065 opacheader => C4::Context->preference("opacheader"),
1066 TagsEnabled => C4::Context->preference("TagsEnabled"),
1067 OPACUserCSS => C4::Context->preference("OPACUserCSS"),
1068 intranetcolorstylesheet => C4::Context->preference("intranetcolorstylesheet"),
1069 intranetstylesheet => C4::Context->preference("intranetstylesheet"),
1070 intranetbookbag => C4::Context->preference("intranetbookbag"),
1071 IntranetNav => C4::Context->preference("IntranetNav"),
1072 IntranetFavicon => C4::Context->preference("IntranetFavicon"),
1073 intranetuserjs => C4::Context->preference("intranetuserjs"),
1074 IndependentBranches=> C4::Context->preference("IndependentBranches"),
1075 AutoLocation => C4::Context->preference("AutoLocation"),
1076 wrongip => $info{'wrongip'},
1077 PatronSelfRegistration => C4::Context->preference("PatronSelfRegistration"),
1078 PatronSelfRegistrationDefaultCategory => C4::Context->preference("PatronSelfRegistrationDefaultCategory"),
1079 persona => C4::Context->preference("Persona"),
1080 opac_css_override => $ENV{'OPAC_CSS_OVERRIDE'},
1083 $template->param( OpacPublic => C4::Context->preference("OpacPublic"));
1084 $template->param( loginprompt => 1 ) unless $info{'nopermission'};
1086 if($type eq 'opac'){
1087 my ($total, $pubshelves) = C4::VirtualShelves::GetSomeShelfNames(undef, 'MASTHEAD');
1089 pubshelves => $total->{pubtotal},
1090 pubshelvesloop => $pubshelves,
1096 # Is authentication against multiple CAS servers enabled?
1097 if (C4::Auth_with_cas::multipleAuth && !$casparam) {
1098 my $casservers = C4::Auth_with_cas::getMultipleAuth();
1100 foreach my $key (keys %$casservers) {
1101 push @tmplservers, {name => $key, value => login_cas_url($query, $key) . "?cas=$key" };
1104 casServersLoop => \@tmplservers
1108 casServerUrl => login_cas_url($query),
1113 invalidCasLogin => $info{'invalidCasLogin'}
1117 my $self_url = $query->url( -absolute => 1 );
1120 LibraryName => C4::Context->preference("LibraryName"),
1122 $template->param( %info );
1123 # $cookie = $query->cookie(CGISESSID => $session->id
1125 print $query->header(
1126 -type => 'text/html',
1127 -charset => 'utf-8',
1134 =head2 check_api_auth
1136 ($status, $cookie, $sessionId) = check_api_auth($query, $userflags);
1138 Given a CGI query containing the parameters 'userid' and 'password' and/or a session
1139 cookie, determine if the user has the privileges specified by C<$userflags>.
1141 C<check_api_auth> is is meant for authenticating users of web services, and
1142 consequently will always return and will not attempt to redirect the user
1145 If a valid session cookie is already present, check_api_auth will return a status
1146 of "ok", the cookie, and the Koha session ID.
1148 If no session cookie is present, check_api_auth will check the 'userid' and 'password
1149 parameters and create a session cookie and Koha session if the supplied credentials
1152 Possible return values in C<$status> are:
1156 =item "ok" -- user authenticated; C<$cookie> and C<$sessionid> have valid values.
1158 =item "failed" -- credentials are not correct; C<$cookie> and C<$sessionid> are undef
1160 =item "maintenance" -- DB is in maintenance mode; no login possible at the moment
1162 =item "expired -- session cookie has expired; API user should resubmit userid and password
1168 sub check_api_auth {
1170 my $flagsrequired = shift;
1172 my $dbh = C4::Context->dbh;
1173 my $timeout = _timeout_syspref();
1175 unless (C4::Context->preference('Version')) {
1176 # database has not been installed yet
1177 return ("maintenance", undef, undef);
1179 my $kohaversion=C4::Context::KOHAVERSION;
1180 $kohaversion =~ s/(.*\..*)\.(.*)\.(.*)/$1$2$3/;
1181 if (C4::Context->preference('Version') < $kohaversion) {
1182 # database in need of version update; assume that
1183 # no API should be called while databsae is in
1185 return ("maintenance", undef, undef);
1188 # FIXME -- most of what follows is a copy-and-paste
1189 # of code from checkauth. There is an obvious need
1190 # for refactoring to separate the various parts of
1191 # the authentication code, but as of 2007-11-19 this
1192 # is deferred so as to not introduce bugs into the
1193 # regular authentication code for Koha 3.0.
1195 # see if we have a valid session cookie already
1196 # however, if a userid parameter is present (i.e., from
1197 # a form submission, assume that any current cookie
1199 my $sessionID = undef;
1200 unless ($query->param('userid')) {
1201 $sessionID = $query->cookie("CGISESSID");
1203 if ($sessionID && not ($cas && $query->param('PT')) ) {
1204 my $session = get_session($sessionID);
1205 C4::Context->_new_userenv($sessionID);
1207 C4::Context::set_userenv(
1208 $session->param('number'), $session->param('id'),
1209 $session->param('cardnumber'), $session->param('firstname'),
1210 $session->param('surname'), $session->param('branch'),
1211 $session->param('branchname'), $session->param('flags'),
1212 $session->param('emailaddress'), $session->param('branchprinter')
1215 my $ip = $session->param('ip');
1216 my $lasttime = $session->param('lasttime');
1217 my $userid = $session->param('id');
1218 if ( $lasttime < time() - $timeout ) {
1222 C4::Context->_unset_userenv($sessionID);
1225 return ("expired", undef, undef);
1226 } elsif ( $ip ne $ENV{'REMOTE_ADDR'} ) {
1227 # IP address changed
1230 C4::Context->_unset_userenv($sessionID);
1233 return ("expired", undef, undef);
1235 my $cookie = $query->cookie(
1236 -name => 'CGISESSID',
1237 -value => $session->id,
1240 $session->param('lasttime',time());
1241 my $flags = haspermission($userid, $flagsrequired);
1243 return ("ok", $cookie, $sessionID);
1247 C4::Context->_unset_userenv($sessionID);
1250 return ("failed", undef, undef);
1254 return ("expired", undef, undef);
1258 my $userid = $query->param('userid');
1259 my $password = $query->param('password');
1260 my ($return, $cardnumber);
1263 if ($cas && $query->param('PT')) {
1265 $debug and print STDERR "## check_api_auth - checking CAS\n";
1266 # In case of a CAS authentication, we use the ticket instead of the password
1267 my $PT = $query->param('PT');
1268 ($return,$cardnumber,$userid) = check_api_auth_cas($dbh, $PT, $query); # EXTERNAL AUTH
1270 # User / password auth
1271 unless ($userid and $password) {
1272 # caller did something wrong, fail the authenticateion
1273 return ("failed", undef, undef);
1275 ( $return, $cardnumber ) = checkpw( $dbh, $userid, $password, $query );
1278 if ($return and haspermission( $userid, $flagsrequired)) {
1279 my $session = get_session("");
1280 return ("failed", undef, undef) unless $session;
1282 my $sessionID = $session->id;
1283 C4::Context->_new_userenv($sessionID);
1284 my $cookie = $query->cookie(
1285 -name => 'CGISESSID',
1286 -value => $sessionID,
1289 if ( $return == 1 ) {
1291 $borrowernumber, $firstname, $surname,
1292 $userflags, $branchcode, $branchname,
1293 $branchprinter, $emailaddress
1297 "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=?"
1299 $sth->execute($userid);
1301 $borrowernumber, $firstname, $surname,
1302 $userflags, $branchcode, $branchname,
1303 $branchprinter, $emailaddress
1304 ) = $sth->fetchrow if ( $sth->rows );
1306 unless ($sth->rows ) {
1307 my $sth = $dbh->prepare(
1308 "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=?"
1310 $sth->execute($cardnumber);
1312 $borrowernumber, $firstname, $surname,
1313 $userflags, $branchcode, $branchname,
1314 $branchprinter, $emailaddress
1315 ) = $sth->fetchrow if ( $sth->rows );
1317 unless ( $sth->rows ) {
1318 $sth->execute($userid);
1320 $borrowernumber, $firstname, $surname, $userflags,
1321 $branchcode, $branchname, $branchprinter, $emailaddress
1322 ) = $sth->fetchrow if ( $sth->rows );
1326 my $ip = $ENV{'REMOTE_ADDR'};
1327 # if they specify at login, use that
1328 if ($query->param('branch')) {
1329 $branchcode = $query->param('branch');
1330 $branchname = GetBranchName($branchcode);
1332 my $branches = GetBranches();
1334 foreach my $br ( keys %$branches ) {
1335 # now we work with the treatment of ip
1336 my $domain = $branches->{$br}->{'branchip'};
1337 if ( $domain && $ip =~ /^$domain/ ) {
1338 $branchcode = $branches->{$br}->{'branchcode'};
1340 # new op dev : add the branchprinter and branchname in the cookie
1341 $branchprinter = $branches->{$br}->{'branchprinter'};
1342 $branchname = $branches->{$br}->{'branchname'};
1345 $session->param('number',$borrowernumber);
1346 $session->param('id',$userid);
1347 $session->param('cardnumber',$cardnumber);
1348 $session->param('firstname',$firstname);
1349 $session->param('surname',$surname);
1350 $session->param('branch',$branchcode);
1351 $session->param('branchname',$branchname);
1352 $session->param('flags',$userflags);
1353 $session->param('emailaddress',$emailaddress);
1354 $session->param('ip',$session->remote_addr());
1355 $session->param('lasttime',time());
1356 } elsif ( $return == 2 ) {
1357 #We suppose the user is the superlibrarian
1358 $session->param('number',0);
1359 $session->param('id',C4::Context->config('user'));
1360 $session->param('cardnumber',C4::Context->config('user'));
1361 $session->param('firstname',C4::Context->config('user'));
1362 $session->param('surname',C4::Context->config('user'));
1363 $session->param('branch','NO_LIBRARY_SET');
1364 $session->param('branchname','NO_LIBRARY_SET');
1365 $session->param('flags',1);
1366 $session->param('emailaddress', C4::Context->preference('KohaAdminEmailAddress'));
1367 $session->param('ip',$session->remote_addr());
1368 $session->param('lasttime',time());
1370 C4::Context::set_userenv(
1371 $session->param('number'), $session->param('id'),
1372 $session->param('cardnumber'), $session->param('firstname'),
1373 $session->param('surname'), $session->param('branch'),
1374 $session->param('branchname'), $session->param('flags'),
1375 $session->param('emailaddress'), $session->param('branchprinter')
1377 return ("ok", $cookie, $sessionID);
1379 return ("failed", undef, undef);
1384 =head2 check_cookie_auth
1386 ($status, $sessionId) = check_api_auth($cookie, $userflags);
1388 Given a CGISESSID cookie set during a previous login to Koha, determine
1389 if the user has the privileges specified by C<$userflags>.
1391 C<check_cookie_auth> is meant for authenticating special services
1392 such as tools/upload-file.pl that are invoked by other pages that
1393 have been authenticated in the usual way.
1395 Possible return values in C<$status> are:
1399 =item "ok" -- user authenticated; C<$sessionID> have valid values.
1401 =item "failed" -- credentials are not correct; C<$sessionid> are undef
1403 =item "maintenance" -- DB is in maintenance mode; no login possible at the moment
1405 =item "expired -- session cookie has expired; API user should resubmit userid and password
1411 sub check_cookie_auth {
1413 my $flagsrequired = shift;
1415 my $dbh = C4::Context->dbh;
1416 my $timeout = _timeout_syspref();
1418 unless (C4::Context->preference('Version')) {
1419 # database has not been installed yet
1420 return ("maintenance", undef);
1422 my $kohaversion=C4::Context::KOHAVERSION;
1423 $kohaversion =~ s/(.*\..*)\.(.*)\.(.*)/$1$2$3/;
1424 if (C4::Context->preference('Version') < $kohaversion) {
1425 # database in need of version update; assume that
1426 # no API should be called while databsae is in
1428 return ("maintenance", undef);
1431 # FIXME -- most of what follows is a copy-and-paste
1432 # of code from checkauth. There is an obvious need
1433 # for refactoring to separate the various parts of
1434 # the authentication code, but as of 2007-11-23 this
1435 # is deferred so as to not introduce bugs into the
1436 # regular authentication code for Koha 3.0.
1438 # see if we have a valid session cookie already
1439 # however, if a userid parameter is present (i.e., from
1440 # a form submission, assume that any current cookie
1442 unless (defined $cookie and $cookie) {
1443 return ("failed", undef);
1445 my $sessionID = $cookie;
1446 my $session = get_session($sessionID);
1447 C4::Context->_new_userenv($sessionID);
1449 C4::Context::set_userenv(
1450 $session->param('number'), $session->param('id'),
1451 $session->param('cardnumber'), $session->param('firstname'),
1452 $session->param('surname'), $session->param('branch'),
1453 $session->param('branchname'), $session->param('flags'),
1454 $session->param('emailaddress'), $session->param('branchprinter')
1457 my $ip = $session->param('ip');
1458 my $lasttime = $session->param('lasttime');
1459 my $userid = $session->param('id');
1460 if ( $lasttime < time() - $timeout ) {
1464 C4::Context->_unset_userenv($sessionID);
1467 return ("expired", undef);
1468 } elsif ( $ip ne $ENV{'REMOTE_ADDR'} ) {
1469 # IP address changed
1472 C4::Context->_unset_userenv($sessionID);
1475 return ("expired", undef);
1477 $session->param('lasttime',time());
1478 my $flags = haspermission($userid, $flagsrequired);
1480 return ("ok", $sessionID);
1484 C4::Context->_unset_userenv($sessionID);
1487 return ("failed", undef);
1491 return ("expired", undef);
1498 my $session = get_session($sessionID);
1500 Given a session ID, retrieve the CGI::Session object used to store
1501 the session's state. The session object can be used to store
1502 data that needs to be accessed by different scripts during a
1505 If the C<$sessionID> parameter is an empty string, a new session
1511 my $sessionID = shift;
1512 my $storage_method = C4::Context->preference('SessionStorage');
1513 my $dbh = C4::Context->dbh;
1515 if ($storage_method eq 'mysql'){
1516 $session = new CGI::Session("driver:MySQL;serializer:yaml;id:md5", $sessionID, {Handle=>$dbh});
1518 elsif ($storage_method eq 'Pg') {
1519 $session = new CGI::Session("driver:PostgreSQL;serializer:yaml;id:md5", $sessionID, {Handle=>$dbh});
1521 elsif ($storage_method eq 'memcached' && C4::Context->ismemcached){
1522 $session = new CGI::Session("driver:memcached;serializer:yaml;id:md5", $sessionID, { Memcached => C4::Context->memcached } );
1525 # catch all defaults to tmp should work on all systems
1526 $session = new CGI::Session("driver:File;serializer:yaml;id:md5", $sessionID, {Directory=>'/tmp'});
1532 my ( $dbh, $userid, $password, $query ) = @_;
1535 $debug and print STDERR "## checkpw - checking LDAP\n";
1536 my ($retval,$retcard,$retuserid) = checkpw_ldap(@_); # EXTERNAL AUTH
1537 ($retval) and return ($retval,$retcard,$retuserid);
1540 if ($cas && $query && $query->param('ticket')) {
1541 $debug and print STDERR "## checkpw - checking CAS\n";
1542 # In case of a CAS authentication, we use the ticket instead of the password
1543 my $ticket = $query->param('ticket');
1544 my ($retval,$retcard,$retuserid) = checkpw_cas($dbh, $ticket, $query); # EXTERNAL AUTH
1545 ($retval) and return ($retval,$retcard,$retuserid);
1549 return checkpw_internal(@_)
1552 sub checkpw_internal {
1553 my ( $dbh, $userid, $password ) = @_;
1557 "select password,cardnumber,borrowernumber,userid,firstname,surname,branchcode,flags from borrowers where userid=?"
1559 $sth->execute($userid);
1561 my ( $stored_hash, $cardnumber, $borrowernumber, $userid, $firstname,
1562 $surname, $branchcode, $flags )
1565 if ( checkpw_hash($password, $stored_hash) ) {
1567 C4::Context->set_userenv( "$borrowernumber", $userid, $cardnumber,
1568 $firstname, $surname, $branchcode, $flags );
1569 return 1, $cardnumber, $userid;
1574 "select password,cardnumber,borrowernumber,userid, firstname,surname,branchcode,flags from borrowers where cardnumber=?"
1576 $sth->execute($userid);
1578 my ( $stored_hash, $cardnumber, $borrowernumber, $userid, $firstname,
1579 $surname, $branchcode, $flags )
1582 if ( checkpw_hash($password, $stored_hash) ) {
1584 C4::Context->set_userenv( $borrowernumber, $userid, $cardnumber,
1585 $firstname, $surname, $branchcode, $flags );
1586 return 1, $cardnumber, $userid;
1589 if ( $userid && $userid eq C4::Context->config('user')
1590 && "$password" eq C4::Context->config('pass') )
1593 # Koha superuser account
1594 # C4::Context->set_userenv(0,0,C4::Context->config('user'),C4::Context->config('user'),C4::Context->config('user'),"",1);
1597 if ( $userid && $userid eq 'demo'
1598 && "$password" eq 'demo'
1599 && C4::Context->config('demo') )
1602 # DEMO => the demo user is allowed to do everything (if demo set to 1 in koha.conf
1603 # some features won't be effective : modify systempref, modify MARC structure,
1610 my ( $password, $stored_hash ) = @_;
1612 return if $stored_hash eq '!';
1614 # check what encryption algorithm was implemented: Bcrypt - if the hash starts with '$2' it is Bcrypt else md5
1616 if ( substr($stored_hash,0,2) eq '$2') {
1617 $hash = hash_password($password, $stored_hash);
1619 $hash = md5_base64($password);
1621 return $hash eq $stored_hash;
1626 my $authflags = getuserflags($flags, $userid, [$dbh]);
1628 Translates integer flags into permissions strings hash.
1630 C<$flags> is the integer userflags value ( borrowers.userflags )
1631 C<$userid> is the members.userid, used for building subpermissions
1632 C<$authflags> is a hashref of permissions
1639 my $dbh = @_ ? shift : C4::Context->dbh;
1642 # I don't want to do this, but if someone logs in as the database
1643 # user, it would be preferable not to spam them to death with
1644 # numeric warnings. So, we make $flags numeric.
1645 no warnings 'numeric';
1648 my $sth = $dbh->prepare("SELECT bit, flag, defaulton FROM userflags");
1651 while ( my ( $bit, $flag, $defaulton ) = $sth->fetchrow ) {
1652 if ( ( $flags & ( 2**$bit ) ) || $defaulton ) {
1653 $userflags->{$flag} = 1;
1656 $userflags->{$flag} = 0;
1659 # get subpermissions and merge with top-level permissions
1660 my $user_subperms = get_user_subpermissions($userid);
1661 foreach my $module (keys %$user_subperms) {
1662 next if $userflags->{$module} == 1; # user already has permission for everything in this module
1663 $userflags->{$module} = $user_subperms->{$module};
1669 =head2 get_user_subpermissions
1671 $user_perm_hashref = get_user_subpermissions($userid);
1673 Given the userid (note, not the borrowernumber) of a staff user,
1674 return a hashref of hashrefs of the specific subpermissions
1675 accorded to the user. An example return is
1679 export_catalog => 1,
1680 import_patrons => 1,
1684 The top-level hash-key is a module or function code from
1685 userflags.flag, while the second-level key is a code
1688 The results of this function do not give a complete picture
1689 of the functions that a staff user can access; it is also
1690 necessary to check borrowers.flags.
1694 sub get_user_subpermissions {
1697 my $dbh = C4::Context->dbh;
1698 my $sth = $dbh->prepare("SELECT flag, user_permissions.code
1699 FROM user_permissions
1700 JOIN permissions USING (module_bit, code)
1701 JOIN userflags ON (module_bit = bit)
1702 JOIN borrowers USING (borrowernumber)
1704 $sth->execute($userid);
1706 my $user_perms = {};
1707 while (my $perm = $sth->fetchrow_hashref) {
1708 $user_perms->{$perm->{'flag'}}->{$perm->{'code'}} = 1;
1713 =head2 get_all_subpermissions
1715 my $perm_hashref = get_all_subpermissions();
1717 Returns a hashref of hashrefs defining all specific
1718 permissions currently defined. The return value
1719 has the same structure as that of C<get_user_subpermissions>,
1720 except that the innermost hash value is the description
1721 of the subpermission.
1725 sub get_all_subpermissions {
1726 my $dbh = C4::Context->dbh;
1727 my $sth = $dbh->prepare("SELECT flag, code, description
1729 JOIN userflags ON (module_bit = bit)");
1733 while (my $perm = $sth->fetchrow_hashref) {
1734 $all_perms->{$perm->{'flag'}}->{$perm->{'code'}} = $perm->{'description'};
1739 =head2 haspermission
1741 $flags = ($userid, $flagsrequired);
1743 C<$userid> the userid of the member
1744 C<$flags> is a hashref of required flags like C<$borrower-<{authflags}>
1746 Returns member's flags or 0 if a permission is not met.
1751 my ($userid, $flagsrequired) = @_;
1752 my $sth = C4::Context->dbh->prepare("SELECT flags FROM borrowers WHERE userid=?");
1753 $sth->execute($userid);
1754 my $row = $sth->fetchrow();
1755 my $flags = getuserflags($row, $userid);
1756 if ( $userid eq C4::Context->config('user') ) {
1757 # Super User Account from /etc/koha.conf
1758 $flags->{'superlibrarian'} = 1;
1760 elsif ( $userid eq 'demo' && C4::Context->config('demo') ) {
1761 # Demo user that can do "anything" (demo=1 in /etc/koha.conf)
1762 $flags->{'superlibrarian'} = 1;
1765 return $flags if $flags->{superlibrarian};
1767 foreach my $module ( keys %$flagsrequired ) {
1768 my $subperm = $flagsrequired->{$module};
1769 if ($subperm eq '*') {
1770 return 0 unless ( $flags->{$module} == 1 or ref($flags->{$module}) );
1772 return 0 unless ( $flags->{$module} == 1 or
1773 ( ref($flags->{$module}) and
1774 exists $flags->{$module}->{$subperm} and
1775 $flags->{$module}->{$subperm} == 1
1781 #FIXME - This fcn should return the failed permission so a suitable error msg can be delivered.
1785 sub getborrowernumber {
1787 my $userenv = C4::Context->userenv;
1788 if ( defined( $userenv ) && ref( $userenv ) eq 'HASH' && $userenv->{number} ) {
1789 return $userenv->{number};
1791 my $dbh = C4::Context->dbh;
1792 for my $field ( 'userid', 'cardnumber' ) {
1794 $dbh->prepare("select borrowernumber from borrowers where $field=?");
1795 $sth->execute($userid);
1797 my ($bnumber) = $sth->fetchrow;
1804 END { } # module clean-up code here (global destructor)
1814 Crypt::Eksblowfish::Bcrypt(3)