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