Bug 10448: can now change framework after duplicating bib record
[koha.git] / C4 / Auth.pm
blob3c0b804a2cf8fac5b1273407dcd7eeb209b4ef01
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 Storable qw(thaw freeze);
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::Branch; # GetBranches
31 use C4::VirtualShelves;
32 use POSIX qw/strftime/;
33 use List::MoreUtils qw/ any /;
35 # use utf8;
36 use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS $debug $ldap $cas $caslogout);
38 BEGIN {
39 sub psgi_env { any { /^psgi\./ } keys %ENV }
40 sub safe_exit {
41 if ( psgi_env ) { die 'psgi:exit' }
42 else { exit }
44 $VERSION = 3.07.00.049; # set version for version checking
46 $debug = $ENV{DEBUG};
47 @ISA = qw(Exporter);
48 @EXPORT = qw(&checkauth &get_template_and_user &haspermission &get_user_subpermissions);
49 @EXPORT_OK = qw(&check_api_auth &get_session &check_cookie_auth &checkpw &get_all_subpermissions &get_user_subpermissions);
50 %EXPORT_TAGS = ( EditPermissions => [qw(get_all_subpermissions get_user_subpermissions)] );
51 $ldap = C4::Context->config('useldapserver') || 0;
52 $cas = C4::Context->preference('casAuthentication');
53 $caslogout = C4::Context->preference('casLogout');
54 require C4::Auth_with_cas; # no import
55 if ($ldap) {
56 require C4::Auth_with_ldap;
57 import C4::Auth_with_ldap qw(checkpw_ldap);
59 if ($cas) {
60 import C4::Auth_with_cas qw(check_api_auth_cas checkpw_cas login_cas logout_cas login_cas_url);
65 =head1 NAME
67 C4::Auth - Authenticates Koha users
69 =head1 SYNOPSIS
71 use CGI;
72 use C4::Auth;
73 use C4::Output;
75 my $query = new CGI;
77 my ($template, $borrowernumber, $cookie)
78 = get_template_and_user(
80 template_name => "opac-main.tmpl",
81 query => $query,
82 type => "opac",
83 authnotrequired => 1,
84 flagsrequired => {borrow => 1, catalogue => '*', tools => 'import_patrons' },
88 output_html_with_http_headers $query, $cookie, $template->output;
90 =head1 DESCRIPTION
92 The main function of this module is to provide
93 authentification. However the get_template_and_user function has
94 been provided so that a users login information is passed along
95 automatically. This gets loaded into the template.
97 =head1 FUNCTIONS
99 =head2 get_template_and_user
101 my ($template, $borrowernumber, $cookie)
102 = get_template_and_user(
104 template_name => "opac-main.tmpl",
105 query => $query,
106 type => "opac",
107 authnotrequired => 1,
108 flagsrequired => {borrow => 1, catalogue => '*', tools => 'import_patrons' },
112 This call passes the C<query>, C<flagsrequired> and C<authnotrequired>
113 to C<&checkauth> (in this module) to perform authentification.
114 See C<&checkauth> for an explanation of these parameters.
116 The C<template_name> is then used to find the correct template for
117 the page. The authenticated users details are loaded onto the
118 template in the HTML::Template LOOP variable C<USER_INFO>. Also the
119 C<sessionID> is passed to the template. This can be used in templates
120 if cookies are disabled. It needs to be put as and input to every
121 authenticated page.
123 More information on the C<gettemplate> sub can be found in the
124 Output.pm module.
126 =cut
128 my $SEARCH_HISTORY_INSERT_SQL =<<EOQ;
129 INSERT INTO search_history(userid, sessionid, query_desc, query_cgi, total, time )
130 VALUES ( ?, ?, ?, ?, ?, FROM_UNIXTIME(?))
133 sub get_template_and_user {
134 my $in = shift;
135 my $template =
136 C4::Templates::gettemplate( $in->{'template_name'}, $in->{'type'}, $in->{'query'}, $in->{'is_plugin'} );
137 my ( $user, $cookie, $sessionID, $flags );
138 if ( $in->{'template_name'} !~m/maintenance/ ) {
139 ( $user, $cookie, $sessionID, $flags ) = checkauth(
140 $in->{'query'},
141 $in->{'authnotrequired'},
142 $in->{'flagsrequired'},
143 $in->{'type'}
147 my $borrowernumber;
148 if ($user) {
149 require C4::Members;
150 # It's possible for $user to be the borrowernumber if they don't have a
151 # userid defined (and are logging in through some other method, such
152 # as SSL certs against an email address)
153 $borrowernumber = getborrowernumber($user) if defined($user);
154 if (!defined($borrowernumber) && defined($user)) {
155 my $borrower = C4::Members::GetMember(borrowernumber => $user);
156 if ($borrower) {
157 $borrowernumber = $user;
158 # A bit of a hack, but I don't know there's a nicer way
159 # to do it.
160 $user = $borrower->{firstname} . ' ' . $borrower->{surname};
164 # user info
165 $template->param( loggedinusername => $user );
166 $template->param( sessionID => $sessionID );
168 my ($total, $pubshelves, $barshelves) = C4::VirtualShelves::GetSomeShelfNames($borrowernumber, 'MASTHEAD');
169 $template->param(
170 pubshelves => $total->{pubtotal},
171 pubshelvesloop => $pubshelves,
172 barshelves => $total->{bartotal},
173 barshelvesloop => $barshelves,
176 my ( $borr ) = C4::Members::GetMemberDetails( $borrowernumber );
177 my @bordat;
178 $bordat[0] = $borr;
179 $template->param( "USER_INFO" => \@bordat );
181 my $all_perms = get_all_subpermissions();
183 my @flagroots = qw(circulate catalogue parameters borrowers permissions reserveforothers borrow
184 editcatalogue updatecharges management tools editauthorities serials reports acquisition);
185 # We are going to use the $flags returned by checkauth
186 # to create the template's parameters that will indicate
187 # which menus the user can access.
188 if ( $flags && $flags->{superlibrarian}==1 ) {
189 $template->param( CAN_user_circulate => 1 );
190 $template->param( CAN_user_catalogue => 1 );
191 $template->param( CAN_user_parameters => 1 );
192 $template->param( CAN_user_borrowers => 1 );
193 $template->param( CAN_user_permissions => 1 );
194 $template->param( CAN_user_reserveforothers => 1 );
195 $template->param( CAN_user_borrow => 1 );
196 $template->param( CAN_user_editcatalogue => 1 );
197 $template->param( CAN_user_updatecharges => 1 );
198 $template->param( CAN_user_acquisition => 1 );
199 $template->param( CAN_user_management => 1 );
200 $template->param( CAN_user_tools => 1 );
201 $template->param( CAN_user_editauthorities => 1 );
202 $template->param( CAN_user_serials => 1 );
203 $template->param( CAN_user_reports => 1 );
204 $template->param( CAN_user_staffaccess => 1 );
205 $template->param( CAN_user_plugins => 1 );
206 $template->param( CAN_user_coursereserves => 1 );
207 foreach my $module (keys %$all_perms) {
208 foreach my $subperm (keys %{ $all_perms->{$module} }) {
209 $template->param( "CAN_user_${module}_${subperm}" => 1 );
214 if ( $flags ) {
215 foreach my $module (keys %$all_perms) {
216 if ( $flags->{$module} == 1) {
217 foreach my $subperm (keys %{ $all_perms->{$module} }) {
218 $template->param( "CAN_user_${module}_${subperm}" => 1 );
220 } elsif ( ref($flags->{$module}) ) {
221 foreach my $subperm (keys %{ $flags->{$module} } ) {
222 $template->param( "CAN_user_${module}_${subperm}" => 1 );
228 if ($flags) {
229 foreach my $module (keys %$flags) {
230 if ( $flags->{$module} == 1 or ref($flags->{$module}) ) {
231 $template->param( "CAN_user_$module" => 1 );
232 if ($module eq "parameters") {
233 $template->param( CAN_user_management => 1 );
238 # Logged-in opac search history
239 # If the requested template is an opac one and opac search history is enabled
240 if ($in->{type} eq 'opac' && C4::Context->preference('EnableOpacSearchHistory')) {
241 my $dbh = C4::Context->dbh;
242 my $query = "SELECT COUNT(*) FROM search_history WHERE userid=?";
243 my $sth = $dbh->prepare($query);
244 $sth->execute($borrowernumber);
246 # If at least one search has already been performed
247 if ($sth->fetchrow_array > 0) {
248 # We show the link in opac
249 $template->param(ShowOpacRecentSearchLink => 1);
252 # And if there's a cookie with searches performed when the user was not logged in,
253 # we add them to the logged-in search history
254 my $searchcookie = $in->{'query'}->cookie('KohaOpacRecentSearches');
255 if ($searchcookie){
256 $searchcookie = uri_unescape($searchcookie);
257 my @recentSearches = @{thaw($searchcookie) || []};
258 if (@recentSearches) {
259 my $sth = $dbh->prepare($SEARCH_HISTORY_INSERT_SQL);
260 $sth->execute( $borrowernumber,
261 $in->{'query'}->cookie("CGISESSID"),
262 $_->{'query_desc'},
263 $_->{'query_cgi'},
264 $_->{'total'},
265 $_->{'time'},
266 ) foreach @recentSearches;
268 # And then, delete the cookie's content
269 my $newsearchcookie = $in->{'query'}->cookie(
270 -name => 'KohaOpacRecentSearches',
271 -value => freeze([]),
272 -HttpOnly => 1,
273 -expires => ''
275 $cookie = [$cookie, $newsearchcookie];
280 else { # if this is an anonymous session, setup to display public lists...
282 $template->param( sessionID => $sessionID );
284 my ($total, $pubshelves) = C4::VirtualShelves::GetSomeShelfNames(undef, 'MASTHEAD');
285 $template->param(
286 pubshelves => $total->{pubtotal},
287 pubshelvesloop => $pubshelves,
290 # Anonymous opac search history
291 # If opac search history is enabled and at least one search has already been performed
292 if (C4::Context->preference('EnableOpacSearchHistory')) {
293 my $searchcookie = $in->{'query'}->cookie('KohaOpacRecentSearches');
294 if ($searchcookie){
295 $searchcookie = uri_unescape($searchcookie);
296 my @recentSearches = @{thaw($searchcookie) || []};
297 # We show the link in opac
298 if (@recentSearches) {
299 $template->param(ShowOpacRecentSearchLink => 1);
304 if(C4::Context->preference('dateformat')){
305 $template->param(dateformat => C4::Context->preference('dateformat'))
308 # these template parameters are set the same regardless of $in->{'type'}
309 $template->param(
310 "BiblioDefaultView".C4::Context->preference("BiblioDefaultView") => 1,
311 EnhancedMessagingPreferences => C4::Context->preference('EnhancedMessagingPreferences'),
312 GoogleJackets => C4::Context->preference("GoogleJackets"),
313 OpenLibraryCovers => C4::Context->preference("OpenLibraryCovers"),
314 KohaAdminEmailAddress => "" . C4::Context->preference("KohaAdminEmailAddress"),
315 LoginBranchcode => (C4::Context->userenv?C4::Context->userenv->{"branch"}:undef),
316 LoginFirstname => (C4::Context->userenv?C4::Context->userenv->{"firstname"}:"Bel"),
317 LoginSurname => C4::Context->userenv?C4::Context->userenv->{"surname"}:"Inconnu",
318 emailaddress => C4::Context->userenv?C4::Context->userenv->{"emailaddress"}:undef,
319 loggedinpersona => C4::Context->userenv?C4::Context->userenv->{"persona"}:undef,
320 TagsEnabled => C4::Context->preference("TagsEnabled"),
321 hide_marc => C4::Context->preference("hide_marc"),
322 item_level_itypes => C4::Context->preference('item-level_itypes'),
323 patronimages => C4::Context->preference("patronimages"),
324 singleBranchMode => C4::Context->preference("singleBranchMode"),
325 XSLTDetailsDisplay => C4::Context->preference("XSLTDetailsDisplay"),
326 XSLTResultsDisplay => C4::Context->preference("XSLTResultsDisplay"),
327 using_https => $in->{'query'}->https() ? 1 : 0,
328 noItemTypeImages => C4::Context->preference("noItemTypeImages"),
329 marcflavour => C4::Context->preference("marcflavour"),
330 persona => C4::Context->preference("persona"),
331 UseCourseReserves => C4::Context->preference("UseCourseReserves"),
333 if ( $in->{'type'} eq "intranet" ) {
334 $template->param(
335 AmazonCoverImages => C4::Context->preference("AmazonCoverImages"),
336 AutoLocation => C4::Context->preference("AutoLocation"),
337 "BiblioDefaultView".C4::Context->preference("IntranetBiblioDefaultView") => 1,
338 CalendarFirstDayOfWeek => (C4::Context->preference("CalendarFirstDayOfWeek") eq "Sunday")?0:1,
339 CircAutocompl => C4::Context->preference("CircAutocompl"),
340 FRBRizeEditions => C4::Context->preference("FRBRizeEditions"),
341 IndependentBranches => C4::Context->preference("IndependentBranches"),
342 IntranetNav => C4::Context->preference("IntranetNav"),
343 IntranetmainUserblock => C4::Context->preference("IntranetmainUserblock"),
344 LibraryName => C4::Context->preference("LibraryName"),
345 LoginBranchname => (C4::Context->userenv?C4::Context->userenv->{"branchname"}:undef),
346 advancedMARCEditor => C4::Context->preference("advancedMARCEditor"),
347 canreservefromotherbranches => C4::Context->preference('canreservefromotherbranches'),
348 intranetcolorstylesheet => C4::Context->preference("intranetcolorstylesheet"),
349 IntranetFavicon => C4::Context->preference("IntranetFavicon"),
350 intranetreadinghistory => C4::Context->preference("intranetreadinghistory"),
351 intranetstylesheet => C4::Context->preference("intranetstylesheet"),
352 IntranetUserCSS => C4::Context->preference("IntranetUserCSS"),
353 intranetuserjs => C4::Context->preference("intranetuserjs"),
354 intranetbookbag => C4::Context->preference("intranetbookbag"),
355 suggestion => C4::Context->preference("suggestion"),
356 virtualshelves => C4::Context->preference("virtualshelves"),
357 StaffSerialIssueDisplayCount => C4::Context->preference("StaffSerialIssueDisplayCount"),
358 EasyAnalyticalRecords => C4::Context->preference('EasyAnalyticalRecords'),
359 LocalCoverImages => C4::Context->preference('LocalCoverImages'),
360 OPACLocalCoverImages => C4::Context->preference('OPACLocalCoverImages'),
361 AllowMultipleCovers => C4::Context->preference('AllowMultipleCovers'),
362 EnableBorrowerFiles => C4::Context->preference('EnableBorrowerFiles'),
363 UseKohaPlugins => C4::Context->preference('UseKohaPlugins'),
366 else {
367 warn "template type should be OPAC, here it is=[" . $in->{'type'} . "]" unless ( $in->{'type'} eq 'opac' );
368 #TODO : replace LibraryName syspref with 'system name', and remove this html processing
369 my $LibraryNameTitle = C4::Context->preference("LibraryName");
370 $LibraryNameTitle =~ s/<(?:\/?)(?:br|p)\s*(?:\/?)>/ /sgi;
371 $LibraryNameTitle =~ s/<(?:[^<>'"]|'(?:[^']*)'|"(?:[^"]*)")*>//sg;
372 # clean up the busc param in the session if the page is not opac-detail
373 if (C4::Context->preference("OpacBrowseResults") && $in->{'template_name'} =~ /opac-(.+)\.(?:tt|tmpl)$/ && $1 !~ /^(?:MARC|ISBD)?detail$/) {
374 my $sessionSearch = get_session($sessionID || $in->{'query'}->cookie("CGISESSID"));
375 $sessionSearch->clear(["busc"]) if ($sessionSearch->param("busc"));
377 # variables passed from CGI: opac_css_override and opac_search_limits.
378 my $opac_search_limit = $ENV{'OPAC_SEARCH_LIMIT'};
379 my $opac_limit_override = $ENV{'OPAC_LIMIT_OVERRIDE'};
380 my $opac_name = '';
381 if (($opac_search_limit && $opac_search_limit =~ /branch:(\w+)/ && $opac_limit_override) || ($in->{'query'}->param('limit') && $in->{'query'}->param('limit') =~ /branch:(\w+)/)){
382 $opac_name = $1; # opac_search_limit is a branch, so we use it.
383 } elsif ( $in->{'query'}->param('multibranchlimit') ) {
384 $opac_name = $in->{'query'}->param('multibranchlimit');
385 } elsif (C4::Context->preference("SearchMyLibraryFirst") && C4::Context->userenv && C4::Context->userenv->{'branch'}) {
386 $opac_name = C4::Context->userenv->{'branch'};
388 $template->param(
389 opaccolorstylesheet => C4::Context->preference("opaccolorstylesheet"),
390 AnonSuggestions => "" . C4::Context->preference("AnonSuggestions"),
391 AuthorisedValueImages => C4::Context->preference("AuthorisedValueImages"),
392 BranchesLoop => GetBranchesLoop($opac_name),
393 BranchCategoriesLoop => GetBranchCategories( undef, undef, 1, $opac_name ),
394 CalendarFirstDayOfWeek => (C4::Context->preference("CalendarFirstDayOfWeek") eq "Sunday")?0:1,
395 LibraryName => "" . C4::Context->preference("LibraryName"),
396 LibraryNameTitle => "" . $LibraryNameTitle,
397 LoginBranchname => C4::Context->userenv?C4::Context->userenv->{"branchname"}:"",
398 OPACAmazonCoverImages => C4::Context->preference("OPACAmazonCoverImages"),
399 OPACFRBRizeEditions => C4::Context->preference("OPACFRBRizeEditions"),
400 OpacHighlightedWords => C4::Context->preference("OpacHighlightedWords"),
401 OPACItemHolds => C4::Context->preference("OPACItemHolds"),
402 OPACShelfBrowser => "". C4::Context->preference("OPACShelfBrowser"),
403 OpacShowRecentComments => C4::Context->preference("OpacShowRecentComments"),
404 OPACURLOpenInNewWindow => "" . C4::Context->preference("OPACURLOpenInNewWindow"),
405 OPACUserCSS => "". C4::Context->preference("OPACUserCSS"),
406 OPACMobileUserCSS => "". C4::Context->preference("OPACMobileUserCSS"),
407 OPACViewOthersSuggestions => "" . C4::Context->preference("OPACViewOthersSuggestions"),
408 OpacAuthorities => C4::Context->preference("OpacAuthorities"),
409 OPACBaseURL => ($in->{'query'}->https() ? "https://" : "http://") . $ENV{'SERVER_NAME'} .
410 ($ENV{'SERVER_PORT'} eq ($in->{'query'}->https() ? "443" : "80") ? '' : ":$ENV{'SERVER_PORT'}"),
411 opac_css_override => $ENV{'OPAC_CSS_OVERRIDE'},
412 opac_search_limit => $opac_search_limit,
413 opac_limit_override => $opac_limit_override,
414 OpacBrowser => C4::Context->preference("OpacBrowser"),
415 OpacCloud => C4::Context->preference("OpacCloud"),
416 OpacKohaUrl => C4::Context->preference("OpacKohaUrl"),
417 OpacMainUserBlock => "" . C4::Context->preference("OpacMainUserBlock"),
418 OpacMainUserBlockMobile => "" . C4::Context->preference("OpacMainUserBlockMobile"),
419 OpacShowFiltersPulldownMobile => C4::Context->preference("OpacShowFiltersPulldownMobile"),
420 OpacShowLibrariesPulldownMobile => C4::Context->preference("OpacShowLibrariesPulldownMobile"),
421 OpacNav => "" . C4::Context->preference("OpacNav"),
422 OpacNavRight => "" . C4::Context->preference("OpacNavRight"),
423 OpacNavBottom => "" . C4::Context->preference("OpacNavBottom"),
424 OpacPasswordChange => C4::Context->preference("OpacPasswordChange"),
425 OPACPatronDetails => C4::Context->preference("OPACPatronDetails"),
426 OPACPrivacy => C4::Context->preference("OPACPrivacy"),
427 OPACFinesTab => C4::Context->preference("OPACFinesTab"),
428 OpacTopissue => C4::Context->preference("OpacTopissue"),
429 RequestOnOpac => C4::Context->preference("RequestOnOpac"),
430 'Version' => C4::Context->preference('Version'),
431 hidelostitems => C4::Context->preference("hidelostitems"),
432 mylibraryfirst => (C4::Context->preference("SearchMyLibraryFirst") && C4::Context->userenv) ? C4::Context->userenv->{'branch'} : '',
433 opaclayoutstylesheet => "" . C4::Context->preference("opaclayoutstylesheet"),
434 opacbookbag => "" . C4::Context->preference("opacbookbag"),
435 opaccredits => "" . C4::Context->preference("opaccredits"),
436 OpacFavicon => C4::Context->preference("OpacFavicon"),
437 opacheader => "" . C4::Context->preference("opacheader"),
438 opaclanguagesdisplay => "" . C4::Context->preference("opaclanguagesdisplay"),
439 opacreadinghistory => C4::Context->preference("opacreadinghistory"),
440 opacsmallimage => "" . C4::Context->preference("opacsmallimage"),
441 opacuserjs => C4::Context->preference("opacuserjs"),
442 opacuserlogin => "" . C4::Context->preference("opacuserlogin"),
443 reviewson => C4::Context->preference("reviewson"),
444 ShowReviewer => C4::Context->preference("ShowReviewer"),
445 ShowReviewerPhoto => C4::Context->preference("ShowReviewerPhoto"),
446 suggestion => "" . C4::Context->preference("suggestion"),
447 virtualshelves => "" . C4::Context->preference("virtualshelves"),
448 OPACSerialIssueDisplayCount => C4::Context->preference("OPACSerialIssueDisplayCount"),
449 OpacAddMastheadLibraryPulldown => C4::Context->preference("OpacAddMastheadLibraryPulldown"),
450 OPACXSLTDetailsDisplay => C4::Context->preference("OPACXSLTDetailsDisplay"),
451 OPACXSLTResultsDisplay => C4::Context->preference("OPACXSLTResultsDisplay"),
452 SyndeticsClientCode => C4::Context->preference("SyndeticsClientCode"),
453 SyndeticsEnabled => C4::Context->preference("SyndeticsEnabled"),
454 SyndeticsCoverImages => C4::Context->preference("SyndeticsCoverImages"),
455 SyndeticsTOC => C4::Context->preference("SyndeticsTOC"),
456 SyndeticsSummary => C4::Context->preference("SyndeticsSummary"),
457 SyndeticsEditions => C4::Context->preference("SyndeticsEditions"),
458 SyndeticsExcerpt => C4::Context->preference("SyndeticsExcerpt"),
459 SyndeticsReviews => C4::Context->preference("SyndeticsReviews"),
460 SyndeticsAuthorNotes => C4::Context->preference("SyndeticsAuthorNotes"),
461 SyndeticsAwards => C4::Context->preference("SyndeticsAwards"),
462 SyndeticsSeries => C4::Context->preference("SyndeticsSeries"),
463 SyndeticsCoverImageSize => C4::Context->preference("SyndeticsCoverImageSize"),
464 OPACLocalCoverImages => C4::Context->preference("OPACLocalCoverImages"),
465 PatronSelfRegistration => C4::Context->preference("PatronSelfRegistration"),
466 PatronSelfRegistrationDefaultCategory => C4::Context->preference("PatronSelfRegistrationDefaultCategory"),
469 $template->param(OpacPublic => '1') if ($user || C4::Context->preference("OpacPublic"));
471 return ( $template, $borrowernumber, $cookie, $flags);
474 =head2 checkauth
476 ($userid, $cookie, $sessionID) = &checkauth($query, $noauth, $flagsrequired, $type);
478 Verifies that the user is authorized to run this script. If
479 the user is authorized, a (userid, cookie, session-id, flags)
480 quadruple is returned. If the user is not authorized but does
481 not have the required privilege (see $flagsrequired below), it
482 displays an error page and exits. Otherwise, it displays the
483 login page and exits.
485 Note that C<&checkauth> will return if and only if the user
486 is authorized, so it should be called early on, before any
487 unfinished operations (e.g., if you've opened a file, then
488 C<&checkauth> won't close it for you).
490 C<$query> is the CGI object for the script calling C<&checkauth>.
492 The C<$noauth> argument is optional. If it is set, then no
493 authorization is required for the script.
495 C<&checkauth> fetches user and session information from C<$query> and
496 ensures that the user is authorized to run scripts that require
497 authorization.
499 The C<$flagsrequired> argument specifies the required privileges
500 the user must have if the username and password are correct.
501 It should be specified as a reference-to-hash; keys in the hash
502 should be the "flags" for the user, as specified in the Members
503 intranet module. Any key specified must correspond to a "flag"
504 in the userflags table. E.g., { circulate => 1 } would specify
505 that the user must have the "circulate" privilege in order to
506 proceed. To make sure that access control is correct, the
507 C<$flagsrequired> parameter must be specified correctly.
509 Koha also has a concept of sub-permissions, also known as
510 granular permissions. This makes the value of each key
511 in the C<flagsrequired> hash take on an additional
512 meaning, i.e.,
516 The user must have access to all subfunctions of the module
517 specified by the hash key.
521 The user must have access to at least one subfunction of the module
522 specified by the hash key.
524 specific permission, e.g., 'export_catalog'
526 The user must have access to the specific subfunction list, which
527 must correspond to a row in the permissions table.
529 The C<$type> argument specifies whether the template should be
530 retrieved from the opac or intranet directory tree. "opac" is
531 assumed if it is not specified; however, if C<$type> is specified,
532 "intranet" is assumed if it is not "opac".
534 If C<$query> does not have a valid session ID associated with it
535 (i.e., the user has not logged in) or if the session has expired,
536 C<&checkauth> presents the user with a login page (from the point of
537 view of the original script, C<&checkauth> does not return). Once the
538 user has authenticated, C<&checkauth> restarts the original script
539 (this time, C<&checkauth> returns).
541 The login page is provided using a HTML::Template, which is set in the
542 systempreferences table or at the top of this file. The variable C<$type>
543 selects which template to use, either the opac or the intranet
544 authentification template.
546 C<&checkauth> returns a user ID, a cookie, and a session ID. The
547 cookie should be sent back to the browser; it verifies that the user
548 has authenticated.
550 =cut
552 sub _version_check {
553 my $type = shift;
554 my $query = shift;
555 my $version;
556 # If Version syspref is unavailable, it means Koha is beeing installed,
557 # and so we must redirect to OPAC maintenance page or to the WebInstaller
558 # also, if OpacMaintenance is ON, OPAC should redirect to maintenance
559 if (C4::Context->preference('OpacMaintenance') && $type eq 'opac') {
560 warn "OPAC Install required, redirecting to maintenance";
561 print $query->redirect("/cgi-bin/koha/maintenance.pl");
562 safe_exit;
564 unless ( $version = C4::Context->preference('Version') ) { # assignment, not comparison
565 if ( $type ne 'opac' ) {
566 warn "Install required, redirecting to Installer";
567 print $query->redirect("/cgi-bin/koha/installer/install.pl");
568 } else {
569 warn "OPAC Install required, redirecting to maintenance";
570 print $query->redirect("/cgi-bin/koha/maintenance.pl");
572 safe_exit;
575 # check that database and koha version are the same
576 # there is no DB version, it's a fresh install,
577 # go to web installer
578 # there is a DB version, compare it to the code version
579 my $kohaversion=C4::Context::KOHAVERSION;
580 # remove the 3 last . to have a Perl number
581 $kohaversion =~ s/(.*\..*)\.(.*)\.(.*)/$1$2$3/;
582 $debug and print STDERR "kohaversion : $kohaversion\n";
583 if ($version < $kohaversion){
584 my $warning = "Database update needed, redirecting to %s. Database is $version and Koha is $kohaversion";
585 if ($type ne 'opac'){
586 warn sprintf($warning, 'Installer');
587 print $query->redirect("/cgi-bin/koha/installer/install.pl?step=3");
588 } else {
589 warn sprintf("OPAC: " . $warning, 'maintenance');
590 print $query->redirect("/cgi-bin/koha/maintenance.pl");
592 safe_exit;
596 sub _session_log {
597 (@_) or return 0;
598 open my $fh, '>>', "/tmp/sessionlog" or warn "ERROR: Cannot append to /tmp/sessionlog";
599 printf $fh join("\n",@_);
600 close $fh;
603 sub _timeout_syspref {
604 my $timeout = C4::Context->preference('timeout') || 600;
605 # value in days, convert in seconds
606 if ($timeout =~ /(\d+)[dD]/) {
607 $timeout = $1 * 86400;
609 return $timeout;
612 sub checkauth {
613 my $query = shift;
614 $debug and warn "Checking Auth";
615 # $authnotrequired will be set for scripts which will run without authentication
616 my $authnotrequired = shift;
617 my $flagsrequired = shift;
618 my $type = shift;
619 my $persona = shift;
620 $type = 'opac' unless $type;
622 my $dbh = C4::Context->dbh;
623 my $timeout = _timeout_syspref();
625 _version_check($type,$query);
626 # state variables
627 my $loggedin = 0;
628 my %info;
629 my ( $userid, $cookie, $sessionID, $flags, $barshelves, $pubshelves );
630 my $logout = $query->param('logout.x');
632 # This parameter is the name of the CAS server we want to authenticate against,
633 # when using authentication against multiple CAS servers, as configured in Auth_cas_servers.yaml
634 my $casparam = $query->param('cas');
636 if ( $userid = $ENV{'REMOTE_USER'} ) {
637 # Using Basic Authentication, no cookies required
638 $cookie = $query->cookie(
639 -name => 'CGISESSID',
640 -value => '',
641 -expires => '',
642 -HttpOnly => 1,
644 $loggedin = 1;
646 elsif ( $persona ){
647 # we dont want to set a session because we are being called by a persona callback
649 elsif ( $sessionID = $query->cookie("CGISESSID") )
650 { # assignment, not comparison
651 my $session = get_session($sessionID);
652 C4::Context->_new_userenv($sessionID);
653 my ($ip, $lasttime, $sessiontype);
654 if ($session){
655 C4::Context::set_userenv(
656 $session->param('number'), $session->param('id'),
657 $session->param('cardnumber'), $session->param('firstname'),
658 $session->param('surname'), $session->param('branch'),
659 $session->param('branchname'), $session->param('flags'),
660 $session->param('emailaddress'), $session->param('branchprinter'),
661 $session->param('persona')
663 C4::Context::set_shelves_userenv('bar',$session->param('barshelves'));
664 C4::Context::set_shelves_userenv('pub',$session->param('pubshelves'));
665 C4::Context::set_shelves_userenv('tot',$session->param('totshelves'));
666 $debug and printf STDERR "AUTH_SESSION: (%s)\t%s %s - %s\n", map {$session->param($_)} qw(cardnumber firstname surname branch) ;
667 $ip = $session->param('ip');
668 $lasttime = $session->param('lasttime');
669 $userid = $session->param('id');
670 $sessiontype = $session->param('sessiontype') || '';
672 if ( ( ($query->param('koha_login_context')) && ($query->param('userid') ne $session->param('id')) )
673 || ( $cas && $query->param('ticket') ) ) {
674 #if a user enters an id ne to the id in the current session, we need to log them in...
675 #first we need to clear the anonymous session...
676 $debug and warn "query id = " . $query->param('userid') . " but session id = " . $session->param('id');
677 $session->flush;
678 $session->delete();
679 C4::Context->_unset_userenv($sessionID);
680 $sessionID = undef;
681 $userid = undef;
683 elsif ($logout) {
684 # voluntary logout the user
685 $session->flush;
686 $session->delete();
687 C4::Context->_unset_userenv($sessionID);
688 #_session_log(sprintf "%20s from %16s logged out at %30s (manually).\n", $userid,$ip,(strftime "%c",localtime));
689 $sessionID = undef;
690 $userid = undef;
692 if ($cas and $caslogout) {
693 logout_cas($query);
696 elsif ( $lasttime < time() - $timeout ) {
697 # timed logout
698 $info{'timed_out'} = 1;
699 $session->delete() if $session;
700 C4::Context->_unset_userenv($sessionID);
701 #_session_log(sprintf "%20s from %16s logged out at %30s (inactivity).\n", $userid,$ip,(strftime "%c",localtime));
702 $userid = undef;
703 $sessionID = undef;
705 elsif ( $ip ne $ENV{'REMOTE_ADDR'} ) {
706 # Different ip than originally logged in from
707 $info{'oldip'} = $ip;
708 $info{'newip'} = $ENV{'REMOTE_ADDR'};
709 $info{'different_ip'} = 1;
710 $session->delete();
711 C4::Context->_unset_userenv($sessionID);
712 #_session_log(sprintf "%20s from %16s logged out at %30s (ip changed to %16s).\n", $userid,$ip,(strftime "%c",localtime), $info{'newip'});
713 $sessionID = undef;
714 $userid = undef;
716 else {
717 $cookie = $query->cookie(
718 -name => 'CGISESSID',
719 -value => $session->id,
720 -HttpOnly => 1
722 $session->param( 'lasttime', time() );
723 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...
724 $flags = haspermission($userid, $flagsrequired);
725 if ($flags) {
726 $loggedin = 1;
727 } else {
728 $info{'nopermission'} = 1;
733 unless ($userid || $sessionID) {
735 #we initiate a session prior to checking for a username to allow for anonymous sessions...
736 my $session = get_session("") or die "Auth ERROR: Cannot get_session()";
737 my $sessionID = $session->id;
738 C4::Context->_new_userenv($sessionID);
739 $cookie = $query->cookie(
740 -name => 'CGISESSID',
741 -value => $session->id,
742 -HttpOnly => 1
744 $userid = $query->param('userid');
745 if ( ( $cas && $query->param('ticket') )
746 || $userid
747 || ( my $pki_field = C4::Context->preference('AllowPKIAuth') ) ne
748 'None' || $persona )
750 my $password = $query->param('password');
752 my ( $return, $cardnumber );
753 if ( $cas && $query->param('ticket') ) {
754 my $retuserid;
755 ( $return, $cardnumber, $retuserid ) =
756 checkpw( $dbh, $userid, $password, $query );
757 $userid = $retuserid;
758 $info{'invalidCasLogin'} = 1 unless ($return);
761 elsif ($persona) {
762 my $value = $persona;
764 # If we're looking up the email, there's a chance that the person
765 # doesn't have a userid. So if there is none, we pass along the
766 # borrower number, and the bits of code that need to know the user
767 # ID will have to be smart enough to handle that.
768 require C4::Members;
769 my @users_info = C4::Members::GetBorrowersWithEmail($value);
770 if (@users_info) {
772 # First the userid, then the borrowernum
773 $value = $users_info[0][1] || $users_info[0][0];
775 else {
776 undef $value;
778 $return = $value ? 1 : 0;
779 $userid = $value;
782 elsif (
783 ( $pki_field eq 'Common Name' && $ENV{'SSL_CLIENT_S_DN_CN'} )
784 || ( $pki_field eq 'emailAddress'
785 && $ENV{'SSL_CLIENT_S_DN_Email'} )
788 my $value;
789 if ( $pki_field eq 'Common Name' ) {
790 $value = $ENV{'SSL_CLIENT_S_DN_CN'};
792 elsif ( $pki_field eq 'emailAddress' ) {
793 $value = $ENV{'SSL_CLIENT_S_DN_Email'};
795 # If we're looking up the email, there's a chance that the person
796 # doesn't have a userid. So if there is none, we pass along the
797 # borrower number, and the bits of code that need to know the user
798 # ID will have to be smart enough to handle that.
799 require C4::Members;
800 my @users_info = C4::Members::GetBorrowersWithEmail($value);
801 if (@users_info) {
803 # First the userid, then the borrowernum
804 $value = $users_info[0][1] || $users_info[0][0];
805 } else {
806 undef $value;
811 $return = $value ? 1 : 0;
812 $userid = $value;
815 else {
816 my $retuserid;
817 ( $return, $cardnumber, $retuserid ) =
818 checkpw( $dbh, $userid, $password, $query );
819 $userid = $retuserid if ( $retuserid ne '' );
821 if ($return) {
822 #_session_log(sprintf "%20s from %16s logged in at %30s.\n", $userid,$ENV{'REMOTE_ADDR'},(strftime '%c', localtime));
823 if ( $flags = haspermission( $userid, $flagsrequired ) ) {
824 $loggedin = 1;
826 else {
827 $info{'nopermission'} = 1;
828 C4::Context->_unset_userenv($sessionID);
830 my ($borrowernumber, $firstname, $surname, $userflags,
831 $branchcode, $branchname, $branchprinter, $emailaddress);
833 if ( $return == 1 ) {
834 my $select = "
835 SELECT borrowernumber, firstname, surname, flags, borrowers.branchcode,
836 branches.branchname as branchname,
837 branches.branchprinter as branchprinter,
838 email
839 FROM borrowers
840 LEFT JOIN branches on borrowers.branchcode=branches.branchcode
842 my $sth = $dbh->prepare("$select where userid=?");
843 $sth->execute($userid);
844 unless ($sth->rows) {
845 $debug and print STDERR "AUTH_1: no rows for userid='$userid'\n";
846 $sth = $dbh->prepare("$select where cardnumber=?");
847 $sth->execute($cardnumber);
849 unless ($sth->rows) {
850 $debug and print STDERR "AUTH_2a: no rows for cardnumber='$cardnumber'\n";
851 $sth->execute($userid);
852 unless ($sth->rows) {
853 $debug and print STDERR "AUTH_2b: no rows for userid='$userid' AS cardnumber\n";
857 if ($sth->rows) {
858 ($borrowernumber, $firstname, $surname, $userflags,
859 $branchcode, $branchname, $branchprinter, $emailaddress) = $sth->fetchrow;
860 $debug and print STDERR "AUTH_3 results: " .
861 "$cardnumber,$borrowernumber,$userid,$firstname,$surname,$userflags,$branchcode,$emailaddress\n";
862 } else {
863 print STDERR "AUTH_3: no results for userid='$userid', cardnumber='$cardnumber'.\n";
866 # launch a sequence to check if we have a ip for the branch, i
867 # if we have one we replace the branchcode of the userenv by the branch bound in the ip.
869 my $ip = $ENV{'REMOTE_ADDR'};
870 # if they specify at login, use that
871 if ($query->param('branch')) {
872 $branchcode = $query->param('branch');
873 $branchname = GetBranchName($branchcode);
875 my $branches = GetBranches();
876 if (C4::Context->boolean_preference('IndependentBranches') && C4::Context->boolean_preference('Autolocation')){
877 # we have to check they are coming from the right ip range
878 my $domain = $branches->{$branchcode}->{'branchip'};
879 if ($ip !~ /^$domain/){
880 $loggedin=0;
881 $info{'wrongip'} = 1;
885 my @branchesloop;
886 foreach my $br ( keys %$branches ) {
887 # now we work with the treatment of ip
888 my $domain = $branches->{$br}->{'branchip'};
889 if ( $domain && $ip =~ /^$domain/ ) {
890 $branchcode = $branches->{$br}->{'branchcode'};
892 # new op dev : add the branchprinter and branchname in the cookie
893 $branchprinter = $branches->{$br}->{'branchprinter'};
894 $branchname = $branches->{$br}->{'branchname'};
897 $session->param('number',$borrowernumber);
898 $session->param('id',$userid);
899 $session->param('cardnumber',$cardnumber);
900 $session->param('firstname',$firstname);
901 $session->param('surname',$surname);
902 $session->param('branch',$branchcode);
903 $session->param('branchname',$branchname);
904 $session->param('flags',$userflags);
905 $session->param('emailaddress',$emailaddress);
906 $session->param('ip',$session->remote_addr());
907 $session->param('lasttime',time());
908 $debug and printf STDERR "AUTH_4: (%s)\t%s %s - %s\n", map {$session->param($_)} qw(cardnumber firstname surname branch) ;
910 elsif ( $return == 2 ) {
911 #We suppose the user is the superlibrarian
912 $borrowernumber = 0;
913 $session->param('number',0);
914 $session->param('id',C4::Context->config('user'));
915 $session->param('cardnumber',C4::Context->config('user'));
916 $session->param('firstname',C4::Context->config('user'));
917 $session->param('surname',C4::Context->config('user'));
918 $session->param('branch','NO_LIBRARY_SET');
919 $session->param('branchname','NO_LIBRARY_SET');
920 $session->param('flags',1);
921 $session->param('emailaddress', C4::Context->preference('KohaAdminEmailAddress'));
922 $session->param('ip',$session->remote_addr());
923 $session->param('lasttime',time());
925 if ($persona){
926 $session->param('persona',1);
928 C4::Context::set_userenv(
929 $session->param('number'), $session->param('id'),
930 $session->param('cardnumber'), $session->param('firstname'),
931 $session->param('surname'), $session->param('branch'),
932 $session->param('branchname'), $session->param('flags'),
933 $session->param('emailaddress'), $session->param('branchprinter'),
934 $session->param('persona')
938 else {
939 if ($userid) {
940 $info{'invalid_username_or_password'} = 1;
941 C4::Context->_unset_userenv($sessionID);
944 } # END if ( $userid = $query->param('userid') )
945 elsif ($type eq "opac") {
946 # if we are here this is an anonymous session; add public lists to it and a few other items...
947 # anonymous sessions are created only for the OPAC
948 $debug and warn "Initiating an anonymous session...";
950 # setting a couple of other session vars...
951 $session->param('ip',$session->remote_addr());
952 $session->param('lasttime',time());
953 $session->param('sessiontype','anon');
955 } # END unless ($userid)
957 # finished authentification, now respond
958 if ( $loggedin || $authnotrequired )
960 # successful login
961 unless ($cookie) {
962 $cookie = $query->cookie(
963 -name => 'CGISESSID',
964 -value => '',
965 -HttpOnly => 1
968 return ( $userid, $cookie, $sessionID, $flags );
973 # AUTH rejected, show the login/password template, after checking the DB.
977 # get the inputs from the incoming query
978 my @inputs = ();
979 foreach my $name ( param $query) {
980 (next) if ( $name eq 'userid' || $name eq 'password' || $name eq 'ticket' );
981 my $value = $query->param($name);
982 push @inputs, { name => $name, value => $value };
985 my $template_name = ( $type eq 'opac' ) ? 'opac-auth.tmpl' : 'auth.tmpl';
986 my $template = C4::Templates::gettemplate($template_name, $type, $query );
987 $template->param(
988 branchloop => GetBranchesLoop(),
989 opaccolorstylesheet => C4::Context->preference("opaccolorstylesheet"),
990 opaclayoutstylesheet => C4::Context->preference("opaclayoutstylesheet"),
991 login => 1,
992 INPUTS => \@inputs,
993 casAuthentication => C4::Context->preference("casAuthentication"),
994 suggestion => C4::Context->preference("suggestion"),
995 virtualshelves => C4::Context->preference("virtualshelves"),
996 LibraryName => C4::Context->preference("LibraryName"),
997 opacuserlogin => C4::Context->preference("opacuserlogin"),
998 OpacNav => C4::Context->preference("OpacNav"),
999 OpacNavRight => C4::Context->preference("OpacNavRight"),
1000 OpacNavBottom => C4::Context->preference("OpacNavBottom"),
1001 opaccredits => C4::Context->preference("opaccredits"),
1002 OpacFavicon => C4::Context->preference("OpacFavicon"),
1003 opacreadinghistory => C4::Context->preference("opacreadinghistory"),
1004 opacsmallimage => C4::Context->preference("opacsmallimage"),
1005 opaclanguagesdisplay => C4::Context->preference("opaclanguagesdisplay"),
1006 opacuserjs => C4::Context->preference("opacuserjs"),
1007 opacbookbag => "" . C4::Context->preference("opacbookbag"),
1008 OpacCloud => C4::Context->preference("OpacCloud"),
1009 OpacTopissue => C4::Context->preference("OpacTopissue"),
1010 OpacAuthorities => C4::Context->preference("OpacAuthorities"),
1011 OpacBrowser => C4::Context->preference("OpacBrowser"),
1012 opacheader => C4::Context->preference("opacheader"),
1013 TagsEnabled => C4::Context->preference("TagsEnabled"),
1014 OPACUserCSS => C4::Context->preference("OPACUserCSS"),
1015 intranetcolorstylesheet => C4::Context->preference("intranetcolorstylesheet"),
1016 intranetstylesheet => C4::Context->preference("intranetstylesheet"),
1017 intranetbookbag => C4::Context->preference("intranetbookbag"),
1018 IntranetNav => C4::Context->preference("IntranetNav"),
1019 IntranetFavicon => C4::Context->preference("IntranetFavicon"),
1020 intranetuserjs => C4::Context->preference("intranetuserjs"),
1021 IndependentBranches=> C4::Context->preference("IndependentBranches"),
1022 AutoLocation => C4::Context->preference("AutoLocation"),
1023 wrongip => $info{'wrongip'},
1024 PatronSelfRegistration => C4::Context->preference("PatronSelfRegistration"),
1025 PatronSelfRegistrationDefaultCategory => C4::Context->preference("PatronSelfRegistrationDefaultCategory"),
1026 persona => C4::Context->preference("Persona"),
1027 opac_css_override => $ENV{'OPAC_CSS_OVERRIDE'},
1030 $template->param( OpacPublic => C4::Context->preference("OpacPublic"));
1031 $template->param( loginprompt => 1 ) unless $info{'nopermission'};
1033 if ($cas) {
1035 # Is authentication against multiple CAS servers enabled?
1036 if (C4::Auth_with_cas::multipleAuth && !$casparam) {
1037 my $casservers = C4::Auth_with_cas::getMultipleAuth();
1038 my @tmplservers;
1039 foreach my $key (keys %$casservers) {
1040 push @tmplservers, {name => $key, value => login_cas_url($query, $key) . "?cas=$key" };
1042 $template->param(
1043 casServersLoop => \@tmplservers
1045 } else {
1046 $template->param(
1047 casServerUrl => login_cas_url($query),
1051 $template->param(
1052 invalidCasLogin => $info{'invalidCasLogin'}
1056 my $self_url = $query->url( -absolute => 1 );
1057 $template->param(
1058 url => $self_url,
1059 LibraryName => C4::Context->preference("LibraryName"),
1061 $template->param( %info );
1062 # $cookie = $query->cookie(CGISESSID => $session->id
1063 # );
1064 print $query->header(
1065 -type => 'text/html',
1066 -charset => 'utf-8',
1067 -cookie => $cookie
1069 $template->output;
1070 safe_exit;
1073 =head2 check_api_auth
1075 ($status, $cookie, $sessionId) = check_api_auth($query, $userflags);
1077 Given a CGI query containing the parameters 'userid' and 'password' and/or a session
1078 cookie, determine if the user has the privileges specified by C<$userflags>.
1080 C<check_api_auth> is is meant for authenticating users of web services, and
1081 consequently will always return and will not attempt to redirect the user
1082 agent.
1084 If a valid session cookie is already present, check_api_auth will return a status
1085 of "ok", the cookie, and the Koha session ID.
1087 If no session cookie is present, check_api_auth will check the 'userid' and 'password
1088 parameters and create a session cookie and Koha session if the supplied credentials
1089 are OK.
1091 Possible return values in C<$status> are:
1093 =over
1095 =item "ok" -- user authenticated; C<$cookie> and C<$sessionid> have valid values.
1097 =item "failed" -- credentials are not correct; C<$cookie> and C<$sessionid> are undef
1099 =item "maintenance" -- DB is in maintenance mode; no login possible at the moment
1101 =item "expired -- session cookie has expired; API user should resubmit userid and password
1103 =back
1105 =cut
1107 sub check_api_auth {
1108 my $query = shift;
1109 my $flagsrequired = shift;
1111 my $dbh = C4::Context->dbh;
1112 my $timeout = _timeout_syspref();
1114 unless (C4::Context->preference('Version')) {
1115 # database has not been installed yet
1116 return ("maintenance", undef, undef);
1118 my $kohaversion=C4::Context::KOHAVERSION;
1119 $kohaversion =~ s/(.*\..*)\.(.*)\.(.*)/$1$2$3/;
1120 if (C4::Context->preference('Version') < $kohaversion) {
1121 # database in need of version update; assume that
1122 # no API should be called while databsae is in
1123 # this condition.
1124 return ("maintenance", undef, undef);
1127 # FIXME -- most of what follows is a copy-and-paste
1128 # of code from checkauth. There is an obvious need
1129 # for refactoring to separate the various parts of
1130 # the authentication code, but as of 2007-11-19 this
1131 # is deferred so as to not introduce bugs into the
1132 # regular authentication code for Koha 3.0.
1134 # see if we have a valid session cookie already
1135 # however, if a userid parameter is present (i.e., from
1136 # a form submission, assume that any current cookie
1137 # is to be ignored
1138 my $sessionID = undef;
1139 unless ($query->param('userid')) {
1140 $sessionID = $query->cookie("CGISESSID");
1142 if ($sessionID && not ($cas && $query->param('PT')) ) {
1143 my $session = get_session($sessionID);
1144 C4::Context->_new_userenv($sessionID);
1145 if ($session) {
1146 C4::Context::set_userenv(
1147 $session->param('number'), $session->param('id'),
1148 $session->param('cardnumber'), $session->param('firstname'),
1149 $session->param('surname'), $session->param('branch'),
1150 $session->param('branchname'), $session->param('flags'),
1151 $session->param('emailaddress'), $session->param('branchprinter')
1154 my $ip = $session->param('ip');
1155 my $lasttime = $session->param('lasttime');
1156 my $userid = $session->param('id');
1157 if ( $lasttime < time() - $timeout ) {
1158 # time out
1159 $session->delete();
1160 C4::Context->_unset_userenv($sessionID);
1161 $userid = undef;
1162 $sessionID = undef;
1163 return ("expired", undef, undef);
1164 } elsif ( $ip ne $ENV{'REMOTE_ADDR'} ) {
1165 # IP address changed
1166 $session->delete();
1167 C4::Context->_unset_userenv($sessionID);
1168 $userid = undef;
1169 $sessionID = undef;
1170 return ("expired", undef, undef);
1171 } else {
1172 my $cookie = $query->cookie(
1173 -name => 'CGISESSID',
1174 -value => $session->id,
1175 -HttpOnly => 1,
1177 $session->param('lasttime',time());
1178 my $flags = haspermission($userid, $flagsrequired);
1179 if ($flags) {
1180 return ("ok", $cookie, $sessionID);
1181 } else {
1182 $session->delete();
1183 C4::Context->_unset_userenv($sessionID);
1184 $userid = undef;
1185 $sessionID = undef;
1186 return ("failed", undef, undef);
1189 } else {
1190 return ("expired", undef, undef);
1192 } else {
1193 # new login
1194 my $userid = $query->param('userid');
1195 my $password = $query->param('password');
1196 my ($return, $cardnumber);
1198 # Proxy CAS auth
1199 if ($cas && $query->param('PT')) {
1200 my $retuserid;
1201 $debug and print STDERR "## check_api_auth - checking CAS\n";
1202 # In case of a CAS authentication, we use the ticket instead of the password
1203 my $PT = $query->param('PT');
1204 ($return,$cardnumber,$userid) = check_api_auth_cas($dbh, $PT, $query); # EXTERNAL AUTH
1205 } else {
1206 # User / password auth
1207 unless ($userid and $password) {
1208 # caller did something wrong, fail the authenticateion
1209 return ("failed", undef, undef);
1211 ( $return, $cardnumber ) = checkpw( $dbh, $userid, $password, $query );
1214 if ($return and haspermission( $userid, $flagsrequired)) {
1215 my $session = get_session("");
1216 return ("failed", undef, undef) unless $session;
1218 my $sessionID = $session->id;
1219 C4::Context->_new_userenv($sessionID);
1220 my $cookie = $query->cookie(
1221 -name => 'CGISESSID',
1222 -value => $sessionID,
1223 -HttpOnly => 1,
1225 if ( $return == 1 ) {
1226 my (
1227 $borrowernumber, $firstname, $surname,
1228 $userflags, $branchcode, $branchname,
1229 $branchprinter, $emailaddress
1231 my $sth =
1232 $dbh->prepare(
1233 "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=?"
1235 $sth->execute($userid);
1237 $borrowernumber, $firstname, $surname,
1238 $userflags, $branchcode, $branchname,
1239 $branchprinter, $emailaddress
1240 ) = $sth->fetchrow if ( $sth->rows );
1242 unless ($sth->rows ) {
1243 my $sth = $dbh->prepare(
1244 "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=?"
1246 $sth->execute($cardnumber);
1248 $borrowernumber, $firstname, $surname,
1249 $userflags, $branchcode, $branchname,
1250 $branchprinter, $emailaddress
1251 ) = $sth->fetchrow if ( $sth->rows );
1253 unless ( $sth->rows ) {
1254 $sth->execute($userid);
1256 $borrowernumber, $firstname, $surname, $userflags,
1257 $branchcode, $branchname, $branchprinter, $emailaddress
1258 ) = $sth->fetchrow if ( $sth->rows );
1262 my $ip = $ENV{'REMOTE_ADDR'};
1263 # if they specify at login, use that
1264 if ($query->param('branch')) {
1265 $branchcode = $query->param('branch');
1266 $branchname = GetBranchName($branchcode);
1268 my $branches = GetBranches();
1269 my @branchesloop;
1270 foreach my $br ( keys %$branches ) {
1271 # now we work with the treatment of ip
1272 my $domain = $branches->{$br}->{'branchip'};
1273 if ( $domain && $ip =~ /^$domain/ ) {
1274 $branchcode = $branches->{$br}->{'branchcode'};
1276 # new op dev : add the branchprinter and branchname in the cookie
1277 $branchprinter = $branches->{$br}->{'branchprinter'};
1278 $branchname = $branches->{$br}->{'branchname'};
1281 $session->param('number',$borrowernumber);
1282 $session->param('id',$userid);
1283 $session->param('cardnumber',$cardnumber);
1284 $session->param('firstname',$firstname);
1285 $session->param('surname',$surname);
1286 $session->param('branch',$branchcode);
1287 $session->param('branchname',$branchname);
1288 $session->param('flags',$userflags);
1289 $session->param('emailaddress',$emailaddress);
1290 $session->param('ip',$session->remote_addr());
1291 $session->param('lasttime',time());
1292 } elsif ( $return == 2 ) {
1293 #We suppose the user is the superlibrarian
1294 $session->param('number',0);
1295 $session->param('id',C4::Context->config('user'));
1296 $session->param('cardnumber',C4::Context->config('user'));
1297 $session->param('firstname',C4::Context->config('user'));
1298 $session->param('surname',C4::Context->config('user'));
1299 $session->param('branch','NO_LIBRARY_SET');
1300 $session->param('branchname','NO_LIBRARY_SET');
1301 $session->param('flags',1);
1302 $session->param('emailaddress', C4::Context->preference('KohaAdminEmailAddress'));
1303 $session->param('ip',$session->remote_addr());
1304 $session->param('lasttime',time());
1306 C4::Context::set_userenv(
1307 $session->param('number'), $session->param('id'),
1308 $session->param('cardnumber'), $session->param('firstname'),
1309 $session->param('surname'), $session->param('branch'),
1310 $session->param('branchname'), $session->param('flags'),
1311 $session->param('emailaddress'), $session->param('branchprinter')
1313 return ("ok", $cookie, $sessionID);
1314 } else {
1315 return ("failed", undef, undef);
1320 =head2 check_cookie_auth
1322 ($status, $sessionId) = check_api_auth($cookie, $userflags);
1324 Given a CGISESSID cookie set during a previous login to Koha, determine
1325 if the user has the privileges specified by C<$userflags>.
1327 C<check_cookie_auth> is meant for authenticating special services
1328 such as tools/upload-file.pl that are invoked by other pages that
1329 have been authenticated in the usual way.
1331 Possible return values in C<$status> are:
1333 =over
1335 =item "ok" -- user authenticated; C<$sessionID> have valid values.
1337 =item "failed" -- credentials are not correct; C<$sessionid> are undef
1339 =item "maintenance" -- DB is in maintenance mode; no login possible at the moment
1341 =item "expired -- session cookie has expired; API user should resubmit userid and password
1343 =back
1345 =cut
1347 sub check_cookie_auth {
1348 my $cookie = shift;
1349 my $flagsrequired = shift;
1351 my $dbh = C4::Context->dbh;
1352 my $timeout = _timeout_syspref();
1354 unless (C4::Context->preference('Version')) {
1355 # database has not been installed yet
1356 return ("maintenance", undef);
1358 my $kohaversion=C4::Context::KOHAVERSION;
1359 $kohaversion =~ s/(.*\..*)\.(.*)\.(.*)/$1$2$3/;
1360 if (C4::Context->preference('Version') < $kohaversion) {
1361 # database in need of version update; assume that
1362 # no API should be called while databsae is in
1363 # this condition.
1364 return ("maintenance", undef);
1367 # FIXME -- most of what follows is a copy-and-paste
1368 # of code from checkauth. There is an obvious need
1369 # for refactoring to separate the various parts of
1370 # the authentication code, but as of 2007-11-23 this
1371 # is deferred so as to not introduce bugs into the
1372 # regular authentication code for Koha 3.0.
1374 # see if we have a valid session cookie already
1375 # however, if a userid parameter is present (i.e., from
1376 # a form submission, assume that any current cookie
1377 # is to be ignored
1378 unless (defined $cookie and $cookie) {
1379 return ("failed", undef);
1381 my $sessionID = $cookie;
1382 my $session = get_session($sessionID);
1383 C4::Context->_new_userenv($sessionID);
1384 if ($session) {
1385 C4::Context::set_userenv(
1386 $session->param('number'), $session->param('id'),
1387 $session->param('cardnumber'), $session->param('firstname'),
1388 $session->param('surname'), $session->param('branch'),
1389 $session->param('branchname'), $session->param('flags'),
1390 $session->param('emailaddress'), $session->param('branchprinter')
1393 my $ip = $session->param('ip');
1394 my $lasttime = $session->param('lasttime');
1395 my $userid = $session->param('id');
1396 if ( $lasttime < time() - $timeout ) {
1397 # time out
1398 $session->delete();
1399 C4::Context->_unset_userenv($sessionID);
1400 $userid = undef;
1401 $sessionID = undef;
1402 return ("expired", undef);
1403 } elsif ( $ip ne $ENV{'REMOTE_ADDR'} ) {
1404 # IP address changed
1405 $session->delete();
1406 C4::Context->_unset_userenv($sessionID);
1407 $userid = undef;
1408 $sessionID = undef;
1409 return ("expired", undef);
1410 } else {
1411 $session->param('lasttime',time());
1412 my $flags = haspermission($userid, $flagsrequired);
1413 if ($flags) {
1414 return ("ok", $sessionID);
1415 } else {
1416 $session->delete();
1417 C4::Context->_unset_userenv($sessionID);
1418 $userid = undef;
1419 $sessionID = undef;
1420 return ("failed", undef);
1423 } else {
1424 return ("expired", undef);
1428 =head2 get_session
1430 use CGI::Session;
1431 my $session = get_session($sessionID);
1433 Given a session ID, retrieve the CGI::Session object used to store
1434 the session's state. The session object can be used to store
1435 data that needs to be accessed by different scripts during a
1436 user's session.
1438 If the C<$sessionID> parameter is an empty string, a new session
1439 will be created.
1441 =cut
1443 sub get_session {
1444 my $sessionID = shift;
1445 my $storage_method = C4::Context->preference('SessionStorage');
1446 my $dbh = C4::Context->dbh;
1447 my $session;
1448 if ($storage_method eq 'mysql'){
1449 $session = new CGI::Session("driver:MySQL;serializer:yaml;id:md5", $sessionID, {Handle=>$dbh});
1451 elsif ($storage_method eq 'Pg') {
1452 $session = new CGI::Session("driver:PostgreSQL;serializer:yaml;id:md5", $sessionID, {Handle=>$dbh});
1454 elsif ($storage_method eq 'memcached' && C4::Context->ismemcached){
1455 $session = new CGI::Session("driver:memcached;serializer:yaml;id:md5", $sessionID, { Memcached => C4::Context->memcached } );
1457 else {
1458 # catch all defaults to tmp should work on all systems
1459 $session = new CGI::Session("driver:File;serializer:yaml;id:md5", $sessionID, {Directory=>'/tmp'});
1461 return $session;
1464 sub checkpw {
1466 my ( $dbh, $userid, $password, $query ) = @_;
1467 if ($ldap) {
1468 $debug and print STDERR "## checkpw - checking LDAP\n";
1469 my ($retval,$retcard,$retuserid) = checkpw_ldap(@_); # EXTERNAL AUTH
1470 ($retval) and return ($retval,$retcard,$retuserid);
1473 if ($cas && $query && $query->param('ticket')) {
1474 $debug and print STDERR "## checkpw - checking CAS\n";
1475 # In case of a CAS authentication, we use the ticket instead of the password
1476 my $ticket = $query->param('ticket');
1477 my ($retval,$retcard,$retuserid) = checkpw_cas($dbh, $ticket, $query); # EXTERNAL AUTH
1478 ($retval) and return ($retval,$retcard,$retuserid);
1479 return 0;
1482 # INTERNAL AUTH
1483 my $sth =
1484 $dbh->prepare(
1485 "select password,cardnumber,borrowernumber,userid,firstname,surname,branchcode,flags from borrowers where userid=?"
1487 $sth->execute($userid);
1488 if ( $sth->rows ) {
1489 my ( $md5password, $cardnumber, $borrowernumber, $userid, $firstname,
1490 $surname, $branchcode, $flags )
1491 = $sth->fetchrow;
1492 if ( md5_base64($password) eq $md5password and $md5password ne "!") {
1494 C4::Context->set_userenv( "$borrowernumber", $userid, $cardnumber,
1495 $firstname, $surname, $branchcode, $flags );
1496 return 1, $cardnumber, $userid;
1499 $sth =
1500 $dbh->prepare(
1501 "select password,cardnumber,borrowernumber,userid, firstname,surname,branchcode,flags from borrowers where cardnumber=?"
1503 $sth->execute($userid);
1504 if ( $sth->rows ) {
1505 my ( $md5password, $cardnumber, $borrowernumber, $userid, $firstname,
1506 $surname, $branchcode, $flags )
1507 = $sth->fetchrow;
1508 if ( md5_base64($password) eq $md5password ) {
1510 C4::Context->set_userenv( $borrowernumber, $userid, $cardnumber,
1511 $firstname, $surname, $branchcode, $flags );
1512 return 1, $cardnumber, $userid;
1515 if ( $userid && $userid eq C4::Context->config('user')
1516 && "$password" eq C4::Context->config('pass') )
1519 # Koha superuser account
1520 # C4::Context->set_userenv(0,0,C4::Context->config('user'),C4::Context->config('user'),C4::Context->config('user'),"",1);
1521 return 2;
1523 if ( $userid && $userid eq 'demo'
1524 && "$password" eq 'demo'
1525 && C4::Context->config('demo') )
1528 # DEMO => the demo user is allowed to do everything (if demo set to 1 in koha.conf
1529 # some features won't be effective : modify systempref, modify MARC structure,
1530 return 2;
1532 return 0;
1535 =head2 getuserflags
1537 my $authflags = getuserflags($flags, $userid, [$dbh]);
1539 Translates integer flags into permissions strings hash.
1541 C<$flags> is the integer userflags value ( borrowers.userflags )
1542 C<$userid> is the members.userid, used for building subpermissions
1543 C<$authflags> is a hashref of permissions
1545 =cut
1547 sub getuserflags {
1548 my $flags = shift;
1549 my $userid = shift;
1550 my $dbh = @_ ? shift : C4::Context->dbh;
1551 my $userflags;
1553 # I don't want to do this, but if someone logs in as the database
1554 # user, it would be preferable not to spam them to death with
1555 # numeric warnings. So, we make $flags numeric.
1556 no warnings 'numeric';
1557 $flags += 0;
1559 my $sth = $dbh->prepare("SELECT bit, flag, defaulton FROM userflags");
1560 $sth->execute;
1562 while ( my ( $bit, $flag, $defaulton ) = $sth->fetchrow ) {
1563 if ( ( $flags & ( 2**$bit ) ) || $defaulton ) {
1564 $userflags->{$flag} = 1;
1566 else {
1567 $userflags->{$flag} = 0;
1571 # get subpermissions and merge with top-level permissions
1572 my $user_subperms = get_user_subpermissions($userid);
1573 foreach my $module (keys %$user_subperms) {
1574 next if $userflags->{$module} == 1; # user already has permission for everything in this module
1575 $userflags->{$module} = $user_subperms->{$module};
1578 return $userflags;
1581 =head2 get_user_subpermissions
1583 $user_perm_hashref = get_user_subpermissions($userid);
1585 Given the userid (note, not the borrowernumber) of a staff user,
1586 return a hashref of hashrefs of the specific subpermissions
1587 accorded to the user. An example return is
1590 tools => {
1591 export_catalog => 1,
1592 import_patrons => 1,
1596 The top-level hash-key is a module or function code from
1597 userflags.flag, while the second-level key is a code
1598 from permissions.
1600 The results of this function do not give a complete picture
1601 of the functions that a staff user can access; it is also
1602 necessary to check borrowers.flags.
1604 =cut
1606 sub get_user_subpermissions {
1607 my $userid = shift;
1609 my $dbh = C4::Context->dbh;
1610 my $sth = $dbh->prepare("SELECT flag, user_permissions.code
1611 FROM user_permissions
1612 JOIN permissions USING (module_bit, code)
1613 JOIN userflags ON (module_bit = bit)
1614 JOIN borrowers USING (borrowernumber)
1615 WHERE userid = ?");
1616 $sth->execute($userid);
1618 my $user_perms = {};
1619 while (my $perm = $sth->fetchrow_hashref) {
1620 $user_perms->{$perm->{'flag'}}->{$perm->{'code'}} = 1;
1622 return $user_perms;
1625 =head2 get_all_subpermissions
1627 my $perm_hashref = get_all_subpermissions();
1629 Returns a hashref of hashrefs defining all specific
1630 permissions currently defined. The return value
1631 has the same structure as that of C<get_user_subpermissions>,
1632 except that the innermost hash value is the description
1633 of the subpermission.
1635 =cut
1637 sub get_all_subpermissions {
1638 my $dbh = C4::Context->dbh;
1639 my $sth = $dbh->prepare("SELECT flag, code, description
1640 FROM permissions
1641 JOIN userflags ON (module_bit = bit)");
1642 $sth->execute();
1644 my $all_perms = {};
1645 while (my $perm = $sth->fetchrow_hashref) {
1646 $all_perms->{$perm->{'flag'}}->{$perm->{'code'}} = $perm->{'description'};
1648 return $all_perms;
1651 =head2 haspermission
1653 $flags = ($userid, $flagsrequired);
1655 C<$userid> the userid of the member
1656 C<$flags> is a hashref of required flags like C<$borrower-&lt;{authflags}>
1658 Returns member's flags or 0 if a permission is not met.
1660 =cut
1662 sub haspermission {
1663 my ($userid, $flagsrequired) = @_;
1664 my $sth = C4::Context->dbh->prepare("SELECT flags FROM borrowers WHERE userid=?");
1665 $sth->execute($userid);
1666 my $flags = getuserflags($sth->fetchrow(), $userid);
1667 if ( $userid eq C4::Context->config('user') ) {
1668 # Super User Account from /etc/koha.conf
1669 $flags->{'superlibrarian'} = 1;
1671 elsif ( $userid eq 'demo' && C4::Context->config('demo') ) {
1672 # Demo user that can do "anything" (demo=1 in /etc/koha.conf)
1673 $flags->{'superlibrarian'} = 1;
1676 return $flags if $flags->{superlibrarian};
1678 foreach my $module ( keys %$flagsrequired ) {
1679 my $subperm = $flagsrequired->{$module};
1680 if ($subperm eq '*') {
1681 return 0 unless ( $flags->{$module} == 1 or ref($flags->{$module}) );
1682 } else {
1683 return 0 unless ( $flags->{$module} == 1 or
1684 ( ref($flags->{$module}) and
1685 exists $flags->{$module}->{$subperm} and
1686 $flags->{$module}->{$subperm} == 1
1691 return $flags;
1692 #FIXME - This fcn should return the failed permission so a suitable error msg can be delivered.
1696 sub getborrowernumber {
1697 my ($userid) = @_;
1698 my $userenv = C4::Context->userenv;
1699 if ( defined( $userenv ) && ref( $userenv ) eq 'HASH' && $userenv->{number} ) {
1700 return $userenv->{number};
1702 my $dbh = C4::Context->dbh;
1703 for my $field ( 'userid', 'cardnumber' ) {
1704 my $sth =
1705 $dbh->prepare("select borrowernumber from borrowers where $field=?");
1706 $sth->execute($userid);
1707 if ( $sth->rows ) {
1708 my ($bnumber) = $sth->fetchrow;
1709 return $bnumber;
1712 return 0;
1716 END { } # module clean-up code here (global destructor)
1718 __END__
1720 =head1 SEE ALSO
1722 CGI(3)
1724 C4::Output(3)
1726 Digest::MD5(3)
1728 =cut