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 decode_json/;
26 use Crypt::Eksblowfish::Bcrypt qw(bcrypt en_base64);
27 use Fcntl qw/O_RDONLY/; # O_RDONLY is used in generate_salt
31 use C4::Templates; # to get the template
32 use C4::Branch; # GetBranches
33 use C4::VirtualShelves;
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 &get_all_subpermissions &get_user_subpermissions
52 ParseSearchHistoryCookie hash_password
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 my $SEARCH_HISTORY_INSERT_SQL =<<EOQ;
133 INSERT INTO search_history(userid, sessionid, query_desc, query_cgi, total, time )
134 VALUES ( ?, ?, ?, ?, ?, FROM_UNIXTIME(?))
137 sub get_template_and_user {
140 C4::Templates::gettemplate( $in->{'template_name'}, $in->{'type'}, $in->{'query'}, $in->{'is_plugin'} );
141 my ( $user, $cookie, $sessionID, $flags );
142 if ( $in->{'template_name'} !~m/maintenance/ ) {
143 ( $user, $cookie, $sessionID, $flags ) = checkauth(
145 $in->{'authnotrequired'},
146 $in->{'flagsrequired'},
154 # It's possible for $user to be the borrowernumber if they don't have a
155 # userid defined (and are logging in through some other method, such
156 # as SSL certs against an email address)
157 $borrowernumber = getborrowernumber($user) if defined($user);
158 if (!defined($borrowernumber) && defined($user)) {
159 my $borrower = C4::Members::GetMember(borrowernumber => $user);
161 $borrowernumber = $user;
162 # A bit of a hack, but I don't know there's a nicer way
164 $user = $borrower->{firstname} . ' ' . $borrower->{surname};
169 $template->param( loggedinusername => $user );
170 $template->param( sessionID => $sessionID );
172 my ($total, $pubshelves, $barshelves) = C4::VirtualShelves::GetSomeShelfNames($borrowernumber, 'MASTHEAD');
174 pubshelves => $total->{pubtotal},
175 pubshelvesloop => $pubshelves,
176 barshelves => $total->{bartotal},
177 barshelvesloop => $barshelves,
180 my ( $borr ) = C4::Members::GetMemberDetails( $borrowernumber );
183 $template->param( "USER_INFO" => \@bordat );
185 my $all_perms = get_all_subpermissions();
187 my @flagroots = qw(circulate catalogue parameters borrowers permissions reserveforothers borrow
188 editcatalogue updatecharges management tools editauthorities serials reports acquisition);
189 # We are going to use the $flags returned by checkauth
190 # to create the template's parameters that will indicate
191 # which menus the user can access.
192 if ( $flags && $flags->{superlibrarian}==1 ) {
193 $template->param( CAN_user_circulate => 1 );
194 $template->param( CAN_user_catalogue => 1 );
195 $template->param( CAN_user_parameters => 1 );
196 $template->param( CAN_user_borrowers => 1 );
197 $template->param( CAN_user_permissions => 1 );
198 $template->param( CAN_user_reserveforothers => 1 );
199 $template->param( CAN_user_borrow => 1 );
200 $template->param( CAN_user_editcatalogue => 1 );
201 $template->param( CAN_user_updatecharges => 1 );
202 $template->param( CAN_user_acquisition => 1 );
203 $template->param( CAN_user_management => 1 );
204 $template->param( CAN_user_tools => 1 );
205 $template->param( CAN_user_editauthorities => 1 );
206 $template->param( CAN_user_serials => 1 );
207 $template->param( CAN_user_reports => 1 );
208 $template->param( CAN_user_staffaccess => 1 );
209 $template->param( CAN_user_plugins => 1 );
210 $template->param( CAN_user_coursereserves => 1 );
211 foreach my $module (keys %$all_perms) {
212 foreach my $subperm (keys %{ $all_perms->{$module} }) {
213 $template->param( "CAN_user_${module}_${subperm}" => 1 );
219 foreach my $module (keys %$all_perms) {
220 if ( $flags->{$module} == 1) {
221 foreach my $subperm (keys %{ $all_perms->{$module} }) {
222 $template->param( "CAN_user_${module}_${subperm}" => 1 );
224 } elsif ( ref($flags->{$module}) ) {
225 foreach my $subperm (keys %{ $flags->{$module} } ) {
226 $template->param( "CAN_user_${module}_${subperm}" => 1 );
233 foreach my $module (keys %$flags) {
234 if ( $flags->{$module} == 1 or ref($flags->{$module}) ) {
235 $template->param( "CAN_user_$module" => 1 );
236 if ($module eq "parameters") {
237 $template->param( CAN_user_management => 1 );
242 # Logged-in opac search history
243 # If the requested template is an opac one and opac search history is enabled
244 if ($in->{type} eq 'opac' && C4::Context->preference('EnableOpacSearchHistory')) {
245 my $dbh = C4::Context->dbh;
246 my $query = "SELECT COUNT(*) FROM search_history WHERE userid=?";
247 my $sth = $dbh->prepare($query);
248 $sth->execute($borrowernumber);
250 # If at least one search has already been performed
251 if ($sth->fetchrow_array > 0) {
252 # We show the link in opac
253 $template->param(ShowOpacRecentSearchLink => 1);
256 # And if there's a cookie with searches performed when the user was not logged in,
257 # we add them to the logged-in search history
258 my @recentSearches = ParseSearchHistoryCookie($in->{'query'});
259 if (@recentSearches) {
260 my $sth = $dbh->prepare($SEARCH_HISTORY_INSERT_SQL);
261 $sth->execute( $borrowernumber,
262 $in->{'query'}->cookie("CGISESSID"),
267 ) foreach @recentSearches;
269 # And then, delete the cookie's content
270 my $newsearchcookie = $in->{'query'}->cookie(
271 -name => 'KohaOpacRecentSearches',
272 -value => encode_json([]),
276 $cookie = [$cookie, $newsearchcookie];
280 else { # if this is an anonymous session, setup to display public lists...
282 $template->param( sessionID => $sessionID );
284 my ($total, $pubshelves) = C4::VirtualShelves::GetSomeShelfNames(undef, 'MASTHEAD');
286 pubshelves => $total->{pubtotal},
287 pubshelvesloop => $pubshelves,
290 # Anonymous opac search history
291 # If opac search history is enabled and at least one search has already been performed
292 if (C4::Context->preference('EnableOpacSearchHistory')) {
293 my @recentSearches = ParseSearchHistoryCookie($in->{'query'});
294 if (@recentSearches) {
295 $template->param(ShowOpacRecentSearchLink => 1);
299 if(C4::Context->preference('dateformat')){
300 $template->param(dateformat => C4::Context->preference('dateformat'))
303 # these template parameters are set the same regardless of $in->{'type'}
305 "BiblioDefaultView".C4::Context->preference("BiblioDefaultView") => 1,
306 EnhancedMessagingPreferences => C4::Context->preference('EnhancedMessagingPreferences'),
307 GoogleJackets => C4::Context->preference("GoogleJackets"),
308 OpenLibraryCovers => C4::Context->preference("OpenLibraryCovers"),
309 KohaAdminEmailAddress => "" . C4::Context->preference("KohaAdminEmailAddress"),
310 LoginBranchcode => (C4::Context->userenv?C4::Context->userenv->{"branch"}:undef),
311 LoginFirstname => (C4::Context->userenv?C4::Context->userenv->{"firstname"}:"Bel"),
312 LoginSurname => C4::Context->userenv?C4::Context->userenv->{"surname"}:"Inconnu",
313 emailaddress => C4::Context->userenv?C4::Context->userenv->{"emailaddress"}:undef,
314 loggedinpersona => C4::Context->userenv?C4::Context->userenv->{"persona"}:undef,
315 TagsEnabled => C4::Context->preference("TagsEnabled"),
316 hide_marc => C4::Context->preference("hide_marc"),
317 item_level_itypes => C4::Context->preference('item-level_itypes'),
318 patronimages => C4::Context->preference("patronimages"),
319 singleBranchMode => C4::Context->preference("singleBranchMode"),
320 XSLTDetailsDisplay => C4::Context->preference("XSLTDetailsDisplay"),
321 XSLTResultsDisplay => C4::Context->preference("XSLTResultsDisplay"),
322 using_https => $in->{'query'}->https() ? 1 : 0,
323 noItemTypeImages => C4::Context->preference("noItemTypeImages"),
324 marcflavour => C4::Context->preference("marcflavour"),
325 persona => C4::Context->preference("persona"),
327 if ( $in->{'type'} eq "intranet" ) {
329 AmazonCoverImages => C4::Context->preference("AmazonCoverImages"),
330 AutoLocation => C4::Context->preference("AutoLocation"),
331 "BiblioDefaultView".C4::Context->preference("IntranetBiblioDefaultView") => 1,
332 CalendarFirstDayOfWeek => (C4::Context->preference("CalendarFirstDayOfWeek") eq "Sunday")?0:1,
333 CircAutocompl => C4::Context->preference("CircAutocompl"),
334 FRBRizeEditions => C4::Context->preference("FRBRizeEditions"),
335 IndependentBranches => C4::Context->preference("IndependentBranches"),
336 IntranetNav => C4::Context->preference("IntranetNav"),
337 IntranetmainUserblock => C4::Context->preference("IntranetmainUserblock"),
338 LibraryName => C4::Context->preference("LibraryName"),
339 LoginBranchname => (C4::Context->userenv?C4::Context->userenv->{"branchname"}:undef),
340 advancedMARCEditor => C4::Context->preference("advancedMARCEditor"),
341 canreservefromotherbranches => C4::Context->preference('canreservefromotherbranches'),
342 intranetcolorstylesheet => C4::Context->preference("intranetcolorstylesheet"),
343 IntranetFavicon => C4::Context->preference("IntranetFavicon"),
344 intranetreadinghistory => C4::Context->preference("intranetreadinghistory"),
345 intranetstylesheet => C4::Context->preference("intranetstylesheet"),
346 IntranetUserCSS => C4::Context->preference("IntranetUserCSS"),
347 intranetuserjs => C4::Context->preference("intranetuserjs"),
348 intranetbookbag => C4::Context->preference("intranetbookbag"),
349 suggestion => C4::Context->preference("suggestion"),
350 virtualshelves => C4::Context->preference("virtualshelves"),
351 StaffSerialIssueDisplayCount => C4::Context->preference("StaffSerialIssueDisplayCount"),
352 EasyAnalyticalRecords => C4::Context->preference('EasyAnalyticalRecords'),
353 LocalCoverImages => C4::Context->preference('LocalCoverImages'),
354 OPACLocalCoverImages => C4::Context->preference('OPACLocalCoverImages'),
355 AllowMultipleCovers => C4::Context->preference('AllowMultipleCovers'),
356 EnableBorrowerFiles => C4::Context->preference('EnableBorrowerFiles'),
357 UseKohaPlugins => C4::Context->preference('UseKohaPlugins'),
358 UseCourseReserves => C4::Context->preference("UseCourseReserves"),
362 warn "template type should be OPAC, here it is=[" . $in->{'type'} . "]" unless ( $in->{'type'} eq 'opac' );
363 #TODO : replace LibraryName syspref with 'system name', and remove this html processing
364 my $LibraryNameTitle = C4::Context->preference("LibraryName");
365 $LibraryNameTitle =~ s/<(?:\/?)(?:br|p)\s*(?:\/?)>/ /sgi;
366 $LibraryNameTitle =~ s/<(?:[^<>'"]|'(?:[^']*)'|"(?:[^"]*)")*>//sg;
367 # clean up the busc param in the session if the page is not opac-detail
368 if (C4::Context->preference("OpacBrowseResults") && $in->{'template_name'} =~ /opac-(.+)\.(?:tt|tmpl)$/ && $1 !~ /^(?:MARC|ISBD)?detail$/) {
369 my $sessionSearch = get_session($sessionID || $in->{'query'}->cookie("CGISESSID"));
370 $sessionSearch->clear(["busc"]) if ($sessionSearch->param("busc"));
372 # variables passed from CGI: opac_css_override and opac_search_limits.
373 my $opac_search_limit = $ENV{'OPAC_SEARCH_LIMIT'};
374 my $opac_limit_override = $ENV{'OPAC_LIMIT_OVERRIDE'};
376 if (($opac_search_limit && $opac_search_limit =~ /branch:(\w+)/ && $opac_limit_override) || ($in->{'query'}->param('limit') && $in->{'query'}->param('limit') =~ /branch:(\w+)/)){
377 $opac_name = $1; # opac_search_limit is a branch, so we use it.
378 } elsif ( $in->{'query'}->param('multibranchlimit') ) {
379 $opac_name = $in->{'query'}->param('multibranchlimit');
380 } elsif (C4::Context->preference("SearchMyLibraryFirst") && C4::Context->userenv && C4::Context->userenv->{'branch'}) {
381 $opac_name = C4::Context->userenv->{'branch'};
384 opaccolorstylesheet => C4::Context->preference("opaccolorstylesheet"),
385 AnonSuggestions => "" . C4::Context->preference("AnonSuggestions"),
386 AuthorisedValueImages => C4::Context->preference("AuthorisedValueImages"),
387 BranchesLoop => GetBranchesLoop($opac_name),
388 BranchCategoriesLoop => GetBranchCategories( 'searchdomain', 1, $opac_name ),
389 CalendarFirstDayOfWeek => (C4::Context->preference("CalendarFirstDayOfWeek") eq "Sunday")?0:1,
390 LibraryName => "" . C4::Context->preference("LibraryName"),
391 LibraryNameTitle => "" . $LibraryNameTitle,
392 LoginBranchname => C4::Context->userenv?C4::Context->userenv->{"branchname"}:"",
393 OPACAmazonCoverImages => C4::Context->preference("OPACAmazonCoverImages"),
394 OPACFRBRizeEditions => C4::Context->preference("OPACFRBRizeEditions"),
395 OpacHighlightedWords => C4::Context->preference("OpacHighlightedWords"),
396 OPACItemHolds => C4::Context->preference("OPACItemHolds"),
397 OPACShelfBrowser => "". C4::Context->preference("OPACShelfBrowser"),
398 OPACURLOpenInNewWindow => "" . C4::Context->preference("OPACURLOpenInNewWindow"),
399 OPACUserCSS => "". C4::Context->preference("OPACUserCSS"),
400 OPACMobileUserCSS => "". C4::Context->preference("OPACMobileUserCSS"),
401 OPACViewOthersSuggestions => "" . C4::Context->preference("OPACViewOthersSuggestions"),
402 OpacAuthorities => C4::Context->preference("OpacAuthorities"),
403 OPACBaseURL => ($in->{'query'}->https() ? "https://" : "http://") . $ENV{'SERVER_NAME'} .
404 ($ENV{'SERVER_PORT'} eq ($in->{'query'}->https() ? "443" : "80") ? '' : ":$ENV{'SERVER_PORT'}"),
405 opac_css_override => $ENV{'OPAC_CSS_OVERRIDE'},
406 opac_search_limit => $opac_search_limit,
407 opac_limit_override => $opac_limit_override,
408 OpacBrowser => C4::Context->preference("OpacBrowser"),
409 OpacCloud => C4::Context->preference("OpacCloud"),
410 OpacKohaUrl => C4::Context->preference("OpacKohaUrl"),
411 OpacMainUserBlock => "" . C4::Context->preference("OpacMainUserBlock"),
412 OpacMainUserBlockMobile => "" . C4::Context->preference("OpacMainUserBlockMobile"),
413 OpacShowFiltersPulldownMobile => C4::Context->preference("OpacShowFiltersPulldownMobile"),
414 OpacShowLibrariesPulldownMobile => C4::Context->preference("OpacShowLibrariesPulldownMobile"),
415 OpacNav => "" . C4::Context->preference("OpacNav"),
416 OpacNavRight => "" . C4::Context->preference("OpacNavRight"),
417 OpacNavBottom => "" . C4::Context->preference("OpacNavBottom"),
418 OpacPasswordChange => C4::Context->preference("OpacPasswordChange"),
419 OPACPatronDetails => C4::Context->preference("OPACPatronDetails"),
420 OPACPrivacy => C4::Context->preference("OPACPrivacy"),
421 OPACFinesTab => C4::Context->preference("OPACFinesTab"),
422 OpacTopissue => C4::Context->preference("OpacTopissue"),
423 RequestOnOpac => C4::Context->preference("RequestOnOpac"),
424 'Version' => C4::Context->preference('Version'),
425 hidelostitems => C4::Context->preference("hidelostitems"),
426 mylibraryfirst => (C4::Context->preference("SearchMyLibraryFirst") && C4::Context->userenv) ? C4::Context->userenv->{'branch'} : '',
427 opaclayoutstylesheet => "" . C4::Context->preference("opaclayoutstylesheet"),
428 opacbookbag => "" . C4::Context->preference("opacbookbag"),
429 opaccredits => "" . C4::Context->preference("opaccredits"),
430 OpacFavicon => C4::Context->preference("OpacFavicon"),
431 opacheader => "" . C4::Context->preference("opacheader"),
432 opaclanguagesdisplay => "" . C4::Context->preference("opaclanguagesdisplay"),
433 opacreadinghistory => C4::Context->preference("opacreadinghistory"),
434 opacsmallimage => "" . C4::Context->preference("opacsmallimage"),
435 opacuserjs => C4::Context->preference("opacuserjs"),
436 opacuserlogin => "" . C4::Context->preference("opacuserlogin"),
437 ShowReviewer => C4::Context->preference("ShowReviewer"),
438 ShowReviewerPhoto => C4::Context->preference("ShowReviewerPhoto"),
439 suggestion => "" . C4::Context->preference("suggestion"),
440 virtualshelves => "" . C4::Context->preference("virtualshelves"),
441 OPACSerialIssueDisplayCount => C4::Context->preference("OPACSerialIssueDisplayCount"),
442 OPACXSLTDetailsDisplay => C4::Context->preference("OPACXSLTDetailsDisplay"),
443 OPACXSLTResultsDisplay => C4::Context->preference("OPACXSLTResultsDisplay"),
444 SyndeticsClientCode => C4::Context->preference("SyndeticsClientCode"),
445 SyndeticsEnabled => C4::Context->preference("SyndeticsEnabled"),
446 SyndeticsCoverImages => C4::Context->preference("SyndeticsCoverImages"),
447 SyndeticsTOC => C4::Context->preference("SyndeticsTOC"),
448 SyndeticsSummary => C4::Context->preference("SyndeticsSummary"),
449 SyndeticsEditions => C4::Context->preference("SyndeticsEditions"),
450 SyndeticsExcerpt => C4::Context->preference("SyndeticsExcerpt"),
451 SyndeticsReviews => C4::Context->preference("SyndeticsReviews"),
452 SyndeticsAuthorNotes => C4::Context->preference("SyndeticsAuthorNotes"),
453 SyndeticsAwards => C4::Context->preference("SyndeticsAwards"),
454 SyndeticsSeries => C4::Context->preference("SyndeticsSeries"),
455 SyndeticsCoverImageSize => C4::Context->preference("SyndeticsCoverImageSize"),
456 OPACLocalCoverImages => C4::Context->preference("OPACLocalCoverImages"),
457 PatronSelfRegistration => C4::Context->preference("PatronSelfRegistration"),
458 PatronSelfRegistrationDefaultCategory => C4::Context->preference("PatronSelfRegistrationDefaultCategory"),
461 $template->param(OpacPublic => '1') if ($user || C4::Context->preference("OpacPublic"));
463 return ( $template, $borrowernumber, $cookie, $flags);
468 ($userid, $cookie, $sessionID) = &checkauth($query, $noauth, $flagsrequired, $type);
470 Verifies that the user is authorized to run this script. If
471 the user is authorized, a (userid, cookie, session-id, flags)
472 quadruple is returned. If the user is not authorized but does
473 not have the required privilege (see $flagsrequired below), it
474 displays an error page and exits. Otherwise, it displays the
475 login page and exits.
477 Note that C<&checkauth> will return if and only if the user
478 is authorized, so it should be called early on, before any
479 unfinished operations (e.g., if you've opened a file, then
480 C<&checkauth> won't close it for you).
482 C<$query> is the CGI object for the script calling C<&checkauth>.
484 The C<$noauth> argument is optional. If it is set, then no
485 authorization is required for the script.
487 C<&checkauth> fetches user and session information from C<$query> and
488 ensures that the user is authorized to run scripts that require
491 The C<$flagsrequired> argument specifies the required privileges
492 the user must have if the username and password are correct.
493 It should be specified as a reference-to-hash; keys in the hash
494 should be the "flags" for the user, as specified in the Members
495 intranet module. Any key specified must correspond to a "flag"
496 in the userflags table. E.g., { circulate => 1 } would specify
497 that the user must have the "circulate" privilege in order to
498 proceed. To make sure that access control is correct, the
499 C<$flagsrequired> parameter must be specified correctly.
501 Koha also has a concept of sub-permissions, also known as
502 granular permissions. This makes the value of each key
503 in the C<flagsrequired> hash take on an additional
508 The user must have access to all subfunctions of the module
509 specified by the hash key.
513 The user must have access to at least one subfunction of the module
514 specified by the hash key.
516 specific permission, e.g., 'export_catalog'
518 The user must have access to the specific subfunction list, which
519 must correspond to a row in the permissions table.
521 The C<$type> argument specifies whether the template should be
522 retrieved from the opac or intranet directory tree. "opac" is
523 assumed if it is not specified; however, if C<$type> is specified,
524 "intranet" is assumed if it is not "opac".
526 If C<$query> does not have a valid session ID associated with it
527 (i.e., the user has not logged in) or if the session has expired,
528 C<&checkauth> presents the user with a login page (from the point of
529 view of the original script, C<&checkauth> does not return). Once the
530 user has authenticated, C<&checkauth> restarts the original script
531 (this time, C<&checkauth> returns).
533 The login page is provided using a HTML::Template, which is set in the
534 systempreferences table or at the top of this file. The variable C<$type>
535 selects which template to use, either the opac or the intranet
536 authentification template.
538 C<&checkauth> returns a user ID, a cookie, and a session ID. The
539 cookie should be sent back to the browser; it verifies that the user
548 # If Version syspref is unavailable, it means Koha is beeing installed,
549 # and so we must redirect to OPAC maintenance page or to the WebInstaller
550 # also, if OpacMaintenance is ON, OPAC should redirect to maintenance
551 if (C4::Context->preference('OpacMaintenance') && $type eq 'opac') {
552 warn "OPAC Install required, redirecting to maintenance";
553 print $query->redirect("/cgi-bin/koha/maintenance.pl");
556 unless ( $version = C4::Context->preference('Version') ) { # assignment, not comparison
557 if ( $type ne 'opac' ) {
558 warn "Install required, redirecting to Installer";
559 print $query->redirect("/cgi-bin/koha/installer/install.pl");
561 warn "OPAC Install required, redirecting to maintenance";
562 print $query->redirect("/cgi-bin/koha/maintenance.pl");
567 # check that database and koha version are the same
568 # there is no DB version, it's a fresh install,
569 # go to web installer
570 # there is a DB version, compare it to the code version
571 my $kohaversion=C4::Context::KOHAVERSION;
572 # remove the 3 last . to have a Perl number
573 $kohaversion =~ s/(.*\..*)\.(.*)\.(.*)/$1$2$3/;
574 $debug and print STDERR "kohaversion : $kohaversion\n";
575 if ($version < $kohaversion){
576 my $warning = "Database update needed, redirecting to %s. Database is $version and Koha is $kohaversion";
577 if ($type ne 'opac'){
578 warn sprintf($warning, 'Installer');
579 print $query->redirect("/cgi-bin/koha/installer/install.pl?step=3");
581 warn sprintf("OPAC: " . $warning, 'maintenance');
582 print $query->redirect("/cgi-bin/koha/maintenance.pl");
590 open my $fh, '>>', "/tmp/sessionlog" or warn "ERROR: Cannot append to /tmp/sessionlog";
591 printf $fh join("\n",@_);
595 sub _timeout_syspref {
596 my $timeout = C4::Context->preference('timeout') || 600;
597 # value in days, convert in seconds
598 if ($timeout =~ /(\d+)[dD]/) {
599 $timeout = $1 * 86400;
606 $debug and warn "Checking Auth";
607 # $authnotrequired will be set for scripts which will run without authentication
608 my $authnotrequired = shift;
609 my $flagsrequired = shift;
612 $type = 'opac' unless $type;
614 my $dbh = C4::Context->dbh;
615 my $timeout = _timeout_syspref();
617 _version_check($type,$query);
621 my ( $userid, $cookie, $sessionID, $flags, $barshelves, $pubshelves );
622 my $logout = $query->param('logout.x');
624 # This parameter is the name of the CAS server we want to authenticate against,
625 # when using authentication against multiple CAS servers, as configured in Auth_cas_servers.yaml
626 my $casparam = $query->param('cas');
628 if ( $userid = $ENV{'REMOTE_USER'} ) {
629 # Using Basic Authentication, no cookies required
630 $cookie = $query->cookie(
631 -name => 'CGISESSID',
639 # we dont want to set a session because we are being called by a persona callback
641 elsif ( $sessionID = $query->cookie("CGISESSID") )
642 { # assignment, not comparison
643 my $session = get_session($sessionID);
644 C4::Context->_new_userenv($sessionID);
645 my ($ip, $lasttime, $sessiontype);
647 C4::Context::set_userenv(
648 $session->param('number'), $session->param('id'),
649 $session->param('cardnumber'), $session->param('firstname'),
650 $session->param('surname'), $session->param('branch'),
651 $session->param('branchname'), $session->param('flags'),
652 $session->param('emailaddress'), $session->param('branchprinter'),
653 $session->param('persona')
655 C4::Context::set_shelves_userenv('bar',$session->param('barshelves'));
656 C4::Context::set_shelves_userenv('pub',$session->param('pubshelves'));
657 C4::Context::set_shelves_userenv('tot',$session->param('totshelves'));
658 $debug and printf STDERR "AUTH_SESSION: (%s)\t%s %s - %s\n", map {$session->param($_)} qw(cardnumber firstname surname branch) ;
659 $ip = $session->param('ip');
660 $lasttime = $session->param('lasttime');
661 $userid = $session->param('id');
662 $sessiontype = $session->param('sessiontype') || '';
664 if ( ( ($query->param('koha_login_context')) && ($query->param('userid') ne $session->param('id')) )
665 || ( $cas && $query->param('ticket') ) ) {
666 #if a user enters an id ne to the id in the current session, we need to log them in...
667 #first we need to clear the anonymous session...
668 $debug and warn "query id = " . $query->param('userid') . " but session id = " . $session->param('id');
671 C4::Context->_unset_userenv($sessionID);
676 # voluntary logout the user
679 C4::Context->_unset_userenv($sessionID);
680 #_session_log(sprintf "%20s from %16s logged out at %30s (manually).\n", $userid,$ip,(strftime "%c",localtime));
684 if ($cas and $caslogout) {
688 elsif ( $lasttime < time() - $timeout ) {
690 $info{'timed_out'} = 1;
691 $session->delete() if $session;
692 C4::Context->_unset_userenv($sessionID);
693 #_session_log(sprintf "%20s from %16s logged out at %30s (inactivity).\n", $userid,$ip,(strftime "%c",localtime));
697 elsif ( $ip ne $ENV{'REMOTE_ADDR'} ) {
698 # Different ip than originally logged in from
699 $info{'oldip'} = $ip;
700 $info{'newip'} = $ENV{'REMOTE_ADDR'};
701 $info{'different_ip'} = 1;
703 C4::Context->_unset_userenv($sessionID);
704 #_session_log(sprintf "%20s from %16s logged out at %30s (ip changed to %16s).\n", $userid,$ip,(strftime "%c",localtime), $info{'newip'});
709 $cookie = $query->cookie(
710 -name => 'CGISESSID',
711 -value => $session->id,
714 $session->param( 'lasttime', time() );
715 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...
716 $flags = haspermission($userid, $flagsrequired);
720 $info{'nopermission'} = 1;
725 unless ($userid || $sessionID) {
727 #we initiate a session prior to checking for a username to allow for anonymous sessions...
728 my $session = get_session("") or die "Auth ERROR: Cannot get_session()";
729 my $sessionID = $session->id;
730 C4::Context->_new_userenv($sessionID);
731 $cookie = $query->cookie(
732 -name => 'CGISESSID',
733 -value => $session->id,
736 $userid = $query->param('userid');
737 if ( ( $cas && $query->param('ticket') )
739 || ( my $pki_field = C4::Context->preference('AllowPKIAuth') ) ne
742 my $password = $query->param('password');
744 my ( $return, $cardnumber );
745 if ( $cas && $query->param('ticket') ) {
747 ( $return, $cardnumber, $retuserid ) =
748 checkpw( $dbh, $userid, $password, $query );
749 $userid = $retuserid;
750 $info{'invalidCasLogin'} = 1 unless ($return);
754 my $value = $persona;
756 # If we're looking up the email, there's a chance that the person
757 # doesn't have a userid. So if there is none, we pass along the
758 # borrower number, and the bits of code that need to know the user
759 # ID will have to be smart enough to handle that.
761 my @users_info = C4::Members::GetBorrowersWithEmail($value);
764 # First the userid, then the borrowernum
765 $value = $users_info[0][1] || $users_info[0][0];
770 $return = $value ? 1 : 0;
775 ( $pki_field eq 'Common Name' && $ENV{'SSL_CLIENT_S_DN_CN'} )
776 || ( $pki_field eq 'emailAddress'
777 && $ENV{'SSL_CLIENT_S_DN_Email'} )
781 if ( $pki_field eq 'Common Name' ) {
782 $value = $ENV{'SSL_CLIENT_S_DN_CN'};
784 elsif ( $pki_field eq 'emailAddress' ) {
785 $value = $ENV{'SSL_CLIENT_S_DN_Email'};
787 # If we're looking up the email, there's a chance that the person
788 # doesn't have a userid. So if there is none, we pass along the
789 # borrower number, and the bits of code that need to know the user
790 # ID will have to be smart enough to handle that.
792 my @users_info = C4::Members::GetBorrowersWithEmail($value);
795 # First the userid, then the borrowernum
796 $value = $users_info[0][1] || $users_info[0][0];
803 $return = $value ? 1 : 0;
809 ( $return, $cardnumber, $retuserid ) =
810 checkpw( $dbh, $userid, $password, $query );
811 $userid = $retuserid if ( $retuserid ne '' );
814 #_session_log(sprintf "%20s from %16s logged in at %30s.\n", $userid,$ENV{'REMOTE_ADDR'},(strftime '%c', localtime));
815 if ( $flags = haspermission( $userid, $flagsrequired ) ) {
819 $info{'nopermission'} = 1;
820 C4::Context->_unset_userenv($sessionID);
822 my ($borrowernumber, $firstname, $surname, $userflags,
823 $branchcode, $branchname, $branchprinter, $emailaddress);
825 if ( $return == 1 ) {
827 SELECT borrowernumber, firstname, surname, flags, borrowers.branchcode,
828 branches.branchname as branchname,
829 branches.branchprinter as branchprinter,
832 LEFT JOIN branches on borrowers.branchcode=branches.branchcode
834 my $sth = $dbh->prepare("$select where userid=?");
835 $sth->execute($userid);
836 unless ($sth->rows) {
837 $debug and print STDERR "AUTH_1: no rows for userid='$userid'\n";
838 $sth = $dbh->prepare("$select where cardnumber=?");
839 $sth->execute($cardnumber);
841 unless ($sth->rows) {
842 $debug and print STDERR "AUTH_2a: no rows for cardnumber='$cardnumber'\n";
843 $sth->execute($userid);
844 unless ($sth->rows) {
845 $debug and print STDERR "AUTH_2b: no rows for userid='$userid' AS cardnumber\n";
850 ($borrowernumber, $firstname, $surname, $userflags,
851 $branchcode, $branchname, $branchprinter, $emailaddress) = $sth->fetchrow;
852 $debug and print STDERR "AUTH_3 results: " .
853 "$cardnumber,$borrowernumber,$userid,$firstname,$surname,$userflags,$branchcode,$emailaddress\n";
855 print STDERR "AUTH_3: no results for userid='$userid', cardnumber='$cardnumber'.\n";
858 # launch a sequence to check if we have a ip for the branch, i
859 # if we have one we replace the branchcode of the userenv by the branch bound in the ip.
861 my $ip = $ENV{'REMOTE_ADDR'};
862 # if they specify at login, use that
863 if ($query->param('branch')) {
864 $branchcode = $query->param('branch');
865 $branchname = GetBranchName($branchcode);
867 my $branches = GetBranches();
868 if (C4::Context->boolean_preference('IndependentBranches') && C4::Context->boolean_preference('Autolocation')){
869 # we have to check they are coming from the right ip range
870 my $domain = $branches->{$branchcode}->{'branchip'};
871 if ($ip !~ /^$domain/){
873 $info{'wrongip'} = 1;
878 foreach my $br ( keys %$branches ) {
879 # now we work with the treatment of ip
880 my $domain = $branches->{$br}->{'branchip'};
881 if ( $domain && $ip =~ /^$domain/ ) {
882 $branchcode = $branches->{$br}->{'branchcode'};
884 # new op dev : add the branchprinter and branchname in the cookie
885 $branchprinter = $branches->{$br}->{'branchprinter'};
886 $branchname = $branches->{$br}->{'branchname'};
889 $session->param('number',$borrowernumber);
890 $session->param('id',$userid);
891 $session->param('cardnumber',$cardnumber);
892 $session->param('firstname',$firstname);
893 $session->param('surname',$surname);
894 $session->param('branch',$branchcode);
895 $session->param('branchname',$branchname);
896 $session->param('flags',$userflags);
897 $session->param('emailaddress',$emailaddress);
898 $session->param('ip',$session->remote_addr());
899 $session->param('lasttime',time());
900 $debug and printf STDERR "AUTH_4: (%s)\t%s %s - %s\n", map {$session->param($_)} qw(cardnumber firstname surname branch) ;
902 elsif ( $return == 2 ) {
903 #We suppose the user is the superlibrarian
905 $session->param('number',0);
906 $session->param('id',C4::Context->config('user'));
907 $session->param('cardnumber',C4::Context->config('user'));
908 $session->param('firstname',C4::Context->config('user'));
909 $session->param('surname',C4::Context->config('user'));
910 $session->param('branch','NO_LIBRARY_SET');
911 $session->param('branchname','NO_LIBRARY_SET');
912 $session->param('flags',1);
913 $session->param('emailaddress', C4::Context->preference('KohaAdminEmailAddress'));
914 $session->param('ip',$session->remote_addr());
915 $session->param('lasttime',time());
918 $session->param('persona',1);
920 C4::Context::set_userenv(
921 $session->param('number'), $session->param('id'),
922 $session->param('cardnumber'), $session->param('firstname'),
923 $session->param('surname'), $session->param('branch'),
924 $session->param('branchname'), $session->param('flags'),
925 $session->param('emailaddress'), $session->param('branchprinter'),
926 $session->param('persona')
932 $info{'invalid_username_or_password'} = 1;
933 C4::Context->_unset_userenv($sessionID);
936 } # END if ( $userid = $query->param('userid') )
937 elsif ($type eq "opac") {
938 # if we are here this is an anonymous session; add public lists to it and a few other items...
939 # anonymous sessions are created only for the OPAC
940 $debug and warn "Initiating an anonymous session...";
942 # setting a couple of other session vars...
943 $session->param('ip',$session->remote_addr());
944 $session->param('lasttime',time());
945 $session->param('sessiontype','anon');
947 } # END unless ($userid)
949 # finished authentification, now respond
950 if ( $loggedin || $authnotrequired )
954 $cookie = $query->cookie(
955 -name => 'CGISESSID',
960 return ( $userid, $cookie, $sessionID, $flags );
965 # AUTH rejected, show the login/password template, after checking the DB.
969 # get the inputs from the incoming query
971 foreach my $name ( param $query) {
972 (next) if ( $name eq 'userid' || $name eq 'password' || $name eq 'ticket' );
973 my $value = $query->param($name);
974 push @inputs, { name => $name, value => $value };
977 my $LibraryNameTitle = C4::Context->preference("LibraryName");
978 $LibraryNameTitle =~ s/<(?:\/?)(?:br|p)\s*(?:\/?)>/ /sgi;
979 $LibraryNameTitle =~ s/<(?:[^<>'"]|'(?:[^']*)'|"(?:[^"]*)")*>//sg;
981 my $template_name = ( $type eq 'opac' ) ? 'opac-auth.tmpl' : 'auth.tmpl';
982 my $template = C4::Templates::gettemplate($template_name, $type, $query );
984 branchloop => GetBranchesLoop(),
985 opaccolorstylesheet => C4::Context->preference("opaccolorstylesheet"),
986 opaclayoutstylesheet => C4::Context->preference("opaclayoutstylesheet"),
989 casAuthentication => C4::Context->preference("casAuthentication"),
990 suggestion => C4::Context->preference("suggestion"),
991 virtualshelves => C4::Context->preference("virtualshelves"),
992 LibraryName => "" . C4::Context->preference("LibraryName"),
993 LibraryNameTitle => "" . $LibraryNameTitle,
994 opacuserlogin => C4::Context->preference("opacuserlogin"),
995 OpacNav => C4::Context->preference("OpacNav"),
996 OpacNavRight => C4::Context->preference("OpacNavRight"),
997 OpacNavBottom => C4::Context->preference("OpacNavBottom"),
998 opaccredits => C4::Context->preference("opaccredits"),
999 OpacFavicon => C4::Context->preference("OpacFavicon"),
1000 opacreadinghistory => C4::Context->preference("opacreadinghistory"),
1001 opacsmallimage => C4::Context->preference("opacsmallimage"),
1002 opaclanguagesdisplay => C4::Context->preference("opaclanguagesdisplay"),
1003 opacuserjs => C4::Context->preference("opacuserjs"),
1004 opacbookbag => "" . C4::Context->preference("opacbookbag"),
1005 OpacCloud => C4::Context->preference("OpacCloud"),
1006 OpacTopissue => C4::Context->preference("OpacTopissue"),
1007 OpacAuthorities => C4::Context->preference("OpacAuthorities"),
1008 OpacBrowser => C4::Context->preference("OpacBrowser"),
1009 opacheader => C4::Context->preference("opacheader"),
1010 TagsEnabled => C4::Context->preference("TagsEnabled"),
1011 OPACUserCSS => C4::Context->preference("OPACUserCSS"),
1012 intranetcolorstylesheet => C4::Context->preference("intranetcolorstylesheet"),
1013 intranetstylesheet => C4::Context->preference("intranetstylesheet"),
1014 intranetbookbag => C4::Context->preference("intranetbookbag"),
1015 IntranetNav => C4::Context->preference("IntranetNav"),
1016 IntranetFavicon => C4::Context->preference("IntranetFavicon"),
1017 intranetuserjs => C4::Context->preference("intranetuserjs"),
1018 IndependentBranches=> C4::Context->preference("IndependentBranches"),
1019 AutoLocation => C4::Context->preference("AutoLocation"),
1020 wrongip => $info{'wrongip'},
1021 PatronSelfRegistration => C4::Context->preference("PatronSelfRegistration"),
1022 PatronSelfRegistrationDefaultCategory => C4::Context->preference("PatronSelfRegistrationDefaultCategory"),
1023 persona => C4::Context->preference("Persona"),
1024 opac_css_override => $ENV{'OPAC_CSS_OVERRIDE'},
1027 $template->param( OpacPublic => C4::Context->preference("OpacPublic"));
1028 $template->param( loginprompt => 1 ) unless $info{'nopermission'};
1030 if($type eq 'opac'){
1031 my ($total, $pubshelves) = C4::VirtualShelves::GetSomeShelfNames(undef, 'MASTHEAD');
1033 pubshelves => $total->{pubtotal},
1034 pubshelvesloop => $pubshelves,
1040 # Is authentication against multiple CAS servers enabled?
1041 if (C4::Auth_with_cas::multipleAuth && !$casparam) {
1042 my $casservers = C4::Auth_with_cas::getMultipleAuth();
1044 foreach my $key (keys %$casservers) {
1045 push @tmplservers, {name => $key, value => login_cas_url($query, $key) . "?cas=$key" };
1048 casServersLoop => \@tmplservers
1052 casServerUrl => login_cas_url($query),
1057 invalidCasLogin => $info{'invalidCasLogin'}
1061 my $self_url = $query->url( -absolute => 1 );
1064 LibraryName => C4::Context->preference("LibraryName"),
1066 $template->param( %info );
1067 # $cookie = $query->cookie(CGISESSID => $session->id
1069 print $query->header(
1070 -type => 'text/html',
1071 -charset => 'utf-8',
1078 =head2 check_api_auth
1080 ($status, $cookie, $sessionId) = check_api_auth($query, $userflags);
1082 Given a CGI query containing the parameters 'userid' and 'password' and/or a session
1083 cookie, determine if the user has the privileges specified by C<$userflags>.
1085 C<check_api_auth> is is meant for authenticating users of web services, and
1086 consequently will always return and will not attempt to redirect the user
1089 If a valid session cookie is already present, check_api_auth will return a status
1090 of "ok", the cookie, and the Koha session ID.
1092 If no session cookie is present, check_api_auth will check the 'userid' and 'password
1093 parameters and create a session cookie and Koha session if the supplied credentials
1096 Possible return values in C<$status> are:
1100 =item "ok" -- user authenticated; C<$cookie> and C<$sessionid> have valid values.
1102 =item "failed" -- credentials are not correct; C<$cookie> and C<$sessionid> are undef
1104 =item "maintenance" -- DB is in maintenance mode; no login possible at the moment
1106 =item "expired -- session cookie has expired; API user should resubmit userid and password
1112 sub check_api_auth {
1114 my $flagsrequired = shift;
1116 my $dbh = C4::Context->dbh;
1117 my $timeout = _timeout_syspref();
1119 unless (C4::Context->preference('Version')) {
1120 # database has not been installed yet
1121 return ("maintenance", undef, undef);
1123 my $kohaversion=C4::Context::KOHAVERSION;
1124 $kohaversion =~ s/(.*\..*)\.(.*)\.(.*)/$1$2$3/;
1125 if (C4::Context->preference('Version') < $kohaversion) {
1126 # database in need of version update; assume that
1127 # no API should be called while databsae is in
1129 return ("maintenance", undef, undef);
1132 # FIXME -- most of what follows is a copy-and-paste
1133 # of code from checkauth. There is an obvious need
1134 # for refactoring to separate the various parts of
1135 # the authentication code, but as of 2007-11-19 this
1136 # is deferred so as to not introduce bugs into the
1137 # regular authentication code for Koha 3.0.
1139 # see if we have a valid session cookie already
1140 # however, if a userid parameter is present (i.e., from
1141 # a form submission, assume that any current cookie
1143 my $sessionID = undef;
1144 unless ($query->param('userid')) {
1145 $sessionID = $query->cookie("CGISESSID");
1147 if ($sessionID && not ($cas && $query->param('PT')) ) {
1148 my $session = get_session($sessionID);
1149 C4::Context->_new_userenv($sessionID);
1151 C4::Context::set_userenv(
1152 $session->param('number'), $session->param('id'),
1153 $session->param('cardnumber'), $session->param('firstname'),
1154 $session->param('surname'), $session->param('branch'),
1155 $session->param('branchname'), $session->param('flags'),
1156 $session->param('emailaddress'), $session->param('branchprinter')
1159 my $ip = $session->param('ip');
1160 my $lasttime = $session->param('lasttime');
1161 my $userid = $session->param('id');
1162 if ( $lasttime < time() - $timeout ) {
1165 C4::Context->_unset_userenv($sessionID);
1168 return ("expired", undef, undef);
1169 } elsif ( $ip ne $ENV{'REMOTE_ADDR'} ) {
1170 # IP address changed
1172 C4::Context->_unset_userenv($sessionID);
1175 return ("expired", undef, undef);
1177 my $cookie = $query->cookie(
1178 -name => 'CGISESSID',
1179 -value => $session->id,
1182 $session->param('lasttime',time());
1183 my $flags = haspermission($userid, $flagsrequired);
1185 return ("ok", $cookie, $sessionID);
1188 C4::Context->_unset_userenv($sessionID);
1191 return ("failed", undef, undef);
1195 return ("expired", undef, undef);
1199 my $userid = $query->param('userid');
1200 my $password = $query->param('password');
1201 my ($return, $cardnumber);
1204 if ($cas && $query->param('PT')) {
1206 $debug and print STDERR "## check_api_auth - checking CAS\n";
1207 # In case of a CAS authentication, we use the ticket instead of the password
1208 my $PT = $query->param('PT');
1209 ($return,$cardnumber,$userid) = check_api_auth_cas($dbh, $PT, $query); # EXTERNAL AUTH
1211 # User / password auth
1212 unless ($userid and $password) {
1213 # caller did something wrong, fail the authenticateion
1214 return ("failed", undef, undef);
1216 ( $return, $cardnumber ) = checkpw( $dbh, $userid, $password, $query );
1219 if ($return and haspermission( $userid, $flagsrequired)) {
1220 my $session = get_session("");
1221 return ("failed", undef, undef) unless $session;
1223 my $sessionID = $session->id;
1224 C4::Context->_new_userenv($sessionID);
1225 my $cookie = $query->cookie(
1226 -name => 'CGISESSID',
1227 -value => $sessionID,
1230 if ( $return == 1 ) {
1232 $borrowernumber, $firstname, $surname,
1233 $userflags, $branchcode, $branchname,
1234 $branchprinter, $emailaddress
1238 "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=?"
1240 $sth->execute($userid);
1242 $borrowernumber, $firstname, $surname,
1243 $userflags, $branchcode, $branchname,
1244 $branchprinter, $emailaddress
1245 ) = $sth->fetchrow if ( $sth->rows );
1247 unless ($sth->rows ) {
1248 my $sth = $dbh->prepare(
1249 "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=?"
1251 $sth->execute($cardnumber);
1253 $borrowernumber, $firstname, $surname,
1254 $userflags, $branchcode, $branchname,
1255 $branchprinter, $emailaddress
1256 ) = $sth->fetchrow if ( $sth->rows );
1258 unless ( $sth->rows ) {
1259 $sth->execute($userid);
1261 $borrowernumber, $firstname, $surname, $userflags,
1262 $branchcode, $branchname, $branchprinter, $emailaddress
1263 ) = $sth->fetchrow if ( $sth->rows );
1267 my $ip = $ENV{'REMOTE_ADDR'};
1268 # if they specify at login, use that
1269 if ($query->param('branch')) {
1270 $branchcode = $query->param('branch');
1271 $branchname = GetBranchName($branchcode);
1273 my $branches = GetBranches();
1275 foreach my $br ( keys %$branches ) {
1276 # now we work with the treatment of ip
1277 my $domain = $branches->{$br}->{'branchip'};
1278 if ( $domain && $ip =~ /^$domain/ ) {
1279 $branchcode = $branches->{$br}->{'branchcode'};
1281 # new op dev : add the branchprinter and branchname in the cookie
1282 $branchprinter = $branches->{$br}->{'branchprinter'};
1283 $branchname = $branches->{$br}->{'branchname'};
1286 $session->param('number',$borrowernumber);
1287 $session->param('id',$userid);
1288 $session->param('cardnumber',$cardnumber);
1289 $session->param('firstname',$firstname);
1290 $session->param('surname',$surname);
1291 $session->param('branch',$branchcode);
1292 $session->param('branchname',$branchname);
1293 $session->param('flags',$userflags);
1294 $session->param('emailaddress',$emailaddress);
1295 $session->param('ip',$session->remote_addr());
1296 $session->param('lasttime',time());
1297 } elsif ( $return == 2 ) {
1298 #We suppose the user is the superlibrarian
1299 $session->param('number',0);
1300 $session->param('id',C4::Context->config('user'));
1301 $session->param('cardnumber',C4::Context->config('user'));
1302 $session->param('firstname',C4::Context->config('user'));
1303 $session->param('surname',C4::Context->config('user'));
1304 $session->param('branch','NO_LIBRARY_SET');
1305 $session->param('branchname','NO_LIBRARY_SET');
1306 $session->param('flags',1);
1307 $session->param('emailaddress', C4::Context->preference('KohaAdminEmailAddress'));
1308 $session->param('ip',$session->remote_addr());
1309 $session->param('lasttime',time());
1311 C4::Context::set_userenv(
1312 $session->param('number'), $session->param('id'),
1313 $session->param('cardnumber'), $session->param('firstname'),
1314 $session->param('surname'), $session->param('branch'),
1315 $session->param('branchname'), $session->param('flags'),
1316 $session->param('emailaddress'), $session->param('branchprinter')
1318 return ("ok", $cookie, $sessionID);
1320 return ("failed", undef, undef);
1325 =head2 check_cookie_auth
1327 ($status, $sessionId) = check_api_auth($cookie, $userflags);
1329 Given a CGISESSID cookie set during a previous login to Koha, determine
1330 if the user has the privileges specified by C<$userflags>.
1332 C<check_cookie_auth> is meant for authenticating special services
1333 such as tools/upload-file.pl that are invoked by other pages that
1334 have been authenticated in the usual way.
1336 Possible return values in C<$status> are:
1340 =item "ok" -- user authenticated; C<$sessionID> have valid values.
1342 =item "failed" -- credentials are not correct; C<$sessionid> are undef
1344 =item "maintenance" -- DB is in maintenance mode; no login possible at the moment
1346 =item "expired -- session cookie has expired; API user should resubmit userid and password
1352 sub check_cookie_auth {
1354 my $flagsrequired = shift;
1356 my $dbh = C4::Context->dbh;
1357 my $timeout = _timeout_syspref();
1359 unless (C4::Context->preference('Version')) {
1360 # database has not been installed yet
1361 return ("maintenance", undef);
1363 my $kohaversion=C4::Context::KOHAVERSION;
1364 $kohaversion =~ s/(.*\..*)\.(.*)\.(.*)/$1$2$3/;
1365 if (C4::Context->preference('Version') < $kohaversion) {
1366 # database in need of version update; assume that
1367 # no API should be called while databsae is in
1369 return ("maintenance", undef);
1372 # FIXME -- most of what follows is a copy-and-paste
1373 # of code from checkauth. There is an obvious need
1374 # for refactoring to separate the various parts of
1375 # the authentication code, but as of 2007-11-23 this
1376 # is deferred so as to not introduce bugs into the
1377 # regular authentication code for Koha 3.0.
1379 # see if we have a valid session cookie already
1380 # however, if a userid parameter is present (i.e., from
1381 # a form submission, assume that any current cookie
1383 unless (defined $cookie and $cookie) {
1384 return ("failed", undef);
1386 my $sessionID = $cookie;
1387 my $session = get_session($sessionID);
1388 C4::Context->_new_userenv($sessionID);
1390 C4::Context::set_userenv(
1391 $session->param('number'), $session->param('id'),
1392 $session->param('cardnumber'), $session->param('firstname'),
1393 $session->param('surname'), $session->param('branch'),
1394 $session->param('branchname'), $session->param('flags'),
1395 $session->param('emailaddress'), $session->param('branchprinter')
1398 my $ip = $session->param('ip');
1399 my $lasttime = $session->param('lasttime');
1400 my $userid = $session->param('id');
1401 if ( $lasttime < time() - $timeout ) {
1404 C4::Context->_unset_userenv($sessionID);
1407 return ("expired", undef);
1408 } elsif ( $ip ne $ENV{'REMOTE_ADDR'} ) {
1409 # IP address changed
1411 C4::Context->_unset_userenv($sessionID);
1414 return ("expired", undef);
1416 $session->param('lasttime',time());
1417 my $flags = haspermission($userid, $flagsrequired);
1419 return ("ok", $sessionID);
1422 C4::Context->_unset_userenv($sessionID);
1425 return ("failed", undef);
1429 return ("expired", undef);
1436 my $session = get_session($sessionID);
1438 Given a session ID, retrieve the CGI::Session object used to store
1439 the session's state. The session object can be used to store
1440 data that needs to be accessed by different scripts during a
1443 If the C<$sessionID> parameter is an empty string, a new session
1449 my $sessionID = shift;
1450 my $storage_method = C4::Context->preference('SessionStorage');
1451 my $dbh = C4::Context->dbh;
1453 if ($storage_method eq 'mysql'){
1454 $session = new CGI::Session("driver:MySQL;serializer:yaml;id:md5", $sessionID, {Handle=>$dbh});
1456 elsif ($storage_method eq 'Pg') {
1457 $session = new CGI::Session("driver:PostgreSQL;serializer:yaml;id:md5", $sessionID, {Handle=>$dbh});
1459 elsif ($storage_method eq 'memcached' && C4::Context->ismemcached){
1460 $session = new CGI::Session("driver:memcached;serializer:yaml;id:md5", $sessionID, { Memcached => C4::Context->memcached } );
1463 # catch all defaults to tmp should work on all systems
1464 $session = new CGI::Session("driver:File;serializer:yaml;id:md5", $sessionID, {Directory=>'/tmp'});
1469 # Using Bcrypt method for hashing. This can be changed to something else in future, if needed.
1471 my $password = shift;
1473 # Generate a salt if one is not passed
1474 my $settings = shift;
1475 unless( defined $settings ){ # if there are no settings, we need to create a salt and append settings
1476 # Set the cost to 8 and append a NULL
1477 $settings = '$2a$08$'.en_base64(generate_salt('weak', 16));
1480 return bcrypt($password, $settings);
1483 =head2 generate_salt
1486 my $salt = C4::Auth::generate_salt($strength, $length);
1490 For general password salting a C<$strength> of C<weak> is recommend,
1491 For generating a server-salt a C<$strength> of C<strong> is recommended
1493 'strong' uses /dev/random which may block until sufficient entropy is acheived.
1494 'weak' uses /dev/urandom and is non-blocking.
1500 C<$length> is a positive integer which specifies the desired length of the returned string
1507 # the implementation of generate_salt is loosely based on Crypt::Random::Provider::File
1509 # strength is 'strong' or 'weak'
1510 # length is number of bytes to read, positive integer
1511 my ($strength, $length) = @_;
1516 die "non-positive strength of '$strength' passed to C4::Auth::generate_salt\n";
1519 if( $strength eq "strong" ){
1520 $source = '/dev/random'; # blocking
1522 unless( $strength eq 'weak' ){
1523 warn "unsuppored strength of '$strength' passed to C4::Auth::generate_salt, defaulting to 'weak'\n";
1525 $source = '/dev/urandom'; # non-blocking
1528 sysopen SOURCE, $source, O_RDONLY
1529 or die "failed to open source '$source' in C4::Auth::generate_salt\n";
1531 # $bytes is the bytes just read
1532 # $string is the concatenation of all the bytes read so far
1533 my( $bytes, $string ) = ("", "");
1535 # keep reading until we have $length bytes in $strength
1536 while( length($string) < $length ){
1537 # return the number of bytes read, 0 (EOF), or -1 (ERROR)
1538 my $return = sysread SOURCE, $bytes, $length - length($string);
1540 # if no bytes were read, keep reading (if using /dev/random it is possible there was insufficient entropy so this may block)
1541 next unless $return;
1542 if( $return == -1 ){
1543 die "error while reading from $source in C4::Auth::generate_salt\n";
1556 my ( $dbh, $userid, $password, $query ) = @_;
1558 $debug and print STDERR "## checkpw - checking LDAP\n";
1559 my ($retval,$retcard,$retuserid) = checkpw_ldap(@_); # EXTERNAL AUTH
1560 ($retval) and return ($retval,$retcard,$retuserid);
1563 if ($cas && $query && $query->param('ticket')) {
1564 $debug and print STDERR "## checkpw - checking CAS\n";
1565 # In case of a CAS authentication, we use the ticket instead of the password
1566 my $ticket = $query->param('ticket');
1567 my ($retval,$retcard,$retuserid) = checkpw_cas($dbh, $ticket, $query); # EXTERNAL AUTH
1568 ($retval) and return ($retval,$retcard,$retuserid);
1575 "select password,cardnumber,borrowernumber,userid,firstname,surname,branchcode,flags from borrowers where userid=?"
1577 $sth->execute($userid);
1579 my ( $stored_hash, $cardnumber, $borrowernumber, $userid, $firstname,
1580 $surname, $branchcode, $flags )
1583 # check what encryption algorithm was implemented: Bcrypt - if the hash starts with '$2' it is Bcrypt else md5
1585 if ( substr($stored_hash,0,2) eq '$2') {
1586 $hash = hash_password($password, $stored_hash);
1588 $hash = md5_base64($password);
1590 if ( $hash eq $stored_hash and $stored_hash ne "!") {
1592 C4::Context->set_userenv( "$borrowernumber", $userid, $cardnumber,
1593 $firstname, $surname, $branchcode, $flags );
1594 return 1, $cardnumber, $userid;
1599 "select password,cardnumber,borrowernumber,userid, firstname,surname,branchcode,flags from borrowers where cardnumber=?"
1601 $sth->execute($userid);
1603 my ( $stored_hash, $cardnumber, $borrowernumber, $userid, $firstname,
1604 $surname, $branchcode, $flags )
1607 # check what encryption algorithm was implemented: Bcrypt - if the hash starts with '$2' it is Bcrypt else md5
1609 if ( substr($stored_hash,0,2) eq '$2') {
1610 $hash = hash_password($password, $stored_hash);
1612 $hash = md5_base64($password);
1615 if ( $hash eq $stored_hash ) {
1617 C4::Context->set_userenv( $borrowernumber, $userid, $cardnumber,
1618 $firstname, $surname, $branchcode, $flags );
1619 return 1, $cardnumber, $userid;
1622 if ( $userid && $userid eq C4::Context->config('user')
1623 && "$password" eq C4::Context->config('pass') )
1626 # Koha superuser account
1627 # C4::Context->set_userenv(0,0,C4::Context->config('user'),C4::Context->config('user'),C4::Context->config('user'),"",1);
1630 if ( $userid && $userid eq 'demo'
1631 && "$password" eq 'demo'
1632 && C4::Context->config('demo') )
1635 # DEMO => the demo user is allowed to do everything (if demo set to 1 in koha.conf
1636 # some features won't be effective : modify systempref, modify MARC structure,
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;
1678 # get subpermissions and merge with top-level permissions
1679 my $user_subperms = get_user_subpermissions($userid);
1680 foreach my $module (keys %$user_subperms) {
1681 next if $userflags->{$module} == 1; # user already has permission for everything in this module
1682 $userflags->{$module} = $user_subperms->{$module};
1688 =head2 get_user_subpermissions
1690 $user_perm_hashref = get_user_subpermissions($userid);
1692 Given the userid (note, not the borrowernumber) of a staff user,
1693 return a hashref of hashrefs of the specific subpermissions
1694 accorded to the user. An example return is
1698 export_catalog => 1,
1699 import_patrons => 1,
1703 The top-level hash-key is a module or function code from
1704 userflags.flag, while the second-level key is a code
1707 The results of this function do not give a complete picture
1708 of the functions that a staff user can access; it is also
1709 necessary to check borrowers.flags.
1713 sub get_user_subpermissions {
1716 my $dbh = C4::Context->dbh;
1717 my $sth = $dbh->prepare("SELECT flag, user_permissions.code
1718 FROM user_permissions
1719 JOIN permissions USING (module_bit, code)
1720 JOIN userflags ON (module_bit = bit)
1721 JOIN borrowers USING (borrowernumber)
1723 $sth->execute($userid);
1725 my $user_perms = {};
1726 while (my $perm = $sth->fetchrow_hashref) {
1727 $user_perms->{$perm->{'flag'}}->{$perm->{'code'}} = 1;
1732 =head2 get_all_subpermissions
1734 my $perm_hashref = get_all_subpermissions();
1736 Returns a hashref of hashrefs defining all specific
1737 permissions currently defined. The return value
1738 has the same structure as that of C<get_user_subpermissions>,
1739 except that the innermost hash value is the description
1740 of the subpermission.
1744 sub get_all_subpermissions {
1745 my $dbh = C4::Context->dbh;
1746 my $sth = $dbh->prepare("SELECT flag, code, description
1748 JOIN userflags ON (module_bit = bit)");
1752 while (my $perm = $sth->fetchrow_hashref) {
1753 $all_perms->{$perm->{'flag'}}->{$perm->{'code'}} = $perm->{'description'};
1758 =head2 haspermission
1760 $flags = ($userid, $flagsrequired);
1762 C<$userid> the userid of the member
1763 C<$flags> is a hashref of required flags like C<$borrower-<{authflags}>
1765 Returns member's flags or 0 if a permission is not met.
1770 my ($userid, $flagsrequired) = @_;
1771 my $sth = C4::Context->dbh->prepare("SELECT flags FROM borrowers WHERE userid=?");
1772 $sth->execute($userid);
1773 my $flags = getuserflags($sth->fetchrow(), $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 sub ParseSearchHistoryCookie {
1824 my $search_cookie = $input->cookie('KohaOpacRecentSearches');
1825 return () unless $search_cookie;
1826 my $obj = eval { decode_json(uri_unescape($search_cookie)) };
1827 return () unless defined $obj;
1828 return () unless ref $obj eq 'ARRAY';
1832 END { } # module clean-up code here (global destructor)