Bug 20640: (follow-up) Degrade gracefully on error
[koha.git] / C4 / Auth.pm
1 package C4::Auth;
2
3 # Copyright 2000-2002 Katipo Communications
4 #
5 # This file is part of Koha.
6 #
7 # Koha is free software; you can redistribute it and/or modify it
8 # under the terms of the GNU General Public License as published by
9 # the Free Software Foundation; either version 3 of the License, or
10 # (at your option) any later version.
11 #
12 # Koha is distributed in the hope that it will be useful, but
13 # WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU General Public License for more details.
16 #
17 # You should have received a copy of the GNU General Public License
18 # along with Koha; if not, see <http://www.gnu.org/licenses>.
19
20 use strict;
21 use warnings;
22 use Digest::MD5 qw(md5_base64);
23 use JSON qw/encode_json/;
24 use URI::Escape;
25 use CGI::Session;
26
27 require Exporter;
28 use C4::Context;
29 use C4::Templates;    # to get the template
30 use C4::Languages;
31 use C4::Search::History;
32 use Koha;
33 use Koha::Caches;
34 use Koha::AuthUtils qw(get_script_name hash_password);
35 use Koha::Checkouts;
36 use Koha::DateUtils qw(dt_from_string);
37 use Koha::Library::Groups;
38 use Koha::Libraries;
39 use Koha::Patrons;
40 use Koha::Patron::Consents;
41 use POSIX qw/strftime/;
42 use List::MoreUtils qw/ any /;
43 use Encode qw( encode is_utf8);
44 use C4::Auth_with_shibboleth;
45
46 # use utf8;
47 use vars qw(@ISA @EXPORT @EXPORT_OK %EXPORT_TAGS $debug $ldap $cas $caslogout);
48
49 BEGIN {
50     sub psgi_env { any { /^psgi\./ } keys %ENV }
51
52     sub safe_exit {
53         if   (psgi_env) { die 'psgi:exit' }
54         else            { exit }
55     }
56
57     $debug     = $ENV{DEBUG};
58     @ISA       = qw(Exporter);
59     @EXPORT    = qw(&checkauth &get_template_and_user &haspermission &get_user_subpermissions);
60     @EXPORT_OK = qw(&check_api_auth &get_session &check_cookie_auth &checkpw &checkpw_internal &checkpw_hash
61       &get_all_subpermissions &get_user_subpermissions track_login_daily
62     );
63     %EXPORT_TAGS = ( EditPermissions => [qw(get_all_subpermissions get_user_subpermissions)] );
64     $ldap      = C4::Context->config('useldapserver') || 0;
65     $cas       = C4::Context->preference('casAuthentication');
66     $caslogout = C4::Context->preference('casLogout');
67     require C4::Auth_with_cas;    # no import
68
69     if ($ldap) {
70         require C4::Auth_with_ldap;
71         import C4::Auth_with_ldap qw(checkpw_ldap);
72     }
73     if ($cas) {
74         import C4::Auth_with_cas qw(check_api_auth_cas checkpw_cas login_cas logout_cas login_cas_url logout_if_required);
75     }
76
77 }
78
79 =head1 NAME
80
81 C4::Auth - Authenticates Koha users
82
83 =head1 SYNOPSIS
84
85   use CGI qw ( -utf8 );
86   use C4::Auth;
87   use C4::Output;
88
89   my $query = new CGI;
90
91   my ($template, $borrowernumber, $cookie)
92     = get_template_and_user(
93         {
94             template_name   => "opac-main.tt",
95             query           => $query,
96       type            => "opac",
97       authnotrequired => 0,
98       flagsrequired   => { catalogue => '*', tools => 'import_patrons' },
99   }
100     );
101
102   output_html_with_http_headers $query, $cookie, $template->output;
103
104 =head1 DESCRIPTION
105
106 The main function of this module is to provide
107 authentification. However the get_template_and_user function has
108 been provided so that a users login information is passed along
109 automatically. This gets loaded into the template.
110
111 =head1 FUNCTIONS
112
113 =head2 get_template_and_user
114
115  my ($template, $borrowernumber, $cookie)
116      = get_template_and_user(
117        {
118          template_name   => "opac-main.tt",
119          query           => $query,
120          type            => "opac",
121          authnotrequired => 0,
122          flagsrequired   => { catalogue => '*', tools => 'import_patrons' },
123        }
124      );
125
126 This call passes the C<query>, C<flagsrequired> and C<authnotrequired>
127 to C<&checkauth> (in this module) to perform authentification.
128 See C<&checkauth> for an explanation of these parameters.
129
130 The C<template_name> is then used to find the correct template for
131 the page. The authenticated users details are loaded onto the
132 template in the logged_in_user variable (which is a Koha::Patron object). Also the
133 C<sessionID> is passed to the template. This can be used in templates
134 if cookies are disabled. It needs to be put as and input to every
135 authenticated page.
136
137 More information on the C<gettemplate> sub can be found in the
138 Output.pm module.
139
140 =cut
141
142 sub get_template_and_user {
143
144     my $in = shift;
145     my ( $user, $cookie, $sessionID, $flags );
146
147     # Get shibboleth login attribute
148     my $shib = C4::Context->config('useshibboleth') && shib_ok();
149     my $shib_login = $shib ? get_login_shib() : undef;
150
151     C4::Context->interface( $in->{type} );
152
153     $in->{'authnotrequired'} ||= 0;
154
155     # the following call includes a bad template check; might croak
156     my $template = C4::Templates::gettemplate(
157         $in->{'template_name'},
158         $in->{'type'},
159         $in->{'query'},
160     );
161
162     if ( $in->{'template_name'} !~ m/maintenance/ ) {
163         ( $user, $cookie, $sessionID, $flags ) = checkauth(
164             $in->{'query'},
165             $in->{'authnotrequired'},
166             $in->{'flagsrequired'},
167             $in->{'type'}
168         );
169     }
170
171     # If we enforce GDPR and the user did not consent, redirect
172     if( $in->{type} eq 'opac' && $user &&
173         $in->{'template_name'} !~ /opac-patron-consent/ &&
174         C4::Context->preference('GDPR_Policy') eq 'Enforced' )
175     {
176         my $consent = Koha::Patron::Consents->search({
177             borrowernumber => getborrowernumber($user),
178             type => 'GDPR_PROCESSING',
179             given_on => { '!=', undef },
180         })->next;
181         if( !$consent ) {
182             print $in->{query}->redirect(-uri => '/cgi-bin/koha/opac-patron-consent.pl', -cookie => $cookie);
183             safe_exit;
184         }
185     }
186
187     if ( $in->{type} eq 'opac' && $user ) {
188         my $kick_out;
189
190         if (
191 # If the user logged in is the SCO user and they try to go out of the SCO module,
192 # log the user out removing the CGISESSID cookie
193                $in->{template_name} !~ m|sco/|
194             && C4::Context->preference('AutoSelfCheckID')
195             && $user eq C4::Context->preference('AutoSelfCheckID')
196           )
197         {
198             $kick_out = 1;
199         }
200         elsif (
201 # If the user logged in is the SCI user and they try to go out of the SCI module,
202 # kick them out unless it is SCO with a valid permission
203 # or they are a superlibrarian
204                $in->{template_name} !~ m|sci/|
205             && haspermission( $user, { self_check => 'self_checkin_module' } )
206             && !(
207                 $in->{template_name} =~ m|sco/| && haspermission(
208                     $user, { self_check => 'self_checkout_module' }
209                 )
210             )
211             && $flags && $flags->{superlibrarian} != 1
212           )
213         {
214             $kick_out = 1;
215         }
216
217         if ($kick_out) {
218             $template = C4::Templates::gettemplate( 'opac-auth.tt', 'opac',
219                 $in->{query} );
220             $cookie = $in->{query}->cookie(
221                 -name     => 'CGISESSID',
222                 -value    => '',
223                 -expires  => '',
224                 -HttpOnly => 1,
225             );
226
227             $template->param(
228                 loginprompt => 1,
229                 script_name => get_script_name(),
230             );
231
232             print $in->{query}->header(
233                 {
234                     type              => 'text/html',
235                     charset           => 'utf-8',
236                     cookie            => $cookie,
237                     'X-Frame-Options' => 'SAMEORIGIN'
238                 }
239               ),
240               $template->output;
241             safe_exit;
242         }
243     }
244
245     my $borrowernumber;
246     if ($user) {
247
248         # It's possible for $user to be the borrowernumber if they don't have a
249         # userid defined (and are logging in through some other method, such
250         # as SSL certs against an email address)
251         my $patron;
252         $borrowernumber = getborrowernumber($user) if defined($user);
253         if ( !defined($borrowernumber) && defined($user) ) {
254             $patron = Koha::Patrons->find( $user );
255             if ($patron) {
256                 $borrowernumber = $user;
257
258                 # A bit of a hack, but I don't know there's a nicer way
259                 # to do it.
260                 $user = $patron->firstname . ' ' . $patron->surname;
261             }
262         } else {
263             $patron = Koha::Patrons->find( $borrowernumber );
264             # FIXME What to do if $patron does not exist?
265         }
266
267         # user info
268         $template->param( loggedinusername   => $user ); # OBSOLETE - Do not reuse this in template, use logged_in_user.userid instead
269         $template->param( loggedinusernumber => $borrowernumber ); # FIXME Should be replaced with logged_in_user.borrowernumber
270         $template->param( logged_in_user     => $patron );
271         $template->param( sessionID          => $sessionID );
272
273         if ( $in->{'type'} eq 'opac' ) {
274             require Koha::Virtualshelves;
275             my $some_private_shelves = Koha::Virtualshelves->get_some_shelves(
276                 {
277                     borrowernumber => $borrowernumber,
278                     category       => 1,
279                 }
280             );
281             my $some_public_shelves = Koha::Virtualshelves->get_some_shelves(
282                 {
283                     category       => 2,
284                 }
285             );
286             $template->param(
287                 some_private_shelves => $some_private_shelves,
288                 some_public_shelves  => $some_public_shelves,
289             );
290         }
291
292         my $all_perms = get_all_subpermissions();
293
294         my @flagroots = qw(circulate catalogue parameters borrowers permissions reserveforothers borrow
295           editcatalogue updatecharges tools editauthorities serials reports acquisition clubs);
296
297         # We are going to use the $flags returned by checkauth
298         # to create the template's parameters that will indicate
299         # which menus the user can access.
300         if ( $flags && $flags->{superlibrarian} == 1 ) {
301             $template->param( CAN_user_circulate        => 1 );
302             $template->param( CAN_user_catalogue        => 1 );
303             $template->param( CAN_user_parameters       => 1 );
304             $template->param( CAN_user_borrowers        => 1 );
305             $template->param( CAN_user_permissions      => 1 );
306             $template->param( CAN_user_reserveforothers => 1 );
307             $template->param( CAN_user_editcatalogue    => 1 );
308             $template->param( CAN_user_updatecharges    => 1 );
309             $template->param( CAN_user_acquisition      => 1 );
310             $template->param( CAN_user_tools            => 1 );
311             $template->param( CAN_user_editauthorities  => 1 );
312             $template->param( CAN_user_serials          => 1 );
313             $template->param( CAN_user_reports          => 1 );
314             $template->param( CAN_user_staffaccess      => 1 );
315             $template->param( CAN_user_plugins          => 1 );
316             $template->param( CAN_user_coursereserves   => 1 );
317             $template->param( CAN_user_clubs            => 1 );
318             $template->param( CAN_user_ill              => 1 );
319             $template->param( CAN_user_stockrotation    => 1 );
320
321             foreach my $module ( keys %$all_perms ) {
322                 foreach my $subperm ( keys %{ $all_perms->{$module} } ) {
323                     $template->param( "CAN_user_${module}_${subperm}" => 1 );
324                 }
325             }
326         }
327
328         if ($flags) {
329             foreach my $module ( keys %$all_perms ) {
330                 if ( defined($flags->{$module}) && $flags->{$module} == 1 ) {
331                     foreach my $subperm ( keys %{ $all_perms->{$module} } ) {
332                         $template->param( "CAN_user_${module}_${subperm}" => 1 );
333                     }
334                 } elsif ( ref( $flags->{$module} ) ) {
335                     foreach my $subperm ( keys %{ $flags->{$module} } ) {
336                         $template->param( "CAN_user_${module}_${subperm}" => 1 );
337                     }
338                 }
339             }
340         }
341
342         if ($flags) {
343             foreach my $module ( keys %$flags ) {
344                 if ( $flags->{$module} == 1 or ref( $flags->{$module} ) ) {
345                     $template->param( "CAN_user_$module" => 1 );
346                 }
347             }
348         }
349
350         # Logged-in opac search history
351         # If the requested template is an opac one and opac search history is enabled
352         if ( $in->{type} eq 'opac' && C4::Context->preference('EnableOpacSearchHistory') ) {
353             my $dbh   = C4::Context->dbh;
354             my $query = "SELECT COUNT(*) FROM search_history WHERE userid=?";
355             my $sth   = $dbh->prepare($query);
356             $sth->execute($borrowernumber);
357
358             # If at least one search has already been performed
359             if ( $sth->fetchrow_array > 0 ) {
360
361                 # We show the link in opac
362                 $template->param( EnableOpacSearchHistory => 1 );
363             }
364             if (C4::Context->preference('LoadSearchHistoryToTheFirstLoggedUser'))
365             {
366                 # And if there are searches performed when the user was not logged in,
367                 # we add them to the logged-in search history
368                 my @recentSearches = C4::Search::History::get_from_session( { cgi => $in->{'query'} } );
369                 if (@recentSearches) {
370                     my $dbh   = C4::Context->dbh;
371                     my $query = q{
372                         INSERT INTO search_history(userid, sessionid, query_desc, query_cgi, type,  total, time )
373                         VALUES (?, ?, ?, ?, ?, ?, ?)
374                     };
375                     my $sth = $dbh->prepare($query);
376                     $sth->execute( $borrowernumber,
377                         $in->{query}->cookie("CGISESSID"),
378                         $_->{query_desc},
379                         $_->{query_cgi},
380                         $_->{type} || 'biblio',
381                         $_->{total},
382                         $_->{time},
383                     ) foreach @recentSearches;
384
385                     # clear out the search history from the session now that
386                     # we've saved it to the database
387                  }
388               }
389               C4::Search::History::set_to_session( { cgi => $in->{'query'}, search_history => [] } );
390
391         } elsif ( $in->{type} eq 'intranet' and C4::Context->preference('EnableSearchHistory') ) {
392             $template->param( EnableSearchHistory => 1 );
393         }
394     }
395     else {    # if this is an anonymous session, setup to display public lists...
396
397         # If shibboleth is enabled, and we're in an anonymous session, we should allow
398         # the user to attempt login via shibboleth.
399         if ($shib) {
400             $template->param( shibbolethAuthentication => $shib,
401                 shibbolethLoginUrl => login_shib_url( $in->{'query'} ),
402             );
403
404             # If shibboleth is enabled and we have a shibboleth login attribute,
405             # but we are in an anonymous session, then we clearly have an invalid
406             # shibboleth koha account.
407             if ($shib_login) {
408                 $template->param( invalidShibLogin => '1' );
409             }
410         }
411
412         $template->param( sessionID => $sessionID );
413
414         if ( $in->{'type'} eq 'opac' ){
415             require Koha::Virtualshelves;
416             my $some_public_shelves = Koha::Virtualshelves->get_some_shelves(
417                 {
418                     category       => 2,
419                 }
420             );
421             $template->param(
422                 some_public_shelves  => $some_public_shelves,
423             );
424         }
425     }
426
427     # Anonymous opac search history
428     # If opac search history is enabled and at least one search has already been performed
429     if ( C4::Context->preference('EnableOpacSearchHistory') ) {
430         my @recentSearches = C4::Search::History::get_from_session( { cgi => $in->{'query'} } );
431         if (@recentSearches) {
432             $template->param( EnableOpacSearchHistory => 1 );
433         }
434     }
435
436     if ( C4::Context->preference('dateformat') ) {
437         $template->param( dateformat => C4::Context->preference('dateformat') );
438     }
439
440     $template->param(auth_forwarded_hash => scalar $in->{'query'}->param('auth_forwarded_hash'));
441
442     # these template parameters are set the same regardless of $in->{'type'}
443
444     # Set the using_https variable for templates
445     # FIXME Under Plack the CGI->https method always returns 'OFF'
446     my $https = $in->{query}->https();
447     my $using_https = ( defined $https and $https ne 'OFF' ) ? 1 : 0;
448
449     my $minPasswordLength = C4::Context->preference('minPasswordLength');
450     $minPasswordLength = 3 if not $minPasswordLength or $minPasswordLength < 3;
451     $template->param(
452         "BiblioDefaultView" . C4::Context->preference("BiblioDefaultView") => 1,
453         EnhancedMessagingPreferences                                       => C4::Context->preference('EnhancedMessagingPreferences'),
454         GoogleJackets                                                      => C4::Context->preference("GoogleJackets"),
455         OpenLibraryCovers                                                  => C4::Context->preference("OpenLibraryCovers"),
456         KohaAdminEmailAddress                                              => "" . C4::Context->preference("KohaAdminEmailAddress"),
457         LoginBranchcode => ( C4::Context->userenv ? C4::Context->userenv->{"branch"}    : undef ),
458         LoginFirstname  => ( C4::Context->userenv ? C4::Context->userenv->{"firstname"} : "Bel" ),
459         LoginSurname    => C4::Context->userenv ? C4::Context->userenv->{"surname"}      : "Inconnu",
460         emailaddress    => C4::Context->userenv ? C4::Context->userenv->{"emailaddress"} : undef,
461         TagsEnabled     => C4::Context->preference("TagsEnabled"),
462         hide_marc       => C4::Context->preference("hide_marc"),
463         item_level_itypes  => C4::Context->preference('item-level_itypes'),
464         patronimages       => C4::Context->preference("patronimages"),
465         singleBranchMode   => ( Koha::Libraries->search->count == 1 ),
466         XSLTDetailsDisplay => C4::Context->preference("XSLTDetailsDisplay"),
467         XSLTResultsDisplay => C4::Context->preference("XSLTResultsDisplay"),
468         using_https        => $using_https,
469         noItemTypeImages   => C4::Context->preference("noItemTypeImages"),
470         marcflavour        => C4::Context->preference("marcflavour"),
471         OPACBaseURL        => C4::Context->preference('OPACBaseURL'),
472         minPasswordLength  => $minPasswordLength,
473     );
474     if ( $in->{'type'} eq "intranet" ) {
475         $template->param(
476             AmazonCoverImages                                                          => C4::Context->preference("AmazonCoverImages"),
477             AutoLocation                                                               => C4::Context->preference("AutoLocation"),
478             "BiblioDefaultView" . C4::Context->preference("IntranetBiblioDefaultView") => 1,
479             CircAutocompl                                                              => C4::Context->preference("CircAutocompl"),
480             FRBRizeEditions                                                            => C4::Context->preference("FRBRizeEditions"),
481             IndependentBranches                                                        => C4::Context->preference("IndependentBranches"),
482             IntranetNav                                                                => C4::Context->preference("IntranetNav"),
483             IntranetmainUserblock                                                      => C4::Context->preference("IntranetmainUserblock"),
484             LibraryName                                                                => C4::Context->preference("LibraryName"),
485             LoginBranchname                                                            => ( C4::Context->userenv ? C4::Context->userenv->{"branchname"} : undef ),
486             advancedMARCEditor                                                         => C4::Context->preference("advancedMARCEditor"),
487             canreservefromotherbranches                                                => C4::Context->preference('canreservefromotherbranches'),
488             intranetcolorstylesheet                                                    => C4::Context->preference("intranetcolorstylesheet"),
489             IntranetFavicon                                                            => C4::Context->preference("IntranetFavicon"),
490             intranetreadinghistory                                                     => C4::Context->preference("intranetreadinghistory"),
491             intranetstylesheet                                                         => C4::Context->preference("intranetstylesheet"),
492             IntranetUserCSS                                                            => C4::Context->preference("IntranetUserCSS"),
493             IntranetUserJS                                                             => C4::Context->preference("IntranetUserJS"),
494             intranetbookbag                                                            => C4::Context->preference("intranetbookbag"),
495             suggestion                                                                 => C4::Context->preference("suggestion"),
496             virtualshelves                                                             => C4::Context->preference("virtualshelves"),
497             StaffSerialIssueDisplayCount                                               => C4::Context->preference("StaffSerialIssueDisplayCount"),
498             EasyAnalyticalRecords                                                      => C4::Context->preference('EasyAnalyticalRecords'),
499             LocalCoverImages                                                           => C4::Context->preference('LocalCoverImages'),
500             OPACLocalCoverImages                                                       => C4::Context->preference('OPACLocalCoverImages'),
501             AllowMultipleCovers                                                        => C4::Context->preference('AllowMultipleCovers'),
502             EnableBorrowerFiles                                                        => C4::Context->preference('EnableBorrowerFiles'),
503             UseKohaPlugins                                                             => C4::Context->preference('UseKohaPlugins'),
504             UseCourseReserves                                                          => C4::Context->preference("UseCourseReserves"),
505             useDischarge                                                               => C4::Context->preference('useDischarge'),
506             pending_checkout_notes                                                     => scalar Koha::Checkouts->search({ noteseen => 0 }),
507         );
508     }
509     else {
510         warn "template type should be OPAC, here it is=[" . $in->{'type'} . "]" unless ( $in->{'type'} eq 'opac' );
511
512         #TODO : replace LibraryName syspref with 'system name', and remove this html processing
513         my $LibraryNameTitle = C4::Context->preference("LibraryName");
514         $LibraryNameTitle =~ s/<(?:\/?)(?:br|p)\s*(?:\/?)>/ /sgi;
515         $LibraryNameTitle =~ s/<(?:[^<>'"]|'(?:[^']*)'|"(?:[^"]*)")*>//sg;
516
517         # clean up the busc param in the session
518         # if the page is not opac-detail and not the "add to list" page
519         # and not the "edit comments" page
520         if ( C4::Context->preference("OpacBrowseResults")
521             && $in->{'template_name'} =~ /opac-(.+)\.(?:tt|tmpl)$/ ) {
522             my $pagename = $1;
523             unless ( $pagename =~ /^(?:MARC|ISBD)?detail$/
524                 or $pagename =~ /^addbybiblionumber$/
525                 or $pagename =~ /^review$/ ) {
526                 my $sessionSearch = get_session( $sessionID || $in->{'query'}->cookie("CGISESSID") );
527                 $sessionSearch->clear( ["busc"] ) if ( $sessionSearch->param("busc") );
528             }
529         }
530
531         # variables passed from CGI: opac_css_override and opac_search_limits.
532         my $opac_search_limit   = $ENV{'OPAC_SEARCH_LIMIT'};
533         my $opac_limit_override = $ENV{'OPAC_LIMIT_OVERRIDE'};
534         my $opac_name           = '';
535         if (
536             ( $opac_limit_override && $opac_search_limit && $opac_search_limit =~ /branch:([\w-]+)/ ) ||
537             ( $in->{'query'}->param('limit') && $in->{'query'}->param('limit') =~ /branch:([\w-]+)/ ) ||
538             ( $in->{'query'}->param('multibranchlimit') && $in->{'query'}->param('multibranchlimit') =~ /multibranchlimit-(\w+)/ )
539           ) {
540             $opac_name = $1;    # opac_search_limit is a branch, so we use it.
541         } elsif ( $in->{'query'}->param('multibranchlimit') ) {
542             $opac_name = $in->{'query'}->param('multibranchlimit');
543         } elsif ( C4::Context->preference("SearchMyLibraryFirst") && C4::Context->userenv && C4::Context->userenv->{'branch'} ) {
544             $opac_name = C4::Context->userenv->{'branch'};
545         }
546
547         my @search_groups = Koha::Library::Groups->get_search_groups({ interface => 'opac' });
548         $template->param(
549             OpacAdditionalStylesheet                   => C4::Context->preference("OpacAdditionalStylesheet"),
550             AnonSuggestions                       => "" . C4::Context->preference("AnonSuggestions"),
551             LibrarySearchGroups                   => \@search_groups,
552             opac_name                             => $opac_name,
553             LibraryName                           => "" . C4::Context->preference("LibraryName"),
554             LibraryNameTitle                      => "" . $LibraryNameTitle,
555             LoginBranchname                       => C4::Context->userenv ? C4::Context->userenv->{"branchname"} : "",
556             OPACAmazonCoverImages                 => C4::Context->preference("OPACAmazonCoverImages"),
557             OPACFRBRizeEditions                   => C4::Context->preference("OPACFRBRizeEditions"),
558             OpacHighlightedWords                  => C4::Context->preference("OpacHighlightedWords"),
559             OPACShelfBrowser                      => "" . C4::Context->preference("OPACShelfBrowser"),
560             OPACURLOpenInNewWindow                => "" . C4::Context->preference("OPACURLOpenInNewWindow"),
561             OPACUserCSS                           => "" . C4::Context->preference("OPACUserCSS"),
562             OpacAuthorities                       => C4::Context->preference("OpacAuthorities"),
563             opac_css_override                     => $ENV{'OPAC_CSS_OVERRIDE'},
564             opac_search_limit                     => $opac_search_limit,
565             opac_limit_override                   => $opac_limit_override,
566             OpacBrowser                           => C4::Context->preference("OpacBrowser"),
567             OpacCloud                             => C4::Context->preference("OpacCloud"),
568             OpacKohaUrl                           => C4::Context->preference("OpacKohaUrl"),
569             OpacMainUserBlock                     => "" . C4::Context->preference("OpacMainUserBlock"),
570             OpacNav                               => "" . C4::Context->preference("OpacNav"),
571             OpacNavRight                          => "" . C4::Context->preference("OpacNavRight"),
572             OpacNavBottom                         => "" . C4::Context->preference("OpacNavBottom"),
573             OpacPasswordChange                    => C4::Context->preference("OpacPasswordChange"),
574             OPACPatronDetails                     => C4::Context->preference("OPACPatronDetails"),
575             OPACPrivacy                           => C4::Context->preference("OPACPrivacy"),
576             OPACFinesTab                          => C4::Context->preference("OPACFinesTab"),
577             OpacTopissue                          => C4::Context->preference("OpacTopissue"),
578             RequestOnOpac                         => C4::Context->preference("RequestOnOpac"),
579             'Version'                             => C4::Context->preference('Version'),
580             hidelostitems                         => C4::Context->preference("hidelostitems"),
581             mylibraryfirst                        => ( C4::Context->preference("SearchMyLibraryFirst") && C4::Context->userenv ) ? C4::Context->userenv->{'branch'} : '',
582             opaclayoutstylesheet                  => "" . C4::Context->preference("opaclayoutstylesheet"),
583             opacbookbag                           => "" . C4::Context->preference("opacbookbag"),
584             opaccredits                           => "" . C4::Context->preference("opaccredits"),
585             OpacFavicon                           => C4::Context->preference("OpacFavicon"),
586             opacheader                            => "" . C4::Context->preference("opacheader"),
587             opaclanguagesdisplay                  => "" . C4::Context->preference("opaclanguagesdisplay"),
588             opacreadinghistory                    => C4::Context->preference("opacreadinghistory"),
589             OPACUserJS                            => C4::Context->preference("OPACUserJS"),
590             opacuserlogin                         => "" . C4::Context->preference("opacuserlogin"),
591             OpenLibrarySearch                     => C4::Context->preference("OpenLibrarySearch"),
592             ShowReviewer                          => C4::Context->preference("ShowReviewer"),
593             ShowReviewerPhoto                     => C4::Context->preference("ShowReviewerPhoto"),
594             suggestion                            => "" . C4::Context->preference("suggestion"),
595             virtualshelves                        => "" . C4::Context->preference("virtualshelves"),
596             OPACSerialIssueDisplayCount           => C4::Context->preference("OPACSerialIssueDisplayCount"),
597             OPACXSLTDetailsDisplay                => C4::Context->preference("OPACXSLTDetailsDisplay"),
598             OPACXSLTResultsDisplay                => C4::Context->preference("OPACXSLTResultsDisplay"),
599             SyndeticsClientCode                   => C4::Context->preference("SyndeticsClientCode"),
600             SyndeticsEnabled                      => C4::Context->preference("SyndeticsEnabled"),
601             SyndeticsCoverImages                  => C4::Context->preference("SyndeticsCoverImages"),
602             SyndeticsTOC                          => C4::Context->preference("SyndeticsTOC"),
603             SyndeticsSummary                      => C4::Context->preference("SyndeticsSummary"),
604             SyndeticsEditions                     => C4::Context->preference("SyndeticsEditions"),
605             SyndeticsExcerpt                      => C4::Context->preference("SyndeticsExcerpt"),
606             SyndeticsReviews                      => C4::Context->preference("SyndeticsReviews"),
607             SyndeticsAuthorNotes                  => C4::Context->preference("SyndeticsAuthorNotes"),
608             SyndeticsAwards                       => C4::Context->preference("SyndeticsAwards"),
609             SyndeticsSeries                       => C4::Context->preference("SyndeticsSeries"),
610             SyndeticsCoverImageSize               => C4::Context->preference("SyndeticsCoverImageSize"),
611             OPACLocalCoverImages                  => C4::Context->preference("OPACLocalCoverImages"),
612             PatronSelfRegistration                => C4::Context->preference("PatronSelfRegistration"),
613             PatronSelfRegistrationDefaultCategory => C4::Context->preference("PatronSelfRegistrationDefaultCategory"),
614             useDischarge                 => C4::Context->preference('useDischarge'),
615         );
616
617         $template->param( OpacPublic => '1' ) if ( $user || C4::Context->preference("OpacPublic") );
618     }
619
620     # Check if we were asked using parameters to force a specific language
621     if ( defined $in->{'query'}->param('language') ) {
622
623         # Extract the language, let C4::Languages::getlanguage choose
624         # what to do
625         my $language = C4::Languages::getlanguage( $in->{'query'} );
626         my $languagecookie = C4::Templates::getlanguagecookie( $in->{'query'}, $language );
627         if ( ref $cookie eq 'ARRAY' ) {
628             push @{$cookie}, $languagecookie;
629         } else {
630             $cookie = [ $cookie, $languagecookie ];
631         }
632     }
633
634     return ( $template, $borrowernumber, $cookie, $flags );
635 }
636
637 =head2 checkauth
638
639   ($userid, $cookie, $sessionID) = &checkauth($query, $noauth, $flagsrequired, $type);
640
641 Verifies that the user is authorized to run this script.  If
642 the user is authorized, a (userid, cookie, session-id, flags)
643 quadruple is returned.  If the user is not authorized but does
644 not have the required privilege (see $flagsrequired below), it
645 displays an error page and exits.  Otherwise, it displays the
646 login page and exits.
647
648 Note that C<&checkauth> will return if and only if the user
649 is authorized, so it should be called early on, before any
650 unfinished operations (e.g., if you've opened a file, then
651 C<&checkauth> won't close it for you).
652
653 C<$query> is the CGI object for the script calling C<&checkauth>.
654
655 The C<$noauth> argument is optional. If it is set, then no
656 authorization is required for the script.
657
658 C<&checkauth> fetches user and session information from C<$query> and
659 ensures that the user is authorized to run scripts that require
660 authorization.
661
662 The C<$flagsrequired> argument specifies the required privileges
663 the user must have if the username and password are correct.
664 It should be specified as a reference-to-hash; keys in the hash
665 should be the "flags" for the user, as specified in the Members
666 intranet module. Any key specified must correspond to a "flag"
667 in the userflags table. E.g., { circulate => 1 } would specify
668 that the user must have the "circulate" privilege in order to
669 proceed. To make sure that access control is correct, the
670 C<$flagsrequired> parameter must be specified correctly.
671
672 Koha also has a concept of sub-permissions, also known as
673 granular permissions.  This makes the value of each key
674 in the C<flagsrequired> hash take on an additional
675 meaning, i.e.,
676
677  1
678
679 The user must have access to all subfunctions of the module
680 specified by the hash key.
681
682  *
683
684 The user must have access to at least one subfunction of the module
685 specified by the hash key.
686
687  specific permission, e.g., 'export_catalog'
688
689 The user must have access to the specific subfunction list, which
690 must correspond to a row in the permissions table.
691
692 The C<$type> argument specifies whether the template should be
693 retrieved from the opac or intranet directory tree.  "opac" is
694 assumed if it is not specified; however, if C<$type> is specified,
695 "intranet" is assumed if it is not "opac".
696
697 If C<$query> does not have a valid session ID associated with it
698 (i.e., the user has not logged in) or if the session has expired,
699 C<&checkauth> presents the user with a login page (from the point of
700 view of the original script, C<&checkauth> does not return). Once the
701 user has authenticated, C<&checkauth> restarts the original script
702 (this time, C<&checkauth> returns).
703
704 The login page is provided using a HTML::Template, which is set in the
705 systempreferences table or at the top of this file. The variable C<$type>
706 selects which template to use, either the opac or the intranet
707 authentification template.
708
709 C<&checkauth> returns a user ID, a cookie, and a session ID. The
710 cookie should be sent back to the browser; it verifies that the user
711 has authenticated.
712
713 =cut
714
715 sub _version_check {
716     my $type  = shift;
717     my $query = shift;
718     my $version;
719
720     # If version syspref is unavailable, it means Koha is being installed,
721     # and so we must redirect to OPAC maintenance page or to the WebInstaller
722     # also, if OpacMaintenance is ON, OPAC should redirect to maintenance
723     if ( C4::Context->preference('OpacMaintenance') && $type eq 'opac' ) {
724         warn "OPAC Install required, redirecting to maintenance";
725         print $query->redirect("/cgi-bin/koha/maintenance.pl");
726         safe_exit;
727     }
728     unless ( $version = C4::Context->preference('Version') ) {    # assignment, not comparison
729         if ( $type ne 'opac' ) {
730             warn "Install required, redirecting to Installer";
731             print $query->redirect("/cgi-bin/koha/installer/install.pl");
732         } else {
733             warn "OPAC Install required, redirecting to maintenance";
734             print $query->redirect("/cgi-bin/koha/maintenance.pl");
735         }
736         safe_exit;
737     }
738
739     # check that database and koha version are the same
740     # there is no DB version, it's a fresh install,
741     # go to web installer
742     # there is a DB version, compare it to the code version
743     my $kohaversion = Koha::version();
744
745     # remove the 3 last . to have a Perl number
746     $kohaversion =~ s/(.*\..*)\.(.*)\.(.*)/$1$2$3/;
747     $debug and print STDERR "kohaversion : $kohaversion\n";
748     if ( $version < $kohaversion ) {
749         my $warning = "Database update needed, redirecting to %s. Database is $version and Koha is $kohaversion";
750         if ( $type ne 'opac' ) {
751             warn sprintf( $warning, 'Installer' );
752             print $query->redirect("/cgi-bin/koha/installer/install.pl?step=1&op=updatestructure");
753         } else {
754             warn sprintf( "OPAC: " . $warning, 'maintenance' );
755             print $query->redirect("/cgi-bin/koha/maintenance.pl");
756         }
757         safe_exit;
758     }
759 }
760
761 sub _session_log {
762     (@_) or return 0;
763     open my $fh, '>>', "/tmp/sessionlog" or warn "ERROR: Cannot append to /tmp/sessionlog";
764     printf $fh join( "\n", @_ );
765     close $fh;
766 }
767
768 sub _timeout_syspref {
769     my $timeout = C4::Context->preference('timeout') || 600;
770
771     # value in days, convert in seconds
772     if ( $timeout =~ /(\d+)[dD]/ ) {
773         $timeout = $1 * 86400;
774     }
775     return $timeout;
776 }
777
778 sub checkauth {
779     my $query = shift;
780     $debug and warn "Checking Auth";
781
782     # Get shibboleth login attribute
783     my $shib = C4::Context->config('useshibboleth') && shib_ok();
784     my $shib_login = $shib ? get_login_shib() : undef;
785
786     # $authnotrequired will be set for scripts which will run without authentication
787     my $authnotrequired = shift;
788     my $flagsrequired   = shift;
789     my $type            = shift;
790     my $emailaddress    = shift;
791     $type = 'opac' unless $type;
792
793     my $dbh     = C4::Context->dbh;
794     my $timeout = _timeout_syspref();
795
796     _version_check( $type, $query );
797
798     # state variables
799     my $loggedin = 0;
800     my %info;
801     my ( $userid, $cookie, $sessionID, $flags );
802     my $logout = $query->param('logout.x');
803
804     my $anon_search_history;
805     my $cas_ticket = '';
806     # This parameter is the name of the CAS server we want to authenticate against,
807     # when using authentication against multiple CAS servers, as configured in Auth_cas_servers.yaml
808     my $casparam = $query->param('cas');
809     my $q_userid = $query->param('userid') // '';
810
811     my $session;
812
813     # Basic authentication is incompatible with the use of Shibboleth,
814     # as Shibboleth may return REMOTE_USER as a Shibboleth attribute,
815     # and it may not be the attribute we want to use to match the koha login.
816     #
817     # Also, do not consider an empty REMOTE_USER.
818     #
819     # Finally, after those tests, we can assume (although if it would be better with
820     # a syspref) that if we get a REMOTE_USER, that's from basic authentication,
821     # and we can affect it to $userid.
822     if ( !$shib and defined( $ENV{'REMOTE_USER'} ) and $ENV{'REMOTE_USER'} ne '' and $userid = $ENV{'REMOTE_USER'} ) {
823
824         # Using Basic Authentication, no cookies required
825         $cookie = $query->cookie(
826             -name     => 'CGISESSID',
827             -value    => '',
828             -expires  => '',
829             -HttpOnly => 1,
830         );
831         $loggedin = 1;
832     }
833     elsif ( $emailaddress) {
834         # the Google OpenID Connect passes an email address
835     }
836     elsif ( $sessionID = $query->cookie("CGISESSID") )
837     {    # assignment, not comparison
838         $session = get_session($sessionID);
839         C4::Context->_new_userenv($sessionID);
840         my ( $ip, $lasttime, $sessiontype );
841         my $s_userid = '';
842         if ($session) {
843             $s_userid = $session->param('id') // '';
844             C4::Context->set_userenv(
845                 $session->param('number'),       $s_userid,
846                 $session->param('cardnumber'),   $session->param('firstname'),
847                 $session->param('surname'),      $session->param('branch'),
848                 $session->param('branchname'),   $session->param('flags'),
849                 $session->param('emailaddress'), $session->param('branchprinter'),
850                 $session->param('shibboleth')
851             );
852             C4::Context::set_shelves_userenv( 'bar', $session->param('barshelves') );
853             C4::Context::set_shelves_userenv( 'pub', $session->param('pubshelves') );
854             C4::Context::set_shelves_userenv( 'tot', $session->param('totshelves') );
855             $debug and printf STDERR "AUTH_SESSION: (%s)\t%s %s - %s\n", map { $session->param($_) } qw(cardnumber firstname surname branch);
856             $ip          = $session->param('ip');
857             $lasttime    = $session->param('lasttime');
858             $userid      = $s_userid;
859             $sessiontype = $session->param('sessiontype') || '';
860         }
861         if ( ( $query->param('koha_login_context') && ( $q_userid ne $s_userid ) )
862             || ( $cas && $query->param('ticket') && !C4::Context->userenv->{'id'} )
863             || ( $shib && $shib_login && !$logout && !C4::Context->userenv->{'id'} )
864         ) {
865
866             #if a user enters an id ne to the id in the current session, we need to log them in...
867             #first we need to clear the anonymous session...
868             $debug and warn "query id = $q_userid but session id = $s_userid";
869             $anon_search_history = $session->param('search_history');
870             $session->delete();
871             $session->flush;
872             C4::Context->_unset_userenv($sessionID);
873             $sessionID = undef;
874             $userid    = undef;
875         }
876         elsif ($logout) {
877
878             # voluntary logout the user
879             # check wether the user was using their shibboleth session or a local one
880             my $shibSuccess = C4::Context->userenv->{'shibboleth'};
881             $session->delete();
882             $session->flush;
883             C4::Context->_unset_userenv($sessionID);
884
885             #_session_log(sprintf "%20s from %16s logged out at %30s (manually).\n", $userid,$ip,(strftime "%c",localtime));
886             $sessionID = undef;
887             $userid    = undef;
888
889             if ($cas and $caslogout) {
890                 logout_cas($query, $type);
891             }
892
893             # If we are in a shibboleth session (shibboleth is enabled, a shibboleth match attribute is set and matches koha matchpoint)
894             if ( $shib and $shib_login and $shibSuccess) {
895                 logout_shib($query);
896             }
897         }
898         elsif ( !$lasttime || ( $lasttime < time() - $timeout ) ) {
899
900             # timed logout
901             $info{'timed_out'} = 1;
902             if ($session) {
903                 $session->delete();
904                 $session->flush;
905             }
906             C4::Context->_unset_userenv($sessionID);
907
908             #_session_log(sprintf "%20s from %16s logged out at %30s (inactivity).\n", $userid,$ip,(strftime "%c",localtime));
909             $userid    = undef;
910             $sessionID = undef;
911         }
912         elsif ( C4::Context->preference('SessionRestrictionByIP') && $ip ne $ENV{'REMOTE_ADDR'} ) {
913
914             # Different ip than originally logged in from
915             $info{'oldip'}        = $ip;
916             $info{'newip'}        = $ENV{'REMOTE_ADDR'};
917             $info{'different_ip'} = 1;
918             $session->delete();
919             $session->flush;
920             C4::Context->_unset_userenv($sessionID);
921
922             #_session_log(sprintf "%20s from %16s logged out at %30s (ip changed to %16s).\n", $userid,$ip,(strftime "%c",localtime), $info{'newip'});
923             $sessionID = undef;
924             $userid    = undef;
925         }
926         else {
927             $cookie = $query->cookie(
928                 -name     => 'CGISESSID',
929                 -value    => $session->id,
930                 -HttpOnly => 1
931             );
932             $session->param( 'lasttime', time() );
933             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...
934                 $flags = haspermission( $userid, $flagsrequired );
935                 if ($flags) {
936                     $loggedin = 1;
937                 } else {
938                     $info{'nopermission'} = 1;
939                 }
940             }
941         }
942     }
943     unless ( $userid || $sessionID ) {
944         #we initiate a session prior to checking for a username to allow for anonymous sessions...
945         my $session = get_session("") or die "Auth ERROR: Cannot get_session()";
946
947         # Save anonymous search history in new session so it can be retrieved
948         # by get_template_and_user to store it in user's search history after
949         # a successful login.
950         if ($anon_search_history) {
951             $session->param( 'search_history', $anon_search_history );
952         }
953
954         $sessionID = $session->id;
955         C4::Context->_new_userenv($sessionID);
956         $cookie = $query->cookie(
957             -name     => 'CGISESSID',
958             -value    => $session->id,
959             -HttpOnly => 1
960         );
961         my $pki_field = C4::Context->preference('AllowPKIAuth');
962         if ( !defined($pki_field) ) {
963             print STDERR "ERROR: Missing system preference AllowPKIAuth.\n";
964             $pki_field = 'None';
965         }
966         if ( ( $cas && $query->param('ticket') )
967             || $q_userid
968             || ( $shib && $shib_login )
969             || $pki_field ne 'None'
970             || $emailaddress )
971         {
972             my $password    = $query->param('password');
973             my $shibSuccess = 0;
974             my ( $return, $cardnumber );
975
976             # If shib is enabled and we have a shib login, does the login match a valid koha user
977             if ( $shib && $shib_login ) {
978                 my $retuserid;
979
980                 # Do not pass password here, else shib will not be checked in checkpw.
981                 ( $return, $cardnumber, $retuserid ) = checkpw( $dbh, $q_userid, undef, $query );
982                 $userid      = $retuserid;
983                 $shibSuccess = $return;
984                 $info{'invalidShibLogin'} = 1 unless ($return);
985             }
986
987             # If shib login and match were successful, skip further login methods
988             unless ($shibSuccess) {
989                 if ( $cas && $query->param('ticket') ) {
990                     my $retuserid;
991                     ( $return, $cardnumber, $retuserid, $cas_ticket ) =
992                       checkpw( $dbh, $userid, $password, $query, $type );
993                     $userid = $retuserid;
994                     $info{'invalidCasLogin'} = 1 unless ($return);
995                 }
996
997                 elsif ( $emailaddress ) {
998                     my $value = $emailaddress;
999
1000                     # If we're looking up the email, there's a chance that the person
1001                     # doesn't have a userid. So if there is none, we pass along the
1002                     # borrower number, and the bits of code that need to know the user
1003                     # ID will have to be smart enough to handle that.
1004                     my $patrons = Koha::Patrons->search({ email => $value });
1005                     if ($patrons->count) {
1006
1007                         # First the userid, then the borrowernum
1008                         my $patron = $patrons->next;
1009                         $value = $patron->userid || $patron->borrowernumber;
1010                     } else {
1011                         undef $value;
1012                     }
1013                     $return = $value ? 1 : 0;
1014                     $userid = $value;
1015                 }
1016
1017                 elsif (
1018                     ( $pki_field eq 'Common Name' && $ENV{'SSL_CLIENT_S_DN_CN'} )
1019                     || ( $pki_field eq 'emailAddress'
1020                         && $ENV{'SSL_CLIENT_S_DN_Email'} )
1021                   )
1022                 {
1023                     my $value;
1024                     if ( $pki_field eq 'Common Name' ) {
1025                         $value = $ENV{'SSL_CLIENT_S_DN_CN'};
1026                     }
1027                     elsif ( $pki_field eq 'emailAddress' ) {
1028                         $value = $ENV{'SSL_CLIENT_S_DN_Email'};
1029
1030                         # If we're looking up the email, there's a chance that the person
1031                         # doesn't have a userid. So if there is none, we pass along the
1032                         # borrower number, and the bits of code that need to know the user
1033                         # ID will have to be smart enough to handle that.
1034                         my $patrons = Koha::Patrons->search({ email => $value });
1035                         if ($patrons->count) {
1036
1037                             # First the userid, then the borrowernum
1038                             my $patron = $patrons->next;
1039                             $value = $patron->userid || $patron->borrowernumber;
1040                         } else {
1041                             undef $value;
1042                         }
1043                     }
1044
1045                     $return = $value ? 1 : 0;
1046                     $userid = $value;
1047
1048                 }
1049                 else {
1050                     my $retuserid;
1051                     ( $return, $cardnumber, $retuserid, $cas_ticket ) =
1052                       checkpw( $dbh, $q_userid, $password, $query, $type );
1053                     $userid = $retuserid if ($retuserid);
1054                     $info{'invalid_username_or_password'} = 1 unless ($return);
1055                 }
1056             }
1057
1058             # $return: 1 = valid user
1059             if ($return) {
1060
1061                 #_session_log(sprintf "%20s from %16s logged in  at %30s.\n", $userid,$ENV{'REMOTE_ADDR'},(strftime '%c', localtime));
1062                 if ( $flags = haspermission( $userid, $flagsrequired ) ) {
1063                     $loggedin = 1;
1064                 }
1065                 else {
1066                     $info{'nopermission'} = 1;
1067                     C4::Context->_unset_userenv($sessionID);
1068                 }
1069                 my ( $borrowernumber, $firstname, $surname, $userflags,
1070                     $branchcode, $branchname, $branchprinter, $emailaddress );
1071
1072                 if ( $return == 1 ) {
1073                     my $select = "
1074                     SELECT borrowernumber, firstname, surname, flags, borrowers.branchcode,
1075                     branches.branchname    as branchname,
1076                     branches.branchprinter as branchprinter,
1077                     email
1078                     FROM borrowers
1079                     LEFT JOIN branches on borrowers.branchcode=branches.branchcode
1080                     ";
1081                     my $sth = $dbh->prepare("$select where userid=?");
1082                     $sth->execute($userid);
1083                     unless ( $sth->rows ) {
1084                         $debug and print STDERR "AUTH_1: no rows for userid='$userid'\n";
1085                         $sth = $dbh->prepare("$select where cardnumber=?");
1086                         $sth->execute($cardnumber);
1087
1088                         unless ( $sth->rows ) {
1089                             $debug and print STDERR "AUTH_2a: no rows for cardnumber='$cardnumber'\n";
1090                             $sth->execute($userid);
1091                             unless ( $sth->rows ) {
1092                                 $debug and print STDERR "AUTH_2b: no rows for userid='$userid' AS cardnumber\n";
1093                             }
1094                         }
1095                     }
1096                     if ( $sth->rows ) {
1097                         ( $borrowernumber, $firstname, $surname, $userflags,
1098                             $branchcode, $branchname, $branchprinter, $emailaddress ) = $sth->fetchrow;
1099                         $debug and print STDERR "AUTH_3 results: " .
1100                           "$cardnumber,$borrowernumber,$userid,$firstname,$surname,$userflags,$branchcode,$emailaddress\n";
1101                     } else {
1102                         print STDERR "AUTH_3: no results for userid='$userid', cardnumber='$cardnumber'.\n";
1103                     }
1104
1105                     # launch a sequence to check if we have a ip for the branch, i
1106                     # if we have one we replace the branchcode of the userenv by the branch bound in the ip.
1107
1108                     my $ip = $ENV{'REMOTE_ADDR'};
1109
1110                     # if they specify at login, use that
1111                     if ( $query->param('branch') ) {
1112                         $branchcode = $query->param('branch');
1113                         my $library = Koha::Libraries->find($branchcode);
1114                         $branchname = $library? $library->branchname: '';
1115                     }
1116                     my $branches = { map { $_->branchcode => $_->unblessed } Koha::Libraries->search };
1117                     if ( $type ne 'opac' and C4::Context->boolean_preference('AutoLocation') ) {
1118
1119                         # we have to check they are coming from the right ip range
1120                         my $domain = $branches->{$branchcode}->{'branchip'};
1121                         $domain =~ s|\.\*||g;
1122                         if ( $ip !~ /^$domain/ ) {
1123                             $loggedin = 0;
1124                             $cookie = $query->cookie(
1125                                 -name     => 'CGISESSID',
1126                                 -value    => '',
1127                                 -HttpOnly => 1
1128                             );
1129                             $info{'wrongip'} = 1;
1130                         }
1131                     }
1132
1133                     foreach my $br ( keys %$branches ) {
1134
1135                         #     now we work with the treatment of ip
1136                         my $domain = $branches->{$br}->{'branchip'};
1137                         if ( $domain && $ip =~ /^$domain/ ) {
1138                             $branchcode = $branches->{$br}->{'branchcode'};
1139
1140                             # new op dev : add the branchprinter and branchname in the cookie
1141                             $branchprinter = $branches->{$br}->{'branchprinter'};
1142                             $branchname    = $branches->{$br}->{'branchname'};
1143                         }
1144                     }
1145                     $session->param( 'number',       $borrowernumber );
1146                     $session->param( 'id',           $userid );
1147                     $session->param( 'cardnumber',   $cardnumber );
1148                     $session->param( 'firstname',    $firstname );
1149                     $session->param( 'surname',      $surname );
1150                     $session->param( 'branch',       $branchcode );
1151                     $session->param( 'branchname',   $branchname );
1152                     $session->param( 'flags',        $userflags );
1153                     $session->param( 'emailaddress', $emailaddress );
1154                     $session->param( 'ip',           $session->remote_addr() );
1155                     $session->param( 'lasttime',     time() );
1156                     $session->param( 'shibboleth',   $shibSuccess );
1157                     $debug and printf STDERR "AUTH_4: (%s)\t%s %s - %s\n", map { $session->param($_) } qw(cardnumber firstname surname branch);
1158                 }
1159                 $session->param('cas_ticket', $cas_ticket) if $cas_ticket;
1160                 C4::Context->set_userenv(
1161                     $session->param('number'),       $session->param('id'),
1162                     $session->param('cardnumber'),   $session->param('firstname'),
1163                     $session->param('surname'),      $session->param('branch'),
1164                     $session->param('branchname'),   $session->param('flags'),
1165                     $session->param('emailaddress'), $session->param('branchprinter'),
1166                     $session->param('shibboleth')
1167                 );
1168
1169             }
1170             # $return: 0 = invalid user
1171             # reset to anonymous session
1172             else {
1173                 $debug and warn "Login failed, resetting anonymous session...";
1174                 if ($userid) {
1175                     $info{'invalid_username_or_password'} = 1;
1176                     C4::Context->_unset_userenv($sessionID);
1177                 }
1178                 $session->param( 'lasttime', time() );
1179                 $session->param( 'ip',       $session->remote_addr() );
1180                 $session->param( 'sessiontype', 'anon' );
1181             }
1182         }    # END if ( $q_userid
1183         elsif ( $type eq "opac" ) {
1184
1185             # if we are here this is an anonymous session; add public lists to it and a few other items...
1186             # anonymous sessions are created only for the OPAC
1187             $debug and warn "Initiating an anonymous session...";
1188
1189             # setting a couple of other session vars...
1190             $session->param( 'ip',          $session->remote_addr() );
1191             $session->param( 'lasttime',    time() );
1192             $session->param( 'sessiontype', 'anon' );
1193         }
1194     }    # END unless ($userid)
1195
1196     # finished authentification, now respond
1197     if ( $loggedin || $authnotrequired )
1198     {
1199         # successful login
1200         unless ($cookie) {
1201             $cookie = $query->cookie(
1202                 -name     => 'CGISESSID',
1203                 -value    => '',
1204                 -HttpOnly => 1
1205             );
1206         }
1207
1208         track_login_daily( $userid );
1209
1210         return ( $userid, $cookie, $sessionID, $flags );
1211     }
1212
1213     #
1214     #
1215     # AUTH rejected, show the login/password template, after checking the DB.
1216     #
1217     #
1218
1219     # get the inputs from the incoming query
1220     my @inputs = ();
1221     foreach my $name ( param $query) {
1222         (next) if ( $name eq 'userid' || $name eq 'password' || $name eq 'ticket' );
1223         my @value = $query->multi_param($name);
1224         push @inputs, { name => $name, value => $_ } for @value;
1225     }
1226
1227     my $patron = Koha::Patrons->find({ userid => $q_userid }); # Not necessary logged in!
1228
1229     my $LibraryNameTitle = C4::Context->preference("LibraryName");
1230     $LibraryNameTitle =~ s/<(?:\/?)(?:br|p)\s*(?:\/?)>/ /sgi;
1231     $LibraryNameTitle =~ s/<(?:[^<>'"]|'(?:[^']*)'|"(?:[^"]*)")*>//sg;
1232
1233     my $template_name = ( $type eq 'opac' ) ? 'opac-auth.tt' : 'auth.tt';
1234     my $template = C4::Templates::gettemplate( $template_name, $type, $query );
1235     $template->param(
1236         OpacAdditionalStylesheet                   => C4::Context->preference("OpacAdditionalStylesheet"),
1237         opaclayoutstylesheet                  => C4::Context->preference("opaclayoutstylesheet"),
1238         login                                 => 1,
1239         INPUTS                                => \@inputs,
1240         script_name                           => get_script_name(),
1241         casAuthentication                     => C4::Context->preference("casAuthentication"),
1242         shibbolethAuthentication              => $shib,
1243         SessionRestrictionByIP                => C4::Context->preference("SessionRestrictionByIP"),
1244         suggestion                            => C4::Context->preference("suggestion"),
1245         virtualshelves                        => C4::Context->preference("virtualshelves"),
1246         LibraryName                           => "" . C4::Context->preference("LibraryName"),
1247         LibraryNameTitle                      => "" . $LibraryNameTitle,
1248         opacuserlogin                         => C4::Context->preference("opacuserlogin"),
1249         OpacNav                               => C4::Context->preference("OpacNav"),
1250         OpacNavRight                          => C4::Context->preference("OpacNavRight"),
1251         OpacNavBottom                         => C4::Context->preference("OpacNavBottom"),
1252         opaccredits                           => C4::Context->preference("opaccredits"),
1253         OpacFavicon                           => C4::Context->preference("OpacFavicon"),
1254         opacreadinghistory                    => C4::Context->preference("opacreadinghistory"),
1255         opaclanguagesdisplay                  => C4::Context->preference("opaclanguagesdisplay"),
1256         OPACUserJS                            => C4::Context->preference("OPACUserJS"),
1257         opacbookbag                           => "" . C4::Context->preference("opacbookbag"),
1258         OpacCloud                             => C4::Context->preference("OpacCloud"),
1259         OpacTopissue                          => C4::Context->preference("OpacTopissue"),
1260         OpacAuthorities                       => C4::Context->preference("OpacAuthorities"),
1261         OpacBrowser                           => C4::Context->preference("OpacBrowser"),
1262         opacheader                            => C4::Context->preference("opacheader"),
1263         TagsEnabled                           => C4::Context->preference("TagsEnabled"),
1264         OPACUserCSS                           => C4::Context->preference("OPACUserCSS"),
1265         intranetcolorstylesheet               => C4::Context->preference("intranetcolorstylesheet"),
1266         intranetstylesheet                    => C4::Context->preference("intranetstylesheet"),
1267         intranetbookbag                       => C4::Context->preference("intranetbookbag"),
1268         IntranetNav                           => C4::Context->preference("IntranetNav"),
1269         IntranetFavicon                       => C4::Context->preference("IntranetFavicon"),
1270         IntranetUserCSS                       => C4::Context->preference("IntranetUserCSS"),
1271         IntranetUserJS                        => C4::Context->preference("IntranetUserJS"),
1272         IndependentBranches                   => C4::Context->preference("IndependentBranches"),
1273         AutoLocation                          => C4::Context->preference("AutoLocation"),
1274         wrongip                               => $info{'wrongip'},
1275         PatronSelfRegistration                => C4::Context->preference("PatronSelfRegistration"),
1276         PatronSelfRegistrationDefaultCategory => C4::Context->preference("PatronSelfRegistrationDefaultCategory"),
1277         opac_css_override                     => $ENV{'OPAC_CSS_OVERRIDE'},
1278         too_many_login_attempts               => ( $patron and $patron->account_locked )
1279     );
1280
1281     $template->param( SCO_login => 1 ) if ( $query->param('sco_user_login') );
1282     $template->param( SCI_login => 1 ) if ( $query->param('sci_user_login') );
1283     $template->param( OpacPublic => C4::Context->preference("OpacPublic") );
1284     $template->param( loginprompt => 1 ) unless $info{'nopermission'};
1285
1286     if ( $type eq 'opac' ) {
1287         require Koha::Virtualshelves;
1288         my $some_public_shelves = Koha::Virtualshelves->get_some_shelves(
1289             {
1290                 category       => 2,
1291             }
1292         );
1293         $template->param(
1294             some_public_shelves  => $some_public_shelves,
1295         );
1296     }
1297
1298     if ($cas) {
1299
1300         # Is authentication against multiple CAS servers enabled?
1301         if ( C4::Auth_with_cas::multipleAuth && !$casparam ) {
1302             my $casservers = C4::Auth_with_cas::getMultipleAuth();
1303             my @tmplservers;
1304             foreach my $key ( keys %$casservers ) {
1305                 push @tmplservers, { name => $key, value => login_cas_url( $query, $key, $type ) . "?cas=$key" };
1306             }
1307             $template->param(
1308                 casServersLoop => \@tmplservers
1309             );
1310         } else {
1311             $template->param(
1312                 casServerUrl => login_cas_url($query, undef, $type),
1313             );
1314         }
1315
1316         $template->param(
1317             invalidCasLogin => $info{'invalidCasLogin'}
1318         );
1319     }
1320
1321     if ($shib) {
1322         $template->param(
1323             shibbolethAuthentication => $shib,
1324             shibbolethLoginUrl       => login_shib_url($query),
1325         );
1326     }
1327
1328     if (C4::Context->preference('GoogleOpenIDConnect')) {
1329         if ($query->param("OpenIDConnectFailed")) {
1330             my $reason = $query->param('OpenIDConnectFailed');
1331             $template->param(invalidGoogleOpenIDConnectLogin => $reason);
1332         }
1333     }
1334
1335     $template->param(
1336         LibraryName => C4::Context->preference("LibraryName"),
1337     );
1338     $template->param(%info);
1339
1340     #    $cookie = $query->cookie(CGISESSID => $session->id
1341     #   );
1342     print $query->header(
1343         {   type              => 'text/html',
1344             charset           => 'utf-8',
1345             cookie            => $cookie,
1346             'X-Frame-Options' => 'SAMEORIGIN'
1347         }
1348       ),
1349       $template->output;
1350     safe_exit;
1351 }
1352
1353 =head2 check_api_auth
1354
1355   ($status, $cookie, $sessionId) = check_api_auth($query, $userflags);
1356
1357 Given a CGI query containing the parameters 'userid' and 'password' and/or a session
1358 cookie, determine if the user has the privileges specified by C<$userflags>.
1359
1360 C<check_api_auth> is is meant for authenticating users of web services, and
1361 consequently will always return and will not attempt to redirect the user
1362 agent.
1363
1364 If a valid session cookie is already present, check_api_auth will return a status
1365 of "ok", the cookie, and the Koha session ID.
1366
1367 If no session cookie is present, check_api_auth will check the 'userid' and 'password
1368 parameters and create a session cookie and Koha session if the supplied credentials
1369 are OK.
1370
1371 Possible return values in C<$status> are:
1372
1373 =over
1374
1375 =item "ok" -- user authenticated; C<$cookie> and C<$sessionid> have valid values.
1376
1377 =item "failed" -- credentials are not correct; C<$cookie> and C<$sessionid> are undef
1378
1379 =item "maintenance" -- DB is in maintenance mode; no login possible at the moment
1380
1381 =item "expired -- session cookie has expired; API user should resubmit userid and password
1382
1383 =back
1384
1385 =cut
1386
1387 sub check_api_auth {
1388
1389     my $query         = shift;
1390     my $flagsrequired = shift;
1391     my $dbh     = C4::Context->dbh;
1392     my $timeout = _timeout_syspref();
1393
1394     unless ( C4::Context->preference('Version') ) {
1395
1396         # database has not been installed yet
1397         return ( "maintenance", undef, undef );
1398     }
1399     my $kohaversion = Koha::version();
1400     $kohaversion =~ s/(.*\..*)\.(.*)\.(.*)/$1$2$3/;
1401     if ( C4::Context->preference('Version') < $kohaversion ) {
1402
1403         # database in need of version update; assume that
1404         # no API should be called while databsae is in
1405         # this condition.
1406         return ( "maintenance", undef, undef );
1407     }
1408
1409     # FIXME -- most of what follows is a copy-and-paste
1410     # of code from checkauth.  There is an obvious need
1411     # for refactoring to separate the various parts of
1412     # the authentication code, but as of 2007-11-19 this
1413     # is deferred so as to not introduce bugs into the
1414     # regular authentication code for Koha 3.0.
1415
1416     # see if we have a valid session cookie already
1417     # however, if a userid parameter is present (i.e., from
1418     # a form submission, assume that any current cookie
1419     # is to be ignored
1420     my $sessionID = undef;
1421     unless ( $query->param('userid') ) {
1422         $sessionID = $query->cookie("CGISESSID");
1423     }
1424     if ( $sessionID && not( $cas && $query->param('PT') ) ) {
1425         my $session = get_session($sessionID);
1426         C4::Context->_new_userenv($sessionID);
1427         if ($session) {
1428             C4::Context->set_userenv(
1429                 $session->param('number'),       $session->param('id'),
1430                 $session->param('cardnumber'),   $session->param('firstname'),
1431                 $session->param('surname'),      $session->param('branch'),
1432                 $session->param('branchname'),   $session->param('flags'),
1433                 $session->param('emailaddress'), $session->param('branchprinter')
1434             );
1435
1436             my $ip       = $session->param('ip');
1437             my $lasttime = $session->param('lasttime');
1438             my $userid   = $session->param('id');
1439             if ( $lasttime < time() - $timeout ) {
1440
1441                 # time out
1442                 $session->delete();
1443                 $session->flush;
1444                 C4::Context->_unset_userenv($sessionID);
1445                 $userid    = undef;
1446                 $sessionID = undef;
1447                 return ( "expired", undef, undef );
1448             } elsif ( C4::Context->preference('SessionRestrictionByIP') && $ip ne $ENV{'REMOTE_ADDR'} ) {
1449
1450                 # IP address changed
1451                 $session->delete();
1452                 $session->flush;
1453                 C4::Context->_unset_userenv($sessionID);
1454                 $userid    = undef;
1455                 $sessionID = undef;
1456                 return ( "expired", undef, undef );
1457             } else {
1458                 my $cookie = $query->cookie(
1459                     -name     => 'CGISESSID',
1460                     -value    => $session->id,
1461                     -HttpOnly => 1,
1462                 );
1463                 $session->param( 'lasttime', time() );
1464                 my $flags = haspermission( $userid, $flagsrequired );
1465                 if ($flags) {
1466                     return ( "ok", $cookie, $sessionID );
1467                 } else {
1468                     $session->delete();
1469                     $session->flush;
1470                     C4::Context->_unset_userenv($sessionID);
1471                     $userid    = undef;
1472                     $sessionID = undef;
1473                     return ( "failed", undef, undef );
1474                 }
1475             }
1476         } else {
1477             return ( "expired", undef, undef );
1478         }
1479     } else {
1480
1481         # new login
1482         my $userid   = $query->param('userid');
1483         my $password = $query->param('password');
1484         my ( $return, $cardnumber, $cas_ticket );
1485
1486         # Proxy CAS auth
1487         if ( $cas && $query->param('PT') ) {
1488             my $retuserid;
1489             $debug and print STDERR "## check_api_auth - checking CAS\n";
1490
1491             # In case of a CAS authentication, we use the ticket instead of the password
1492             my $PT = $query->param('PT');
1493             ( $return, $cardnumber, $userid, $cas_ticket ) = check_api_auth_cas( $dbh, $PT, $query );    # EXTERNAL AUTH
1494         } else {
1495
1496             # User / password auth
1497             unless ( $userid and $password ) {
1498
1499                 # caller did something wrong, fail the authenticateion
1500                 return ( "failed", undef, undef );
1501             }
1502             my $newuserid;
1503             ( $return, $cardnumber, $newuserid, $cas_ticket ) = checkpw( $dbh, $userid, $password, $query );
1504         }
1505
1506         if ( $return and haspermission( $userid, $flagsrequired ) ) {
1507             my $session = get_session("");
1508             return ( "failed", undef, undef ) unless $session;
1509
1510             my $sessionID = $session->id;
1511             C4::Context->_new_userenv($sessionID);
1512             my $cookie = $query->cookie(
1513                 -name     => 'CGISESSID',
1514                 -value    => $sessionID,
1515                 -HttpOnly => 1,
1516             );
1517             if ( $return == 1 ) {
1518                 my (
1519                     $borrowernumber, $firstname,  $surname,
1520                     $userflags,      $branchcode, $branchname,
1521                     $branchprinter,  $emailaddress
1522                 );
1523                 my $sth =
1524                   $dbh->prepare(
1525 "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=?"
1526                   );
1527                 $sth->execute($userid);
1528                 (
1529                     $borrowernumber, $firstname,  $surname,
1530                     $userflags,      $branchcode, $branchname,
1531                     $branchprinter,  $emailaddress
1532                 ) = $sth->fetchrow if ( $sth->rows );
1533
1534                 unless ( $sth->rows ) {
1535                     my $sth = $dbh->prepare(
1536 "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=?"
1537                     );
1538                     $sth->execute($cardnumber);
1539                     (
1540                         $borrowernumber, $firstname,  $surname,
1541                         $userflags,      $branchcode, $branchname,
1542                         $branchprinter,  $emailaddress
1543                     ) = $sth->fetchrow if ( $sth->rows );
1544
1545                     unless ( $sth->rows ) {
1546                         $sth->execute($userid);
1547                         (
1548                             $borrowernumber, $firstname,  $surname,       $userflags,
1549                             $branchcode,     $branchname, $branchprinter, $emailaddress
1550                         ) = $sth->fetchrow if ( $sth->rows );
1551                     }
1552                 }
1553
1554                 my $ip = $ENV{'REMOTE_ADDR'};
1555
1556                 # if they specify at login, use that
1557                 if ( $query->param('branch') ) {
1558                     $branchcode = $query->param('branch');
1559                     my $library = Koha::Libraries->find($branchcode);
1560                     $branchname = $library? $library->branchname: '';
1561                 }
1562                 my $branches = { map { $_->branchcode => $_->unblessed } Koha::Libraries->search };
1563                 foreach my $br ( keys %$branches ) {
1564
1565                     #     now we work with the treatment of ip
1566                     my $domain = $branches->{$br}->{'branchip'};
1567                     if ( $domain && $ip =~ /^$domain/ ) {
1568                         $branchcode = $branches->{$br}->{'branchcode'};
1569
1570                         # new op dev : add the branchprinter and branchname in the cookie
1571                         $branchprinter = $branches->{$br}->{'branchprinter'};
1572                         $branchname    = $branches->{$br}->{'branchname'};
1573                     }
1574                 }
1575                 $session->param( 'number',       $borrowernumber );
1576                 $session->param( 'id',           $userid );
1577                 $session->param( 'cardnumber',   $cardnumber );
1578                 $session->param( 'firstname',    $firstname );
1579                 $session->param( 'surname',      $surname );
1580                 $session->param( 'branch',       $branchcode );
1581                 $session->param( 'branchname',   $branchname );
1582                 $session->param( 'flags',        $userflags );
1583                 $session->param( 'emailaddress', $emailaddress );
1584                 $session->param( 'ip',           $session->remote_addr() );
1585                 $session->param( 'lasttime',     time() );
1586             }
1587             $session->param( 'cas_ticket', $cas_ticket);
1588             C4::Context->set_userenv(
1589                 $session->param('number'),       $session->param('id'),
1590                 $session->param('cardnumber'),   $session->param('firstname'),
1591                 $session->param('surname'),      $session->param('branch'),
1592                 $session->param('branchname'),   $session->param('flags'),
1593                 $session->param('emailaddress'), $session->param('branchprinter')
1594             );
1595             return ( "ok", $cookie, $sessionID );
1596         } else {
1597             return ( "failed", undef, undef );
1598         }
1599     }
1600 }
1601
1602 =head2 check_cookie_auth
1603
1604   ($status, $sessionId) = check_api_auth($cookie, $userflags);
1605
1606 Given a CGISESSID cookie set during a previous login to Koha, determine
1607 if the user has the privileges specified by C<$userflags>.
1608
1609 C<check_cookie_auth> is meant for authenticating special services
1610 such as tools/upload-file.pl that are invoked by other pages that
1611 have been authenticated in the usual way.
1612
1613 Possible return values in C<$status> are:
1614
1615 =over
1616
1617 =item "ok" -- user authenticated; C<$sessionID> have valid values.
1618
1619 =item "failed" -- credentials are not correct; C<$sessionid> are undef
1620
1621 =item "maintenance" -- DB is in maintenance mode; no login possible at the moment
1622
1623 =item "expired -- session cookie has expired; API user should resubmit userid and password
1624
1625 =back
1626
1627 =cut
1628
1629 sub check_cookie_auth {
1630     my $cookie        = shift;
1631     my $flagsrequired = shift;
1632     my $params        = shift;
1633
1634     my $remote_addr = $params->{remote_addr} || $ENV{REMOTE_ADDR};
1635     my $dbh     = C4::Context->dbh;
1636     my $timeout = _timeout_syspref();
1637
1638     unless ( C4::Context->preference('Version') ) {
1639
1640         # database has not been installed yet
1641         return ( "maintenance", undef );
1642     }
1643     my $kohaversion = Koha::version();
1644     $kohaversion =~ s/(.*\..*)\.(.*)\.(.*)/$1$2$3/;
1645     if ( C4::Context->preference('Version') < $kohaversion ) {
1646
1647         # database in need of version update; assume that
1648         # no API should be called while databsae is in
1649         # this condition.
1650         return ( "maintenance", undef );
1651     }
1652
1653     # FIXME -- most of what follows is a copy-and-paste
1654     # of code from checkauth.  There is an obvious need
1655     # for refactoring to separate the various parts of
1656     # the authentication code, but as of 2007-11-23 this
1657     # is deferred so as to not introduce bugs into the
1658     # regular authentication code for Koha 3.0.
1659
1660     # see if we have a valid session cookie already
1661     # however, if a userid parameter is present (i.e., from
1662     # a form submission, assume that any current cookie
1663     # is to be ignored
1664     unless ( defined $cookie and $cookie ) {
1665         return ( "failed", undef );
1666     }
1667     my $sessionID = $cookie;
1668     my $session   = get_session($sessionID);
1669     C4::Context->_new_userenv($sessionID);
1670     if ($session) {
1671         C4::Context->set_userenv(
1672             $session->param('number'),       $session->param('id'),
1673             $session->param('cardnumber'),   $session->param('firstname'),
1674             $session->param('surname'),      $session->param('branch'),
1675             $session->param('branchname'),   $session->param('flags'),
1676             $session->param('emailaddress'), $session->param('branchprinter')
1677         );
1678
1679         my $ip       = $session->param('ip');
1680         my $lasttime = $session->param('lasttime');
1681         my $userid   = $session->param('id');
1682         if ( $lasttime < time() - $timeout ) {
1683
1684             # time out
1685             $session->delete();
1686             $session->flush;
1687             C4::Context->_unset_userenv($sessionID);
1688             $userid    = undef;
1689             $sessionID = undef;
1690             return ("expired", undef);
1691         } elsif ( C4::Context->preference('SessionRestrictionByIP') && $ip ne $remote_addr ) {
1692
1693             # IP address changed
1694             $session->delete();
1695             $session->flush;
1696             C4::Context->_unset_userenv($sessionID);
1697             $userid    = undef;
1698             $sessionID = undef;
1699             return ( "expired", undef );
1700         } else {
1701             $session->param( 'lasttime', time() );
1702             my $flags = haspermission( $userid, $flagsrequired );
1703             if ($flags) {
1704                 return ( "ok", $sessionID );
1705             } else {
1706                 $session->delete();
1707                 $session->flush;
1708                 C4::Context->_unset_userenv($sessionID);
1709                 $userid    = undef;
1710                 $sessionID = undef;
1711                 return ( "failed", undef );
1712             }
1713         }
1714     } else {
1715         return ( "expired", undef );
1716     }
1717 }
1718
1719 =head2 get_session
1720
1721   use CGI::Session;
1722   my $session = get_session($sessionID);
1723
1724 Given a session ID, retrieve the CGI::Session object used to store
1725 the session's state.  The session object can be used to store
1726 data that needs to be accessed by different scripts during a
1727 user's session.
1728
1729 If the C<$sessionID> parameter is an empty string, a new session
1730 will be created.
1731
1732 =cut
1733
1734 sub _get_session_params {
1735     my $storage_method = C4::Context->preference('SessionStorage');
1736     if ( $storage_method eq 'mysql' ) {
1737         my $dbh = C4::Context->dbh;
1738         return { dsn => "driver:MySQL;serializer:yaml;id:md5", dsn_args => { Handle => $dbh } };
1739     }
1740     elsif ( $storage_method eq 'Pg' ) {
1741         my $dbh = C4::Context->dbh;
1742         return { dsn => "driver:PostgreSQL;serializer:yaml;id:md5", dsn_args => { Handle => $dbh } };
1743     }
1744     elsif ( $storage_method eq 'memcached' && Koha::Caches->get_instance->memcached_cache ) {
1745         my $memcached = Koha::Caches->get_instance()->memcached_cache;
1746         return { dsn => "driver:memcached;serializer:yaml;id:md5", dsn_args => { Memcached => $memcached } };
1747     }
1748     else {
1749         # catch all defaults to tmp should work on all systems
1750         my $dir = C4::Context::temporary_directory;
1751         my $instance = C4::Context->config( 'database' ); #actually for packages not exactly the instance name, but generally safer to leave it as it is
1752         return { dsn => "driver:File;serializer:yaml;id:md5", dsn_args => { Directory => "$dir/cgisess_$instance" } };
1753     }
1754 }
1755
1756 sub get_session {
1757     my $sessionID      = shift;
1758     my $params = _get_session_params();
1759     return new CGI::Session( $params->{dsn}, $sessionID, $params->{dsn_args} );
1760 }
1761
1762
1763 # FIXME no_set_userenv may be replaced with force_branchcode_for_userenv
1764 # (or something similar)
1765 # Currently it's only passed from C4::SIP::ILS::Patron::check_password, but
1766 # not having a userenv defined could cause a crash.
1767 sub checkpw {
1768     my ( $dbh, $userid, $password, $query, $type, $no_set_userenv ) = @_;
1769     $type = 'opac' unless $type;
1770
1771     # Get shibboleth login attribute
1772     my $shib = C4::Context->config('useshibboleth') && shib_ok();
1773     my $shib_login = $shib ? get_login_shib() : undef;
1774
1775     my @return;
1776     my $patron = Koha::Patrons->find({ userid => $userid });
1777     my $check_internal_as_fallback = 0;
1778     my $passwd_ok = 0;
1779     # Note: checkpw_* routines returns:
1780     # 1 if auth is ok
1781     # 0 if auth is nok
1782     # -1 if user bind failed (LDAP only)
1783
1784     if ( $patron and $patron->account_locked ) {
1785         # Nothing to check, account is locked
1786     } elsif ($ldap && defined($password)) {
1787         $debug and print STDERR "## checkpw - checking LDAP\n";
1788         my ( $retval, $retcard, $retuserid ) = checkpw_ldap(@_);    # EXTERNAL AUTH
1789         if ( $retval == 1 ) {
1790             @return = ( $retval, $retcard, $retuserid );
1791             $passwd_ok = 1;
1792         }
1793         $check_internal_as_fallback = 1 if $retval == 0;
1794
1795     } elsif ( $cas && $query && $query->param('ticket') ) {
1796         $debug and print STDERR "## checkpw - checking CAS\n";
1797
1798         # In case of a CAS authentication, we use the ticket instead of the password
1799         my $ticket = $query->param('ticket');
1800         $query->delete('ticket');                                   # remove ticket to come back to original URL
1801         my ( $retval, $retcard, $retuserid, $cas_ticket ) = checkpw_cas( $dbh, $ticket, $query, $type );    # EXTERNAL AUTH
1802         if ( $retval ) {
1803             @return = ( $retval, $retcard, $retuserid, $cas_ticket );
1804         } else {
1805             @return = (0);
1806         }
1807         $passwd_ok = $retval;
1808     }
1809
1810     # If we are in a shibboleth session (shibboleth is enabled, and a shibboleth match attribute is present)
1811     # Check for password to asertain whether we want to be testing against shibboleth or another method this
1812     # time around.
1813     elsif ( $shib && $shib_login && !$password ) {
1814
1815         $debug and print STDERR "## checkpw - checking Shibboleth\n";
1816
1817         # In case of a Shibboleth authentication, we expect a shibboleth user attribute
1818         # (defined under shibboleth mapping in koha-conf.xml) to contain the login of the
1819         # shibboleth-authenticated user
1820
1821         # Then, we check if it matches a valid koha user
1822         if ($shib_login) {
1823             my ( $retval, $retcard, $retuserid ) = C4::Auth_with_shibboleth::checkpw_shib($shib_login);    # EXTERNAL AUTH
1824             if ( $retval ) {
1825                 @return = ( $retval, $retcard, $retuserid );
1826             }
1827             $passwd_ok = $retval;
1828         }
1829     } else {
1830         $check_internal_as_fallback = 1;
1831     }
1832
1833     # INTERNAL AUTH
1834     if ( $check_internal_as_fallback ) {
1835         @return = checkpw_internal( $dbh, $userid, $password, $no_set_userenv);
1836         $passwd_ok = 1 if $return[0] > 0; # 1 or 2
1837     }
1838
1839     if( $patron ) {
1840         if ( $passwd_ok ) {
1841             $patron->update({ login_attempts => 0 });
1842         } else {
1843             $patron->update({ login_attempts => $patron->login_attempts + 1 });
1844         }
1845     }
1846     return @return;
1847 }
1848
1849 sub checkpw_internal {
1850     my ( $dbh, $userid, $password, $no_set_userenv ) = @_;
1851
1852     $password = Encode::encode( 'UTF-8', $password )
1853       if Encode::is_utf8($password);
1854
1855     my $sth =
1856       $dbh->prepare(
1857         "select password,cardnumber,borrowernumber,userid,firstname,surname,borrowers.branchcode,branches.branchname,flags from borrowers join branches on borrowers.branchcode=branches.branchcode where userid=?"
1858       );
1859     $sth->execute($userid);
1860     if ( $sth->rows ) {
1861         my ( $stored_hash, $cardnumber, $borrowernumber, $userid, $firstname,
1862             $surname, $branchcode, $branchname, $flags )
1863           = $sth->fetchrow;
1864
1865         if ( checkpw_hash( $password, $stored_hash ) ) {
1866
1867             C4::Context->set_userenv( "$borrowernumber", $userid, $cardnumber,
1868                 $firstname, $surname, $branchcode, $branchname, $flags ) unless $no_set_userenv;
1869             return 1, $cardnumber, $userid;
1870         }
1871     }
1872     $sth =
1873       $dbh->prepare(
1874         "select password,cardnumber,borrowernumber,userid,firstname,surname,borrowers.branchcode,branches.branchname,flags from borrowers join branches on borrowers.branchcode=branches.branchcode where cardnumber=?"
1875       );
1876     $sth->execute($userid);
1877     if ( $sth->rows ) {
1878         my ( $stored_hash, $cardnumber, $borrowernumber, $userid, $firstname,
1879             $surname, $branchcode, $branchname, $flags )
1880           = $sth->fetchrow;
1881
1882         if ( checkpw_hash( $password, $stored_hash ) ) {
1883
1884             C4::Context->set_userenv( $borrowernumber, $userid, $cardnumber,
1885                 $firstname, $surname, $branchcode, $branchname, $flags ) unless $no_set_userenv;
1886             return 1, $cardnumber, $userid;
1887         }
1888     }
1889     return 0;
1890 }
1891
1892 sub checkpw_hash {
1893     my ( $password, $stored_hash ) = @_;
1894
1895     return if $stored_hash eq '!';
1896
1897     # check what encryption algorithm was implemented: Bcrypt - if the hash starts with '$2' it is Bcrypt else md5
1898     my $hash;
1899     if ( substr( $stored_hash, 0, 2 ) eq '$2' ) {
1900         $hash = hash_password( $password, $stored_hash );
1901     } else {
1902         $hash = md5_base64($password);
1903     }
1904     return $hash eq $stored_hash;
1905 }
1906
1907 =head2 getuserflags
1908
1909     my $authflags = getuserflags($flags, $userid, [$dbh]);
1910
1911 Translates integer flags into permissions strings hash.
1912
1913 C<$flags> is the integer userflags value ( borrowers.userflags )
1914 C<$userid> is the members.userid, used for building subpermissions
1915 C<$authflags> is a hashref of permissions
1916
1917 =cut
1918
1919 sub getuserflags {
1920     my $flags  = shift;
1921     my $userid = shift;
1922     my $dbh    = @_ ? shift : C4::Context->dbh;
1923     my $userflags;
1924     {
1925         # I don't want to do this, but if someone logs in as the database
1926         # user, it would be preferable not to spam them to death with
1927         # numeric warnings. So, we make $flags numeric.
1928         no warnings 'numeric';
1929         $flags += 0;
1930     }
1931     my $sth = $dbh->prepare("SELECT bit, flag, defaulton FROM userflags");
1932     $sth->execute;
1933
1934     while ( my ( $bit, $flag, $defaulton ) = $sth->fetchrow ) {
1935         if ( ( $flags & ( 2**$bit ) ) || $defaulton ) {
1936             $userflags->{$flag} = 1;
1937         }
1938         else {
1939             $userflags->{$flag} = 0;
1940         }
1941     }
1942
1943     # get subpermissions and merge with top-level permissions
1944     my $user_subperms = get_user_subpermissions($userid);
1945     foreach my $module ( keys %$user_subperms ) {
1946         next if $userflags->{$module} == 1;    # user already has permission for everything in this module
1947         $userflags->{$module} = $user_subperms->{$module};
1948     }
1949
1950     return $userflags;
1951 }
1952
1953 =head2 get_user_subpermissions
1954
1955   $user_perm_hashref = get_user_subpermissions($userid);
1956
1957 Given the userid (note, not the borrowernumber) of a staff user,
1958 return a hashref of hashrefs of the specific subpermissions
1959 accorded to the user.  An example return is
1960
1961  {
1962     tools => {
1963         export_catalog => 1,
1964         import_patrons => 1,
1965     }
1966  }
1967
1968 The top-level hash-key is a module or function code from
1969 userflags.flag, while the second-level key is a code
1970 from permissions.
1971
1972 The results of this function do not give a complete picture
1973 of the functions that a staff user can access; it is also
1974 necessary to check borrowers.flags.
1975
1976 =cut
1977
1978 sub get_user_subpermissions {
1979     my $userid = shift;
1980
1981     my $dbh = C4::Context->dbh;
1982     my $sth = $dbh->prepare( "SELECT flag, user_permissions.code
1983                              FROM user_permissions
1984                              JOIN permissions USING (module_bit, code)
1985                              JOIN userflags ON (module_bit = bit)
1986                              JOIN borrowers USING (borrowernumber)
1987                              WHERE userid = ?" );
1988     $sth->execute($userid);
1989
1990     my $user_perms = {};
1991     while ( my $perm = $sth->fetchrow_hashref ) {
1992         $user_perms->{ $perm->{'flag'} }->{ $perm->{'code'} } = 1;
1993     }
1994     return $user_perms;
1995 }
1996
1997 =head2 get_all_subpermissions
1998
1999   my $perm_hashref = get_all_subpermissions();
2000
2001 Returns a hashref of hashrefs defining all specific
2002 permissions currently defined.  The return value
2003 has the same structure as that of C<get_user_subpermissions>,
2004 except that the innermost hash value is the description
2005 of the subpermission.
2006
2007 =cut
2008
2009 sub get_all_subpermissions {
2010     my $dbh = C4::Context->dbh;
2011     my $sth = $dbh->prepare( "SELECT flag, code
2012                              FROM permissions
2013                              JOIN userflags ON (module_bit = bit)" );
2014     $sth->execute();
2015
2016     my $all_perms = {};
2017     while ( my $perm = $sth->fetchrow_hashref ) {
2018         $all_perms->{ $perm->{'flag'} }->{ $perm->{'code'} } = 1;
2019     }
2020     return $all_perms;
2021 }
2022
2023 =head2 haspermission
2024
2025   $flags = ($userid, $flagsrequired);
2026
2027 C<$userid> the userid of the member
2028 C<$flags> is a hashref of required flags like C<$borrower-&lt;{authflags}> 
2029
2030 Returns member's flags or 0 if a permission is not met.
2031
2032 =cut
2033
2034 sub haspermission {
2035     my ( $userid, $flagsrequired ) = @_;
2036     my $sth = C4::Context->dbh->prepare("SELECT flags FROM borrowers WHERE userid=?");
2037     $sth->execute($userid);
2038     my $row = $sth->fetchrow();
2039     my $flags = getuserflags( $row, $userid );
2040
2041     return $flags if $flags->{superlibrarian};
2042
2043     foreach my $module ( keys %$flagsrequired ) {
2044         my $subperm = $flagsrequired->{$module};
2045         if ( $subperm eq '*' ) {
2046             return 0 unless ( $flags->{$module} == 1 or ref( $flags->{$module} ) );
2047         } else {
2048             return 0 unless (
2049                 ( defined $flags->{$module} and
2050                     $flags->{$module} == 1 )
2051                 or
2052                 ( ref( $flags->{$module} ) and
2053                     exists $flags->{$module}->{$subperm} and
2054                     $flags->{$module}->{$subperm} == 1 )
2055             );
2056         }
2057     }
2058     return $flags;
2059
2060     #FIXME - This fcn should return the failed permission so a suitable error msg can be delivered.
2061 }
2062
2063 sub getborrowernumber {
2064     my ($userid) = @_;
2065     my $userenv = C4::Context->userenv;
2066     if ( defined($userenv) && ref($userenv) eq 'HASH' && $userenv->{number} ) {
2067         return $userenv->{number};
2068     }
2069     my $dbh = C4::Context->dbh;
2070     for my $field ( 'userid', 'cardnumber' ) {
2071         my $sth =
2072           $dbh->prepare("select borrowernumber from borrowers where $field=?");
2073         $sth->execute($userid);
2074         if ( $sth->rows ) {
2075             my ($bnumber) = $sth->fetchrow;
2076             return $bnumber;
2077         }
2078     }
2079     return 0;
2080 }
2081
2082 =head2 track_login_daily
2083
2084     track_login_daily( $userid );
2085
2086 Wraps the call to $patron->track_login, the method used to update borrowers.lastseen. We only call track_login once a day.
2087
2088 =cut
2089
2090 sub track_login_daily {
2091     my $userid = shift;
2092     return if !$userid || !C4::Context->preference('TrackLastPatronActivity');
2093
2094     my $cache     = Koha::Caches->get_instance();
2095     my $cache_key = "track_login_" . $userid;
2096     my $cached    = $cache->get_from_cache($cache_key);
2097     my $today = dt_from_string()->ymd;
2098     return if $cached && $cached eq $today;
2099
2100     my $patron = Koha::Patrons->find({ userid => $userid });
2101     return unless $patron;
2102     $patron->track_login;
2103     $cache->set_in_cache( $cache_key, $today );
2104 }
2105
2106 END { }    # module clean-up code here (global destructor)
2107 1;
2108 __END__
2109
2110 =head1 SEE ALSO
2111
2112 CGI(3)
2113
2114 C4::Output(3)
2115
2116 Crypt::Eksblowfish::Bcrypt(3)
2117
2118 Digest::MD5(3)
2119
2120 =cut