Bug 11856: Add confirm option to POD in advance_notices.pl
[koha.git] / C4 / Auth.pm
blob95b271765c375e43315bfda57dddd21c9a16618f
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 => 1,
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 => 1,
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 my $template = C4::Templates::gettemplate(
141 $in->{'template_name'},
142 $in->{'type'},
143 $in->{'query'},
144 $in->{'is_plugin'}
147 if ( $in->{'template_name'} !~m/maintenance/ ) {
148 ( $user, $cookie, $sessionID, $flags ) = checkauth(
149 $in->{'query'},
150 $in->{'authnotrequired'},
151 $in->{'flagsrequired'},
152 $in->{'type'}
156 my $borrowernumber;
157 if ($user) {
158 require C4::Members;
159 # It's possible for $user to be the borrowernumber if they don't have a
160 # userid defined (and are logging in through some other method, such
161 # as SSL certs against an email address)
162 $borrowernumber = getborrowernumber($user) if defined($user);
163 if (!defined($borrowernumber) && defined($user)) {
164 my $borrower = C4::Members::GetMember(borrowernumber => $user);
165 if ($borrower) {
166 $borrowernumber = $user;
167 # A bit of a hack, but I don't know there's a nicer way
168 # to do it.
169 $user = $borrower->{firstname} . ' ' . $borrower->{surname};
173 # user info
174 $template->param( loggedinusername => $user );
175 $template->param( sessionID => $sessionID );
177 my ($total, $pubshelves, $barshelves) = C4::VirtualShelves::GetSomeShelfNames($borrowernumber, 'MASTHEAD');
178 $template->param(
179 pubshelves => $total->{pubtotal},
180 pubshelvesloop => $pubshelves,
181 barshelves => $total->{bartotal},
182 barshelvesloop => $barshelves,
185 my ( $borr ) = C4::Members::GetMemberDetails( $borrowernumber );
186 my @bordat;
187 $bordat[0] = $borr;
188 $template->param( "USER_INFO" => \@bordat );
190 my $all_perms = get_all_subpermissions();
192 my @flagroots = qw(circulate catalogue parameters borrowers permissions reserveforothers borrow
193 editcatalogue updatecharges management tools editauthorities serials reports acquisition);
194 # We are going to use the $flags returned by checkauth
195 # to create the template's parameters that will indicate
196 # which menus the user can access.
197 if ( $flags && $flags->{superlibrarian}==1 ) {
198 $template->param( CAN_user_circulate => 1 );
199 $template->param( CAN_user_catalogue => 1 );
200 $template->param( CAN_user_parameters => 1 );
201 $template->param( CAN_user_borrowers => 1 );
202 $template->param( CAN_user_permissions => 1 );
203 $template->param( CAN_user_reserveforothers => 1 );
204 $template->param( CAN_user_borrow => 1 );
205 $template->param( CAN_user_editcatalogue => 1 );
206 $template->param( CAN_user_updatecharges => 1 );
207 $template->param( CAN_user_acquisition => 1 );
208 $template->param( CAN_user_management => 1 );
209 $template->param( CAN_user_tools => 1 );
210 $template->param( CAN_user_editauthorities => 1 );
211 $template->param( CAN_user_serials => 1 );
212 $template->param( CAN_user_reports => 1 );
213 $template->param( CAN_user_staffaccess => 1 );
214 $template->param( CAN_user_plugins => 1 );
215 $template->param( CAN_user_coursereserves => 1 );
216 foreach my $module (keys %$all_perms) {
217 foreach my $subperm (keys %{ $all_perms->{$module} }) {
218 $template->param( "CAN_user_${module}_${subperm}" => 1 );
223 if ( $flags ) {
224 foreach my $module (keys %$all_perms) {
225 if ( $flags->{$module} == 1) {
226 foreach my $subperm (keys %{ $all_perms->{$module} }) {
227 $template->param( "CAN_user_${module}_${subperm}" => 1 );
229 } elsif ( ref($flags->{$module}) ) {
230 foreach my $subperm (keys %{ $flags->{$module} } ) {
231 $template->param( "CAN_user_${module}_${subperm}" => 1 );
237 if ($flags) {
238 foreach my $module (keys %$flags) {
239 if ( $flags->{$module} == 1 or ref($flags->{$module}) ) {
240 $template->param( "CAN_user_$module" => 1 );
241 if ($module eq "parameters") {
242 $template->param( CAN_user_management => 1 );
247 # Logged-in opac search history
248 # If the requested template is an opac one and opac search history is enabled
249 if ($in->{type} eq 'opac' && C4::Context->preference('EnableOpacSearchHistory')) {
250 my $dbh = C4::Context->dbh;
251 my $query = "SELECT COUNT(*) FROM search_history WHERE userid=?";
252 my $sth = $dbh->prepare($query);
253 $sth->execute($borrowernumber);
255 # If at least one search has already been performed
256 if ($sth->fetchrow_array > 0) {
257 # We show the link in opac
258 $template->param( EnableOpacSearchHistory => 1 );
261 # And if there are searches performed when the user was not logged in,
262 # we add them to the logged-in search history
263 my @recentSearches = C4::Search::History::get_from_session({ cgi => $in->{'query'} });
264 if (@recentSearches) {
265 my $dbh = C4::Context->dbh;
266 my $query = q{
267 INSERT INTO search_history(userid, sessionid, query_desc, query_cgi, type, total, time )
268 VALUES (?, ?, ?, ?, ?, ?, ?)
271 my $sth = $dbh->prepare($query);
272 $sth->execute( $borrowernumber,
273 $in->{query}->cookie("CGISESSID"),
274 $_->{query_desc},
275 $_->{query_cgi},
276 $_->{type} || 'biblio',
277 $_->{total},
278 $_->{time},
279 ) foreach @recentSearches;
281 # clear out the search history from the session now that
282 # we've saved it to the database
283 C4::Search::History::set_to_session({ cgi => $in->{'query'}, search_history => [] });
285 } elsif ( $in->{type} eq 'intranet' and C4::Context->preference('EnableSearchHistory') ) {
286 $template->param( EnableSearchHistory => 1 );
289 else { # if this is an anonymous session, setup to display public lists...
291 $template->param( sessionID => $sessionID );
293 my ($total, $pubshelves) = C4::VirtualShelves::GetSomeShelfNames(undef, 'MASTHEAD');
294 $template->param(
295 pubshelves => $total->{pubtotal},
296 pubshelvesloop => $pubshelves,
299 # Anonymous opac search history
300 # If opac search history is enabled and at least one search has already been performed
301 if (C4::Context->preference('EnableOpacSearchHistory')) {
302 my @recentSearches = C4::Search::History::get_from_session({ cgi => $in->{'query'} });
303 if (@recentSearches) {
304 $template->param(EnableOpacSearchHistory => 1);
308 if(C4::Context->preference('dateformat')){
309 $template->param(dateformat => C4::Context->preference('dateformat'))
312 # these template parameters are set the same regardless of $in->{'type'}
314 # Set the using_https variable for templates
315 # FIXME Under Plack the CGI->https method always returns 'OFF'
316 my $https = $in->{query}->https();
317 my $using_https = (defined $https and $https ne 'OFF') ? 1 : 0;
319 $template->param(
320 "BiblioDefaultView".C4::Context->preference("BiblioDefaultView") => 1,
321 EnhancedMessagingPreferences => C4::Context->preference('EnhancedMessagingPreferences'),
322 GoogleJackets => C4::Context->preference("GoogleJackets"),
323 OpenLibraryCovers => C4::Context->preference("OpenLibraryCovers"),
324 KohaAdminEmailAddress => "" . C4::Context->preference("KohaAdminEmailAddress"),
325 LoginBranchcode => (C4::Context->userenv?C4::Context->userenv->{"branch"}:undef),
326 LoginFirstname => (C4::Context->userenv?C4::Context->userenv->{"firstname"}:"Bel"),
327 LoginSurname => C4::Context->userenv?C4::Context->userenv->{"surname"}:"Inconnu",
328 emailaddress => C4::Context->userenv?C4::Context->userenv->{"emailaddress"}:undef,
329 loggedinpersona => C4::Context->userenv?C4::Context->userenv->{"persona"}:undef,
330 TagsEnabled => C4::Context->preference("TagsEnabled"),
331 hide_marc => C4::Context->preference("hide_marc"),
332 item_level_itypes => C4::Context->preference('item-level_itypes'),
333 patronimages => C4::Context->preference("patronimages"),
334 singleBranchMode => C4::Context->preference("singleBranchMode"),
335 XSLTDetailsDisplay => C4::Context->preference("XSLTDetailsDisplay"),
336 XSLTResultsDisplay => C4::Context->preference("XSLTResultsDisplay"),
337 using_https => $using_https,
338 noItemTypeImages => C4::Context->preference("noItemTypeImages"),
339 marcflavour => C4::Context->preference("marcflavour"),
340 persona => C4::Context->preference("persona"),
342 if ( $in->{'type'} eq "intranet" ) {
343 $template->param(
344 AmazonCoverImages => C4::Context->preference("AmazonCoverImages"),
345 AutoLocation => C4::Context->preference("AutoLocation"),
346 "BiblioDefaultView".C4::Context->preference("IntranetBiblioDefaultView") => 1,
347 CalendarFirstDayOfWeek => (C4::Context->preference("CalendarFirstDayOfWeek") eq "Sunday")?0:1,
348 CircAutocompl => C4::Context->preference("CircAutocompl"),
349 FRBRizeEditions => C4::Context->preference("FRBRizeEditions"),
350 IndependentBranches => C4::Context->preference("IndependentBranches"),
351 IntranetNav => C4::Context->preference("IntranetNav"),
352 IntranetmainUserblock => C4::Context->preference("IntranetmainUserblock"),
353 LibraryName => C4::Context->preference("LibraryName"),
354 LoginBranchname => (C4::Context->userenv?C4::Context->userenv->{"branchname"}:undef),
355 advancedMARCEditor => C4::Context->preference("advancedMARCEditor"),
356 canreservefromotherbranches => C4::Context->preference('canreservefromotherbranches'),
357 intranetcolorstylesheet => C4::Context->preference("intranetcolorstylesheet"),
358 IntranetFavicon => C4::Context->preference("IntranetFavicon"),
359 intranetreadinghistory => C4::Context->preference("intranetreadinghistory"),
360 intranetstylesheet => C4::Context->preference("intranetstylesheet"),
361 IntranetUserCSS => C4::Context->preference("IntranetUserCSS"),
362 intranetuserjs => C4::Context->preference("intranetuserjs"),
363 intranetbookbag => C4::Context->preference("intranetbookbag"),
364 suggestion => C4::Context->preference("suggestion"),
365 virtualshelves => C4::Context->preference("virtualshelves"),
366 StaffSerialIssueDisplayCount => C4::Context->preference("StaffSerialIssueDisplayCount"),
367 EasyAnalyticalRecords => C4::Context->preference('EasyAnalyticalRecords'),
368 LocalCoverImages => C4::Context->preference('LocalCoverImages'),
369 OPACLocalCoverImages => C4::Context->preference('OPACLocalCoverImages'),
370 AllowMultipleCovers => C4::Context->preference('AllowMultipleCovers'),
371 EnableBorrowerFiles => C4::Context->preference('EnableBorrowerFiles'),
372 UseKohaPlugins => C4::Context->preference('UseKohaPlugins'),
373 UseCourseReserves => C4::Context->preference("UseCourseReserves"),
376 else {
377 warn "template type should be OPAC, here it is=[" . $in->{'type'} . "]" unless ( $in->{'type'} eq 'opac' );
378 #TODO : replace LibraryName syspref with 'system name', and remove this html processing
379 my $LibraryNameTitle = C4::Context->preference("LibraryName");
380 $LibraryNameTitle =~ s/<(?:\/?)(?:br|p)\s*(?:\/?)>/ /sgi;
381 $LibraryNameTitle =~ s/<(?:[^<>'"]|'(?:[^']*)'|"(?:[^"]*)")*>//sg;
382 # clean up the busc param in the session if the page is not opac-detail and not the "add to list" page
383 if ( C4::Context->preference("OpacBrowseResults")
384 && $in->{'template_name'} =~ /opac-(.+)\.(?:tt|tmpl)$/ ) {
385 my $pagename = $1;
386 unless ( $pagename =~ /^(?:MARC|ISBD)?detail$/
387 or $pagename =~ /^addbybiblionumber$/ ) {
388 my $sessionSearch = get_session($sessionID || $in->{'query'}->cookie("CGISESSID"));
389 $sessionSearch->clear(["busc"]) if ($sessionSearch->param("busc"));
392 # variables passed from CGI: opac_css_override and opac_search_limits.
393 my $opac_search_limit = $ENV{'OPAC_SEARCH_LIMIT'};
394 my $opac_limit_override = $ENV{'OPAC_LIMIT_OVERRIDE'};
395 my $opac_name = '';
396 if (
397 ($opac_limit_override && $opac_search_limit && $opac_search_limit =~ /branch:(\w+)/) ||
398 ($in->{'query'}->param('limit') && $in->{'query'}->param('limit') =~ /branch:(\w+)/) ||
399 ($in->{'query'}->param('multibranchlimit') && $in->{'query'}->param('multibranchlimit') =~ /multibranchlimit-(\w+)/)
401 $opac_name = $1; # opac_search_limit is a branch, so we use it.
402 } elsif ( $in->{'query'}->param('multibranchlimit') ) {
403 $opac_name = $in->{'query'}->param('multibranchlimit');
404 } elsif (C4::Context->preference("SearchMyLibraryFirst") && C4::Context->userenv && C4::Context->userenv->{'branch'}) {
405 $opac_name = C4::Context->userenv->{'branch'};
407 $template->param(
408 opaccolorstylesheet => C4::Context->preference("opaccolorstylesheet"),
409 AnonSuggestions => "" . C4::Context->preference("AnonSuggestions"),
410 AuthorisedValueImages => C4::Context->preference("AuthorisedValueImages"),
411 BranchesLoop => GetBranchesLoop($opac_name),
412 BranchCategoriesLoop => GetBranchCategories( 'searchdomain', 1, $opac_name ),
413 CalendarFirstDayOfWeek => (C4::Context->preference("CalendarFirstDayOfWeek") eq "Sunday")?0:1,
414 LibraryName => "" . C4::Context->preference("LibraryName"),
415 LibraryNameTitle => "" . $LibraryNameTitle,
416 LoginBranchname => C4::Context->userenv?C4::Context->userenv->{"branchname"}:"",
417 OPACAmazonCoverImages => C4::Context->preference("OPACAmazonCoverImages"),
418 OPACFRBRizeEditions => C4::Context->preference("OPACFRBRizeEditions"),
419 OpacHighlightedWords => C4::Context->preference("OpacHighlightedWords"),
420 OPACItemHolds => C4::Context->preference("OPACItemHolds"),
421 OPACShelfBrowser => "". C4::Context->preference("OPACShelfBrowser"),
422 OPACURLOpenInNewWindow => "" . C4::Context->preference("OPACURLOpenInNewWindow"),
423 OPACUserCSS => "". C4::Context->preference("OPACUserCSS"),
424 OPACMobileUserCSS => "". C4::Context->preference("OPACMobileUserCSS"),
425 OPACViewOthersSuggestions => "" . C4::Context->preference("OPACViewOthersSuggestions"),
426 OpacAuthorities => C4::Context->preference("OpacAuthorities"),
427 OPACBaseURL => ($in->{'query'}->https() ? "https://" : "http://") . $ENV{'SERVER_NAME'} .
428 ($ENV{'SERVER_PORT'} eq ($in->{'query'}->https() ? "443" : "80") ? '' : ":$ENV{'SERVER_PORT'}"),
429 opac_css_override => $ENV{'OPAC_CSS_OVERRIDE'},
430 opac_search_limit => $opac_search_limit,
431 opac_limit_override => $opac_limit_override,
432 OpacBrowser => C4::Context->preference("OpacBrowser"),
433 OpacCloud => C4::Context->preference("OpacCloud"),
434 OpacKohaUrl => C4::Context->preference("OpacKohaUrl"),
435 OpacMainUserBlock => "" . C4::Context->preference("OpacMainUserBlock"),
436 OpacMainUserBlockMobile => "" . C4::Context->preference("OpacMainUserBlockMobile"),
437 OpacShowFiltersPulldownMobile => C4::Context->preference("OpacShowFiltersPulldownMobile"),
438 OpacShowLibrariesPulldownMobile => C4::Context->preference("OpacShowLibrariesPulldownMobile"),
439 OpacNav => "" . C4::Context->preference("OpacNav"),
440 OpacNavRight => "" . C4::Context->preference("OpacNavRight"),
441 OpacNavBottom => "" . C4::Context->preference("OpacNavBottom"),
442 OpacPasswordChange => C4::Context->preference("OpacPasswordChange"),
443 OPACPatronDetails => C4::Context->preference("OPACPatronDetails"),
444 OPACPrivacy => C4::Context->preference("OPACPrivacy"),
445 OPACFinesTab => C4::Context->preference("OPACFinesTab"),
446 OpacTopissue => C4::Context->preference("OpacTopissue"),
447 RequestOnOpac => C4::Context->preference("RequestOnOpac"),
448 'Version' => C4::Context->preference('Version'),
449 hidelostitems => C4::Context->preference("hidelostitems"),
450 mylibraryfirst => (C4::Context->preference("SearchMyLibraryFirst") && C4::Context->userenv) ? C4::Context->userenv->{'branch'} : '',
451 opaclayoutstylesheet => "" . C4::Context->preference("opaclayoutstylesheet"),
452 opacbookbag => "" . C4::Context->preference("opacbookbag"),
453 opaccredits => "" . C4::Context->preference("opaccredits"),
454 OpacFavicon => C4::Context->preference("OpacFavicon"),
455 opacheader => "" . C4::Context->preference("opacheader"),
456 opaclanguagesdisplay => "" . C4::Context->preference("opaclanguagesdisplay"),
457 opacreadinghistory => C4::Context->preference("opacreadinghistory"),
458 opacsmallimage => "" . C4::Context->preference("opacsmallimage"),
459 opacuserjs => C4::Context->preference("opacuserjs"),
460 opacuserlogin => "" . C4::Context->preference("opacuserlogin"),
461 ShowReviewer => C4::Context->preference("ShowReviewer"),
462 ShowReviewerPhoto => C4::Context->preference("ShowReviewerPhoto"),
463 suggestion => "" . C4::Context->preference("suggestion"),
464 virtualshelves => "" . C4::Context->preference("virtualshelves"),
465 OPACSerialIssueDisplayCount => C4::Context->preference("OPACSerialIssueDisplayCount"),
466 OPACXSLTDetailsDisplay => C4::Context->preference("OPACXSLTDetailsDisplay"),
467 OPACXSLTResultsDisplay => C4::Context->preference("OPACXSLTResultsDisplay"),
468 SyndeticsClientCode => C4::Context->preference("SyndeticsClientCode"),
469 SyndeticsEnabled => C4::Context->preference("SyndeticsEnabled"),
470 SyndeticsCoverImages => C4::Context->preference("SyndeticsCoverImages"),
471 SyndeticsTOC => C4::Context->preference("SyndeticsTOC"),
472 SyndeticsSummary => C4::Context->preference("SyndeticsSummary"),
473 SyndeticsEditions => C4::Context->preference("SyndeticsEditions"),
474 SyndeticsExcerpt => C4::Context->preference("SyndeticsExcerpt"),
475 SyndeticsReviews => C4::Context->preference("SyndeticsReviews"),
476 SyndeticsAuthorNotes => C4::Context->preference("SyndeticsAuthorNotes"),
477 SyndeticsAwards => C4::Context->preference("SyndeticsAwards"),
478 SyndeticsSeries => C4::Context->preference("SyndeticsSeries"),
479 SyndeticsCoverImageSize => C4::Context->preference("SyndeticsCoverImageSize"),
480 OPACLocalCoverImages => C4::Context->preference("OPACLocalCoverImages"),
481 PatronSelfRegistration => C4::Context->preference("PatronSelfRegistration"),
482 PatronSelfRegistrationDefaultCategory => C4::Context->preference("PatronSelfRegistrationDefaultCategory"),
485 $template->param(OpacPublic => '1') if ($user || C4::Context->preference("OpacPublic"));
488 # Check if we were asked using parameters to force a specific language
489 if ( defined $in->{'query'}->param('language') ) {
490 # Extract the language, let C4::Languages::getlanguage choose
491 # what to do
492 my $language = C4::Languages::getlanguage($in->{'query'});
493 my $languagecookie = C4::Templates::getlanguagecookie($in->{'query'},$language);
494 if ( ref $cookie eq 'ARRAY' ) {
495 push @{ $cookie }, $languagecookie;
496 } else {
497 $cookie = [$cookie, $languagecookie];
501 return ( $template, $borrowernumber, $cookie, $flags);
504 =head2 checkauth
506 ($userid, $cookie, $sessionID) = &checkauth($query, $noauth, $flagsrequired, $type);
508 Verifies that the user is authorized to run this script. If
509 the user is authorized, a (userid, cookie, session-id, flags)
510 quadruple is returned. If the user is not authorized but does
511 not have the required privilege (see $flagsrequired below), it
512 displays an error page and exits. Otherwise, it displays the
513 login page and exits.
515 Note that C<&checkauth> will return if and only if the user
516 is authorized, so it should be called early on, before any
517 unfinished operations (e.g., if you've opened a file, then
518 C<&checkauth> won't close it for you).
520 C<$query> is the CGI object for the script calling C<&checkauth>.
522 The C<$noauth> argument is optional. If it is set, then no
523 authorization is required for the script.
525 C<&checkauth> fetches user and session information from C<$query> and
526 ensures that the user is authorized to run scripts that require
527 authorization.
529 The C<$flagsrequired> argument specifies the required privileges
530 the user must have if the username and password are correct.
531 It should be specified as a reference-to-hash; keys in the hash
532 should be the "flags" for the user, as specified in the Members
533 intranet module. Any key specified must correspond to a "flag"
534 in the userflags table. E.g., { circulate => 1 } would specify
535 that the user must have the "circulate" privilege in order to
536 proceed. To make sure that access control is correct, the
537 C<$flagsrequired> parameter must be specified correctly.
539 Koha also has a concept of sub-permissions, also known as
540 granular permissions. This makes the value of each key
541 in the C<flagsrequired> hash take on an additional
542 meaning, i.e.,
546 The user must have access to all subfunctions of the module
547 specified by the hash key.
551 The user must have access to at least one subfunction of the module
552 specified by the hash key.
554 specific permission, e.g., 'export_catalog'
556 The user must have access to the specific subfunction list, which
557 must correspond to a row in the permissions table.
559 The C<$type> argument specifies whether the template should be
560 retrieved from the opac or intranet directory tree. "opac" is
561 assumed if it is not specified; however, if C<$type> is specified,
562 "intranet" is assumed if it is not "opac".
564 If C<$query> does not have a valid session ID associated with it
565 (i.e., the user has not logged in) or if the session has expired,
566 C<&checkauth> presents the user with a login page (from the point of
567 view of the original script, C<&checkauth> does not return). Once the
568 user has authenticated, C<&checkauth> restarts the original script
569 (this time, C<&checkauth> returns).
571 The login page is provided using a HTML::Template, which is set in the
572 systempreferences table or at the top of this file. The variable C<$type>
573 selects which template to use, either the opac or the intranet
574 authentification template.
576 C<&checkauth> returns a user ID, a cookie, and a session ID. The
577 cookie should be sent back to the browser; it verifies that the user
578 has authenticated.
580 =cut
582 sub _version_check {
583 my $type = shift;
584 my $query = shift;
585 my $version;
586 # If Version syspref is unavailable, it means Koha is beeing installed,
587 # and so we must redirect to OPAC maintenance page or to the WebInstaller
588 # also, if OpacMaintenance is ON, OPAC should redirect to maintenance
589 if (C4::Context->preference('OpacMaintenance') && $type eq 'opac') {
590 warn "OPAC Install required, redirecting to maintenance";
591 print $query->redirect("/cgi-bin/koha/maintenance.pl");
592 safe_exit;
594 unless ( $version = C4::Context->preference('Version') ) { # assignment, not comparison
595 if ( $type ne 'opac' ) {
596 warn "Install required, redirecting to Installer";
597 print $query->redirect("/cgi-bin/koha/installer/install.pl");
598 } else {
599 warn "OPAC Install required, redirecting to maintenance";
600 print $query->redirect("/cgi-bin/koha/maintenance.pl");
602 safe_exit;
605 # check that database and koha version are the same
606 # there is no DB version, it's a fresh install,
607 # go to web installer
608 # there is a DB version, compare it to the code version
609 my $kohaversion=C4::Context::KOHAVERSION;
610 # remove the 3 last . to have a Perl number
611 $kohaversion =~ s/(.*\..*)\.(.*)\.(.*)/$1$2$3/;
612 $debug and print STDERR "kohaversion : $kohaversion\n";
613 if ($version < $kohaversion){
614 my $warning = "Database update needed, redirecting to %s. Database is $version and Koha is $kohaversion";
615 if ($type ne 'opac'){
616 warn sprintf($warning, 'Installer');
617 print $query->redirect("/cgi-bin/koha/installer/install.pl?step=3");
618 } else {
619 warn sprintf("OPAC: " . $warning, 'maintenance');
620 print $query->redirect("/cgi-bin/koha/maintenance.pl");
622 safe_exit;
626 sub _session_log {
627 (@_) or return 0;
628 open my $fh, '>>', "/tmp/sessionlog" or warn "ERROR: Cannot append to /tmp/sessionlog";
629 printf $fh join("\n",@_);
630 close $fh;
633 sub _timeout_syspref {
634 my $timeout = C4::Context->preference('timeout') || 600;
635 # value in days, convert in seconds
636 if ($timeout =~ /(\d+)[dD]/) {
637 $timeout = $1 * 86400;
639 return $timeout;
642 sub checkauth {
643 my $query = shift;
644 $debug and warn "Checking Auth";
645 # $authnotrequired will be set for scripts which will run without authentication
646 my $authnotrequired = shift;
647 my $flagsrequired = shift;
648 my $type = shift;
649 my $persona = shift;
650 $type = 'opac' unless $type;
652 my $dbh = C4::Context->dbh;
653 my $timeout = _timeout_syspref();
655 _version_check($type,$query);
656 # state variables
657 my $loggedin = 0;
658 my %info;
659 my ( $userid, $cookie, $sessionID, $flags, $barshelves, $pubshelves );
660 my $logout = $query->param('logout.x');
662 my $anon_search_history;
664 # This parameter is the name of the CAS server we want to authenticate against,
665 # when using authentication against multiple CAS servers, as configured in Auth_cas_servers.yaml
666 my $casparam = $query->param('cas');
667 my $q_userid = $query->param('userid') // '';
669 if ( $userid = $ENV{'REMOTE_USER'} ) {
670 # Using Basic Authentication, no cookies required
671 $cookie = $query->cookie(
672 -name => 'CGISESSID',
673 -value => '',
674 -expires => '',
675 -HttpOnly => 1,
677 $loggedin = 1;
679 elsif ( $persona ){
680 # we dont want to set a session because we are being called by a persona callback
682 elsif ( $sessionID = $query->cookie("CGISESSID") )
683 { # assignment, not comparison
684 my $session = get_session($sessionID);
685 C4::Context->_new_userenv($sessionID);
686 my ($ip, $lasttime, $sessiontype);
687 my $s_userid = '';
688 if ($session){
689 $s_userid = $session->param('id') // '';
690 C4::Context::set_userenv(
691 $session->param('number'), $s_userid,
692 $session->param('cardnumber'), $session->param('firstname'),
693 $session->param('surname'), $session->param('branch'),
694 $session->param('branchname'), $session->param('flags'),
695 $session->param('emailaddress'), $session->param('branchprinter'),
696 $session->param('persona')
698 C4::Context::set_shelves_userenv('bar',$session->param('barshelves'));
699 C4::Context::set_shelves_userenv('pub',$session->param('pubshelves'));
700 C4::Context::set_shelves_userenv('tot',$session->param('totshelves'));
701 $debug and printf STDERR "AUTH_SESSION: (%s)\t%s %s - %s\n", map {$session->param($_)} qw(cardnumber firstname surname branch) ;
702 $ip = $session->param('ip');
703 $lasttime = $session->param('lasttime');
704 $userid = $s_userid;
705 $sessiontype = $session->param('sessiontype') || '';
707 if ( ( $query->param('koha_login_context') && ($q_userid ne $s_userid) )
708 || ( $cas && $query->param('ticket') ) ) {
709 #if a user enters an id ne to the id in the current session, we need to log them in...
710 #first we need to clear the anonymous session...
711 $debug and warn "query id = $q_userid but session id = $s_userid";
712 $anon_search_history = $session->param('search_history');
713 $session->delete();
714 $session->flush;
715 C4::Context->_unset_userenv($sessionID);
716 $sessionID = undef;
717 $userid = undef;
719 elsif ($logout) {
720 # voluntary logout the user
721 $session->delete();
722 $session->flush;
723 C4::Context->_unset_userenv($sessionID);
724 #_session_log(sprintf "%20s from %16s logged out at %30s (manually).\n", $userid,$ip,(strftime "%c",localtime));
725 $sessionID = undef;
726 $userid = undef;
728 if ($cas and $caslogout) {
729 logout_cas($query);
732 elsif ( !$lasttime || ($lasttime < time() - $timeout) ) {
733 # timed logout
734 $info{'timed_out'} = 1;
735 if ($session) {
736 $session->delete();
737 $session->flush;
739 C4::Context->_unset_userenv($sessionID);
740 #_session_log(sprintf "%20s from %16s logged out at %30s (inactivity).\n", $userid,$ip,(strftime "%c",localtime));
741 $userid = undef;
742 $sessionID = undef;
744 elsif ( $ip ne $ENV{'REMOTE_ADDR'} ) {
745 # Different ip than originally logged in from
746 $info{'oldip'} = $ip;
747 $info{'newip'} = $ENV{'REMOTE_ADDR'};
748 $info{'different_ip'} = 1;
749 $session->delete();
750 $session->flush;
751 C4::Context->_unset_userenv($sessionID);
752 #_session_log(sprintf "%20s from %16s logged out at %30s (ip changed to %16s).\n", $userid,$ip,(strftime "%c",localtime), $info{'newip'});
753 $sessionID = undef;
754 $userid = undef;
756 else {
757 $cookie = $query->cookie(
758 -name => 'CGISESSID',
759 -value => $session->id,
760 -HttpOnly => 1
762 $session->param( 'lasttime', time() );
763 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...
764 $flags = haspermission($userid, $flagsrequired);
765 if ($flags) {
766 $loggedin = 1;
767 } else {
768 $info{'nopermission'} = 1;
773 unless ($userid || $sessionID) {
775 #we initiate a session prior to checking for a username to allow for anonymous sessions...
776 my $session = get_session("") or die "Auth ERROR: Cannot get_session()";
778 # Save anonymous search history in new session so it can be retrieved
779 # by get_template_and_user to store it in user's search history after
780 # a successful login.
781 if ($anon_search_history) {
782 $session->param('search_history', $anon_search_history);
785 my $sessionID = $session->id;
786 C4::Context->_new_userenv($sessionID);
787 $cookie = $query->cookie(
788 -name => 'CGISESSID',
789 -value => $session->id,
790 -HttpOnly => 1
792 $userid = $q_userid;
793 my $pki_field = C4::Context->preference('AllowPKIAuth');
794 if (! defined($pki_field) ) {
795 print STDERR "ERROR: Missing system preference AllowPKIAuth.\n";
796 $pki_field = 'None';
798 if ( ( $cas && $query->param('ticket') )
799 || $userid
800 || $pki_field ne 'None'
801 || $persona )
803 my $password = $query->param('password');
805 my ( $return, $cardnumber );
806 if ( $cas && $query->param('ticket') ) {
807 my $retuserid;
808 ( $return, $cardnumber, $retuserid ) =
809 checkpw( $dbh, $userid, $password, $query );
810 $userid = $retuserid;
811 $info{'invalidCasLogin'} = 1 unless ($return);
814 elsif ($persona) {
815 my $value = $persona;
817 # If we're looking up the email, there's a chance that the person
818 # doesn't have a userid. So if there is none, we pass along the
819 # borrower number, and the bits of code that need to know the user
820 # ID will have to be smart enough to handle that.
821 require C4::Members;
822 my @users_info = C4::Members::GetBorrowersWithEmail($value);
823 if (@users_info) {
825 # First the userid, then the borrowernum
826 $value = $users_info[0][1] || $users_info[0][0];
828 else {
829 undef $value;
831 $return = $value ? 1 : 0;
832 $userid = $value;
835 elsif (
836 ( $pki_field eq 'Common Name' && $ENV{'SSL_CLIENT_S_DN_CN'} )
837 || ( $pki_field eq 'emailAddress'
838 && $ENV{'SSL_CLIENT_S_DN_Email'} )
841 my $value;
842 if ( $pki_field eq 'Common Name' ) {
843 $value = $ENV{'SSL_CLIENT_S_DN_CN'};
845 elsif ( $pki_field eq 'emailAddress' ) {
846 $value = $ENV{'SSL_CLIENT_S_DN_Email'};
848 # If we're looking up the email, there's a chance that the person
849 # doesn't have a userid. So if there is none, we pass along the
850 # borrower number, and the bits of code that need to know the user
851 # ID will have to be smart enough to handle that.
852 require C4::Members;
853 my @users_info = C4::Members::GetBorrowersWithEmail($value);
854 if (@users_info) {
856 # First the userid, then the borrowernum
857 $value = $users_info[0][1] || $users_info[0][0];
858 } else {
859 undef $value;
864 $return = $value ? 1 : 0;
865 $userid = $value;
868 else {
869 my $retuserid;
870 ( $return, $cardnumber, $retuserid ) =
871 checkpw( $dbh, $userid, $password, $query );
872 $userid = $retuserid if ( $retuserid );
874 if ($return) {
875 #_session_log(sprintf "%20s from %16s logged in at %30s.\n", $userid,$ENV{'REMOTE_ADDR'},(strftime '%c', localtime));
876 if ( $flags = haspermission( $userid, $flagsrequired ) ) {
877 $loggedin = 1;
879 else {
880 $info{'nopermission'} = 1;
881 C4::Context->_unset_userenv($sessionID);
883 my ($borrowernumber, $firstname, $surname, $userflags,
884 $branchcode, $branchname, $branchprinter, $emailaddress);
886 if ( $return == 1 ) {
887 my $select = "
888 SELECT borrowernumber, firstname, surname, flags, borrowers.branchcode,
889 branches.branchname as branchname,
890 branches.branchprinter as branchprinter,
891 email
892 FROM borrowers
893 LEFT JOIN branches on borrowers.branchcode=branches.branchcode
895 my $sth = $dbh->prepare("$select where userid=?");
896 $sth->execute($userid);
897 unless ($sth->rows) {
898 $debug and print STDERR "AUTH_1: no rows for userid='$userid'\n";
899 $sth = $dbh->prepare("$select where cardnumber=?");
900 $sth->execute($cardnumber);
902 unless ($sth->rows) {
903 $debug and print STDERR "AUTH_2a: no rows for cardnumber='$cardnumber'\n";
904 $sth->execute($userid);
905 unless ($sth->rows) {
906 $debug and print STDERR "AUTH_2b: no rows for userid='$userid' AS cardnumber\n";
910 if ($sth->rows) {
911 ($borrowernumber, $firstname, $surname, $userflags,
912 $branchcode, $branchname, $branchprinter, $emailaddress) = $sth->fetchrow;
913 $debug and print STDERR "AUTH_3 results: " .
914 "$cardnumber,$borrowernumber,$userid,$firstname,$surname,$userflags,$branchcode,$emailaddress\n";
915 } else {
916 print STDERR "AUTH_3: no results for userid='$userid', cardnumber='$cardnumber'.\n";
919 # launch a sequence to check if we have a ip for the branch, i
920 # if we have one we replace the branchcode of the userenv by the branch bound in the ip.
922 my $ip = $ENV{'REMOTE_ADDR'};
923 # if they specify at login, use that
924 if ($query->param('branch')) {
925 $branchcode = $query->param('branch');
926 $branchname = GetBranchName($branchcode);
928 my $branches = GetBranches();
929 if (C4::Context->boolean_preference('IndependentBranches') && C4::Context->boolean_preference('Autolocation')){
930 # we have to check they are coming from the right ip range
931 my $domain = $branches->{$branchcode}->{'branchip'};
932 if ($ip !~ /^$domain/){
933 $loggedin=0;
934 $info{'wrongip'} = 1;
938 my @branchesloop;
939 foreach my $br ( keys %$branches ) {
940 # now we work with the treatment of ip
941 my $domain = $branches->{$br}->{'branchip'};
942 if ( $domain && $ip =~ /^$domain/ ) {
943 $branchcode = $branches->{$br}->{'branchcode'};
945 # new op dev : add the branchprinter and branchname in the cookie
946 $branchprinter = $branches->{$br}->{'branchprinter'};
947 $branchname = $branches->{$br}->{'branchname'};
950 $session->param('number',$borrowernumber);
951 $session->param('id',$userid);
952 $session->param('cardnumber',$cardnumber);
953 $session->param('firstname',$firstname);
954 $session->param('surname',$surname);
955 $session->param('branch',$branchcode);
956 $session->param('branchname',$branchname);
957 $session->param('flags',$userflags);
958 $session->param('emailaddress',$emailaddress);
959 $session->param('ip',$session->remote_addr());
960 $session->param('lasttime',time());
961 $debug and printf STDERR "AUTH_4: (%s)\t%s %s - %s\n", map {$session->param($_)} qw(cardnumber firstname surname branch) ;
963 elsif ( $return == 2 ) {
964 #We suppose the user is the superlibrarian
965 $borrowernumber = 0;
966 $session->param('number',0);
967 $session->param('id',C4::Context->config('user'));
968 $session->param('cardnumber',C4::Context->config('user'));
969 $session->param('firstname',C4::Context->config('user'));
970 $session->param('surname',C4::Context->config('user'));
971 $session->param('branch','NO_LIBRARY_SET');
972 $session->param('branchname','NO_LIBRARY_SET');
973 $session->param('flags',1);
974 $session->param('emailaddress', C4::Context->preference('KohaAdminEmailAddress'));
975 $session->param('ip',$session->remote_addr());
976 $session->param('lasttime',time());
978 if ($persona){
979 $session->param('persona',1);
981 C4::Context::set_userenv(
982 $session->param('number'), $session->param('id'),
983 $session->param('cardnumber'), $session->param('firstname'),
984 $session->param('surname'), $session->param('branch'),
985 $session->param('branchname'), $session->param('flags'),
986 $session->param('emailaddress'), $session->param('branchprinter'),
987 $session->param('persona')
991 else {
992 if ($userid) {
993 $info{'invalid_username_or_password'} = 1;
994 C4::Context->_unset_userenv($sessionID);
996 $session->param('lasttime',time());
997 $session->param('ip',$session->remote_addr());
999 } # END if ( $userid = $query->param('userid') )
1000 elsif ($type eq "opac") {
1001 # if we are here this is an anonymous session; add public lists to it and a few other items...
1002 # anonymous sessions are created only for the OPAC
1003 $debug and warn "Initiating an anonymous session...";
1005 # setting a couple of other session vars...
1006 $session->param('ip',$session->remote_addr());
1007 $session->param('lasttime',time());
1008 $session->param('sessiontype','anon');
1010 } # END unless ($userid)
1012 # finished authentification, now respond
1013 if ( $loggedin || $authnotrequired )
1015 # successful login
1016 unless ($cookie) {
1017 $cookie = $query->cookie(
1018 -name => 'CGISESSID',
1019 -value => '',
1020 -HttpOnly => 1
1023 return ( $userid, $cookie, $sessionID, $flags );
1028 # AUTH rejected, show the login/password template, after checking the DB.
1032 # get the inputs from the incoming query
1033 my @inputs = ();
1034 foreach my $name ( param $query) {
1035 (next) if ( $name eq 'userid' || $name eq 'password' || $name eq 'ticket' );
1036 my $value = $query->param($name);
1037 push @inputs, { name => $name, value => $value };
1040 my $LibraryNameTitle = C4::Context->preference("LibraryName");
1041 $LibraryNameTitle =~ s/<(?:\/?)(?:br|p)\s*(?:\/?)>/ /sgi;
1042 $LibraryNameTitle =~ s/<(?:[^<>'"]|'(?:[^']*)'|"(?:[^"]*)")*>//sg;
1044 my $template_name = ( $type eq 'opac' ) ? 'opac-auth.tmpl' : 'auth.tmpl';
1045 my $template = C4::Templates::gettemplate($template_name, $type, $query );
1046 $template->param(
1047 branchloop => GetBranchesLoop(),
1048 opaccolorstylesheet => C4::Context->preference("opaccolorstylesheet"),
1049 opaclayoutstylesheet => C4::Context->preference("opaclayoutstylesheet"),
1050 login => 1,
1051 INPUTS => \@inputs,
1052 casAuthentication => C4::Context->preference("casAuthentication"),
1053 suggestion => C4::Context->preference("suggestion"),
1054 virtualshelves => C4::Context->preference("virtualshelves"),
1055 LibraryName => "" . C4::Context->preference("LibraryName"),
1056 LibraryNameTitle => "" . $LibraryNameTitle,
1057 opacuserlogin => C4::Context->preference("opacuserlogin"),
1058 OpacNav => C4::Context->preference("OpacNav"),
1059 OpacNavRight => C4::Context->preference("OpacNavRight"),
1060 OpacNavBottom => C4::Context->preference("OpacNavBottom"),
1061 opaccredits => C4::Context->preference("opaccredits"),
1062 OpacFavicon => C4::Context->preference("OpacFavicon"),
1063 opacreadinghistory => C4::Context->preference("opacreadinghistory"),
1064 opacsmallimage => C4::Context->preference("opacsmallimage"),
1065 opaclanguagesdisplay => C4::Context->preference("opaclanguagesdisplay"),
1066 opacuserjs => C4::Context->preference("opacuserjs"),
1067 opacbookbag => "" . C4::Context->preference("opacbookbag"),
1068 OpacCloud => C4::Context->preference("OpacCloud"),
1069 OpacTopissue => C4::Context->preference("OpacTopissue"),
1070 OpacAuthorities => C4::Context->preference("OpacAuthorities"),
1071 OpacBrowser => C4::Context->preference("OpacBrowser"),
1072 opacheader => C4::Context->preference("opacheader"),
1073 TagsEnabled => C4::Context->preference("TagsEnabled"),
1074 OPACUserCSS => C4::Context->preference("OPACUserCSS"),
1075 intranetcolorstylesheet => C4::Context->preference("intranetcolorstylesheet"),
1076 intranetstylesheet => C4::Context->preference("intranetstylesheet"),
1077 intranetbookbag => C4::Context->preference("intranetbookbag"),
1078 IntranetNav => C4::Context->preference("IntranetNav"),
1079 IntranetFavicon => C4::Context->preference("IntranetFavicon"),
1080 intranetuserjs => C4::Context->preference("intranetuserjs"),
1081 IndependentBranches=> C4::Context->preference("IndependentBranches"),
1082 AutoLocation => C4::Context->preference("AutoLocation"),
1083 wrongip => $info{'wrongip'},
1084 PatronSelfRegistration => C4::Context->preference("PatronSelfRegistration"),
1085 PatronSelfRegistrationDefaultCategory => C4::Context->preference("PatronSelfRegistrationDefaultCategory"),
1086 persona => C4::Context->preference("Persona"),
1087 opac_css_override => $ENV{'OPAC_CSS_OVERRIDE'},
1090 $template->param( OpacPublic => C4::Context->preference("OpacPublic"));
1091 $template->param( loginprompt => 1 ) unless $info{'nopermission'};
1093 if($type eq 'opac'){
1094 my ($total, $pubshelves) = C4::VirtualShelves::GetSomeShelfNames(undef, 'MASTHEAD');
1095 $template->param(
1096 pubshelves => $total->{pubtotal},
1097 pubshelvesloop => $pubshelves,
1101 if ($cas) {
1103 # Is authentication against multiple CAS servers enabled?
1104 if (C4::Auth_with_cas::multipleAuth && !$casparam) {
1105 my $casservers = C4::Auth_with_cas::getMultipleAuth();
1106 my @tmplservers;
1107 foreach my $key (keys %$casservers) {
1108 push @tmplservers, {name => $key, value => login_cas_url($query, $key) . "?cas=$key" };
1110 $template->param(
1111 casServersLoop => \@tmplservers
1113 } else {
1114 $template->param(
1115 casServerUrl => login_cas_url($query),
1119 $template->param(
1120 invalidCasLogin => $info{'invalidCasLogin'}
1124 my $self_url = $query->url( -absolute => 1 );
1125 $template->param(
1126 url => $self_url,
1127 LibraryName => C4::Context->preference("LibraryName"),
1129 $template->param( %info );
1130 # $cookie = $query->cookie(CGISESSID => $session->id
1131 # );
1132 print $query->header(
1133 -type => 'text/html',
1134 -charset => 'utf-8',
1135 -cookie => $cookie
1137 $template->output;
1138 safe_exit;
1141 =head2 check_api_auth
1143 ($status, $cookie, $sessionId) = check_api_auth($query, $userflags);
1145 Given a CGI query containing the parameters 'userid' and 'password' and/or a session
1146 cookie, determine if the user has the privileges specified by C<$userflags>.
1148 C<check_api_auth> is is meant for authenticating users of web services, and
1149 consequently will always return and will not attempt to redirect the user
1150 agent.
1152 If a valid session cookie is already present, check_api_auth will return a status
1153 of "ok", the cookie, and the Koha session ID.
1155 If no session cookie is present, check_api_auth will check the 'userid' and 'password
1156 parameters and create a session cookie and Koha session if the supplied credentials
1157 are OK.
1159 Possible return values in C<$status> are:
1161 =over
1163 =item "ok" -- user authenticated; C<$cookie> and C<$sessionid> have valid values.
1165 =item "failed" -- credentials are not correct; C<$cookie> and C<$sessionid> are undef
1167 =item "maintenance" -- DB is in maintenance mode; no login possible at the moment
1169 =item "expired -- session cookie has expired; API user should resubmit userid and password
1171 =back
1173 =cut
1175 sub check_api_auth {
1176 my $query = shift;
1177 my $flagsrequired = shift;
1179 my $dbh = C4::Context->dbh;
1180 my $timeout = _timeout_syspref();
1182 unless (C4::Context->preference('Version')) {
1183 # database has not been installed yet
1184 return ("maintenance", undef, undef);
1186 my $kohaversion=C4::Context::KOHAVERSION;
1187 $kohaversion =~ s/(.*\..*)\.(.*)\.(.*)/$1$2$3/;
1188 if (C4::Context->preference('Version') < $kohaversion) {
1189 # database in need of version update; assume that
1190 # no API should be called while databsae is in
1191 # this condition.
1192 return ("maintenance", undef, undef);
1195 # FIXME -- most of what follows is a copy-and-paste
1196 # of code from checkauth. There is an obvious need
1197 # for refactoring to separate the various parts of
1198 # the authentication code, but as of 2007-11-19 this
1199 # is deferred so as to not introduce bugs into the
1200 # regular authentication code for Koha 3.0.
1202 # see if we have a valid session cookie already
1203 # however, if a userid parameter is present (i.e., from
1204 # a form submission, assume that any current cookie
1205 # is to be ignored
1206 my $sessionID = undef;
1207 unless ($query->param('userid')) {
1208 $sessionID = $query->cookie("CGISESSID");
1210 if ($sessionID && not ($cas && $query->param('PT')) ) {
1211 my $session = get_session($sessionID);
1212 C4::Context->_new_userenv($sessionID);
1213 if ($session) {
1214 C4::Context::set_userenv(
1215 $session->param('number'), $session->param('id'),
1216 $session->param('cardnumber'), $session->param('firstname'),
1217 $session->param('surname'), $session->param('branch'),
1218 $session->param('branchname'), $session->param('flags'),
1219 $session->param('emailaddress'), $session->param('branchprinter')
1222 my $ip = $session->param('ip');
1223 my $lasttime = $session->param('lasttime');
1224 my $userid = $session->param('id');
1225 if ( $lasttime < time() - $timeout ) {
1226 # time out
1227 $session->delete();
1228 $session->flush;
1229 C4::Context->_unset_userenv($sessionID);
1230 $userid = undef;
1231 $sessionID = undef;
1232 return ("expired", undef, undef);
1233 } elsif ( $ip ne $ENV{'REMOTE_ADDR'} ) {
1234 # IP address changed
1235 $session->delete();
1236 $session->flush;
1237 C4::Context->_unset_userenv($sessionID);
1238 $userid = undef;
1239 $sessionID = undef;
1240 return ("expired", undef, undef);
1241 } else {
1242 my $cookie = $query->cookie(
1243 -name => 'CGISESSID',
1244 -value => $session->id,
1245 -HttpOnly => 1,
1247 $session->param('lasttime',time());
1248 my $flags = haspermission($userid, $flagsrequired);
1249 if ($flags) {
1250 return ("ok", $cookie, $sessionID);
1251 } else {
1252 $session->delete();
1253 $session->flush;
1254 C4::Context->_unset_userenv($sessionID);
1255 $userid = undef;
1256 $sessionID = undef;
1257 return ("failed", undef, undef);
1260 } else {
1261 return ("expired", undef, undef);
1263 } else {
1264 # new login
1265 my $userid = $query->param('userid');
1266 my $password = $query->param('password');
1267 my ($return, $cardnumber);
1269 # Proxy CAS auth
1270 if ($cas && $query->param('PT')) {
1271 my $retuserid;
1272 $debug and print STDERR "## check_api_auth - checking CAS\n";
1273 # In case of a CAS authentication, we use the ticket instead of the password
1274 my $PT = $query->param('PT');
1275 ($return,$cardnumber,$userid) = check_api_auth_cas($dbh, $PT, $query); # EXTERNAL AUTH
1276 } else {
1277 # User / password auth
1278 unless ($userid and $password) {
1279 # caller did something wrong, fail the authenticateion
1280 return ("failed", undef, undef);
1282 ( $return, $cardnumber ) = checkpw( $dbh, $userid, $password, $query );
1285 if ($return and haspermission( $userid, $flagsrequired)) {
1286 my $session = get_session("");
1287 return ("failed", undef, undef) unless $session;
1289 my $sessionID = $session->id;
1290 C4::Context->_new_userenv($sessionID);
1291 my $cookie = $query->cookie(
1292 -name => 'CGISESSID',
1293 -value => $sessionID,
1294 -HttpOnly => 1,
1296 if ( $return == 1 ) {
1297 my (
1298 $borrowernumber, $firstname, $surname,
1299 $userflags, $branchcode, $branchname,
1300 $branchprinter, $emailaddress
1302 my $sth =
1303 $dbh->prepare(
1304 "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=?"
1306 $sth->execute($userid);
1308 $borrowernumber, $firstname, $surname,
1309 $userflags, $branchcode, $branchname,
1310 $branchprinter, $emailaddress
1311 ) = $sth->fetchrow if ( $sth->rows );
1313 unless ($sth->rows ) {
1314 my $sth = $dbh->prepare(
1315 "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=?"
1317 $sth->execute($cardnumber);
1319 $borrowernumber, $firstname, $surname,
1320 $userflags, $branchcode, $branchname,
1321 $branchprinter, $emailaddress
1322 ) = $sth->fetchrow if ( $sth->rows );
1324 unless ( $sth->rows ) {
1325 $sth->execute($userid);
1327 $borrowernumber, $firstname, $surname, $userflags,
1328 $branchcode, $branchname, $branchprinter, $emailaddress
1329 ) = $sth->fetchrow if ( $sth->rows );
1333 my $ip = $ENV{'REMOTE_ADDR'};
1334 # if they specify at login, use that
1335 if ($query->param('branch')) {
1336 $branchcode = $query->param('branch');
1337 $branchname = GetBranchName($branchcode);
1339 my $branches = GetBranches();
1340 my @branchesloop;
1341 foreach my $br ( keys %$branches ) {
1342 # now we work with the treatment of ip
1343 my $domain = $branches->{$br}->{'branchip'};
1344 if ( $domain && $ip =~ /^$domain/ ) {
1345 $branchcode = $branches->{$br}->{'branchcode'};
1347 # new op dev : add the branchprinter and branchname in the cookie
1348 $branchprinter = $branches->{$br}->{'branchprinter'};
1349 $branchname = $branches->{$br}->{'branchname'};
1352 $session->param('number',$borrowernumber);
1353 $session->param('id',$userid);
1354 $session->param('cardnumber',$cardnumber);
1355 $session->param('firstname',$firstname);
1356 $session->param('surname',$surname);
1357 $session->param('branch',$branchcode);
1358 $session->param('branchname',$branchname);
1359 $session->param('flags',$userflags);
1360 $session->param('emailaddress',$emailaddress);
1361 $session->param('ip',$session->remote_addr());
1362 $session->param('lasttime',time());
1363 } elsif ( $return == 2 ) {
1364 #We suppose the user is the superlibrarian
1365 $session->param('number',0);
1366 $session->param('id',C4::Context->config('user'));
1367 $session->param('cardnumber',C4::Context->config('user'));
1368 $session->param('firstname',C4::Context->config('user'));
1369 $session->param('surname',C4::Context->config('user'));
1370 $session->param('branch','NO_LIBRARY_SET');
1371 $session->param('branchname','NO_LIBRARY_SET');
1372 $session->param('flags',1);
1373 $session->param('emailaddress', C4::Context->preference('KohaAdminEmailAddress'));
1374 $session->param('ip',$session->remote_addr());
1375 $session->param('lasttime',time());
1377 C4::Context::set_userenv(
1378 $session->param('number'), $session->param('id'),
1379 $session->param('cardnumber'), $session->param('firstname'),
1380 $session->param('surname'), $session->param('branch'),
1381 $session->param('branchname'), $session->param('flags'),
1382 $session->param('emailaddress'), $session->param('branchprinter')
1384 return ("ok", $cookie, $sessionID);
1385 } else {
1386 return ("failed", undef, undef);
1391 =head2 check_cookie_auth
1393 ($status, $sessionId) = check_api_auth($cookie, $userflags);
1395 Given a CGISESSID cookie set during a previous login to Koha, determine
1396 if the user has the privileges specified by C<$userflags>.
1398 C<check_cookie_auth> is meant for authenticating special services
1399 such as tools/upload-file.pl that are invoked by other pages that
1400 have been authenticated in the usual way.
1402 Possible return values in C<$status> are:
1404 =over
1406 =item "ok" -- user authenticated; C<$sessionID> have valid values.
1408 =item "failed" -- credentials are not correct; C<$sessionid> are undef
1410 =item "maintenance" -- DB is in maintenance mode; no login possible at the moment
1412 =item "expired -- session cookie has expired; API user should resubmit userid and password
1414 =back
1416 =cut
1418 sub check_cookie_auth {
1419 my $cookie = shift;
1420 my $flagsrequired = shift;
1422 my $dbh = C4::Context->dbh;
1423 my $timeout = _timeout_syspref();
1425 unless (C4::Context->preference('Version')) {
1426 # database has not been installed yet
1427 return ("maintenance", undef);
1429 my $kohaversion=C4::Context::KOHAVERSION;
1430 $kohaversion =~ s/(.*\..*)\.(.*)\.(.*)/$1$2$3/;
1431 if (C4::Context->preference('Version') < $kohaversion) {
1432 # database in need of version update; assume that
1433 # no API should be called while databsae is in
1434 # this condition.
1435 return ("maintenance", undef);
1438 # FIXME -- most of what follows is a copy-and-paste
1439 # of code from checkauth. There is an obvious need
1440 # for refactoring to separate the various parts of
1441 # the authentication code, but as of 2007-11-23 this
1442 # is deferred so as to not introduce bugs into the
1443 # regular authentication code for Koha 3.0.
1445 # see if we have a valid session cookie already
1446 # however, if a userid parameter is present (i.e., from
1447 # a form submission, assume that any current cookie
1448 # is to be ignored
1449 unless (defined $cookie and $cookie) {
1450 return ("failed", undef);
1452 my $sessionID = $cookie;
1453 my $session = get_session($sessionID);
1454 C4::Context->_new_userenv($sessionID);
1455 if ($session) {
1456 C4::Context::set_userenv(
1457 $session->param('number'), $session->param('id'),
1458 $session->param('cardnumber'), $session->param('firstname'),
1459 $session->param('surname'), $session->param('branch'),
1460 $session->param('branchname'), $session->param('flags'),
1461 $session->param('emailaddress'), $session->param('branchprinter')
1464 my $ip = $session->param('ip');
1465 my $lasttime = $session->param('lasttime');
1466 my $userid = $session->param('id');
1467 if ( $lasttime < time() - $timeout ) {
1468 # time out
1469 $session->delete();
1470 $session->flush;
1471 C4::Context->_unset_userenv($sessionID);
1472 $userid = undef;
1473 $sessionID = undef;
1474 return ("expired", undef);
1475 } elsif ( $ip ne $ENV{'REMOTE_ADDR'} ) {
1476 # IP address changed
1477 $session->delete();
1478 $session->flush;
1479 C4::Context->_unset_userenv($sessionID);
1480 $userid = undef;
1481 $sessionID = undef;
1482 return ("expired", undef);
1483 } else {
1484 $session->param('lasttime',time());
1485 my $flags = haspermission($userid, $flagsrequired);
1486 if ($flags) {
1487 return ("ok", $sessionID);
1488 } else {
1489 $session->delete();
1490 $session->flush;
1491 C4::Context->_unset_userenv($sessionID);
1492 $userid = undef;
1493 $sessionID = undef;
1494 return ("failed", undef);
1497 } else {
1498 return ("expired", undef);
1502 =head2 get_session
1504 use CGI::Session;
1505 my $session = get_session($sessionID);
1507 Given a session ID, retrieve the CGI::Session object used to store
1508 the session's state. The session object can be used to store
1509 data that needs to be accessed by different scripts during a
1510 user's session.
1512 If the C<$sessionID> parameter is an empty string, a new session
1513 will be created.
1515 =cut
1517 sub get_session {
1518 my $sessionID = shift;
1519 my $storage_method = C4::Context->preference('SessionStorage');
1520 my $dbh = C4::Context->dbh;
1521 my $session;
1522 if ($storage_method eq 'mysql'){
1523 $session = new CGI::Session("driver:MySQL;serializer:yaml;id:md5", $sessionID, {Handle=>$dbh});
1525 elsif ($storage_method eq 'Pg') {
1526 $session = new CGI::Session("driver:PostgreSQL;serializer:yaml;id:md5", $sessionID, {Handle=>$dbh});
1528 elsif ($storage_method eq 'memcached' && C4::Context->ismemcached){
1529 $session = new CGI::Session("driver:memcached;serializer:yaml;id:md5", $sessionID, { Memcached => C4::Context->memcached } );
1531 else {
1532 # catch all defaults to tmp should work on all systems
1533 $session = new CGI::Session("driver:File;serializer:yaml;id:md5", $sessionID, {Directory=>'/tmp'});
1535 return $session;
1538 sub checkpw {
1539 my ( $dbh, $userid, $password, $query ) = @_;
1541 if ($ldap) {
1542 $debug and print STDERR "## checkpw - checking LDAP\n";
1543 my ($retval,$retcard,$retuserid) = checkpw_ldap(@_); # EXTERNAL AUTH
1544 ($retval) and return ($retval,$retcard,$retuserid);
1547 if ($cas && $query && $query->param('ticket')) {
1548 $debug and print STDERR "## checkpw - checking CAS\n";
1549 # In case of a CAS authentication, we use the ticket instead of the password
1550 my $ticket = $query->param('ticket');
1551 $query->delete('ticket'); # remove ticket to come back to original URL
1552 my ($retval,$retcard,$retuserid) = checkpw_cas($dbh, $ticket, $query); # EXTERNAL AUTH
1553 ($retval) and return ($retval,$retcard,$retuserid);
1554 return 0;
1557 return checkpw_internal(@_)
1560 sub checkpw_internal {
1561 my ( $dbh, $userid, $password ) = @_;
1563 my $sth =
1564 $dbh->prepare(
1565 "select password,cardnumber,borrowernumber,userid,firstname,surname,branchcode,flags from borrowers where userid=?"
1567 $sth->execute($userid);
1568 if ( $sth->rows ) {
1569 my ( $stored_hash, $cardnumber, $borrowernumber, $userid, $firstname,
1570 $surname, $branchcode, $flags )
1571 = $sth->fetchrow;
1573 if ( checkpw_hash($password, $stored_hash) ) {
1575 C4::Context->set_userenv( "$borrowernumber", $userid, $cardnumber,
1576 $firstname, $surname, $branchcode, $flags );
1577 return 1, $cardnumber, $userid;
1580 $sth =
1581 $dbh->prepare(
1582 "select password,cardnumber,borrowernumber,userid, firstname,surname,branchcode,flags from borrowers where cardnumber=?"
1584 $sth->execute($userid);
1585 if ( $sth->rows ) {
1586 my ( $stored_hash, $cardnumber, $borrowernumber, $userid, $firstname,
1587 $surname, $branchcode, $flags )
1588 = $sth->fetchrow;
1590 if ( checkpw_hash($password, $stored_hash) ) {
1592 C4::Context->set_userenv( $borrowernumber, $userid, $cardnumber,
1593 $firstname, $surname, $branchcode, $flags );
1594 return 1, $cardnumber, $userid;
1597 if ( $userid && $userid eq C4::Context->config('user')
1598 && "$password" eq C4::Context->config('pass') )
1601 # Koha superuser account
1602 # C4::Context->set_userenv(0,0,C4::Context->config('user'),C4::Context->config('user'),C4::Context->config('user'),"",1);
1603 return 2;
1605 if ( $userid && $userid eq 'demo'
1606 && "$password" eq 'demo'
1607 && C4::Context->config('demo') )
1610 # DEMO => the demo user is allowed to do everything (if demo set to 1 in koha.conf
1611 # some features won't be effective : modify systempref, modify MARC structure,
1612 return 2;
1614 return 0;
1617 sub checkpw_hash {
1618 my ( $password, $stored_hash ) = @_;
1620 return if $stored_hash eq '!';
1622 # check what encryption algorithm was implemented: Bcrypt - if the hash starts with '$2' it is Bcrypt else md5
1623 my $hash;
1624 if ( substr($stored_hash,0,2) eq '$2') {
1625 $hash = hash_password($password, $stored_hash);
1626 } else {
1627 $hash = md5_base64($password);
1629 return $hash eq $stored_hash;
1632 =head2 getuserflags
1634 my $authflags = getuserflags($flags, $userid, [$dbh]);
1636 Translates integer flags into permissions strings hash.
1638 C<$flags> is the integer userflags value ( borrowers.userflags )
1639 C<$userid> is the members.userid, used for building subpermissions
1640 C<$authflags> is a hashref of permissions
1642 =cut
1644 sub getuserflags {
1645 my $flags = shift;
1646 my $userid = shift;
1647 my $dbh = @_ ? shift : C4::Context->dbh;
1648 my $userflags;
1650 # I don't want to do this, but if someone logs in as the database
1651 # user, it would be preferable not to spam them to death with
1652 # numeric warnings. So, we make $flags numeric.
1653 no warnings 'numeric';
1654 $flags += 0;
1656 my $sth = $dbh->prepare("SELECT bit, flag, defaulton FROM userflags");
1657 $sth->execute;
1659 while ( my ( $bit, $flag, $defaulton ) = $sth->fetchrow ) {
1660 if ( ( $flags & ( 2**$bit ) ) || $defaulton ) {
1661 $userflags->{$flag} = 1;
1663 else {
1664 $userflags->{$flag} = 0;
1667 # get subpermissions and merge with top-level permissions
1668 my $user_subperms = get_user_subpermissions($userid);
1669 foreach my $module (keys %$user_subperms) {
1670 next if $userflags->{$module} == 1; # user already has permission for everything in this module
1671 $userflags->{$module} = $user_subperms->{$module};
1674 return $userflags;
1677 =head2 get_user_subpermissions
1679 $user_perm_hashref = get_user_subpermissions($userid);
1681 Given the userid (note, not the borrowernumber) of a staff user,
1682 return a hashref of hashrefs of the specific subpermissions
1683 accorded to the user. An example return is
1686 tools => {
1687 export_catalog => 1,
1688 import_patrons => 1,
1692 The top-level hash-key is a module or function code from
1693 userflags.flag, while the second-level key is a code
1694 from permissions.
1696 The results of this function do not give a complete picture
1697 of the functions that a staff user can access; it is also
1698 necessary to check borrowers.flags.
1700 =cut
1702 sub get_user_subpermissions {
1703 my $userid = shift;
1705 my $dbh = C4::Context->dbh;
1706 my $sth = $dbh->prepare("SELECT flag, user_permissions.code
1707 FROM user_permissions
1708 JOIN permissions USING (module_bit, code)
1709 JOIN userflags ON (module_bit = bit)
1710 JOIN borrowers USING (borrowernumber)
1711 WHERE userid = ?");
1712 $sth->execute($userid);
1714 my $user_perms = {};
1715 while (my $perm = $sth->fetchrow_hashref) {
1716 $user_perms->{$perm->{'flag'}}->{$perm->{'code'}} = 1;
1718 return $user_perms;
1721 =head2 get_all_subpermissions
1723 my $perm_hashref = get_all_subpermissions();
1725 Returns a hashref of hashrefs defining all specific
1726 permissions currently defined. The return value
1727 has the same structure as that of C<get_user_subpermissions>,
1728 except that the innermost hash value is the description
1729 of the subpermission.
1731 =cut
1733 sub get_all_subpermissions {
1734 my $dbh = C4::Context->dbh;
1735 my $sth = $dbh->prepare("SELECT flag, code, description
1736 FROM permissions
1737 JOIN userflags ON (module_bit = bit)");
1738 $sth->execute();
1740 my $all_perms = {};
1741 while (my $perm = $sth->fetchrow_hashref) {
1742 $all_perms->{$perm->{'flag'}}->{$perm->{'code'}} = $perm->{'description'};
1744 return $all_perms;
1747 =head2 haspermission
1749 $flags = ($userid, $flagsrequired);
1751 C<$userid> the userid of the member
1752 C<$flags> is a hashref of required flags like C<$borrower-&lt;{authflags}>
1754 Returns member's flags or 0 if a permission is not met.
1756 =cut
1758 sub haspermission {
1759 my ($userid, $flagsrequired) = @_;
1760 my $sth = C4::Context->dbh->prepare("SELECT flags FROM borrowers WHERE userid=?");
1761 $sth->execute($userid);
1762 my $row = $sth->fetchrow();
1763 my $flags = getuserflags($row, $userid);
1764 if ( $userid eq C4::Context->config('user') ) {
1765 # Super User Account from /etc/koha.conf
1766 $flags->{'superlibrarian'} = 1;
1768 elsif ( $userid eq 'demo' && C4::Context->config('demo') ) {
1769 # Demo user that can do "anything" (demo=1 in /etc/koha.conf)
1770 $flags->{'superlibrarian'} = 1;
1773 return $flags if $flags->{superlibrarian};
1775 foreach my $module ( keys %$flagsrequired ) {
1776 my $subperm = $flagsrequired->{$module};
1777 if ($subperm eq '*') {
1778 return 0 unless ( $flags->{$module} == 1 or ref($flags->{$module}) );
1779 } else {
1780 return 0 unless ( $flags->{$module} == 1 or
1781 ( ref($flags->{$module}) and
1782 exists $flags->{$module}->{$subperm} and
1783 $flags->{$module}->{$subperm} == 1
1788 return $flags;
1789 #FIXME - This fcn should return the failed permission so a suitable error msg can be delivered.
1793 sub getborrowernumber {
1794 my ($userid) = @_;
1795 my $userenv = C4::Context->userenv;
1796 if ( defined( $userenv ) && ref( $userenv ) eq 'HASH' && $userenv->{number} ) {
1797 return $userenv->{number};
1799 my $dbh = C4::Context->dbh;
1800 for my $field ( 'userid', 'cardnumber' ) {
1801 my $sth =
1802 $dbh->prepare("select borrowernumber from borrowers where $field=?");
1803 $sth->execute($userid);
1804 if ( $sth->rows ) {
1805 my ($bnumber) = $sth->fetchrow;
1806 return $bnumber;
1809 return 0;
1812 END { } # module clean-up code here (global destructor)
1814 __END__
1816 =head1 SEE ALSO
1818 CGI(3)
1820 C4::Output(3)
1822 Crypt::Eksblowfish::Bcrypt(3)
1824 Digest::MD5(3)
1826 =cut