Bug 12263: Fix startup issues blocking response to HUP
[koha.git] / C4 / Auth.pm
blob1bbc0bdb3750f88cfa14b66e23d20ac2f165a6ef
1 package C4::Auth;
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
10 # version.
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.
20 use strict;
21 use warnings;
22 use Digest::MD5 qw(md5_base64);
23 use JSON qw/encode_json/;
24 use URI::Escape;
25 use CGI::Session;
27 require Exporter;
28 use C4::Context;
29 use C4::Templates; # to get the template
30 use C4::Languages;
31 use C4::Branch; # GetBranches
32 use C4::Search::History;
33 use C4::VirtualShelves;
34 use Koha::AuthUtils qw(hash_password);
35 use POSIX qw/strftime/;
36 use List::MoreUtils qw/ any /;
38 # use utf8;
39 use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS $debug $ldap $cas $caslogout);
41 BEGIN {
42 sub psgi_env { any { /^psgi\./ } keys %ENV }
43 sub safe_exit {
44 if ( psgi_env ) { die 'psgi:exit' }
45 else { exit }
47 $VERSION = 3.07.00.049; # set version for version checking
49 $debug = $ENV{DEBUG};
50 @ISA = qw(Exporter);
51 @EXPORT = qw(&checkauth &get_template_and_user &haspermission &get_user_subpermissions);
52 @EXPORT_OK = qw(&check_api_auth &get_session &check_cookie_auth &checkpw &checkpw_internal &checkpw_hash
53 &get_all_subpermissions &get_user_subpermissions
55 %EXPORT_TAGS = ( EditPermissions => [qw(get_all_subpermissions get_user_subpermissions)] );
56 $ldap = C4::Context->config('useldapserver') || 0;
57 $cas = C4::Context->preference('casAuthentication');
58 $caslogout = C4::Context->preference('casLogout');
59 require C4::Auth_with_cas; # no import
60 if ($ldap) {
61 require C4::Auth_with_ldap;
62 import C4::Auth_with_ldap qw(checkpw_ldap);
64 if ($cas) {
65 import C4::Auth_with_cas qw(check_api_auth_cas checkpw_cas login_cas logout_cas login_cas_url);
70 =head1 NAME
72 C4::Auth - Authenticates Koha users
74 =head1 SYNOPSIS
76 use CGI;
77 use C4::Auth;
78 use C4::Output;
80 my $query = new CGI;
82 my ($template, $borrowernumber, $cookie)
83 = get_template_and_user(
85 template_name => "opac-main.tmpl",
86 query => $query,
87 type => "opac",
88 authnotrequired => 0,
89 flagsrequired => {borrow => 1, catalogue => '*', tools => 'import_patrons' },
93 output_html_with_http_headers $query, $cookie, $template->output;
95 =head1 DESCRIPTION
97 The main function of this module is to provide
98 authentification. However the get_template_and_user function has
99 been provided so that a users login information is passed along
100 automatically. This gets loaded into the template.
102 =head1 FUNCTIONS
104 =head2 get_template_and_user
106 my ($template, $borrowernumber, $cookie)
107 = get_template_and_user(
109 template_name => "opac-main.tmpl",
110 query => $query,
111 type => "opac",
112 authnotrequired => 0,
113 flagsrequired => {borrow => 1, catalogue => '*', tools => 'import_patrons' },
117 This call passes the C<query>, C<flagsrequired> and C<authnotrequired>
118 to C<&checkauth> (in this module) to perform authentification.
119 See C<&checkauth> for an explanation of these parameters.
121 The C<template_name> is then used to find the correct template for
122 the page. The authenticated users details are loaded onto the
123 template in the HTML::Template LOOP variable C<USER_INFO>. Also the
124 C<sessionID> is passed to the template. This can be used in templates
125 if cookies are disabled. It needs to be put as and input to every
126 authenticated page.
128 More information on the C<gettemplate> sub can be found in the
129 Output.pm module.
131 =cut
133 sub get_template_and_user {
135 my $in = shift;
136 my ( $user, $cookie, $sessionID, $flags );
138 C4::Context->interface($in->{type});
140 $in->{'authnotrequired'} ||= 0;
141 my $template = C4::Templates::gettemplate(
142 $in->{'template_name'},
143 $in->{'type'},
144 $in->{'query'},
145 $in->{'is_plugin'}
148 if ( $in->{'template_name'} !~m/maintenance/ ) {
149 ( $user, $cookie, $sessionID, $flags ) = checkauth(
150 $in->{'query'},
151 $in->{'authnotrequired'},
152 $in->{'flagsrequired'},
153 $in->{'type'}
157 my $borrowernumber;
158 if ($user) {
159 require C4::Members;
160 # It's possible for $user to be the borrowernumber if they don't have a
161 # userid defined (and are logging in through some other method, such
162 # as SSL certs against an email address)
163 $borrowernumber = getborrowernumber($user) if defined($user);
164 if (!defined($borrowernumber) && defined($user)) {
165 my $borrower = C4::Members::GetMember(borrowernumber => $user);
166 if ($borrower) {
167 $borrowernumber = $user;
168 # A bit of a hack, but I don't know there's a nicer way
169 # to do it.
170 $user = $borrower->{firstname} . ' ' . $borrower->{surname};
174 # user info
175 $template->param( loggedinusername => $user );
176 $template->param( sessionID => $sessionID );
178 my ($total, $pubshelves, $barshelves) = C4::VirtualShelves::GetSomeShelfNames($borrowernumber, 'MASTHEAD');
179 $template->param(
180 pubshelves => $total->{pubtotal},
181 pubshelvesloop => $pubshelves,
182 barshelves => $total->{bartotal},
183 barshelvesloop => $barshelves,
186 my ( $borr ) = C4::Members::GetMemberDetails( $borrowernumber );
187 my @bordat;
188 $bordat[0] = $borr;
189 $template->param( "USER_INFO" => \@bordat );
191 my $all_perms = get_all_subpermissions();
193 my @flagroots = qw(circulate catalogue parameters borrowers permissions reserveforothers borrow
194 editcatalogue updatecharges management tools editauthorities serials reports acquisition);
195 # We are going to use the $flags returned by checkauth
196 # to create the template's parameters that will indicate
197 # which menus the user can access.
198 if ( $flags && $flags->{superlibrarian}==1 ) {
199 $template->param( CAN_user_circulate => 1 );
200 $template->param( CAN_user_catalogue => 1 );
201 $template->param( CAN_user_parameters => 1 );
202 $template->param( CAN_user_borrowers => 1 );
203 $template->param( CAN_user_permissions => 1 );
204 $template->param( CAN_user_reserveforothers => 1 );
205 $template->param( CAN_user_borrow => 1 );
206 $template->param( CAN_user_editcatalogue => 1 );
207 $template->param( CAN_user_updatecharges => 1 );
208 $template->param( CAN_user_acquisition => 1 );
209 $template->param( CAN_user_management => 1 );
210 $template->param( CAN_user_tools => 1 );
211 $template->param( CAN_user_editauthorities => 1 );
212 $template->param( CAN_user_serials => 1 );
213 $template->param( CAN_user_reports => 1 );
214 $template->param( CAN_user_staffaccess => 1 );
215 $template->param( CAN_user_plugins => 1 );
216 $template->param( CAN_user_coursereserves => 1 );
217 foreach my $module (keys %$all_perms) {
218 foreach my $subperm (keys %{ $all_perms->{$module} }) {
219 $template->param( "CAN_user_${module}_${subperm}" => 1 );
224 if ( $flags ) {
225 foreach my $module (keys %$all_perms) {
226 if ( $flags->{$module} == 1) {
227 foreach my $subperm (keys %{ $all_perms->{$module} }) {
228 $template->param( "CAN_user_${module}_${subperm}" => 1 );
230 } elsif ( ref($flags->{$module}) ) {
231 foreach my $subperm (keys %{ $flags->{$module} } ) {
232 $template->param( "CAN_user_${module}_${subperm}" => 1 );
238 if ($flags) {
239 foreach my $module (keys %$flags) {
240 if ( $flags->{$module} == 1 or ref($flags->{$module}) ) {
241 $template->param( "CAN_user_$module" => 1 );
242 if ($module eq "parameters") {
243 $template->param( CAN_user_management => 1 );
248 # Logged-in opac search history
249 # If the requested template is an opac one and opac search history is enabled
250 if ($in->{type} eq 'opac' && C4::Context->preference('EnableOpacSearchHistory')) {
251 my $dbh = C4::Context->dbh;
252 my $query = "SELECT COUNT(*) FROM search_history WHERE userid=?";
253 my $sth = $dbh->prepare($query);
254 $sth->execute($borrowernumber);
256 # If at least one search has already been performed
257 if ($sth->fetchrow_array > 0) {
258 # We show the link in opac
259 $template->param( EnableOpacSearchHistory => 1 );
262 # And if there are searches performed when the user was not logged in,
263 # we add them to the logged-in search history
264 my @recentSearches = C4::Search::History::get_from_session({ cgi => $in->{'query'} });
265 if (@recentSearches) {
266 my $dbh = C4::Context->dbh;
267 my $query = q{
268 INSERT INTO search_history(userid, sessionid, query_desc, query_cgi, type, total, time )
269 VALUES (?, ?, ?, ?, ?, ?, ?)
272 my $sth = $dbh->prepare($query);
273 $sth->execute( $borrowernumber,
274 $in->{query}->cookie("CGISESSID"),
275 $_->{query_desc},
276 $_->{query_cgi},
277 $_->{type} || 'biblio',
278 $_->{total},
279 $_->{time},
280 ) foreach @recentSearches;
282 # clear out the search history from the session now that
283 # we've saved it to the database
284 C4::Search::History::set_to_session({ cgi => $in->{'query'}, search_history => [] });
286 } elsif ( $in->{type} eq 'intranet' and C4::Context->preference('EnableSearchHistory') ) {
287 $template->param( EnableSearchHistory => 1 );
290 else { # if this is an anonymous session, setup to display public lists...
292 $template->param( sessionID => $sessionID );
294 my ($total, $pubshelves) = C4::VirtualShelves::GetSomeShelfNames(undef, 'MASTHEAD');
295 $template->param(
296 pubshelves => $total->{pubtotal},
297 pubshelvesloop => $pubshelves,
300 # Anonymous opac search history
301 # If opac search history is enabled and at least one search has already been performed
302 if (C4::Context->preference('EnableOpacSearchHistory')) {
303 my @recentSearches = C4::Search::History::get_from_session({ cgi => $in->{'query'} });
304 if (@recentSearches) {
305 $template->param(EnableOpacSearchHistory => 1);
309 if(C4::Context->preference('dateformat')){
310 $template->param(dateformat => C4::Context->preference('dateformat'))
313 # these template parameters are set the same regardless of $in->{'type'}
315 # Set the using_https variable for templates
316 # FIXME Under Plack the CGI->https method always returns 'OFF'
317 my $https = $in->{query}->https();
318 my $using_https = (defined $https and $https ne 'OFF') ? 1 : 0;
320 $template->param(
321 "BiblioDefaultView".C4::Context->preference("BiblioDefaultView") => 1,
322 EnhancedMessagingPreferences => C4::Context->preference('EnhancedMessagingPreferences'),
323 GoogleJackets => C4::Context->preference("GoogleJackets"),
324 OpenLibraryCovers => C4::Context->preference("OpenLibraryCovers"),
325 KohaAdminEmailAddress => "" . C4::Context->preference("KohaAdminEmailAddress"),
326 LoginBranchcode => (C4::Context->userenv?C4::Context->userenv->{"branch"}:undef),
327 LoginFirstname => (C4::Context->userenv?C4::Context->userenv->{"firstname"}:"Bel"),
328 LoginSurname => C4::Context->userenv?C4::Context->userenv->{"surname"}:"Inconnu",
329 emailaddress => C4::Context->userenv?C4::Context->userenv->{"emailaddress"}:undef,
330 loggedinpersona => C4::Context->userenv?C4::Context->userenv->{"persona"}:undef,
331 TagsEnabled => C4::Context->preference("TagsEnabled"),
332 hide_marc => C4::Context->preference("hide_marc"),
333 item_level_itypes => C4::Context->preference('item-level_itypes'),
334 patronimages => C4::Context->preference("patronimages"),
335 singleBranchMode => C4::Context->preference("singleBranchMode"),
336 XSLTDetailsDisplay => C4::Context->preference("XSLTDetailsDisplay"),
337 XSLTResultsDisplay => C4::Context->preference("XSLTResultsDisplay"),
338 using_https => $using_https,
339 noItemTypeImages => C4::Context->preference("noItemTypeImages"),
340 marcflavour => C4::Context->preference("marcflavour"),
341 persona => C4::Context->preference("persona"),
343 if ( $in->{'type'} eq "intranet" ) {
344 $template->param(
345 AmazonCoverImages => C4::Context->preference("AmazonCoverImages"),
346 AutoLocation => C4::Context->preference("AutoLocation"),
347 "BiblioDefaultView".C4::Context->preference("IntranetBiblioDefaultView") => 1,
348 CalendarFirstDayOfWeek => (C4::Context->preference("CalendarFirstDayOfWeek") eq "Sunday")?0:1,
349 CircAutocompl => C4::Context->preference("CircAutocompl"),
350 FRBRizeEditions => C4::Context->preference("FRBRizeEditions"),
351 IndependentBranches => C4::Context->preference("IndependentBranches"),
352 IntranetNav => C4::Context->preference("IntranetNav"),
353 IntranetmainUserblock => C4::Context->preference("IntranetmainUserblock"),
354 LibraryName => C4::Context->preference("LibraryName"),
355 LoginBranchname => (C4::Context->userenv?C4::Context->userenv->{"branchname"}:undef),
356 advancedMARCEditor => C4::Context->preference("advancedMARCEditor"),
357 canreservefromotherbranches => C4::Context->preference('canreservefromotherbranches'),
358 intranetcolorstylesheet => C4::Context->preference("intranetcolorstylesheet"),
359 IntranetFavicon => C4::Context->preference("IntranetFavicon"),
360 intranetreadinghistory => C4::Context->preference("intranetreadinghistory"),
361 intranetstylesheet => C4::Context->preference("intranetstylesheet"),
362 IntranetUserCSS => C4::Context->preference("IntranetUserCSS"),
363 intranetuserjs => C4::Context->preference("intranetuserjs"),
364 intranetbookbag => C4::Context->preference("intranetbookbag"),
365 suggestion => C4::Context->preference("suggestion"),
366 virtualshelves => C4::Context->preference("virtualshelves"),
367 StaffSerialIssueDisplayCount => C4::Context->preference("StaffSerialIssueDisplayCount"),
368 EasyAnalyticalRecords => C4::Context->preference('EasyAnalyticalRecords'),
369 LocalCoverImages => C4::Context->preference('LocalCoverImages'),
370 OPACLocalCoverImages => C4::Context->preference('OPACLocalCoverImages'),
371 AllowMultipleCovers => C4::Context->preference('AllowMultipleCovers'),
372 EnableBorrowerFiles => C4::Context->preference('EnableBorrowerFiles'),
373 UseKohaPlugins => C4::Context->preference('UseKohaPlugins'),
374 UseCourseReserves => C4::Context->preference("UseCourseReserves"),
377 else {
378 warn "template type should be OPAC, here it is=[" . $in->{'type'} . "]" unless ( $in->{'type'} eq 'opac' );
379 #TODO : replace LibraryName syspref with 'system name', and remove this html processing
380 my $LibraryNameTitle = C4::Context->preference("LibraryName");
381 $LibraryNameTitle =~ s/<(?:\/?)(?:br|p)\s*(?:\/?)>/ /sgi;
382 $LibraryNameTitle =~ s/<(?:[^<>'"]|'(?:[^']*)'|"(?:[^"]*)")*>//sg;
383 # clean up the busc param in the session if the page is not opac-detail and not the "add to list" page
384 if ( C4::Context->preference("OpacBrowseResults")
385 && $in->{'template_name'} =~ /opac-(.+)\.(?:tt|tmpl)$/ ) {
386 my $pagename = $1;
387 unless ( $pagename =~ /^(?:MARC|ISBD)?detail$/
388 or $pagename =~ /^addbybiblionumber$/ ) {
389 my $sessionSearch = get_session($sessionID || $in->{'query'}->cookie("CGISESSID"));
390 $sessionSearch->clear(["busc"]) if ($sessionSearch->param("busc"));
393 # variables passed from CGI: opac_css_override and opac_search_limits.
394 my $opac_search_limit = $ENV{'OPAC_SEARCH_LIMIT'};
395 my $opac_limit_override = $ENV{'OPAC_LIMIT_OVERRIDE'};
396 my $opac_name = '';
397 if (
398 ($opac_limit_override && $opac_search_limit && $opac_search_limit =~ /branch:(\w+)/) ||
399 ($in->{'query'}->param('limit') && $in->{'query'}->param('limit') =~ /branch:(\w+)/) ||
400 ($in->{'query'}->param('multibranchlimit') && $in->{'query'}->param('multibranchlimit') =~ /multibranchlimit-(\w+)/)
402 $opac_name = $1; # opac_search_limit is a branch, so we use it.
403 } elsif ( $in->{'query'}->param('multibranchlimit') ) {
404 $opac_name = $in->{'query'}->param('multibranchlimit');
405 } elsif (C4::Context->preference("SearchMyLibraryFirst") && C4::Context->userenv && C4::Context->userenv->{'branch'}) {
406 $opac_name = C4::Context->userenv->{'branch'};
408 # FIXME Under Plack the CGI->https method always returns 'OFF' ($using_https will be set to 0 in this case)
409 my $opac_base_url = C4::Context->preference("OPACBaseURL"); #FIXME uses $using_https below as well
410 if (!$opac_base_url){
411 $opac_base_url = $ENV{'SERVER_NAME'} . ($ENV{'SERVER_PORT'} eq ($using_https ? "443" : "80") ? '' : ":$ENV{'SERVER_PORT'}");
413 $template->param(
414 opaccolorstylesheet => C4::Context->preference("opaccolorstylesheet"),
415 AnonSuggestions => "" . C4::Context->preference("AnonSuggestions"),
416 AuthorisedValueImages => C4::Context->preference("AuthorisedValueImages"),
417 BranchesLoop => GetBranchesLoop($opac_name),
418 BranchCategoriesLoop => GetBranchCategories( 'searchdomain', 1, $opac_name ),
419 CalendarFirstDayOfWeek => (C4::Context->preference("CalendarFirstDayOfWeek") eq "Sunday")?0:1,
420 LibraryName => "" . C4::Context->preference("LibraryName"),
421 LibraryNameTitle => "" . $LibraryNameTitle,
422 LoginBranchname => C4::Context->userenv?C4::Context->userenv->{"branchname"}:"",
423 OPACAmazonCoverImages => C4::Context->preference("OPACAmazonCoverImages"),
424 OPACFRBRizeEditions => C4::Context->preference("OPACFRBRizeEditions"),
425 OpacHighlightedWords => C4::Context->preference("OpacHighlightedWords"),
426 OPACItemHolds => C4::Context->preference("OPACItemHolds"),
427 OPACShelfBrowser => "". C4::Context->preference("OPACShelfBrowser"),
428 OPACURLOpenInNewWindow => "" . C4::Context->preference("OPACURLOpenInNewWindow"),
429 OPACUserCSS => "". C4::Context->preference("OPACUserCSS"),
430 OPACMobileUserCSS => "". C4::Context->preference("OPACMobileUserCSS"),
431 OPACViewOthersSuggestions => "" . C4::Context->preference("OPACViewOthersSuggestions"),
432 OpacAuthorities => C4::Context->preference("OpacAuthorities"),
433 OPACBaseURL => ($using_https ? "https://" : "http://") . $opac_base_url,
434 opac_css_override => $ENV{'OPAC_CSS_OVERRIDE'},
435 opac_search_limit => $opac_search_limit,
436 opac_limit_override => $opac_limit_override,
437 OpacBrowser => C4::Context->preference("OpacBrowser"),
438 OpacCloud => C4::Context->preference("OpacCloud"),
439 OpacKohaUrl => C4::Context->preference("OpacKohaUrl"),
440 OpacMainUserBlock => "" . C4::Context->preference("OpacMainUserBlock"),
441 OpacMainUserBlockMobile => "" . C4::Context->preference("OpacMainUserBlockMobile"),
442 OpacShowFiltersPulldownMobile => C4::Context->preference("OpacShowFiltersPulldownMobile"),
443 OpacShowLibrariesPulldownMobile => C4::Context->preference("OpacShowLibrariesPulldownMobile"),
444 OpacNav => "" . C4::Context->preference("OpacNav"),
445 OpacNavRight => "" . C4::Context->preference("OpacNavRight"),
446 OpacNavBottom => "" . C4::Context->preference("OpacNavBottom"),
447 OpacPasswordChange => C4::Context->preference("OpacPasswordChange"),
448 OPACPatronDetails => C4::Context->preference("OPACPatronDetails"),
449 OPACPrivacy => C4::Context->preference("OPACPrivacy"),
450 OPACFinesTab => C4::Context->preference("OPACFinesTab"),
451 OpacTopissue => C4::Context->preference("OpacTopissue"),
452 RequestOnOpac => C4::Context->preference("RequestOnOpac"),
453 'Version' => C4::Context->preference('Version'),
454 hidelostitems => C4::Context->preference("hidelostitems"),
455 mylibraryfirst => (C4::Context->preference("SearchMyLibraryFirst") && C4::Context->userenv) ? C4::Context->userenv->{'branch'} : '',
456 opaclayoutstylesheet => "" . C4::Context->preference("opaclayoutstylesheet"),
457 opacbookbag => "" . C4::Context->preference("opacbookbag"),
458 opaccredits => "" . C4::Context->preference("opaccredits"),
459 OpacFavicon => C4::Context->preference("OpacFavicon"),
460 opacheader => "" . C4::Context->preference("opacheader"),
461 opaclanguagesdisplay => "" . C4::Context->preference("opaclanguagesdisplay"),
462 opacreadinghistory => C4::Context->preference("opacreadinghistory"),
463 opacsmallimage => "" . C4::Context->preference("opacsmallimage"),
464 opacuserjs => C4::Context->preference("opacuserjs"),
465 opacuserlogin => "" . C4::Context->preference("opacuserlogin"),
466 ShowReviewer => C4::Context->preference("ShowReviewer"),
467 ShowReviewerPhoto => C4::Context->preference("ShowReviewerPhoto"),
468 suggestion => "" . C4::Context->preference("suggestion"),
469 virtualshelves => "" . C4::Context->preference("virtualshelves"),
470 OPACSerialIssueDisplayCount => C4::Context->preference("OPACSerialIssueDisplayCount"),
471 OPACXSLTDetailsDisplay => C4::Context->preference("OPACXSLTDetailsDisplay"),
472 OPACXSLTResultsDisplay => C4::Context->preference("OPACXSLTResultsDisplay"),
473 SyndeticsClientCode => C4::Context->preference("SyndeticsClientCode"),
474 SyndeticsEnabled => C4::Context->preference("SyndeticsEnabled"),
475 SyndeticsCoverImages => C4::Context->preference("SyndeticsCoverImages"),
476 SyndeticsTOC => C4::Context->preference("SyndeticsTOC"),
477 SyndeticsSummary => C4::Context->preference("SyndeticsSummary"),
478 SyndeticsEditions => C4::Context->preference("SyndeticsEditions"),
479 SyndeticsExcerpt => C4::Context->preference("SyndeticsExcerpt"),
480 SyndeticsReviews => C4::Context->preference("SyndeticsReviews"),
481 SyndeticsAuthorNotes => C4::Context->preference("SyndeticsAuthorNotes"),
482 SyndeticsAwards => C4::Context->preference("SyndeticsAwards"),
483 SyndeticsSeries => C4::Context->preference("SyndeticsSeries"),
484 SyndeticsCoverImageSize => C4::Context->preference("SyndeticsCoverImageSize"),
485 OPACLocalCoverImages => C4::Context->preference("OPACLocalCoverImages"),
486 PatronSelfRegistration => C4::Context->preference("PatronSelfRegistration"),
487 PatronSelfRegistrationDefaultCategory => C4::Context->preference("PatronSelfRegistrationDefaultCategory"),
490 $template->param(OpacPublic => '1') if ($user || C4::Context->preference("OpacPublic"));
493 # Check if we were asked using parameters to force a specific language
494 if ( defined $in->{'query'}->param('language') ) {
495 # Extract the language, let C4::Languages::getlanguage choose
496 # what to do
497 my $language = C4::Languages::getlanguage($in->{'query'});
498 my $languagecookie = C4::Templates::getlanguagecookie($in->{'query'},$language);
499 if ( ref $cookie eq 'ARRAY' ) {
500 push @{ $cookie }, $languagecookie;
501 } else {
502 $cookie = [$cookie, $languagecookie];
506 return ( $template, $borrowernumber, $cookie, $flags);
509 =head2 checkauth
511 ($userid, $cookie, $sessionID) = &checkauth($query, $noauth, $flagsrequired, $type);
513 Verifies that the user is authorized to run this script. If
514 the user is authorized, a (userid, cookie, session-id, flags)
515 quadruple is returned. If the user is not authorized but does
516 not have the required privilege (see $flagsrequired below), it
517 displays an error page and exits. Otherwise, it displays the
518 login page and exits.
520 Note that C<&checkauth> will return if and only if the user
521 is authorized, so it should be called early on, before any
522 unfinished operations (e.g., if you've opened a file, then
523 C<&checkauth> won't close it for you).
525 C<$query> is the CGI object for the script calling C<&checkauth>.
527 The C<$noauth> argument is optional. If it is set, then no
528 authorization is required for the script.
530 C<&checkauth> fetches user and session information from C<$query> and
531 ensures that the user is authorized to run scripts that require
532 authorization.
534 The C<$flagsrequired> argument specifies the required privileges
535 the user must have if the username and password are correct.
536 It should be specified as a reference-to-hash; keys in the hash
537 should be the "flags" for the user, as specified in the Members
538 intranet module. Any key specified must correspond to a "flag"
539 in the userflags table. E.g., { circulate => 1 } would specify
540 that the user must have the "circulate" privilege in order to
541 proceed. To make sure that access control is correct, the
542 C<$flagsrequired> parameter must be specified correctly.
544 Koha also has a concept of sub-permissions, also known as
545 granular permissions. This makes the value of each key
546 in the C<flagsrequired> hash take on an additional
547 meaning, i.e.,
551 The user must have access to all subfunctions of the module
552 specified by the hash key.
556 The user must have access to at least one subfunction of the module
557 specified by the hash key.
559 specific permission, e.g., 'export_catalog'
561 The user must have access to the specific subfunction list, which
562 must correspond to a row in the permissions table.
564 The C<$type> argument specifies whether the template should be
565 retrieved from the opac or intranet directory tree. "opac" is
566 assumed if it is not specified; however, if C<$type> is specified,
567 "intranet" is assumed if it is not "opac".
569 If C<$query> does not have a valid session ID associated with it
570 (i.e., the user has not logged in) or if the session has expired,
571 C<&checkauth> presents the user with a login page (from the point of
572 view of the original script, C<&checkauth> does not return). Once the
573 user has authenticated, C<&checkauth> restarts the original script
574 (this time, C<&checkauth> returns).
576 The login page is provided using a HTML::Template, which is set in the
577 systempreferences table or at the top of this file. The variable C<$type>
578 selects which template to use, either the opac or the intranet
579 authentification template.
581 C<&checkauth> returns a user ID, a cookie, and a session ID. The
582 cookie should be sent back to the browser; it verifies that the user
583 has authenticated.
585 =cut
587 sub _version_check {
588 my $type = shift;
589 my $query = shift;
590 my $version;
591 # If Version syspref is unavailable, it means Koha is beeing installed,
592 # and so we must redirect to OPAC maintenance page or to the WebInstaller
593 # also, if OpacMaintenance is ON, OPAC should redirect to maintenance
594 if (C4::Context->preference('OpacMaintenance') && $type eq 'opac') {
595 warn "OPAC Install required, redirecting to maintenance";
596 print $query->redirect("/cgi-bin/koha/maintenance.pl");
597 safe_exit;
599 unless ( $version = C4::Context->preference('Version') ) { # assignment, not comparison
600 if ( $type ne 'opac' ) {
601 warn "Install required, redirecting to Installer";
602 print $query->redirect("/cgi-bin/koha/installer/install.pl");
603 } else {
604 warn "OPAC Install required, redirecting to maintenance";
605 print $query->redirect("/cgi-bin/koha/maintenance.pl");
607 safe_exit;
610 # check that database and koha version are the same
611 # there is no DB version, it's a fresh install,
612 # go to web installer
613 # there is a DB version, compare it to the code version
614 my $kohaversion=C4::Context::KOHAVERSION;
615 # remove the 3 last . to have a Perl number
616 $kohaversion =~ s/(.*\..*)\.(.*)\.(.*)/$1$2$3/;
617 $debug and print STDERR "kohaversion : $kohaversion\n";
618 if ($version < $kohaversion){
619 my $warning = "Database update needed, redirecting to %s. Database is $version and Koha is $kohaversion";
620 if ($type ne 'opac'){
621 warn sprintf($warning, 'Installer');
622 print $query->redirect("/cgi-bin/koha/installer/install.pl?step=3");
623 } else {
624 warn sprintf("OPAC: " . $warning, 'maintenance');
625 print $query->redirect("/cgi-bin/koha/maintenance.pl");
627 safe_exit;
631 sub _session_log {
632 (@_) or return 0;
633 open my $fh, '>>', "/tmp/sessionlog" or warn "ERROR: Cannot append to /tmp/sessionlog";
634 printf $fh join("\n",@_);
635 close $fh;
638 sub _timeout_syspref {
639 my $timeout = C4::Context->preference('timeout') || 600;
640 # value in days, convert in seconds
641 if ($timeout =~ /(\d+)[dD]/) {
642 $timeout = $1 * 86400;
644 return $timeout;
647 sub checkauth {
648 my $query = shift;
649 $debug and warn "Checking Auth";
650 # $authnotrequired will be set for scripts which will run without authentication
651 my $authnotrequired = shift;
652 my $flagsrequired = shift;
653 my $type = shift;
654 my $persona = shift;
655 $type = 'opac' unless $type;
657 my $dbh = C4::Context->dbh;
658 my $timeout = _timeout_syspref();
660 _version_check($type,$query);
661 # state variables
662 my $loggedin = 0;
663 my %info;
664 my ( $userid, $cookie, $sessionID, $flags, $barshelves, $pubshelves );
665 my $logout = $query->param('logout.x');
667 my $anon_search_history;
669 # This parameter is the name of the CAS server we want to authenticate against,
670 # when using authentication against multiple CAS servers, as configured in Auth_cas_servers.yaml
671 my $casparam = $query->param('cas');
672 my $q_userid = $query->param('userid') // '';
674 if ( $userid = $ENV{'REMOTE_USER'} ) {
675 # Using Basic Authentication, no cookies required
676 $cookie = $query->cookie(
677 -name => 'CGISESSID',
678 -value => '',
679 -expires => '',
680 -HttpOnly => 1,
682 $loggedin = 1;
684 elsif ( $persona ){
685 # we dont want to set a session because we are being called by a persona callback
687 elsif ( $sessionID = $query->cookie("CGISESSID") )
688 { # assignment, not comparison
689 my $session = get_session($sessionID);
690 C4::Context->_new_userenv($sessionID);
691 my ($ip, $lasttime, $sessiontype);
692 my $s_userid = '';
693 if ($session){
694 $s_userid = $session->param('id') // '';
695 C4::Context::set_userenv(
696 $session->param('number'), $s_userid,
697 $session->param('cardnumber'), $session->param('firstname'),
698 $session->param('surname'), $session->param('branch'),
699 $session->param('branchname'), $session->param('flags'),
700 $session->param('emailaddress'), $session->param('branchprinter'),
701 $session->param('persona')
703 C4::Context::set_shelves_userenv('bar',$session->param('barshelves'));
704 C4::Context::set_shelves_userenv('pub',$session->param('pubshelves'));
705 C4::Context::set_shelves_userenv('tot',$session->param('totshelves'));
706 $debug and printf STDERR "AUTH_SESSION: (%s)\t%s %s - %s\n", map {$session->param($_)} qw(cardnumber firstname surname branch) ;
707 $ip = $session->param('ip');
708 $lasttime = $session->param('lasttime');
709 $userid = $s_userid;
710 $sessiontype = $session->param('sessiontype') || '';
712 if ( ( $query->param('koha_login_context') && ($q_userid ne $s_userid) )
713 || ( $cas && $query->param('ticket') ) ) {
714 #if a user enters an id ne to the id in the current session, we need to log them in...
715 #first we need to clear the anonymous session...
716 $debug and warn "query id = $q_userid but session id = $s_userid";
717 $anon_search_history = $session->param('search_history');
718 $session->delete();
719 $session->flush;
720 C4::Context->_unset_userenv($sessionID);
721 $sessionID = undef;
722 $userid = undef;
724 elsif ($logout) {
725 # voluntary logout the user
726 $session->delete();
727 $session->flush;
728 C4::Context->_unset_userenv($sessionID);
729 #_session_log(sprintf "%20s from %16s logged out at %30s (manually).\n", $userid,$ip,(strftime "%c",localtime));
730 $sessionID = undef;
731 $userid = undef;
733 if ($cas and $caslogout) {
734 logout_cas($query);
737 elsif ( !$lasttime || ($lasttime < time() - $timeout) ) {
738 # timed logout
739 $info{'timed_out'} = 1;
740 if ($session) {
741 $session->delete();
742 $session->flush;
744 C4::Context->_unset_userenv($sessionID);
745 #_session_log(sprintf "%20s from %16s logged out at %30s (inactivity).\n", $userid,$ip,(strftime "%c",localtime));
746 $userid = undef;
747 $sessionID = undef;
749 elsif ( $ip ne $ENV{'REMOTE_ADDR'} ) {
750 # Different ip than originally logged in from
751 $info{'oldip'} = $ip;
752 $info{'newip'} = $ENV{'REMOTE_ADDR'};
753 $info{'different_ip'} = 1;
754 $session->delete();
755 $session->flush;
756 C4::Context->_unset_userenv($sessionID);
757 #_session_log(sprintf "%20s from %16s logged out at %30s (ip changed to %16s).\n", $userid,$ip,(strftime "%c",localtime), $info{'newip'});
758 $sessionID = undef;
759 $userid = undef;
761 else {
762 $cookie = $query->cookie(
763 -name => 'CGISESSID',
764 -value => $session->id,
765 -HttpOnly => 1
767 $session->param( 'lasttime', time() );
768 unless ( $sessiontype && $sessiontype eq 'anon' ) { #if this is an anonymous session, we want to update the session, but not behave as if they are logged in...
769 $flags = haspermission($userid, $flagsrequired);
770 if ($flags) {
771 $loggedin = 1;
772 } else {
773 $info{'nopermission'} = 1;
778 unless ($userid || $sessionID) {
780 #we initiate a session prior to checking for a username to allow for anonymous sessions...
781 my $session = get_session("") or die "Auth ERROR: Cannot get_session()";
783 # Save anonymous search history in new session so it can be retrieved
784 # by get_template_and_user to store it in user's search history after
785 # a successful login.
786 if ($anon_search_history) {
787 $session->param('search_history', $anon_search_history);
790 my $sessionID = $session->id;
791 C4::Context->_new_userenv($sessionID);
792 $cookie = $query->cookie(
793 -name => 'CGISESSID',
794 -value => $session->id,
795 -HttpOnly => 1
797 $userid = $q_userid;
798 my $pki_field = C4::Context->preference('AllowPKIAuth');
799 if (! defined($pki_field) ) {
800 print STDERR "ERROR: Missing system preference AllowPKIAuth.\n";
801 $pki_field = 'None';
803 if ( ( $cas && $query->param('ticket') )
804 || $userid
805 || $pki_field ne 'None'
806 || $persona )
808 my $password = $query->param('password');
810 my ( $return, $cardnumber );
811 if ( $cas && $query->param('ticket') ) {
812 my $retuserid;
813 ( $return, $cardnumber, $retuserid ) =
814 checkpw( $dbh, $userid, $password, $query );
815 $userid = $retuserid;
816 $info{'invalidCasLogin'} = 1 unless ($return);
819 elsif ($persona) {
820 my $value = $persona;
822 # If we're looking up the email, there's a chance that the person
823 # doesn't have a userid. So if there is none, we pass along the
824 # borrower number, and the bits of code that need to know the user
825 # ID will have to be smart enough to handle that.
826 require C4::Members;
827 my @users_info = C4::Members::GetBorrowersWithEmail($value);
828 if (@users_info) {
830 # First the userid, then the borrowernum
831 $value = $users_info[0][1] || $users_info[0][0];
833 else {
834 undef $value;
836 $return = $value ? 1 : 0;
837 $userid = $value;
840 elsif (
841 ( $pki_field eq 'Common Name' && $ENV{'SSL_CLIENT_S_DN_CN'} )
842 || ( $pki_field eq 'emailAddress'
843 && $ENV{'SSL_CLIENT_S_DN_Email'} )
846 my $value;
847 if ( $pki_field eq 'Common Name' ) {
848 $value = $ENV{'SSL_CLIENT_S_DN_CN'};
850 elsif ( $pki_field eq 'emailAddress' ) {
851 $value = $ENV{'SSL_CLIENT_S_DN_Email'};
853 # If we're looking up the email, there's a chance that the person
854 # doesn't have a userid. So if there is none, we pass along the
855 # borrower number, and the bits of code that need to know the user
856 # ID will have to be smart enough to handle that.
857 require C4::Members;
858 my @users_info = C4::Members::GetBorrowersWithEmail($value);
859 if (@users_info) {
861 # First the userid, then the borrowernum
862 $value = $users_info[0][1] || $users_info[0][0];
863 } else {
864 undef $value;
869 $return = $value ? 1 : 0;
870 $userid = $value;
873 else {
874 my $retuserid;
875 ( $return, $cardnumber, $retuserid ) =
876 checkpw( $dbh, $userid, $password, $query );
877 $userid = $retuserid if ( $retuserid );
879 if ($return) {
880 #_session_log(sprintf "%20s from %16s logged in at %30s.\n", $userid,$ENV{'REMOTE_ADDR'},(strftime '%c', localtime));
881 if ( $flags = haspermission( $userid, $flagsrequired ) ) {
882 $loggedin = 1;
884 else {
885 $info{'nopermission'} = 1;
886 C4::Context->_unset_userenv($sessionID);
888 my ($borrowernumber, $firstname, $surname, $userflags,
889 $branchcode, $branchname, $branchprinter, $emailaddress);
891 if ( $return == 1 ) {
892 my $select = "
893 SELECT borrowernumber, firstname, surname, flags, borrowers.branchcode,
894 branches.branchname as branchname,
895 branches.branchprinter as branchprinter,
896 email
897 FROM borrowers
898 LEFT JOIN branches on borrowers.branchcode=branches.branchcode
900 my $sth = $dbh->prepare("$select where userid=?");
901 $sth->execute($userid);
902 unless ($sth->rows) {
903 $debug and print STDERR "AUTH_1: no rows for userid='$userid'\n";
904 $sth = $dbh->prepare("$select where cardnumber=?");
905 $sth->execute($cardnumber);
907 unless ($sth->rows) {
908 $debug and print STDERR "AUTH_2a: no rows for cardnumber='$cardnumber'\n";
909 $sth->execute($userid);
910 unless ($sth->rows) {
911 $debug and print STDERR "AUTH_2b: no rows for userid='$userid' AS cardnumber\n";
915 if ($sth->rows) {
916 ($borrowernumber, $firstname, $surname, $userflags,
917 $branchcode, $branchname, $branchprinter, $emailaddress) = $sth->fetchrow;
918 $debug and print STDERR "AUTH_3 results: " .
919 "$cardnumber,$borrowernumber,$userid,$firstname,$surname,$userflags,$branchcode,$emailaddress\n";
920 } else {
921 print STDERR "AUTH_3: no results for userid='$userid', cardnumber='$cardnumber'.\n";
924 # launch a sequence to check if we have a ip for the branch, i
925 # if we have one we replace the branchcode of the userenv by the branch bound in the ip.
927 my $ip = $ENV{'REMOTE_ADDR'};
928 # if they specify at login, use that
929 if ($query->param('branch')) {
930 $branchcode = $query->param('branch');
931 $branchname = GetBranchName($branchcode);
933 my $branches = GetBranches();
934 if (C4::Context->boolean_preference('IndependentBranches') && C4::Context->boolean_preference('Autolocation')){
935 # we have to check they are coming from the right ip range
936 my $domain = $branches->{$branchcode}->{'branchip'};
937 if ($ip !~ /^$domain/){
938 $loggedin=0;
939 $info{'wrongip'} = 1;
943 my @branchesloop;
944 foreach my $br ( keys %$branches ) {
945 # now we work with the treatment of ip
946 my $domain = $branches->{$br}->{'branchip'};
947 if ( $domain && $ip =~ /^$domain/ ) {
948 $branchcode = $branches->{$br}->{'branchcode'};
950 # new op dev : add the branchprinter and branchname in the cookie
951 $branchprinter = $branches->{$br}->{'branchprinter'};
952 $branchname = $branches->{$br}->{'branchname'};
955 $session->param('number',$borrowernumber);
956 $session->param('id',$userid);
957 $session->param('cardnumber',$cardnumber);
958 $session->param('firstname',$firstname);
959 $session->param('surname',$surname);
960 $session->param('branch',$branchcode);
961 $session->param('branchname',$branchname);
962 $session->param('flags',$userflags);
963 $session->param('emailaddress',$emailaddress);
964 $session->param('ip',$session->remote_addr());
965 $session->param('lasttime',time());
966 $debug and printf STDERR "AUTH_4: (%s)\t%s %s - %s\n", map {$session->param($_)} qw(cardnumber firstname surname branch) ;
968 elsif ( $return == 2 ) {
969 #We suppose the user is the superlibrarian
970 $borrowernumber = 0;
971 $session->param('number',0);
972 $session->param('id',C4::Context->config('user'));
973 $session->param('cardnumber',C4::Context->config('user'));
974 $session->param('firstname',C4::Context->config('user'));
975 $session->param('surname',C4::Context->config('user'));
976 $session->param('branch','NO_LIBRARY_SET');
977 $session->param('branchname','NO_LIBRARY_SET');
978 $session->param('flags',1);
979 $session->param('emailaddress', C4::Context->preference('KohaAdminEmailAddress'));
980 $session->param('ip',$session->remote_addr());
981 $session->param('lasttime',time());
983 if ($persona){
984 $session->param('persona',1);
986 C4::Context::set_userenv(
987 $session->param('number'), $session->param('id'),
988 $session->param('cardnumber'), $session->param('firstname'),
989 $session->param('surname'), $session->param('branch'),
990 $session->param('branchname'), $session->param('flags'),
991 $session->param('emailaddress'), $session->param('branchprinter'),
992 $session->param('persona')
996 else {
997 if ($userid) {
998 $info{'invalid_username_or_password'} = 1;
999 C4::Context->_unset_userenv($sessionID);
1001 $session->param('lasttime',time());
1002 $session->param('ip',$session->remote_addr());
1004 } # END if ( $userid = $query->param('userid') )
1005 elsif ($type eq "opac") {
1006 # if we are here this is an anonymous session; add public lists to it and a few other items...
1007 # anonymous sessions are created only for the OPAC
1008 $debug and warn "Initiating an anonymous session...";
1010 # setting a couple of other session vars...
1011 $session->param('ip',$session->remote_addr());
1012 $session->param('lasttime',time());
1013 $session->param('sessiontype','anon');
1015 } # END unless ($userid)
1017 # finished authentification, now respond
1018 if ( $loggedin || $authnotrequired )
1020 # successful login
1021 unless ($cookie) {
1022 $cookie = $query->cookie(
1023 -name => 'CGISESSID',
1024 -value => '',
1025 -HttpOnly => 1
1028 return ( $userid, $cookie, $sessionID, $flags );
1033 # AUTH rejected, show the login/password template, after checking the DB.
1037 # get the inputs from the incoming query
1038 my @inputs = ();
1039 foreach my $name ( param $query) {
1040 (next) if ( $name eq 'userid' || $name eq 'password' || $name eq 'ticket' );
1041 my $value = $query->param($name);
1042 push @inputs, { name => $name, value => $value };
1045 my $LibraryNameTitle = C4::Context->preference("LibraryName");
1046 $LibraryNameTitle =~ s/<(?:\/?)(?:br|p)\s*(?:\/?)>/ /sgi;
1047 $LibraryNameTitle =~ s/<(?:[^<>'"]|'(?:[^']*)'|"(?:[^"]*)")*>//sg;
1049 my $template_name = ( $type eq 'opac' ) ? 'opac-auth.tmpl' : 'auth.tmpl';
1050 my $template = C4::Templates::gettemplate($template_name, $type, $query );
1051 $template->param(
1052 branchloop => GetBranchesLoop(),
1053 opaccolorstylesheet => C4::Context->preference("opaccolorstylesheet"),
1054 opaclayoutstylesheet => C4::Context->preference("opaclayoutstylesheet"),
1055 login => 1,
1056 INPUTS => \@inputs,
1057 casAuthentication => C4::Context->preference("casAuthentication"),
1058 suggestion => C4::Context->preference("suggestion"),
1059 virtualshelves => C4::Context->preference("virtualshelves"),
1060 LibraryName => "" . C4::Context->preference("LibraryName"),
1061 LibraryNameTitle => "" . $LibraryNameTitle,
1062 opacuserlogin => C4::Context->preference("opacuserlogin"),
1063 OpacNav => C4::Context->preference("OpacNav"),
1064 OpacNavRight => C4::Context->preference("OpacNavRight"),
1065 OpacNavBottom => C4::Context->preference("OpacNavBottom"),
1066 opaccredits => C4::Context->preference("opaccredits"),
1067 OpacFavicon => C4::Context->preference("OpacFavicon"),
1068 opacreadinghistory => C4::Context->preference("opacreadinghistory"),
1069 opacsmallimage => C4::Context->preference("opacsmallimage"),
1070 opaclanguagesdisplay => C4::Context->preference("opaclanguagesdisplay"),
1071 opacuserjs => C4::Context->preference("opacuserjs"),
1072 opacbookbag => "" . C4::Context->preference("opacbookbag"),
1073 OpacCloud => C4::Context->preference("OpacCloud"),
1074 OpacTopissue => C4::Context->preference("OpacTopissue"),
1075 OpacAuthorities => C4::Context->preference("OpacAuthorities"),
1076 OpacBrowser => C4::Context->preference("OpacBrowser"),
1077 opacheader => C4::Context->preference("opacheader"),
1078 TagsEnabled => C4::Context->preference("TagsEnabled"),
1079 OPACUserCSS => C4::Context->preference("OPACUserCSS"),
1080 intranetcolorstylesheet => C4::Context->preference("intranetcolorstylesheet"),
1081 intranetstylesheet => C4::Context->preference("intranetstylesheet"),
1082 intranetbookbag => C4::Context->preference("intranetbookbag"),
1083 IntranetNav => C4::Context->preference("IntranetNav"),
1084 IntranetFavicon => C4::Context->preference("IntranetFavicon"),
1085 intranetuserjs => C4::Context->preference("intranetuserjs"),
1086 IndependentBranches=> C4::Context->preference("IndependentBranches"),
1087 AutoLocation => C4::Context->preference("AutoLocation"),
1088 wrongip => $info{'wrongip'},
1089 PatronSelfRegistration => C4::Context->preference("PatronSelfRegistration"),
1090 PatronSelfRegistrationDefaultCategory => C4::Context->preference("PatronSelfRegistrationDefaultCategory"),
1091 persona => C4::Context->preference("Persona"),
1092 opac_css_override => $ENV{'OPAC_CSS_OVERRIDE'},
1095 $template->param( OpacPublic => C4::Context->preference("OpacPublic"));
1096 $template->param( loginprompt => 1 ) unless $info{'nopermission'};
1098 if($type eq 'opac'){
1099 my ($total, $pubshelves) = C4::VirtualShelves::GetSomeShelfNames(undef, 'MASTHEAD');
1100 $template->param(
1101 pubshelves => $total->{pubtotal},
1102 pubshelvesloop => $pubshelves,
1106 if ($cas) {
1108 # Is authentication against multiple CAS servers enabled?
1109 if (C4::Auth_with_cas::multipleAuth && !$casparam) {
1110 my $casservers = C4::Auth_with_cas::getMultipleAuth();
1111 my @tmplservers;
1112 foreach my $key (keys %$casservers) {
1113 push @tmplservers, {name => $key, value => login_cas_url($query, $key) . "?cas=$key" };
1115 $template->param(
1116 casServersLoop => \@tmplservers
1118 } else {
1119 $template->param(
1120 casServerUrl => login_cas_url($query),
1124 $template->param(
1125 invalidCasLogin => $info{'invalidCasLogin'}
1129 my $self_url = $query->url( -absolute => 1 );
1130 $template->param(
1131 url => $self_url,
1132 LibraryName => C4::Context->preference("LibraryName"),
1134 $template->param( %info );
1135 # $cookie = $query->cookie(CGISESSID => $session->id
1136 # );
1137 print $query->header(
1138 -type => 'text/html',
1139 -charset => 'utf-8',
1140 -cookie => $cookie
1142 $template->output;
1143 safe_exit;
1146 =head2 check_api_auth
1148 ($status, $cookie, $sessionId) = check_api_auth($query, $userflags);
1150 Given a CGI query containing the parameters 'userid' and 'password' and/or a session
1151 cookie, determine if the user has the privileges specified by C<$userflags>.
1153 C<check_api_auth> is is meant for authenticating users of web services, and
1154 consequently will always return and will not attempt to redirect the user
1155 agent.
1157 If a valid session cookie is already present, check_api_auth will return a status
1158 of "ok", the cookie, and the Koha session ID.
1160 If no session cookie is present, check_api_auth will check the 'userid' and 'password
1161 parameters and create a session cookie and Koha session if the supplied credentials
1162 are OK.
1164 Possible return values in C<$status> are:
1166 =over
1168 =item "ok" -- user authenticated; C<$cookie> and C<$sessionid> have valid values.
1170 =item "failed" -- credentials are not correct; C<$cookie> and C<$sessionid> are undef
1172 =item "maintenance" -- DB is in maintenance mode; no login possible at the moment
1174 =item "expired -- session cookie has expired; API user should resubmit userid and password
1176 =back
1178 =cut
1180 sub check_api_auth {
1181 my $query = shift;
1182 my $flagsrequired = shift;
1184 my $dbh = C4::Context->dbh;
1185 my $timeout = _timeout_syspref();
1187 unless (C4::Context->preference('Version')) {
1188 # database has not been installed yet
1189 return ("maintenance", undef, undef);
1191 my $kohaversion=C4::Context::KOHAVERSION;
1192 $kohaversion =~ s/(.*\..*)\.(.*)\.(.*)/$1$2$3/;
1193 if (C4::Context->preference('Version') < $kohaversion) {
1194 # database in need of version update; assume that
1195 # no API should be called while databsae is in
1196 # this condition.
1197 return ("maintenance", undef, undef);
1200 # FIXME -- most of what follows is a copy-and-paste
1201 # of code from checkauth. There is an obvious need
1202 # for refactoring to separate the various parts of
1203 # the authentication code, but as of 2007-11-19 this
1204 # is deferred so as to not introduce bugs into the
1205 # regular authentication code for Koha 3.0.
1207 # see if we have a valid session cookie already
1208 # however, if a userid parameter is present (i.e., from
1209 # a form submission, assume that any current cookie
1210 # is to be ignored
1211 my $sessionID = undef;
1212 unless ($query->param('userid')) {
1213 $sessionID = $query->cookie("CGISESSID");
1215 if ($sessionID && not ($cas && $query->param('PT')) ) {
1216 my $session = get_session($sessionID);
1217 C4::Context->_new_userenv($sessionID);
1218 if ($session) {
1219 C4::Context::set_userenv(
1220 $session->param('number'), $session->param('id'),
1221 $session->param('cardnumber'), $session->param('firstname'),
1222 $session->param('surname'), $session->param('branch'),
1223 $session->param('branchname'), $session->param('flags'),
1224 $session->param('emailaddress'), $session->param('branchprinter')
1227 my $ip = $session->param('ip');
1228 my $lasttime = $session->param('lasttime');
1229 my $userid = $session->param('id');
1230 if ( $lasttime < time() - $timeout ) {
1231 # time out
1232 $session->delete();
1233 $session->flush;
1234 C4::Context->_unset_userenv($sessionID);
1235 $userid = undef;
1236 $sessionID = undef;
1237 return ("expired", undef, undef);
1238 } elsif ( $ip ne $ENV{'REMOTE_ADDR'} ) {
1239 # IP address changed
1240 $session->delete();
1241 $session->flush;
1242 C4::Context->_unset_userenv($sessionID);
1243 $userid = undef;
1244 $sessionID = undef;
1245 return ("expired", undef, undef);
1246 } else {
1247 my $cookie = $query->cookie(
1248 -name => 'CGISESSID',
1249 -value => $session->id,
1250 -HttpOnly => 1,
1252 $session->param('lasttime',time());
1253 my $flags = haspermission($userid, $flagsrequired);
1254 if ($flags) {
1255 return ("ok", $cookie, $sessionID);
1256 } else {
1257 $session->delete();
1258 $session->flush;
1259 C4::Context->_unset_userenv($sessionID);
1260 $userid = undef;
1261 $sessionID = undef;
1262 return ("failed", undef, undef);
1265 } else {
1266 return ("expired", undef, undef);
1268 } else {
1269 # new login
1270 my $userid = $query->param('userid');
1271 my $password = $query->param('password');
1272 my ($return, $cardnumber);
1274 # Proxy CAS auth
1275 if ($cas && $query->param('PT')) {
1276 my $retuserid;
1277 $debug and print STDERR "## check_api_auth - checking CAS\n";
1278 # In case of a CAS authentication, we use the ticket instead of the password
1279 my $PT = $query->param('PT');
1280 ($return,$cardnumber,$userid) = check_api_auth_cas($dbh, $PT, $query); # EXTERNAL AUTH
1281 } else {
1282 # User / password auth
1283 unless ($userid and $password) {
1284 # caller did something wrong, fail the authenticateion
1285 return ("failed", undef, undef);
1287 ( $return, $cardnumber ) = checkpw( $dbh, $userid, $password, $query );
1290 if ($return and haspermission( $userid, $flagsrequired)) {
1291 my $session = get_session("");
1292 return ("failed", undef, undef) unless $session;
1294 my $sessionID = $session->id;
1295 C4::Context->_new_userenv($sessionID);
1296 my $cookie = $query->cookie(
1297 -name => 'CGISESSID',
1298 -value => $sessionID,
1299 -HttpOnly => 1,
1301 if ( $return == 1 ) {
1302 my (
1303 $borrowernumber, $firstname, $surname,
1304 $userflags, $branchcode, $branchname,
1305 $branchprinter, $emailaddress
1307 my $sth =
1308 $dbh->prepare(
1309 "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=?"
1311 $sth->execute($userid);
1313 $borrowernumber, $firstname, $surname,
1314 $userflags, $branchcode, $branchname,
1315 $branchprinter, $emailaddress
1316 ) = $sth->fetchrow if ( $sth->rows );
1318 unless ($sth->rows ) {
1319 my $sth = $dbh->prepare(
1320 "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=?"
1322 $sth->execute($cardnumber);
1324 $borrowernumber, $firstname, $surname,
1325 $userflags, $branchcode, $branchname,
1326 $branchprinter, $emailaddress
1327 ) = $sth->fetchrow if ( $sth->rows );
1329 unless ( $sth->rows ) {
1330 $sth->execute($userid);
1332 $borrowernumber, $firstname, $surname, $userflags,
1333 $branchcode, $branchname, $branchprinter, $emailaddress
1334 ) = $sth->fetchrow if ( $sth->rows );
1338 my $ip = $ENV{'REMOTE_ADDR'};
1339 # if they specify at login, use that
1340 if ($query->param('branch')) {
1341 $branchcode = $query->param('branch');
1342 $branchname = GetBranchName($branchcode);
1344 my $branches = GetBranches();
1345 my @branchesloop;
1346 foreach my $br ( keys %$branches ) {
1347 # now we work with the treatment of ip
1348 my $domain = $branches->{$br}->{'branchip'};
1349 if ( $domain && $ip =~ /^$domain/ ) {
1350 $branchcode = $branches->{$br}->{'branchcode'};
1352 # new op dev : add the branchprinter and branchname in the cookie
1353 $branchprinter = $branches->{$br}->{'branchprinter'};
1354 $branchname = $branches->{$br}->{'branchname'};
1357 $session->param('number',$borrowernumber);
1358 $session->param('id',$userid);
1359 $session->param('cardnumber',$cardnumber);
1360 $session->param('firstname',$firstname);
1361 $session->param('surname',$surname);
1362 $session->param('branch',$branchcode);
1363 $session->param('branchname',$branchname);
1364 $session->param('flags',$userflags);
1365 $session->param('emailaddress',$emailaddress);
1366 $session->param('ip',$session->remote_addr());
1367 $session->param('lasttime',time());
1368 } elsif ( $return == 2 ) {
1369 #We suppose the user is the superlibrarian
1370 $session->param('number',0);
1371 $session->param('id',C4::Context->config('user'));
1372 $session->param('cardnumber',C4::Context->config('user'));
1373 $session->param('firstname',C4::Context->config('user'));
1374 $session->param('surname',C4::Context->config('user'));
1375 $session->param('branch','NO_LIBRARY_SET');
1376 $session->param('branchname','NO_LIBRARY_SET');
1377 $session->param('flags',1);
1378 $session->param('emailaddress', C4::Context->preference('KohaAdminEmailAddress'));
1379 $session->param('ip',$session->remote_addr());
1380 $session->param('lasttime',time());
1382 C4::Context::set_userenv(
1383 $session->param('number'), $session->param('id'),
1384 $session->param('cardnumber'), $session->param('firstname'),
1385 $session->param('surname'), $session->param('branch'),
1386 $session->param('branchname'), $session->param('flags'),
1387 $session->param('emailaddress'), $session->param('branchprinter')
1389 return ("ok", $cookie, $sessionID);
1390 } else {
1391 return ("failed", undef, undef);
1396 =head2 check_cookie_auth
1398 ($status, $sessionId) = check_api_auth($cookie, $userflags);
1400 Given a CGISESSID cookie set during a previous login to Koha, determine
1401 if the user has the privileges specified by C<$userflags>.
1403 C<check_cookie_auth> is meant for authenticating special services
1404 such as tools/upload-file.pl that are invoked by other pages that
1405 have been authenticated in the usual way.
1407 Possible return values in C<$status> are:
1409 =over
1411 =item "ok" -- user authenticated; C<$sessionID> have valid values.
1413 =item "failed" -- credentials are not correct; C<$sessionid> are undef
1415 =item "maintenance" -- DB is in maintenance mode; no login possible at the moment
1417 =item "expired -- session cookie has expired; API user should resubmit userid and password
1419 =back
1421 =cut
1423 sub check_cookie_auth {
1424 my $cookie = shift;
1425 my $flagsrequired = shift;
1427 my $dbh = C4::Context->dbh;
1428 my $timeout = _timeout_syspref();
1430 unless (C4::Context->preference('Version')) {
1431 # database has not been installed yet
1432 return ("maintenance", undef);
1434 my $kohaversion=C4::Context::KOHAVERSION;
1435 $kohaversion =~ s/(.*\..*)\.(.*)\.(.*)/$1$2$3/;
1436 if (C4::Context->preference('Version') < $kohaversion) {
1437 # database in need of version update; assume that
1438 # no API should be called while databsae is in
1439 # this condition.
1440 return ("maintenance", undef);
1443 # FIXME -- most of what follows is a copy-and-paste
1444 # of code from checkauth. There is an obvious need
1445 # for refactoring to separate the various parts of
1446 # the authentication code, but as of 2007-11-23 this
1447 # is deferred so as to not introduce bugs into the
1448 # regular authentication code for Koha 3.0.
1450 # see if we have a valid session cookie already
1451 # however, if a userid parameter is present (i.e., from
1452 # a form submission, assume that any current cookie
1453 # is to be ignored
1454 unless (defined $cookie and $cookie) {
1455 return ("failed", undef);
1457 my $sessionID = $cookie;
1458 my $session = get_session($sessionID);
1459 C4::Context->_new_userenv($sessionID);
1460 if ($session) {
1461 C4::Context::set_userenv(
1462 $session->param('number'), $session->param('id'),
1463 $session->param('cardnumber'), $session->param('firstname'),
1464 $session->param('surname'), $session->param('branch'),
1465 $session->param('branchname'), $session->param('flags'),
1466 $session->param('emailaddress'), $session->param('branchprinter')
1469 my $ip = $session->param('ip');
1470 my $lasttime = $session->param('lasttime');
1471 my $userid = $session->param('id');
1472 if ( $lasttime < time() - $timeout ) {
1473 # time out
1474 $session->delete();
1475 $session->flush;
1476 C4::Context->_unset_userenv($sessionID);
1477 $userid = undef;
1478 $sessionID = undef;
1479 return ("expired", undef);
1480 } elsif ( $ip ne $ENV{'REMOTE_ADDR'} ) {
1481 # IP address changed
1482 $session->delete();
1483 $session->flush;
1484 C4::Context->_unset_userenv($sessionID);
1485 $userid = undef;
1486 $sessionID = undef;
1487 return ("expired", undef);
1488 } else {
1489 $session->param('lasttime',time());
1490 my $flags = haspermission($userid, $flagsrequired);
1491 if ($flags) {
1492 return ("ok", $sessionID);
1493 } else {
1494 $session->delete();
1495 $session->flush;
1496 C4::Context->_unset_userenv($sessionID);
1497 $userid = undef;
1498 $sessionID = undef;
1499 return ("failed", undef);
1502 } else {
1503 return ("expired", undef);
1507 =head2 get_session
1509 use CGI::Session;
1510 my $session = get_session($sessionID);
1512 Given a session ID, retrieve the CGI::Session object used to store
1513 the session's state. The session object can be used to store
1514 data that needs to be accessed by different scripts during a
1515 user's session.
1517 If the C<$sessionID> parameter is an empty string, a new session
1518 will be created.
1520 =cut
1522 sub get_session {
1523 my $sessionID = shift;
1524 my $storage_method = C4::Context->preference('SessionStorage');
1525 my $dbh = C4::Context->dbh;
1526 my $session;
1527 if ($storage_method eq 'mysql'){
1528 $session = new CGI::Session("driver:MySQL;serializer:yaml;id:md5", $sessionID, {Handle=>$dbh});
1530 elsif ($storage_method eq 'Pg') {
1531 $session = new CGI::Session("driver:PostgreSQL;serializer:yaml;id:md5", $sessionID, {Handle=>$dbh});
1533 elsif ($storage_method eq 'memcached' && C4::Context->ismemcached){
1534 $session = new CGI::Session("driver:memcached;serializer:yaml;id:md5", $sessionID, { Memcached => C4::Context->memcached } );
1536 else {
1537 # catch all defaults to tmp should work on all systems
1538 $session = new CGI::Session("driver:File;serializer:yaml;id:md5", $sessionID, {Directory=>'/tmp'});
1540 return $session;
1543 sub checkpw {
1544 my ( $dbh, $userid, $password, $query ) = @_;
1546 if ($ldap) {
1547 $debug and print STDERR "## checkpw - checking LDAP\n";
1548 my ($retval,$retcard,$retuserid) = checkpw_ldap(@_); # EXTERNAL AUTH
1549 ($retval) and return ($retval,$retcard,$retuserid);
1552 if ($cas && $query && $query->param('ticket')) {
1553 $debug and print STDERR "## checkpw - checking CAS\n";
1554 # In case of a CAS authentication, we use the ticket instead of the password
1555 my $ticket = $query->param('ticket');
1556 $query->delete('ticket'); # remove ticket to come back to original URL
1557 my ($retval,$retcard,$retuserid) = checkpw_cas($dbh, $ticket, $query); # EXTERNAL AUTH
1558 ($retval) and return ($retval,$retcard,$retuserid);
1559 return 0;
1562 return checkpw_internal(@_)
1565 sub checkpw_internal {
1566 my ( $dbh, $userid, $password ) = @_;
1568 if ( $userid && $userid eq C4::Context->config('user') ) {
1569 if ( $password && $password eq C4::Context->config('pass') ) {
1570 # Koha superuser account
1571 # C4::Context->set_userenv(0,0,C4::Context->config('user'),C4::Context->config('user'),C4::Context->config('user'),"",1);
1572 return 2;
1574 else {
1575 return 0;
1579 my $sth =
1580 $dbh->prepare(
1581 "select password,cardnumber,borrowernumber,userid,firstname,surname,branchcode,flags from borrowers where userid=?"
1583 $sth->execute($userid);
1584 if ( $sth->rows ) {
1585 my ( $stored_hash, $cardnumber, $borrowernumber, $userid, $firstname,
1586 $surname, $branchcode, $flags )
1587 = $sth->fetchrow;
1589 if ( checkpw_hash($password, $stored_hash) ) {
1591 C4::Context->set_userenv( "$borrowernumber", $userid, $cardnumber,
1592 $firstname, $surname, $branchcode, $flags );
1593 return 1, $cardnumber, $userid;
1596 $sth =
1597 $dbh->prepare(
1598 "select password,cardnumber,borrowernumber,userid, firstname,surname,branchcode,flags from borrowers where cardnumber=?"
1600 $sth->execute($userid);
1601 if ( $sth->rows ) {
1602 my ( $stored_hash, $cardnumber, $borrowernumber, $userid, $firstname,
1603 $surname, $branchcode, $flags )
1604 = $sth->fetchrow;
1606 if ( checkpw_hash($password, $stored_hash) ) {
1608 C4::Context->set_userenv( $borrowernumber, $userid, $cardnumber,
1609 $firstname, $surname, $branchcode, $flags );
1610 return 1, $cardnumber, $userid;
1613 if ( $userid && $userid eq 'demo'
1614 && "$password" eq 'demo'
1615 && C4::Context->config('demo') )
1618 # DEMO => the demo user is allowed to do everything (if demo set to 1 in koha.conf
1619 # some features won't be effective : modify systempref, modify MARC structure,
1620 return 2;
1622 return 0;
1625 sub checkpw_hash {
1626 my ( $password, $stored_hash ) = @_;
1628 return if $stored_hash eq '!';
1630 # check what encryption algorithm was implemented: Bcrypt - if the hash starts with '$2' it is Bcrypt else md5
1631 my $hash;
1632 if ( substr($stored_hash,0,2) eq '$2') {
1633 $hash = hash_password($password, $stored_hash);
1634 } else {
1635 $hash = md5_base64($password);
1637 return $hash eq $stored_hash;
1640 =head2 getuserflags
1642 my $authflags = getuserflags($flags, $userid, [$dbh]);
1644 Translates integer flags into permissions strings hash.
1646 C<$flags> is the integer userflags value ( borrowers.userflags )
1647 C<$userid> is the members.userid, used for building subpermissions
1648 C<$authflags> is a hashref of permissions
1650 =cut
1652 sub getuserflags {
1653 my $flags = shift;
1654 my $userid = shift;
1655 my $dbh = @_ ? shift : C4::Context->dbh;
1656 my $userflags;
1658 # I don't want to do this, but if someone logs in as the database
1659 # user, it would be preferable not to spam them to death with
1660 # numeric warnings. So, we make $flags numeric.
1661 no warnings 'numeric';
1662 $flags += 0;
1664 my $sth = $dbh->prepare("SELECT bit, flag, defaulton FROM userflags");
1665 $sth->execute;
1667 while ( my ( $bit, $flag, $defaulton ) = $sth->fetchrow ) {
1668 if ( ( $flags & ( 2**$bit ) ) || $defaulton ) {
1669 $userflags->{$flag} = 1;
1671 else {
1672 $userflags->{$flag} = 0;
1675 # get subpermissions and merge with top-level permissions
1676 my $user_subperms = get_user_subpermissions($userid);
1677 foreach my $module (keys %$user_subperms) {
1678 next if $userflags->{$module} == 1; # user already has permission for everything in this module
1679 $userflags->{$module} = $user_subperms->{$module};
1682 return $userflags;
1685 =head2 get_user_subpermissions
1687 $user_perm_hashref = get_user_subpermissions($userid);
1689 Given the userid (note, not the borrowernumber) of a staff user,
1690 return a hashref of hashrefs of the specific subpermissions
1691 accorded to the user. An example return is
1694 tools => {
1695 export_catalog => 1,
1696 import_patrons => 1,
1700 The top-level hash-key is a module or function code from
1701 userflags.flag, while the second-level key is a code
1702 from permissions.
1704 The results of this function do not give a complete picture
1705 of the functions that a staff user can access; it is also
1706 necessary to check borrowers.flags.
1708 =cut
1710 sub get_user_subpermissions {
1711 my $userid = shift;
1713 my $dbh = C4::Context->dbh;
1714 my $sth = $dbh->prepare("SELECT flag, user_permissions.code
1715 FROM user_permissions
1716 JOIN permissions USING (module_bit, code)
1717 JOIN userflags ON (module_bit = bit)
1718 JOIN borrowers USING (borrowernumber)
1719 WHERE userid = ?");
1720 $sth->execute($userid);
1722 my $user_perms = {};
1723 while (my $perm = $sth->fetchrow_hashref) {
1724 $user_perms->{$perm->{'flag'}}->{$perm->{'code'}} = 1;
1726 return $user_perms;
1729 =head2 get_all_subpermissions
1731 my $perm_hashref = get_all_subpermissions();
1733 Returns a hashref of hashrefs defining all specific
1734 permissions currently defined. The return value
1735 has the same structure as that of C<get_user_subpermissions>,
1736 except that the innermost hash value is the description
1737 of the subpermission.
1739 =cut
1741 sub get_all_subpermissions {
1742 my $dbh = C4::Context->dbh;
1743 my $sth = $dbh->prepare("SELECT flag, code, description
1744 FROM permissions
1745 JOIN userflags ON (module_bit = bit)");
1746 $sth->execute();
1748 my $all_perms = {};
1749 while (my $perm = $sth->fetchrow_hashref) {
1750 $all_perms->{$perm->{'flag'}}->{$perm->{'code'}} = $perm->{'description'};
1752 return $all_perms;
1755 =head2 haspermission
1757 $flags = ($userid, $flagsrequired);
1759 C<$userid> the userid of the member
1760 C<$flags> is a hashref of required flags like C<$borrower-&lt;{authflags}>
1762 Returns member's flags or 0 if a permission is not met.
1764 =cut
1766 sub haspermission {
1767 my ($userid, $flagsrequired) = @_;
1768 my $sth = C4::Context->dbh->prepare("SELECT flags FROM borrowers WHERE userid=?");
1769 $sth->execute($userid);
1770 my $row = $sth->fetchrow();
1771 my $flags = getuserflags($row, $userid);
1772 if ( $userid eq C4::Context->config('user') ) {
1773 # Super User Account from /etc/koha.conf
1774 $flags->{'superlibrarian'} = 1;
1776 elsif ( $userid eq 'demo' && C4::Context->config('demo') ) {
1777 # Demo user that can do "anything" (demo=1 in /etc/koha.conf)
1778 $flags->{'superlibrarian'} = 1;
1781 return $flags if $flags->{superlibrarian};
1783 foreach my $module ( keys %$flagsrequired ) {
1784 my $subperm = $flagsrequired->{$module};
1785 if ($subperm eq '*') {
1786 return 0 unless ( $flags->{$module} == 1 or ref($flags->{$module}) );
1787 } else {
1788 return 0 unless ( $flags->{$module} == 1 or
1789 ( ref($flags->{$module}) and
1790 exists $flags->{$module}->{$subperm} and
1791 $flags->{$module}->{$subperm} == 1
1796 return $flags;
1797 #FIXME - This fcn should return the failed permission so a suitable error msg can be delivered.
1801 sub getborrowernumber {
1802 my ($userid) = @_;
1803 my $userenv = C4::Context->userenv;
1804 if ( defined( $userenv ) && ref( $userenv ) eq 'HASH' && $userenv->{number} ) {
1805 return $userenv->{number};
1807 my $dbh = C4::Context->dbh;
1808 for my $field ( 'userid', 'cardnumber' ) {
1809 my $sth =
1810 $dbh->prepare("select borrowernumber from borrowers where $field=?");
1811 $sth->execute($userid);
1812 if ( $sth->rows ) {
1813 my ($bnumber) = $sth->fetchrow;
1814 return $bnumber;
1817 return 0;
1820 END { } # module clean-up code here (global destructor)
1822 __END__
1824 =head1 SEE ALSO
1826 CGI(3)
1828 C4::Output(3)
1830 Crypt::Eksblowfish::Bcrypt(3)
1832 Digest::MD5(3)
1834 =cut