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