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