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