3 # Copyright 2000-2002 Katipo Communications
5 # This file is part of Koha.
7 # Koha is free software; you can redistribute it and/or modify it under the
8 # terms of the GNU General Public License as published by the Free Software
9 # Foundation; either version 2 of the License, or (at your option) any later
12 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
13 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14 # A PARTICULAR PURPOSE. See the GNU General Public License for more details.
16 # You should have received a copy of the GNU General Public License along
17 # with Koha; if not, write to the Free Software Foundation, Inc.,
18 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
22 use Digest
::MD5
qw(md5_base64);
23 use JSON qw
/encode_json/;
29 use C4
::Templates
; # to get the template
31 use C4
::Branch
; # GetBranches
32 use C4
::Search
::History
;
33 use C4
::VirtualShelves
;
34 use Koha
::AuthUtils
qw(hash_password);
35 use POSIX qw
/strftime/;
36 use List
::MoreUtils qw
/ any /;
39 use vars
qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS $debug $ldap $cas $caslogout);
42 sub psgi_env { any { /^psgi\./ } keys %ENV }
44 if ( psgi_env ) { die 'psgi:exit' }
47 $VERSION = 3.07.00.049; # set version for version checking
51 @EXPORT = qw(&checkauth &get_template_and_user &haspermission &get_user_subpermissions);
52 @EXPORT_OK = qw(&check_api_auth &get_session &check_cookie_auth &checkpw &checkpw_internal &checkpw_hash
53 &get_all_subpermissions &get_user_subpermissions
55 %EXPORT_TAGS = ( EditPermissions
=> [qw(get_all_subpermissions get_user_subpermissions)] );
56 $ldap = C4
::Context
->config('useldapserver') || 0;
57 $cas = C4
::Context
->preference('casAuthentication');
58 $caslogout = C4
::Context
->preference('casLogout');
59 require C4
::Auth_with_cas
; # no import
61 require C4
::Auth_with_ldap
;
62 import C4
::Auth_with_ldap
qw(checkpw_ldap);
65 import C4
::Auth_with_cas
qw(check_api_auth_cas checkpw_cas login_cas logout_cas login_cas_url);
72 C4::Auth - Authenticates Koha users
82 my ($template, $borrowernumber, $cookie)
83 = get_template_and_user(
85 template_name => "opac-main.tmpl",
89 flagsrequired => {borrow => 1, catalogue => '*', tools => 'import_patrons' },
93 output_html_with_http_headers $query, $cookie, $template->output;
97 The main function of this module is to provide
98 authentification. However the get_template_and_user function has
99 been provided so that a users login information is passed along
100 automatically. This gets loaded into the template.
104 =head2 get_template_and_user
106 my ($template, $borrowernumber, $cookie)
107 = get_template_and_user(
109 template_name => "opac-main.tmpl",
112 authnotrequired => 0,
113 flagsrequired => {borrow => 1, catalogue => '*', tools => 'import_patrons' },
117 This call passes the C<query>, C<flagsrequired> and C<authnotrequired>
118 to C<&checkauth> (in this module) to perform authentification.
119 See C<&checkauth> for an explanation of these parameters.
121 The C<template_name> is then used to find the correct template for
122 the page. The authenticated users details are loaded onto the
123 template in the HTML::Template LOOP variable C<USER_INFO>. Also the
124 C<sessionID> is passed to the template. This can be used in templates
125 if cookies are disabled. It needs to be put as and input to every
128 More information on the C<gettemplate> sub can be found in the
133 sub get_template_and_user
{
136 my ( $user, $cookie, $sessionID, $flags );
138 C4
::Context
->interface($in->{type
});
140 $in->{'authnotrequired'} ||= 0;
141 my $template = C4
::Templates
::gettemplate
(
142 $in->{'template_name'},
148 if ( $in->{'template_name'} !~m/maintenance/ ) {
149 ( $user, $cookie, $sessionID, $flags ) = checkauth
(
151 $in->{'authnotrequired'},
152 $in->{'flagsrequired'},
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);
167 $borrowernumber = $user;
168 # A bit of a hack, but I don't know there's a nicer way
170 $user = $borrower->{firstname
} . ' ' . $borrower->{surname
};
175 $template->param( loggedinusername
=> $user );
176 $template->param( sessionID
=> $sessionID );
178 my ($total, $pubshelves, $barshelves) = C4
::VirtualShelves
::GetSomeShelfNames
($borrowernumber, 'MASTHEAD');
180 pubshelves
=> $total->{pubtotal
},
181 pubshelvesloop
=> $pubshelves,
182 barshelves
=> $total->{bartotal
},
183 barshelvesloop
=> $barshelves,
186 my ( $borr ) = C4
::Members
::GetMemberDetails
( $borrowernumber );
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 );
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 );
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;
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"),
277 $_->{type
} || 'biblio',
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');
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;
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" ) {
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"),
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)$/ ) {
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'};
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'}");
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
497 my $language = C4
::Languages
::getlanguage
($in->{'query'});
498 my $languagecookie = C4
::Templates
::getlanguagecookie
($in->{'query'},$language);
499 if ( ref $cookie eq 'ARRAY' ) {
500 push @
{ $cookie }, $languagecookie;
502 $cookie = [$cookie, $languagecookie];
506 return ( $template, $borrowernumber, $cookie, $flags);
511 ($userid, $cookie, $sessionID) = &checkauth($query, $noauth, $flagsrequired, $type);
513 Verifies that the user is authorized to run this script. If
514 the user is authorized, a (userid, cookie, session-id, flags)
515 quadruple is returned. If the user is not authorized but does
516 not have the required privilege (see $flagsrequired below), it
517 displays an error page and exits. Otherwise, it displays the
518 login page and exits.
520 Note that C<&checkauth> will return if and only if the user
521 is authorized, so it should be called early on, before any
522 unfinished operations (e.g., if you've opened a file, then
523 C<&checkauth> won't close it for you).
525 C<$query> is the CGI object for the script calling C<&checkauth>.
527 The C<$noauth> argument is optional. If it is set, then no
528 authorization is required for the script.
530 C<&checkauth> fetches user and session information from C<$query> and
531 ensures that the user is authorized to run scripts that require
534 The C<$flagsrequired> argument specifies the required privileges
535 the user must have if the username and password are correct.
536 It should be specified as a reference-to-hash; keys in the hash
537 should be the "flags" for the user, as specified in the Members
538 intranet module. Any key specified must correspond to a "flag"
539 in the userflags table. E.g., { circulate => 1 } would specify
540 that the user must have the "circulate" privilege in order to
541 proceed. To make sure that access control is correct, the
542 C<$flagsrequired> parameter must be specified correctly.
544 Koha also has a concept of sub-permissions, also known as
545 granular permissions. This makes the value of each key
546 in the C<flagsrequired> hash take on an additional
551 The user must have access to all subfunctions of the module
552 specified by the hash key.
556 The user must have access to at least one subfunction of the module
557 specified by the hash key.
559 specific permission, e.g., 'export_catalog'
561 The user must have access to the specific subfunction list, which
562 must correspond to a row in the permissions table.
564 The C<$type> argument specifies whether the template should be
565 retrieved from the opac or intranet directory tree. "opac" is
566 assumed if it is not specified; however, if C<$type> is specified,
567 "intranet" is assumed if it is not "opac".
569 If C<$query> does not have a valid session ID associated with it
570 (i.e., the user has not logged in) or if the session has expired,
571 C<&checkauth> presents the user with a login page (from the point of
572 view of the original script, C<&checkauth> does not return). Once the
573 user has authenticated, C<&checkauth> restarts the original script
574 (this time, C<&checkauth> returns).
576 The login page is provided using a HTML::Template, which is set in the
577 systempreferences table or at the top of this file. The variable C<$type>
578 selects which template to use, either the opac or the intranet
579 authentification template.
581 C<&checkauth> returns a user ID, a cookie, and a session ID. The
582 cookie should be sent back to the browser; it verifies that the user
591 # If Version syspref is unavailable, it means Koha is beeing installed,
592 # and so we must redirect to OPAC maintenance page or to the WebInstaller
593 # also, if OpacMaintenance is ON, OPAC should redirect to maintenance
594 if (C4
::Context
->preference('OpacMaintenance') && $type eq 'opac') {
595 warn "OPAC Install required, redirecting to maintenance";
596 print $query->redirect("/cgi-bin/koha/maintenance.pl");
599 unless ( $version = C4
::Context
->preference('Version') ) { # assignment, not comparison
600 if ( $type ne 'opac' ) {
601 warn "Install required, redirecting to Installer";
602 print $query->redirect("/cgi-bin/koha/installer/install.pl");
604 warn "OPAC Install required, redirecting to maintenance";
605 print $query->redirect("/cgi-bin/koha/maintenance.pl");
610 # check that database and koha version are the same
611 # there is no DB version, it's a fresh install,
612 # go to web installer
613 # there is a DB version, compare it to the code version
614 my $kohaversion=C4
::Context
::KOHAVERSION
;
615 # remove the 3 last . to have a Perl number
616 $kohaversion =~ s/(.*\..*)\.(.*)\.(.*)/$1$2$3/;
617 $debug and print STDERR
"kohaversion : $kohaversion\n";
618 if ($version < $kohaversion){
619 my $warning = "Database update needed, redirecting to %s. Database is $version and Koha is $kohaversion";
620 if ($type ne 'opac'){
621 warn sprintf($warning, 'Installer');
622 print $query->redirect("/cgi-bin/koha/installer/install.pl?step=3");
624 warn sprintf("OPAC: " . $warning, 'maintenance');
625 print $query->redirect("/cgi-bin/koha/maintenance.pl");
633 open my $fh, '>>', "/tmp/sessionlog" or warn "ERROR: Cannot append to /tmp/sessionlog";
634 printf $fh join("\n",@_);
638 sub _timeout_syspref
{
639 my $timeout = C4
::Context
->preference('timeout') || 600;
640 # value in days, convert in seconds
641 if ($timeout =~ /(\d+)[dD]/) {
642 $timeout = $1 * 86400;
649 $debug and warn "Checking Auth";
650 # $authnotrequired will be set for scripts which will run without authentication
651 my $authnotrequired = shift;
652 my $flagsrequired = shift;
655 $type = 'opac' unless $type;
657 my $dbh = C4
::Context
->dbh;
658 my $timeout = _timeout_syspref
();
660 _version_check
($type,$query);
664 my ( $userid, $cookie, $sessionID, $flags, $barshelves, $pubshelves );
665 my $logout = $query->param('logout.x');
667 my $anon_search_history;
669 # This parameter is the name of the CAS server we want to authenticate against,
670 # when using authentication against multiple CAS servers, as configured in Auth_cas_servers.yaml
671 my $casparam = $query->param('cas');
672 my $q_userid = $query->param('userid') // '';
674 if ( $userid = $ENV{'REMOTE_USER'} ) {
675 # Using Basic Authentication, no cookies required
676 $cookie = $query->cookie(
677 -name
=> 'CGISESSID',
685 # we dont want to set a session because we are being called by a persona callback
687 elsif ( $sessionID = $query->cookie("CGISESSID") )
688 { # assignment, not comparison
689 my $session = get_session
($sessionID);
690 C4
::Context
->_new_userenv($sessionID);
691 my ($ip, $lasttime, $sessiontype);
694 $s_userid = $session->param('id') // '';
695 C4
::Context
::set_userenv
(
696 $session->param('number'), $s_userid,
697 $session->param('cardnumber'), $session->param('firstname'),
698 $session->param('surname'), $session->param('branch'),
699 $session->param('branchname'), $session->param('flags'),
700 $session->param('emailaddress'), $session->param('branchprinter'),
701 $session->param('persona')
703 C4
::Context
::set_shelves_userenv
('bar',$session->param('barshelves'));
704 C4
::Context
::set_shelves_userenv
('pub',$session->param('pubshelves'));
705 C4
::Context
::set_shelves_userenv
('tot',$session->param('totshelves'));
706 $debug and printf STDERR
"AUTH_SESSION: (%s)\t%s %s - %s\n", map {$session->param($_)} qw(cardnumber firstname surname branch) ;
707 $ip = $session->param('ip');
708 $lasttime = $session->param('lasttime');
710 $sessiontype = $session->param('sessiontype') || '';
712 if ( ( $query->param('koha_login_context') && ($q_userid ne $s_userid) )
713 || ( $cas && $query->param('ticket') ) ) {
714 #if a user enters an id ne to the id in the current session, we need to log them in...
715 #first we need to clear the anonymous session...
716 $debug and warn "query id = $q_userid but session id = $s_userid";
717 $anon_search_history = $session->param('search_history');
720 C4
::Context
->_unset_userenv($sessionID);
725 # voluntary logout the user
728 C4
::Context
->_unset_userenv($sessionID);
729 #_session_log(sprintf "%20s from %16s logged out at %30s (manually).\n", $userid,$ip,(strftime "%c",localtime));
733 if ($cas and $caslogout) {
737 elsif ( !$lasttime || ($lasttime < time() - $timeout) ) {
739 $info{'timed_out'} = 1;
744 C4
::Context
->_unset_userenv($sessionID);
745 #_session_log(sprintf "%20s from %16s logged out at %30s (inactivity).\n", $userid,$ip,(strftime "%c",localtime));
749 elsif ( $ip ne $ENV{'REMOTE_ADDR'} ) {
750 # Different ip than originally logged in from
751 $info{'oldip'} = $ip;
752 $info{'newip'} = $ENV{'REMOTE_ADDR'};
753 $info{'different_ip'} = 1;
756 C4
::Context
->_unset_userenv($sessionID);
757 #_session_log(sprintf "%20s from %16s logged out at %30s (ip changed to %16s).\n", $userid,$ip,(strftime "%c",localtime), $info{'newip'});
762 $cookie = $query->cookie(
763 -name
=> 'CGISESSID',
764 -value
=> $session->id,
767 $session->param( 'lasttime', time() );
768 unless ( $sessiontype && $sessiontype eq 'anon' ) { #if this is an anonymous session, we want to update the session, but not behave as if they are logged in...
769 $flags = haspermission
($userid, $flagsrequired);
773 $info{'nopermission'} = 1;
778 unless ($userid || $sessionID) {
780 #we initiate a session prior to checking for a username to allow for anonymous sessions...
781 my $session = get_session
("") or die "Auth ERROR: Cannot get_session()";
783 # Save anonymous search history in new session so it can be retrieved
784 # by get_template_and_user to store it in user's search history after
785 # a successful login.
786 if ($anon_search_history) {
787 $session->param('search_history', $anon_search_history);
790 my $sessionID = $session->id;
791 C4
::Context
->_new_userenv($sessionID);
792 $cookie = $query->cookie(
793 -name
=> 'CGISESSID',
794 -value
=> $session->id,
798 my $pki_field = C4
::Context
->preference('AllowPKIAuth');
799 if (! defined($pki_field) ) {
800 print STDERR
"ERROR: Missing system preference AllowPKIAuth.\n";
803 if ( ( $cas && $query->param('ticket') )
805 || $pki_field ne 'None'
808 my $password = $query->param('password');
810 my ( $return, $cardnumber );
811 if ( $cas && $query->param('ticket') ) {
813 ( $return, $cardnumber, $retuserid ) =
814 checkpw
( $dbh, $userid, $password, $query );
815 $userid = $retuserid;
816 $info{'invalidCasLogin'} = 1 unless ($return);
820 my $value = $persona;
822 # If we're looking up the email, there's a chance that the person
823 # doesn't have a userid. So if there is none, we pass along the
824 # borrower number, and the bits of code that need to know the user
825 # ID will have to be smart enough to handle that.
827 my @users_info = C4
::Members
::GetBorrowersWithEmail
($value);
830 # First the userid, then the borrowernum
831 $value = $users_info[0][1] || $users_info[0][0];
836 $return = $value ?
1 : 0;
841 ( $pki_field eq 'Common Name' && $ENV{'SSL_CLIENT_S_DN_CN'} )
842 || ( $pki_field eq 'emailAddress'
843 && $ENV{'SSL_CLIENT_S_DN_Email'} )
847 if ( $pki_field eq 'Common Name' ) {
848 $value = $ENV{'SSL_CLIENT_S_DN_CN'};
850 elsif ( $pki_field eq 'emailAddress' ) {
851 $value = $ENV{'SSL_CLIENT_S_DN_Email'};
853 # If we're looking up the email, there's a chance that the person
854 # doesn't have a userid. So if there is none, we pass along the
855 # borrower number, and the bits of code that need to know the user
856 # ID will have to be smart enough to handle that.
858 my @users_info = C4
::Members
::GetBorrowersWithEmail
($value);
861 # First the userid, then the borrowernum
862 $value = $users_info[0][1] || $users_info[0][0];
869 $return = $value ?
1 : 0;
875 ( $return, $cardnumber, $retuserid ) =
876 checkpw
( $dbh, $userid, $password, $query );
877 $userid = $retuserid if ( $retuserid );
880 #_session_log(sprintf "%20s from %16s logged in at %30s.\n", $userid,$ENV{'REMOTE_ADDR'},(strftime '%c', localtime));
881 if ( $flags = haspermission
( $userid, $flagsrequired ) ) {
885 $info{'nopermission'} = 1;
886 C4
::Context
->_unset_userenv($sessionID);
888 my ($borrowernumber, $firstname, $surname, $userflags,
889 $branchcode, $branchname, $branchprinter, $emailaddress);
891 if ( $return == 1 ) {
893 SELECT borrowernumber, firstname, surname, flags, borrowers.branchcode,
894 branches.branchname as branchname,
895 branches.branchprinter as branchprinter,
898 LEFT JOIN branches on borrowers.branchcode=branches.branchcode
900 my $sth = $dbh->prepare("$select where userid=?");
901 $sth->execute($userid);
902 unless ($sth->rows) {
903 $debug and print STDERR
"AUTH_1: no rows for userid='$userid'\n";
904 $sth = $dbh->prepare("$select where cardnumber=?");
905 $sth->execute($cardnumber);
907 unless ($sth->rows) {
908 $debug and print STDERR
"AUTH_2a: no rows for cardnumber='$cardnumber'\n";
909 $sth->execute($userid);
910 unless ($sth->rows) {
911 $debug and print STDERR
"AUTH_2b: no rows for userid='$userid' AS cardnumber\n";
916 ($borrowernumber, $firstname, $surname, $userflags,
917 $branchcode, $branchname, $branchprinter, $emailaddress) = $sth->fetchrow;
918 $debug and print STDERR
"AUTH_3 results: " .
919 "$cardnumber,$borrowernumber,$userid,$firstname,$surname,$userflags,$branchcode,$emailaddress\n";
921 print STDERR
"AUTH_3: no results for userid='$userid', cardnumber='$cardnumber'.\n";
924 # launch a sequence to check if we have a ip for the branch, i
925 # if we have one we replace the branchcode of the userenv by the branch bound in the ip.
927 my $ip = $ENV{'REMOTE_ADDR'};
928 # if they specify at login, use that
929 if ($query->param('branch')) {
930 $branchcode = $query->param('branch');
931 $branchname = GetBranchName
($branchcode);
933 my $branches = GetBranches
();
934 if (C4
::Context
->boolean_preference('IndependentBranches') && C4
::Context
->boolean_preference('Autolocation')){
935 # we have to check they are coming from the right ip range
936 my $domain = $branches->{$branchcode}->{'branchip'};
937 if ($ip !~ /^$domain/){
939 $info{'wrongip'} = 1;
944 foreach my $br ( keys %$branches ) {
945 # now we work with the treatment of ip
946 my $domain = $branches->{$br}->{'branchip'};
947 if ( $domain && $ip =~ /^$domain/ ) {
948 $branchcode = $branches->{$br}->{'branchcode'};
950 # new op dev : add the branchprinter and branchname in the cookie
951 $branchprinter = $branches->{$br}->{'branchprinter'};
952 $branchname = $branches->{$br}->{'branchname'};
955 $session->param('number',$borrowernumber);
956 $session->param('id',$userid);
957 $session->param('cardnumber',$cardnumber);
958 $session->param('firstname',$firstname);
959 $session->param('surname',$surname);
960 $session->param('branch',$branchcode);
961 $session->param('branchname',$branchname);
962 $session->param('flags',$userflags);
963 $session->param('emailaddress',$emailaddress);
964 $session->param('ip',$session->remote_addr());
965 $session->param('lasttime',time());
966 $debug and printf STDERR
"AUTH_4: (%s)\t%s %s - %s\n", map {$session->param($_)} qw(cardnumber firstname surname branch) ;
968 elsif ( $return == 2 ) {
969 #We suppose the user is the superlibrarian
971 $session->param('number',0);
972 $session->param('id',C4
::Context
->config('user'));
973 $session->param('cardnumber',C4
::Context
->config('user'));
974 $session->param('firstname',C4
::Context
->config('user'));
975 $session->param('surname',C4
::Context
->config('user'));
976 $session->param('branch','NO_LIBRARY_SET');
977 $session->param('branchname','NO_LIBRARY_SET');
978 $session->param('flags',1);
979 $session->param('emailaddress', C4
::Context
->preference('KohaAdminEmailAddress'));
980 $session->param('ip',$session->remote_addr());
981 $session->param('lasttime',time());
984 $session->param('persona',1);
986 C4
::Context
::set_userenv
(
987 $session->param('number'), $session->param('id'),
988 $session->param('cardnumber'), $session->param('firstname'),
989 $session->param('surname'), $session->param('branch'),
990 $session->param('branchname'), $session->param('flags'),
991 $session->param('emailaddress'), $session->param('branchprinter'),
992 $session->param('persona')
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 )
1022 $cookie = $query->cookie(
1023 -name
=> 'CGISESSID',
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
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 );
1052 branchloop
=> GetBranchesLoop
(),
1053 opaccolorstylesheet
=> C4
::Context
->preference("opaccolorstylesheet"),
1054 opaclayoutstylesheet
=> C4
::Context
->preference("opaclayoutstylesheet"),
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');
1101 pubshelves
=> $total->{pubtotal
},
1102 pubshelvesloop
=> $pubshelves,
1108 # Is authentication against multiple CAS servers enabled?
1109 if (C4
::Auth_with_cas
::multipleAuth
&& !$casparam) {
1110 my $casservers = C4
::Auth_with_cas
::getMultipleAuth
();
1112 foreach my $key (keys %$casservers) {
1113 push @tmplservers, {name
=> $key, value
=> login_cas_url
($query, $key) . "?cas=$key" };
1116 casServersLoop
=> \
@tmplservers
1120 casServerUrl
=> login_cas_url
($query),
1125 invalidCasLogin
=> $info{'invalidCasLogin'}
1129 my $self_url = $query->url( -absolute
=> 1 );
1132 LibraryName
=> C4
::Context
->preference("LibraryName"),
1134 $template->param( %info );
1135 # $cookie = $query->cookie(CGISESSID => $session->id
1137 print $query->header(
1138 -type
=> 'text/html',
1139 -charset
=> 'utf-8',
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
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
1164 Possible return values in C<$status> are:
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
1180 sub check_api_auth
{
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
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
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);
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 ) {
1234 C4
::Context
->_unset_userenv($sessionID);
1237 return ("expired", undef, undef);
1238 } elsif ( $ip ne $ENV{'REMOTE_ADDR'} ) {
1239 # IP address changed
1242 C4
::Context
->_unset_userenv($sessionID);
1245 return ("expired", undef, undef);
1247 my $cookie = $query->cookie(
1248 -name
=> 'CGISESSID',
1249 -value
=> $session->id,
1252 $session->param('lasttime',time());
1253 my $flags = haspermission
($userid, $flagsrequired);
1255 return ("ok", $cookie, $sessionID);
1259 C4
::Context
->_unset_userenv($sessionID);
1262 return ("failed", undef, undef);
1266 return ("expired", undef, undef);
1270 my $userid = $query->param('userid');
1271 my $password = $query->param('password');
1272 my ($return, $cardnumber);
1275 if ($cas && $query->param('PT')) {
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
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,
1301 if ( $return == 1 ) {
1303 $borrowernumber, $firstname, $surname,
1304 $userflags, $branchcode, $branchname,
1305 $branchprinter, $emailaddress
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
();
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);
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:
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
1423 sub check_cookie_auth
{
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
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
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);
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 ) {
1476 C4
::Context
->_unset_userenv($sessionID);
1479 return ("expired", undef);
1480 } elsif ( $ip ne $ENV{'REMOTE_ADDR'} ) {
1481 # IP address changed
1484 C4
::Context
->_unset_userenv($sessionID);
1487 return ("expired", undef);
1489 $session->param('lasttime',time());
1490 my $flags = haspermission
($userid, $flagsrequired);
1492 return ("ok", $sessionID);
1496 C4
::Context
->_unset_userenv($sessionID);
1499 return ("failed", undef);
1503 return ("expired", undef);
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
1517 If the C<$sessionID> parameter is an empty string, a new session
1523 my $sessionID = shift;
1524 my $storage_method = C4
::Context
->preference('SessionStorage');
1525 my $dbh = C4
::Context
->dbh;
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 } );
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'});
1544 my ( $dbh, $userid, $password, $query ) = @_;
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);
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);
1581 "select password,cardnumber,borrowernumber,userid,firstname,surname,branchcode,flags from borrowers where userid=?"
1583 $sth->execute($userid);
1585 my ( $stored_hash, $cardnumber, $borrowernumber, $userid, $firstname,
1586 $surname, $branchcode, $flags )
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;
1598 "select password,cardnumber,borrowernumber,userid, firstname,surname,branchcode,flags from borrowers where cardnumber=?"
1600 $sth->execute($userid);
1602 my ( $stored_hash, $cardnumber, $borrowernumber, $userid, $firstname,
1603 $surname, $branchcode, $flags )
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,
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
1632 if ( substr($stored_hash,0,2) eq '$2') {
1633 $hash = hash_password
($password, $stored_hash);
1635 $hash = md5_base64
($password);
1637 return $hash eq $stored_hash;
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
1655 my $dbh = @_ ?
shift : C4
::Context
->dbh;
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';
1664 my $sth = $dbh->prepare("SELECT bit, flag, defaulton FROM userflags");
1667 while ( my ( $bit, $flag, $defaulton ) = $sth->fetchrow ) {
1668 if ( ( $flags & ( 2**$bit ) ) || $defaulton ) {
1669 $userflags->{$flag} = 1;
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};
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
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
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.
1710 sub get_user_subpermissions
{
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)
1720 $sth->execute($userid);
1722 my $user_perms = {};
1723 while (my $perm = $sth->fetchrow_hashref) {
1724 $user_perms->{$perm->{'flag'}}->{$perm->{'code'}} = 1;
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.
1741 sub get_all_subpermissions
{
1742 my $dbh = C4
::Context
->dbh;
1743 my $sth = $dbh->prepare("SELECT flag, code, description
1745 JOIN userflags ON (module_bit = bit)");
1749 while (my $perm = $sth->fetchrow_hashref) {
1750 $all_perms->{$perm->{'flag'}}->{$perm->{'code'}} = $perm->{'description'};
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-<{authflags}>
1762 Returns member's flags or 0 if a permission is not met.
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}) );
1788 return 0 unless ( $flags->{$module} == 1 or
1789 ( ref($flags->{$module}) and
1790 exists $flags->{$module}->{$subperm} and
1791 $flags->{$module}->{$subperm} == 1
1797 #FIXME - This fcn should return the failed permission so a suitable error msg can be delivered.
1801 sub getborrowernumber
{
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' ) {
1810 $dbh->prepare("select borrowernumber from borrowers where $field=?");
1811 $sth->execute($userid);
1813 my ($bnumber) = $sth->fetchrow;
1820 END { } # module clean-up code here (global destructor)
1830 Crypt::Eksblowfish::Bcrypt(3)