Bug 24786: Allow setting a register for the session
[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 = CGI->new;
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                 $session->param('register_id')
872             );
873             C4::Context::set_shelves_userenv( 'bar', $session->param('barshelves') );
874             C4::Context::set_shelves_userenv( 'pub', $session->param('pubshelves') );
875             C4::Context::set_shelves_userenv( 'tot', $session->param('totshelves') );
876             $debug and printf STDERR "AUTH_SESSION: (%s)\t%s %s - %s\n", map { $session->param($_) } qw(cardnumber firstname surname branch);
877             $ip          = $session->param('ip');
878             $lasttime    = $session->param('lasttime');
879             $userid      = $s_userid;
880             $sessiontype = $session->param('sessiontype') || '';
881         }
882         if ( ( $query->param('koha_login_context') && ( $q_userid ne $s_userid ) )
883             || ( $cas && $query->param('ticket') && !C4::Context->userenv->{'id'} )
884             || ( $shib && $shib_login && !$logout && !C4::Context->userenv->{'id'} )
885         ) {
886
887             #if a user enters an id ne to the id in the current session, we need to log them in...
888             #first we need to clear the anonymous session...
889             $debug and warn "query id = $q_userid but session id = $s_userid";
890             $anon_search_history = $session->param('search_history');
891             $session->delete();
892             $session->flush;
893             C4::Context->_unset_userenv($sessionID);
894             $sessionID = undef;
895             $userid    = undef;
896         }
897         elsif ($logout) {
898
899             # voluntary logout the user
900             # check wether the user was using their shibboleth session or a local one
901             my $shibSuccess = C4::Context->userenv->{'shibboleth'};
902             $session->delete();
903             $session->flush;
904             C4::Context->_unset_userenv($sessionID);
905
906             #_session_log(sprintf "%20s from %16s logged out at %30s (manually).\n", $userid,$ip,(strftime "%c",localtime));
907             $sessionID = undef;
908             $userid    = undef;
909
910             if ($cas and $caslogout) {
911                 logout_cas($query, $type);
912             }
913
914             # If we are in a shibboleth session (shibboleth is enabled, a shibboleth match attribute is set and matches koha matchpoint)
915             if ( $shib and $shib_login and $shibSuccess) {
916                 logout_shib($query);
917             }
918         }
919         elsif ( !$lasttime || ( $lasttime < time() - $timeout ) ) {
920
921             # timed logout
922             $info{'timed_out'} = 1;
923             if ($session) {
924                 $session->delete();
925                 $session->flush;
926             }
927             C4::Context->_unset_userenv($sessionID);
928
929             #_session_log(sprintf "%20s from %16s logged out at %30s (inactivity).\n", $userid,$ip,(strftime "%c",localtime));
930             $userid    = undef;
931             $sessionID = undef;
932         }
933         elsif ( C4::Context->preference('SessionRestrictionByIP') && $ip ne $ENV{'REMOTE_ADDR'} ) {
934
935             # Different ip than originally logged in from
936             $info{'oldip'}        = $ip;
937             $info{'newip'}        = $ENV{'REMOTE_ADDR'};
938             $info{'different_ip'} = 1;
939             $session->delete();
940             $session->flush;
941             C4::Context->_unset_userenv($sessionID);
942
943             #_session_log(sprintf "%20s from %16s logged out at %30s (ip changed to %16s).\n", $userid,$ip,(strftime "%c",localtime), $info{'newip'});
944             $sessionID = undef;
945             $userid    = undef;
946         }
947         else {
948             $cookie = $query->cookie(
949                 -name     => 'CGISESSID',
950                 -value    => $session->id,
951                 -HttpOnly => 1,
952                 -secure => ( C4::Context->https_enabled() ? 1 : 0 ),
953             );
954             $session->param( 'lasttime', time() );
955             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...
956                 $flags = haspermission( $userid, $flagsrequired );
957                 if ($flags) {
958                     $loggedin = 1;
959                 } else {
960                     $info{'nopermission'} = 1;
961                 }
962             }
963         }
964     }
965     unless ( $userid || $sessionID ) {
966         #we initiate a session prior to checking for a username to allow for anonymous sessions...
967         my $session = get_session("") or die "Auth ERROR: Cannot get_session()";
968
969         # Save anonymous search history in new session so it can be retrieved
970         # by get_template_and_user to store it in user's search history after
971         # a successful login.
972         if ($anon_search_history) {
973             $session->param( 'search_history', $anon_search_history );
974         }
975
976         $sessionID = $session->id;
977         C4::Context->_new_userenv($sessionID);
978         $cookie = $query->cookie(
979             -name     => 'CGISESSID',
980             -value    => $session->id,
981             -HttpOnly => 1,
982             -secure => ( C4::Context->https_enabled() ? 1 : 0 ),
983         );
984         my $pki_field = C4::Context->preference('AllowPKIAuth');
985         if ( !defined($pki_field) ) {
986             print STDERR "ERROR: Missing system preference AllowPKIAuth.\n";
987             $pki_field = 'None';
988         }
989         if ( ( $cas && $query->param('ticket') )
990             || $q_userid
991             || ( $shib && $shib_login )
992             || $pki_field ne 'None'
993             || $emailaddress )
994         {
995             my $password    = $query->param('password');
996             my $shibSuccess = 0;
997             my ( $return, $cardnumber );
998
999             # If shib is enabled and we have a shib login, does the login match a valid koha user
1000             if ( $shib && $shib_login ) {
1001                 my $retuserid;
1002
1003                 # Do not pass password here, else shib will not be checked in checkpw.
1004                 ( $return, $cardnumber, $retuserid ) = checkpw( $dbh, $q_userid, undef, $query );
1005                 $userid      = $retuserid;
1006                 $shibSuccess = $return;
1007                 $info{'invalidShibLogin'} = 1 unless ($return);
1008             }
1009
1010             # If shib login and match were successful, skip further login methods
1011             unless ($shibSuccess) {
1012                 if ( $cas && $query->param('ticket') ) {
1013                     my $retuserid;
1014                     ( $return, $cardnumber, $retuserid, $cas_ticket ) =
1015                       checkpw( $dbh, $userid, $password, $query, $type );
1016                     $userid = $retuserid;
1017                     $info{'invalidCasLogin'} = 1 unless ($return);
1018                 }
1019
1020                 elsif ( $emailaddress ) {
1021                     my $value = $emailaddress;
1022
1023                     # If we're looking up the email, there's a chance that the person
1024                     # doesn't have a userid. So if there is none, we pass along the
1025                     # borrower number, and the bits of code that need to know the user
1026                     # ID will have to be smart enough to handle that.
1027                     my $patrons = Koha::Patrons->search({ email => $value });
1028                     if ($patrons->count) {
1029
1030                         # First the userid, then the borrowernum
1031                         my $patron = $patrons->next;
1032                         $value = $patron->userid || $patron->borrowernumber;
1033                     } else {
1034                         undef $value;
1035                     }
1036                     $return = $value ? 1 : 0;
1037                     $userid = $value;
1038                 }
1039
1040                 elsif (
1041                     ( $pki_field eq 'Common Name' && $ENV{'SSL_CLIENT_S_DN_CN'} )
1042                     || ( $pki_field eq 'emailAddress'
1043                         && $ENV{'SSL_CLIENT_S_DN_Email'} )
1044                   )
1045                 {
1046                     my $value;
1047                     if ( $pki_field eq 'Common Name' ) {
1048                         $value = $ENV{'SSL_CLIENT_S_DN_CN'};
1049                     }
1050                     elsif ( $pki_field eq 'emailAddress' ) {
1051                         $value = $ENV{'SSL_CLIENT_S_DN_Email'};
1052
1053                         # If we're looking up the email, there's a chance that the person
1054                         # doesn't have a userid. So if there is none, we pass along the
1055                         # borrower number, and the bits of code that need to know the user
1056                         # ID will have to be smart enough to handle that.
1057                         my $patrons = Koha::Patrons->search({ email => $value });
1058                         if ($patrons->count) {
1059
1060                             # First the userid, then the borrowernum
1061                             my $patron = $patrons->next;
1062                             $value = $patron->userid || $patron->borrowernumber;
1063                         } else {
1064                             undef $value;
1065                         }
1066                     }
1067
1068                     $return = $value ? 1 : 0;
1069                     $userid = $value;
1070
1071                 }
1072                 else {
1073                     my $retuserid;
1074                     ( $return, $cardnumber, $retuserid, $cas_ticket ) =
1075                       checkpw( $dbh, $q_userid, $password, $query, $type );
1076                     $userid = $retuserid if ($retuserid);
1077                     $info{'invalid_username_or_password'} = 1 unless ($return);
1078                 }
1079             }
1080
1081             # $return: 1 = valid user
1082             if ($return) {
1083
1084                 #_session_log(sprintf "%20s from %16s logged in  at %30s.\n", $userid,$ENV{'REMOTE_ADDR'},(strftime '%c', localtime));
1085                 if ( $flags = haspermission( $userid, $flagsrequired ) ) {
1086                     $loggedin = 1;
1087                 }
1088                 else {
1089                     $info{'nopermission'} = 1;
1090                     C4::Context->_unset_userenv($sessionID);
1091                 }
1092                 my ( $borrowernumber, $firstname, $surname, $userflags,
1093                     $branchcode, $branchname, $emailaddress, $desk_id,
1094                     $desk_name, $register_id );
1095
1096                 if ( $return == 1 ) {
1097                     my $select = "
1098                     SELECT borrowernumber, firstname, surname, flags, borrowers.branchcode,
1099                     branches.branchname    as branchname, email
1100                     FROM borrowers
1101                     LEFT JOIN branches on borrowers.branchcode=branches.branchcode
1102                     ";
1103                     my $sth = $dbh->prepare("$select where userid=?");
1104                     $sth->execute($userid);
1105                     unless ( $sth->rows ) {
1106                         $debug and print STDERR "AUTH_1: no rows for userid='$userid'\n";
1107                         $sth = $dbh->prepare("$select where cardnumber=?");
1108                         $sth->execute($cardnumber);
1109
1110                         unless ( $sth->rows ) {
1111                             $debug and print STDERR "AUTH_2a: no rows for cardnumber='$cardnumber'\n";
1112                             $sth->execute($userid);
1113                             unless ( $sth->rows ) {
1114                                 $debug and print STDERR "AUTH_2b: no rows for userid='$userid' AS cardnumber\n";
1115                             }
1116                         }
1117                     }
1118                     if ( $sth->rows ) {
1119                         ( $borrowernumber, $firstname, $surname, $userflags,
1120                             $branchcode, $branchname, $emailaddress ) = $sth->fetchrow;
1121                         $debug and print STDERR "AUTH_3 results: " .
1122                           "$cardnumber,$borrowernumber,$userid,$firstname,$surname,$userflags,$branchcode,$emailaddress\n";
1123                     } else {
1124                         print STDERR "AUTH_3: no results for userid='$userid', cardnumber='$cardnumber'.\n";
1125                     }
1126
1127                     # launch a sequence to check if we have a ip for the branch, i
1128                     # if we have one we replace the branchcode of the userenv by the branch bound in the ip.
1129
1130                     my $ip = $ENV{'REMOTE_ADDR'};
1131
1132                     # if they specify at login, use that
1133                     if ( $query->param('branch') ) {
1134                         $branchcode = $query->param('branch');
1135                         my $library = Koha::Libraries->find($branchcode);
1136                         $branchname = $library? $library->branchname: '';
1137                     }
1138                     if ( $query->param('desk_id') ) {
1139                         $desk_id = $query->param('desk_id');
1140                         my $desk = Koha::Desks->find($desk_id);
1141                         $desk_name = $desk ? $desk->desk_name : '';
1142                     }
1143                     if ( $query->param('register_id') ) {
1144                         $register_id = $query->param('register_id');
1145                     }
1146                     my $branches = { map { $_->branchcode => $_->unblessed } Koha::Libraries->search };
1147                     if ( $type ne 'opac' and C4::Context->boolean_preference('AutoLocation') ) {
1148
1149                         # we have to check they are coming from the right ip range
1150                         my $domain = $branches->{$branchcode}->{'branchip'};
1151                         $domain =~ s|\.\*||g;
1152                         if ( $ip !~ /^$domain/ ) {
1153                             $loggedin = 0;
1154                             $cookie = $query->cookie(
1155                                 -name     => 'CGISESSID',
1156                                 -value    => '',
1157                                 -HttpOnly => 1,
1158                                 -secure => ( C4::Context->https_enabled() ? 1 : 0 ),
1159                             );
1160                             $info{'wrongip'} = 1;
1161                         }
1162                     }
1163
1164                     foreach my $br ( keys %$branches ) {
1165
1166                         #     now we work with the treatment of ip
1167                         my $domain = $branches->{$br}->{'branchip'};
1168                         if ( $domain && $ip =~ /^$domain/ ) {
1169                             $branchcode = $branches->{$br}->{'branchcode'};
1170
1171                             # new op dev : add the branchname to the cookie
1172                             $branchname    = $branches->{$br}->{'branchname'};
1173                         }
1174                     }
1175                     $session->param( 'number',       $borrowernumber );
1176                     $session->param( 'id',           $userid );
1177                     $session->param( 'cardnumber',   $cardnumber );
1178                     $session->param( 'firstname',    $firstname );
1179                     $session->param( 'surname',      $surname );
1180                     $session->param( 'branch',       $branchcode );
1181                     $session->param( 'branchname',   $branchname );
1182                     $session->param( 'desk_id',      $desk_id);
1183                     $session->param( 'desk_name',     $desk_name);
1184                     $session->param( 'flags',        $userflags );
1185                     $session->param( 'emailaddress', $emailaddress );
1186                     $session->param( 'ip',           $session->remote_addr() );
1187                     $session->param( 'lasttime',     time() );
1188                     $session->param( 'interface',    $type);
1189                     $session->param( 'shibboleth',   $shibSuccess );
1190                     $session->param( 'register_id',  $register_id );
1191                     $debug and printf STDERR "AUTH_4: (%s)\t%s %s - %s\n", map { $session->param($_) } qw(cardnumber firstname surname branch);
1192                 }
1193                 $session->param('cas_ticket', $cas_ticket) if $cas_ticket;
1194                 C4::Context->set_userenv(
1195                     $session->param('number'),       $session->param('id'),
1196                     $session->param('cardnumber'),   $session->param('firstname'),
1197                     $session->param('surname'),      $session->param('branch'),
1198                     $session->param('branchname'),   $session->param('flags'),
1199                     $session->param('emailaddress'), $session->param('shibboleth'),
1200                     $session->param('desk_id'),      $session->param('desk_name'),
1201                     $session->param('register_id')
1202                 );
1203
1204             }
1205             # $return: 0 = invalid user
1206             # reset to anonymous session
1207             else {
1208                 $debug and warn "Login failed, resetting anonymous session...";
1209                 if ($userid) {
1210                     $info{'invalid_username_or_password'} = 1;
1211                     C4::Context->_unset_userenv($sessionID);
1212                 }
1213                 $session->param( 'lasttime', time() );
1214                 $session->param( 'ip',       $session->remote_addr() );
1215                 $session->param( 'sessiontype', 'anon' );
1216                 $session->param( 'interface', $type);
1217             }
1218         }    # END if ( $q_userid
1219         elsif ( $type eq "opac" ) {
1220
1221             # if we are here this is an anonymous session; add public lists to it and a few other items...
1222             # anonymous sessions are created only for the OPAC
1223             $debug and warn "Initiating an anonymous session...";
1224
1225             # setting a couple of other session vars...
1226             $session->param( 'ip',          $session->remote_addr() );
1227             $session->param( 'lasttime',    time() );
1228             $session->param( 'sessiontype', 'anon' );
1229             $session->param( 'interface', $type);
1230         }
1231     }    # END unless ($userid)
1232
1233     # finished authentification, now respond
1234     if ( $loggedin || $authnotrequired )
1235     {
1236         # successful login
1237         unless ($cookie) {
1238             $cookie = $query->cookie(
1239                 -name     => 'CGISESSID',
1240                 -value    => '',
1241                 -HttpOnly => 1,
1242                 -secure => ( C4::Context->https_enabled() ? 1 : 0 ),
1243             );
1244         }
1245
1246         track_login_daily( $userid );
1247
1248         # In case, that this request was a login attempt, we want to prevent that users can repost the opac login
1249         # request. We therefore redirect the user to the requested page again without the login parameters.
1250         # See Post/Redirect/Get (PRG) design pattern: https://en.wikipedia.org/wiki/Post/Redirect/Get
1251         if ( $type eq "opac" && $query->param('koha_login_context') && $query->param('koha_login_context') ne 'sco' && $query->param('password') && $query->param('userid') ) {
1252             my $uri = URI->new($query->url(-relative=>1, -query_string=>1));
1253             $uri->query_param_delete('userid');
1254             $uri->query_param_delete('password');
1255             $uri->query_param_delete('koha_login_context');
1256             print $query->redirect(-uri => $uri->as_string, -cookie => $cookie, -status=>'303 See other');
1257             exit;
1258         }
1259
1260         return ( $userid, $cookie, $sessionID, $flags );
1261     }
1262
1263     #
1264     #
1265     # AUTH rejected, show the login/password template, after checking the DB.
1266     #
1267     #
1268
1269     # get the inputs from the incoming query
1270     my @inputs = ();
1271     foreach my $name ( param $query) {
1272         (next) if ( $name eq 'userid' || $name eq 'password' || $name eq 'ticket' );
1273         my @value = $query->multi_param($name);
1274         push @inputs, { name => $name, value => $_ } for @value;
1275     }
1276
1277     my $patron = Koha::Patrons->find({ userid => $q_userid }); # Not necessary logged in!
1278
1279     my $LibraryNameTitle = C4::Context->preference("LibraryName");
1280     $LibraryNameTitle =~ s/<(?:\/?)(?:br|p)\s*(?:\/?)>/ /sgi;
1281     $LibraryNameTitle =~ s/<(?:[^<>'"]|'(?:[^']*)'|"(?:[^"]*)")*>//sg;
1282
1283     my $auth_template_name = ( $type eq 'opac' ) ? 'opac-auth.tt' : 'auth.tt';
1284     my $template = C4::Templates::gettemplate( $auth_template_name, $type, $query );
1285     $template->param(
1286         login                                 => 1,
1287         INPUTS                                => \@inputs,
1288         script_name                           => get_script_name(),
1289         casAuthentication                     => C4::Context->preference("casAuthentication"),
1290         shibbolethAuthentication              => $shib,
1291         SessionRestrictionByIP                => C4::Context->preference("SessionRestrictionByIP"),
1292         suggestion                            => C4::Context->preference("suggestion"),
1293         virtualshelves                        => C4::Context->preference("virtualshelves"),
1294         LibraryName                           => "" . C4::Context->preference("LibraryName"),
1295         LibraryNameTitle                      => "" . $LibraryNameTitle,
1296         opacuserlogin                         => C4::Context->preference("opacuserlogin"),
1297         OpacNav                               => C4::Context->preference("OpacNav"),
1298         OpacNavBottom                         => C4::Context->preference("OpacNavBottom"),
1299         OpacFavicon                           => C4::Context->preference("OpacFavicon"),
1300         opacreadinghistory                    => C4::Context->preference("opacreadinghistory"),
1301         opaclanguagesdisplay                  => C4::Context->preference("opaclanguagesdisplay"),
1302         OPACUserJS                            => C4::Context->preference("OPACUserJS"),
1303         opacbookbag                           => "" . C4::Context->preference("opacbookbag"),
1304         OpacCloud                             => C4::Context->preference("OpacCloud"),
1305         OpacTopissue                          => C4::Context->preference("OpacTopissue"),
1306         OpacAuthorities                       => C4::Context->preference("OpacAuthorities"),
1307         OpacBrowser                           => C4::Context->preference("OpacBrowser"),
1308         TagsEnabled                           => C4::Context->preference("TagsEnabled"),
1309         OPACUserCSS                           => C4::Context->preference("OPACUserCSS"),
1310         intranetcolorstylesheet               => C4::Context->preference("intranetcolorstylesheet"),
1311         intranetstylesheet                    => C4::Context->preference("intranetstylesheet"),
1312         intranetbookbag                       => C4::Context->preference("intranetbookbag"),
1313         IntranetNav                           => C4::Context->preference("IntranetNav"),
1314         IntranetFavicon                       => C4::Context->preference("IntranetFavicon"),
1315         IntranetUserCSS                       => C4::Context->preference("IntranetUserCSS"),
1316         IntranetUserJS                        => C4::Context->preference("IntranetUserJS"),
1317         IndependentBranches                   => C4::Context->preference("IndependentBranches"),
1318         AutoLocation                          => C4::Context->preference("AutoLocation"),
1319         wrongip                               => $info{'wrongip'},
1320         PatronSelfRegistration                => C4::Context->preference("PatronSelfRegistration"),
1321         PatronSelfRegistrationDefaultCategory => C4::Context->preference("PatronSelfRegistrationDefaultCategory"),
1322         opac_css_override                     => $ENV{'OPAC_CSS_OVERRIDE'},
1323         too_many_login_attempts               => ( $patron and $patron->account_locked )
1324     );
1325
1326     $template->param( SCO_login => 1 ) if ( $query->param('sco_user_login') );
1327     $template->param( SCI_login => 1 ) if ( $query->param('sci_user_login') );
1328     $template->param( OpacPublic => C4::Context->preference("OpacPublic") );
1329     $template->param( loginprompt => 1 ) unless $info{'nopermission'};
1330
1331     if ( $type eq 'opac' ) {
1332         require Koha::Virtualshelves;
1333         my $some_public_shelves = Koha::Virtualshelves->get_some_shelves(
1334             {
1335                 category       => 2,
1336             }
1337         );
1338         $template->param(
1339             some_public_shelves  => $some_public_shelves,
1340         );
1341     }
1342
1343     if ($cas) {
1344
1345         # Is authentication against multiple CAS servers enabled?
1346         if ( C4::Auth_with_cas::multipleAuth && !$casparam ) {
1347             my $casservers = C4::Auth_with_cas::getMultipleAuth();
1348             my @tmplservers;
1349             foreach my $key ( keys %$casservers ) {
1350                 push @tmplservers, { name => $key, value => login_cas_url( $query, $key, $type ) . "?cas=$key" };
1351             }
1352             $template->param(
1353                 casServersLoop => \@tmplservers
1354             );
1355         } else {
1356             $template->param(
1357                 casServerUrl => login_cas_url($query, undef, $type),
1358             );
1359         }
1360
1361         $template->param(
1362             invalidCasLogin => $info{'invalidCasLogin'}
1363         );
1364     }
1365
1366     if ($shib) {
1367         $template->param(
1368             shibbolethAuthentication => $shib,
1369             shibbolethLoginUrl       => login_shib_url($query),
1370         );
1371     }
1372
1373     if (C4::Context->preference('GoogleOpenIDConnect')) {
1374         if ($query->param("OpenIDConnectFailed")) {
1375             my $reason = $query->param('OpenIDConnectFailed');
1376             $template->param(invalidGoogleOpenIDConnectLogin => $reason);
1377         }
1378     }
1379
1380     $template->param(
1381         LibraryName => C4::Context->preference("LibraryName"),
1382     );
1383     $template->param(%info);
1384
1385     #    $cookie = $query->cookie(CGISESSID => $session->id
1386     #   );
1387     print $query->header(
1388         {   type              => 'text/html',
1389             charset           => 'utf-8',
1390             cookie            => $cookie,
1391             'X-Frame-Options' => 'SAMEORIGIN'
1392         }
1393       ),
1394       $template->output;
1395     safe_exit;
1396 }
1397
1398 =head2 check_api_auth
1399
1400   ($status, $cookie, $sessionId) = check_api_auth($query, $userflags);
1401
1402 Given a CGI query containing the parameters 'userid' and 'password' and/or a session
1403 cookie, determine if the user has the privileges specified by C<$userflags>.
1404
1405 C<check_api_auth> is is meant for authenticating users of web services, and
1406 consequently will always return and will not attempt to redirect the user
1407 agent.
1408
1409 If a valid session cookie is already present, check_api_auth will return a status
1410 of "ok", the cookie, and the Koha session ID.
1411
1412 If no session cookie is present, check_api_auth will check the 'userid' and 'password
1413 parameters and create a session cookie and Koha session if the supplied credentials
1414 are OK.
1415
1416 Possible return values in C<$status> are:
1417
1418 =over
1419
1420 =item "ok" -- user authenticated; C<$cookie> and C<$sessionid> have valid values.
1421
1422 =item "failed" -- credentials are not correct; C<$cookie> and C<$sessionid> are undef
1423
1424 =item "maintenance" -- DB is in maintenance mode; no login possible at the moment
1425
1426 =item "expired -- session cookie has expired; API user should resubmit userid and password
1427
1428 =back
1429
1430 =cut
1431
1432 sub check_api_auth {
1433
1434     my $query         = shift;
1435     my $flagsrequired = shift;
1436     my $dbh     = C4::Context->dbh;
1437     my $timeout = _timeout_syspref();
1438
1439     unless ( C4::Context->preference('Version') ) {
1440
1441         # database has not been installed yet
1442         return ( "maintenance", undef, undef );
1443     }
1444     my $kohaversion = Koha::version();
1445     $kohaversion =~ s/(.*\..*)\.(.*)\.(.*)/$1$2$3/;
1446     if ( C4::Context->preference('Version') < $kohaversion ) {
1447
1448         # database in need of version update; assume that
1449         # no API should be called while databsae is in
1450         # this condition.
1451         return ( "maintenance", undef, undef );
1452     }
1453
1454     # FIXME -- most of what follows is a copy-and-paste
1455     # of code from checkauth.  There is an obvious need
1456     # for refactoring to separate the various parts of
1457     # the authentication code, but as of 2007-11-19 this
1458     # is deferred so as to not introduce bugs into the
1459     # regular authentication code for Koha 3.0.
1460
1461     # see if we have a valid session cookie already
1462     # however, if a userid parameter is present (i.e., from
1463     # a form submission, assume that any current cookie
1464     # is to be ignored
1465     my $sessionID = undef;
1466     unless ( $query->param('userid') ) {
1467         $sessionID = $query->cookie("CGISESSID");
1468     }
1469     if ( $sessionID && not( $cas && $query->param('PT') ) ) {
1470         my $session = get_session($sessionID);
1471         C4::Context->_new_userenv($sessionID);
1472         if ($session) {
1473             C4::Context->interface($session->param('interface'));
1474             C4::Context->set_userenv(
1475                 $session->param('number'),       $session->param('id'),
1476                 $session->param('cardnumber'),   $session->param('firstname'),
1477                 $session->param('surname'),      $session->param('branch'),
1478                 $session->param('branchname'),   $session->param('flags'),
1479                 $session->param('emailaddress'), $session->param('shibboleth'),
1480                 $session->param('desk_id'),      $session->param('desk_name'),
1481                 $session->param('register_id')
1482             );
1483
1484             my $ip       = $session->param('ip');
1485             my $lasttime = $session->param('lasttime');
1486             my $userid   = $session->param('id');
1487             if ( $lasttime < time() - $timeout ) {
1488
1489                 # time out
1490                 $session->delete();
1491                 $session->flush;
1492                 C4::Context->_unset_userenv($sessionID);
1493                 $userid    = undef;
1494                 $sessionID = undef;
1495                 return ( "expired", undef, undef );
1496             } elsif ( C4::Context->preference('SessionRestrictionByIP') && $ip ne $ENV{'REMOTE_ADDR'} ) {
1497
1498                 # IP address changed
1499                 $session->delete();
1500                 $session->flush;
1501                 C4::Context->_unset_userenv($sessionID);
1502                 $userid    = undef;
1503                 $sessionID = undef;
1504                 return ( "expired", undef, undef );
1505             } else {
1506                 my $cookie = $query->cookie(
1507                     -name     => 'CGISESSID',
1508                     -value    => $session->id,
1509                     -HttpOnly => 1,
1510                     -secure => ( C4::Context->https_enabled() ? 1 : 0 ),
1511                 );
1512                 $session->param( 'lasttime', time() );
1513                 my $flags = haspermission( $userid, $flagsrequired );
1514                 if ($flags) {
1515                     return ( "ok", $cookie, $sessionID );
1516                 } else {
1517                     $session->delete();
1518                     $session->flush;
1519                     C4::Context->_unset_userenv($sessionID);
1520                     $userid    = undef;
1521                     $sessionID = undef;
1522                     return ( "failed", undef, undef );
1523                 }
1524             }
1525         } else {
1526             return ( "expired", undef, undef );
1527         }
1528     } else {
1529
1530         # new login
1531         my $userid   = $query->param('userid');
1532         my $password = $query->param('password');
1533         my ( $return, $cardnumber, $cas_ticket );
1534
1535         # Proxy CAS auth
1536         if ( $cas && $query->param('PT') ) {
1537             my $retuserid;
1538             $debug and print STDERR "## check_api_auth - checking CAS\n";
1539
1540             # In case of a CAS authentication, we use the ticket instead of the password
1541             my $PT = $query->param('PT');
1542             ( $return, $cardnumber, $userid, $cas_ticket ) = check_api_auth_cas( $dbh, $PT, $query );    # EXTERNAL AUTH
1543         } else {
1544
1545             # User / password auth
1546             unless ( $userid and $password ) {
1547
1548                 # caller did something wrong, fail the authenticateion
1549                 return ( "failed", undef, undef );
1550             }
1551             my $newuserid;
1552             ( $return, $cardnumber, $newuserid, $cas_ticket ) = checkpw( $dbh, $userid, $password, $query );
1553         }
1554
1555         if ( $return and haspermission( $userid, $flagsrequired ) ) {
1556             my $session = get_session("");
1557             return ( "failed", undef, undef ) unless $session;
1558
1559             my $sessionID = $session->id;
1560             C4::Context->_new_userenv($sessionID);
1561             my $cookie = $query->cookie(
1562                 -name     => 'CGISESSID',
1563                 -value    => $sessionID,
1564                 -HttpOnly => 1,
1565                 -secure => ( C4::Context->https_enabled() ? 1 : 0 ),
1566             );
1567             if ( $return == 1 ) {
1568                 my (
1569                     $borrowernumber, $firstname,  $surname,
1570                     $userflags,      $branchcode, $branchname,
1571                     $emailaddress
1572                 );
1573                 my $sth =
1574                   $dbh->prepare(
1575 "select borrowernumber, firstname, surname, flags, borrowers.branchcode, branches.branchname as branchname, email from borrowers left join branches on borrowers.branchcode=branches.branchcode where userid=?"
1576                   );
1577                 $sth->execute($userid);
1578                 (
1579                     $borrowernumber, $firstname,  $surname,
1580                     $userflags,      $branchcode, $branchname,
1581                     $emailaddress
1582                 ) = $sth->fetchrow if ( $sth->rows );
1583
1584                 unless ( $sth->rows ) {
1585                     my $sth = $dbh->prepare(
1586 "select borrowernumber, firstname, surname, flags, borrowers.branchcode, branches.branchname as branchname, email from borrowers left join branches on borrowers.branchcode=branches.branchcode where cardnumber=?"
1587                     );
1588                     $sth->execute($cardnumber);
1589                     (
1590                         $borrowernumber, $firstname,  $surname,
1591                         $userflags,      $branchcode, $branchname,
1592                         $emailaddress
1593                     ) = $sth->fetchrow if ( $sth->rows );
1594
1595                     unless ( $sth->rows ) {
1596                         $sth->execute($userid);
1597                         (
1598                             $borrowernumber, $firstname,  $surname,       $userflags,
1599                             $branchcode,     $branchname, $emailaddress
1600                         ) = $sth->fetchrow if ( $sth->rows );
1601                     }
1602                 }
1603
1604                 my $ip = $ENV{'REMOTE_ADDR'};
1605
1606                 # if they specify at login, use that
1607                 if ( $query->param('branch') ) {
1608                     $branchcode = $query->param('branch');
1609                     my $library = Koha::Libraries->find($branchcode);
1610                     $branchname = $library? $library->branchname: '';
1611                 }
1612                 my $branches = { map { $_->branchcode => $_->unblessed } Koha::Libraries->search };
1613                 foreach my $br ( keys %$branches ) {
1614
1615                     #     now we work with the treatment of ip
1616                     my $domain = $branches->{$br}->{'branchip'};
1617                     if ( $domain && $ip =~ /^$domain/ ) {
1618                         $branchcode = $branches->{$br}->{'branchcode'};
1619
1620                         # new op dev : add the branchname to the cookie
1621                         $branchname    = $branches->{$br}->{'branchname'};
1622                     }
1623                 }
1624                 $session->param( 'number',       $borrowernumber );
1625                 $session->param( 'id',           $userid );
1626                 $session->param( 'cardnumber',   $cardnumber );
1627                 $session->param( 'firstname',    $firstname );
1628                 $session->param( 'surname',      $surname );
1629                 $session->param( 'branch',       $branchcode );
1630                 $session->param( 'branchname',   $branchname );
1631                 $session->param( 'flags',        $userflags );
1632                 $session->param( 'emailaddress', $emailaddress );
1633                 $session->param( 'ip',           $session->remote_addr() );
1634                 $session->param( 'lasttime',     time() );
1635                 $session->param( 'interface',    'api'  );
1636             }
1637             $session->param( 'cas_ticket', $cas_ticket);
1638             C4::Context->set_userenv(
1639                 $session->param('number'),       $session->param('id'),
1640                 $session->param('cardnumber'),   $session->param('firstname'),
1641                 $session->param('surname'),      $session->param('branch'),
1642                 $session->param('branchname'),   $session->param('flags'),
1643                 $session->param('emailaddress'), $session->param('shibboleth'),
1644                 $session->param('desk_id'),      $session->param('desk_name'),
1645                 $session->param('register_id')
1646             );
1647             return ( "ok", $cookie, $sessionID );
1648         } else {
1649             return ( "failed", undef, undef );
1650         }
1651     }
1652 }
1653
1654 =head2 check_cookie_auth
1655
1656   ($status, $sessionId) = check_api_auth($cookie, $userflags);
1657
1658 Given a CGISESSID cookie set during a previous login to Koha, determine
1659 if the user has the privileges specified by C<$userflags>. C<$userflags>
1660 is passed unaltered into C<haspermission> and as such accepts all options
1661 avaiable to that routine with the one caveat that C<check_api_auth> will
1662 also allow 'undef' to be passed and in such a case the permissions check
1663 will be skipped altogether.
1664
1665 C<check_cookie_auth> is meant for authenticating special services
1666 such as tools/upload-file.pl that are invoked by other pages that
1667 have been authenticated in the usual way.
1668
1669 Possible return values in C<$status> are:
1670
1671 =over
1672
1673 =item "ok" -- user authenticated; C<$sessionID> have valid values.
1674
1675 =item "failed" -- credentials are not correct; C<$sessionid> are undef
1676
1677 =item "maintenance" -- DB is in maintenance mode; no login possible at the moment
1678
1679 =item "expired -- session cookie has expired; API user should resubmit userid and password
1680
1681 =back
1682
1683 =cut
1684
1685 sub check_cookie_auth {
1686     my $cookie        = shift;
1687     my $flagsrequired = shift;
1688     my $params        = shift;
1689
1690     my $remote_addr = $params->{remote_addr} || $ENV{REMOTE_ADDR};
1691     my $dbh     = C4::Context->dbh;
1692     my $timeout = _timeout_syspref();
1693
1694     unless ( C4::Context->preference('Version') ) {
1695
1696         # database has not been installed yet
1697         return ( "maintenance", undef );
1698     }
1699     my $kohaversion = Koha::version();
1700     $kohaversion =~ s/(.*\..*)\.(.*)\.(.*)/$1$2$3/;
1701     if ( C4::Context->preference('Version') < $kohaversion ) {
1702
1703         # database in need of version update; assume that
1704         # no API should be called while databsae is in
1705         # this condition.
1706         return ( "maintenance", undef );
1707     }
1708
1709     # FIXME -- most of what follows is a copy-and-paste
1710     # of code from checkauth.  There is an obvious need
1711     # for refactoring to separate the various parts of
1712     # the authentication code, but as of 2007-11-23 this
1713     # is deferred so as to not introduce bugs into the
1714     # regular authentication code for Koha 3.0.
1715
1716     # see if we have a valid session cookie already
1717     # however, if a userid parameter is present (i.e., from
1718     # a form submission, assume that any current cookie
1719     # is to be ignored
1720     unless ( defined $cookie and $cookie ) {
1721         return ( "failed", undef );
1722     }
1723     my $sessionID = $cookie;
1724     my $session   = get_session($sessionID);
1725     C4::Context->_new_userenv($sessionID);
1726     if ($session) {
1727         C4::Context->interface($session->param('interface'));
1728         C4::Context->set_userenv(
1729             $session->param('number'),       $session->param('id'),
1730             $session->param('cardnumber'),   $session->param('firstname'),
1731             $session->param('surname'),      $session->param('branch'),
1732             $session->param('branchname'),   $session->param('flags'),
1733             $session->param('emailaddress'), $session->param('shibboleth'),
1734             $session->param('desk_id'),      $session->param('desk_name'),
1735             $session->param('register_id')
1736         );
1737
1738         my $ip       = $session->param('ip');
1739         my $lasttime = $session->param('lasttime');
1740         my $userid   = $session->param('id');
1741         if ( $lasttime < time() - $timeout ) {
1742
1743             # time out
1744             $session->delete();
1745             $session->flush;
1746             C4::Context->_unset_userenv($sessionID);
1747             $userid    = undef;
1748             $sessionID = undef;
1749             return ("expired", undef);
1750         } elsif ( C4::Context->preference('SessionRestrictionByIP') && $ip ne $remote_addr ) {
1751
1752             # IP address changed
1753             $session->delete();
1754             $session->flush;
1755             C4::Context->_unset_userenv($sessionID);
1756             $userid    = undef;
1757             $sessionID = undef;
1758             return ( "expired", undef );
1759         } else {
1760             $session->param( 'lasttime', time() );
1761             my $flags = defined($flagsrequired) ? haspermission( $userid, $flagsrequired ) : 1;
1762             if ($flags) {
1763                 return ( "ok", $sessionID );
1764             } else {
1765                 $session->delete();
1766                 $session->flush;
1767                 C4::Context->_unset_userenv($sessionID);
1768                 $userid    = undef;
1769                 $sessionID = undef;
1770                 return ( "failed", undef );
1771             }
1772         }
1773     } else {
1774         return ( "expired", undef );
1775     }
1776 }
1777
1778 =head2 get_session
1779
1780   use CGI::Session;
1781   my $session = get_session($sessionID);
1782
1783 Given a session ID, retrieve the CGI::Session object used to store
1784 the session's state.  The session object can be used to store
1785 data that needs to be accessed by different scripts during a
1786 user's session.
1787
1788 If the C<$sessionID> parameter is an empty string, a new session
1789 will be created.
1790
1791 =cut
1792
1793 sub _get_session_params {
1794     my $storage_method = C4::Context->preference('SessionStorage');
1795     if ( $storage_method eq 'mysql' ) {
1796         my $dbh = C4::Context->dbh;
1797         return { dsn => "driver:MySQL;serializer:yaml;id:md5", dsn_args => { Handle => $dbh } };
1798     }
1799     elsif ( $storage_method eq 'Pg' ) {
1800         my $dbh = C4::Context->dbh;
1801         return { dsn => "driver:PostgreSQL;serializer:yaml;id:md5", dsn_args => { Handle => $dbh } };
1802     }
1803     elsif ( $storage_method eq 'memcached' && Koha::Caches->get_instance->memcached_cache ) {
1804         my $memcached = Koha::Caches->get_instance()->memcached_cache;
1805         return { dsn => "driver:memcached;serializer:yaml;id:md5", dsn_args => { Memcached => $memcached } };
1806     }
1807     else {
1808         # catch all defaults to tmp should work on all systems
1809         my $dir = C4::Context::temporary_directory;
1810         my $instance = C4::Context->config( 'database' ); #actually for packages not exactly the instance name, but generally safer to leave it as it is
1811         return { dsn => "driver:File;serializer:yaml;id:md5", dsn_args => { Directory => "$dir/cgisess_$instance" } };
1812     }
1813 }
1814
1815 sub get_session {
1816     my $sessionID      = shift;
1817     my $params = _get_session_params();
1818     return CGI::Session->new( $params->{dsn}, $sessionID, $params->{dsn_args} );
1819 }
1820
1821
1822 # FIXME no_set_userenv may be replaced with force_branchcode_for_userenv
1823 # (or something similar)
1824 # Currently it's only passed from C4::SIP::ILS::Patron::check_password, but
1825 # not having a userenv defined could cause a crash.
1826 sub checkpw {
1827     my ( $dbh, $userid, $password, $query, $type, $no_set_userenv ) = @_;
1828     $type = 'opac' unless $type;
1829
1830     # Get shibboleth login attribute
1831     my $shib = C4::Context->config('useshibboleth') && shib_ok();
1832     my $shib_login = $shib ? get_login_shib() : undef;
1833
1834     my @return;
1835     my $patron;
1836     if ( defined $userid ){
1837         $patron = Koha::Patrons->find({ userid => $userid });
1838         $patron = Koha::Patrons->find({ cardnumber => $userid }) unless $patron;
1839     }
1840     my $check_internal_as_fallback = 0;
1841     my $passwd_ok = 0;
1842     # Note: checkpw_* routines returns:
1843     # 1 if auth is ok
1844     # 0 if auth is nok
1845     # -1 if user bind failed (LDAP only)
1846
1847     if ( $patron and $patron->account_locked ) {
1848         # Nothing to check, account is locked
1849     } elsif ($ldap && defined($password)) {
1850         $debug and print STDERR "## checkpw - checking LDAP\n";
1851         my ( $retval, $retcard, $retuserid ) = checkpw_ldap(@_);    # EXTERNAL AUTH
1852         if ( $retval == 1 ) {
1853             @return = ( $retval, $retcard, $retuserid );
1854             $passwd_ok = 1;
1855         }
1856         $check_internal_as_fallback = 1 if $retval == 0;
1857
1858     } elsif ( $cas && $query && $query->param('ticket') ) {
1859         $debug and print STDERR "## checkpw - checking CAS\n";
1860
1861         # In case of a CAS authentication, we use the ticket instead of the password
1862         my $ticket = $query->param('ticket');
1863         $query->delete('ticket');                                   # remove ticket to come back to original URL
1864         my ( $retval, $retcard, $retuserid, $cas_ticket ) = checkpw_cas( $dbh, $ticket, $query, $type );    # EXTERNAL AUTH
1865         if ( $retval ) {
1866             @return = ( $retval, $retcard, $retuserid, $cas_ticket );
1867         } else {
1868             @return = (0);
1869         }
1870         $passwd_ok = $retval;
1871     }
1872
1873     # If we are in a shibboleth session (shibboleth is enabled, and a shibboleth match attribute is present)
1874     # Check for password to asertain whether we want to be testing against shibboleth or another method this
1875     # time around.
1876     elsif ( $shib && $shib_login && !$password ) {
1877
1878         $debug and print STDERR "## checkpw - checking Shibboleth\n";
1879
1880         # In case of a Shibboleth authentication, we expect a shibboleth user attribute
1881         # (defined under shibboleth mapping in koha-conf.xml) to contain the login of the
1882         # shibboleth-authenticated user
1883
1884         # Then, we check if it matches a valid koha user
1885         if ($shib_login) {
1886             my ( $retval, $retcard, $retuserid ) = C4::Auth_with_shibboleth::checkpw_shib($shib_login);    # EXTERNAL AUTH
1887             if ( $retval ) {
1888                 @return = ( $retval, $retcard, $retuserid );
1889             }
1890             $passwd_ok = $retval;
1891         }
1892     } else {
1893         $check_internal_as_fallback = 1;
1894     }
1895
1896     # INTERNAL AUTH
1897     if ( $check_internal_as_fallback ) {
1898         @return = checkpw_internal( $dbh, $userid, $password, $no_set_userenv);
1899         $passwd_ok = 1 if $return[0] > 0; # 1 or 2
1900     }
1901
1902     if( $patron ) {
1903         if ( $passwd_ok ) {
1904             $patron->update({ login_attempts => 0 });
1905         } elsif( !$patron->account_locked ) {
1906             $patron->update({ login_attempts => $patron->login_attempts + 1 });
1907         }
1908     }
1909
1910     # Optionally log success or failure
1911     if( $patron && $passwd_ok && C4::Context->preference('AuthSuccessLog') ) {
1912         logaction( 'AUTH', 'SUCCESS', $patron->id, "Valid password for $userid", $type );
1913     } elsif( !$passwd_ok && C4::Context->preference('AuthFailureLog') ) {
1914         logaction( 'AUTH', 'FAILURE', $patron ? $patron->id : 0, "Wrong password for $userid", $type );
1915     }
1916
1917     return @return;
1918 }
1919
1920 sub checkpw_internal {
1921     my ( $dbh, $userid, $password, $no_set_userenv ) = @_;
1922
1923     $password = Encode::encode( 'UTF-8', $password )
1924       if Encode::is_utf8($password);
1925
1926     my $sth =
1927       $dbh->prepare(
1928         "select password,cardnumber,borrowernumber,userid,firstname,surname,borrowers.branchcode,branches.branchname,flags from borrowers join branches on borrowers.branchcode=branches.branchcode where userid=?"
1929       );
1930     $sth->execute($userid);
1931     if ( $sth->rows ) {
1932         my ( $stored_hash, $cardnumber, $borrowernumber, $userid, $firstname,
1933             $surname, $branchcode, $branchname, $flags )
1934           = $sth->fetchrow;
1935
1936         if ( checkpw_hash( $password, $stored_hash ) ) {
1937
1938             C4::Context->set_userenv( "$borrowernumber", $userid, $cardnumber,
1939                 $firstname, $surname, $branchcode, $branchname, $flags ) unless $no_set_userenv;
1940             return 1, $cardnumber, $userid;
1941         }
1942     }
1943     $sth =
1944       $dbh->prepare(
1945         "select password,cardnumber,borrowernumber,userid,firstname,surname,borrowers.branchcode,branches.branchname,flags from borrowers join branches on borrowers.branchcode=branches.branchcode where cardnumber=?"
1946       );
1947     $sth->execute($userid);
1948     if ( $sth->rows ) {
1949         my ( $stored_hash, $cardnumber, $borrowernumber, $userid, $firstname,
1950             $surname, $branchcode, $branchname, $flags )
1951           = $sth->fetchrow;
1952
1953         if ( checkpw_hash( $password, $stored_hash ) ) {
1954
1955             C4::Context->set_userenv( $borrowernumber, $userid, $cardnumber,
1956                 $firstname, $surname, $branchcode, $branchname, $flags ) unless $no_set_userenv;
1957             return 1, $cardnumber, $userid;
1958         }
1959     }
1960     return 0;
1961 }
1962
1963 sub checkpw_hash {
1964     my ( $password, $stored_hash ) = @_;
1965
1966     return if $stored_hash eq '!';
1967
1968     # check what encryption algorithm was implemented: Bcrypt - if the hash starts with '$2' it is Bcrypt else md5
1969     my $hash;
1970     if ( substr( $stored_hash, 0, 2 ) eq '$2' ) {
1971         $hash = hash_password( $password, $stored_hash );
1972     } else {
1973         $hash = md5_base64($password);
1974     }
1975     return $hash eq $stored_hash;
1976 }
1977
1978 =head2 getuserflags
1979
1980     my $authflags = getuserflags($flags, $userid, [$dbh]);
1981
1982 Translates integer flags into permissions strings hash.
1983
1984 C<$flags> is the integer userflags value ( borrowers.userflags )
1985 C<$userid> is the members.userid, used for building subpermissions
1986 C<$authflags> is a hashref of permissions
1987
1988 =cut
1989
1990 sub getuserflags {
1991     my $flags  = shift;
1992     my $userid = shift;
1993     my $dbh    = @_ ? shift : C4::Context->dbh;
1994     my $userflags;
1995     {
1996         # I don't want to do this, but if someone logs in as the database
1997         # user, it would be preferable not to spam them to death with
1998         # numeric warnings. So, we make $flags numeric.
1999         no warnings 'numeric';
2000         $flags += 0;
2001     }
2002     my $sth = $dbh->prepare("SELECT bit, flag, defaulton FROM userflags");
2003     $sth->execute;
2004
2005     while ( my ( $bit, $flag, $defaulton ) = $sth->fetchrow ) {
2006         if ( ( $flags & ( 2**$bit ) ) || $defaulton ) {
2007             $userflags->{$flag} = 1;
2008         }
2009         else {
2010             $userflags->{$flag} = 0;
2011         }
2012     }
2013
2014     # get subpermissions and merge with top-level permissions
2015     my $user_subperms = get_user_subpermissions($userid);
2016     foreach my $module ( keys %$user_subperms ) {
2017         next if $userflags->{$module} == 1;    # user already has permission for everything in this module
2018         $userflags->{$module} = $user_subperms->{$module};
2019     }
2020
2021     return $userflags;
2022 }
2023
2024 =head2 get_user_subpermissions
2025
2026   $user_perm_hashref = get_user_subpermissions($userid);
2027
2028 Given the userid (note, not the borrowernumber) of a staff user,
2029 return a hashref of hashrefs of the specific subpermissions
2030 accorded to the user.  An example return is
2031
2032  {
2033     tools => {
2034         export_catalog => 1,
2035         import_patrons => 1,
2036     }
2037  }
2038
2039 The top-level hash-key is a module or function code from
2040 userflags.flag, while the second-level key is a code
2041 from permissions.
2042
2043 The results of this function do not give a complete picture
2044 of the functions that a staff user can access; it is also
2045 necessary to check borrowers.flags.
2046
2047 =cut
2048
2049 sub get_user_subpermissions {
2050     my $userid = shift;
2051
2052     my $dbh = C4::Context->dbh;
2053     my $sth = $dbh->prepare( "SELECT flag, user_permissions.code
2054                              FROM user_permissions
2055                              JOIN permissions USING (module_bit, code)
2056                              JOIN userflags ON (module_bit = bit)
2057                              JOIN borrowers USING (borrowernumber)
2058                              WHERE userid = ?" );
2059     $sth->execute($userid);
2060
2061     my $user_perms = {};
2062     while ( my $perm = $sth->fetchrow_hashref ) {
2063         $user_perms->{ $perm->{'flag'} }->{ $perm->{'code'} } = 1;
2064     }
2065     return $user_perms;
2066 }
2067
2068 =head2 get_all_subpermissions
2069
2070   my $perm_hashref = get_all_subpermissions();
2071
2072 Returns a hashref of hashrefs defining all specific
2073 permissions currently defined.  The return value
2074 has the same structure as that of C<get_user_subpermissions>,
2075 except that the innermost hash value is the description
2076 of the subpermission.
2077
2078 =cut
2079
2080 sub get_all_subpermissions {
2081     my $dbh = C4::Context->dbh;
2082     my $sth = $dbh->prepare( "SELECT flag, code
2083                              FROM permissions
2084                              JOIN userflags ON (module_bit = bit)" );
2085     $sth->execute();
2086
2087     my $all_perms = {};
2088     while ( my $perm = $sth->fetchrow_hashref ) {
2089         $all_perms->{ $perm->{'flag'} }->{ $perm->{'code'} } = 1;
2090     }
2091     return $all_perms;
2092 }
2093
2094 =head2 haspermission
2095
2096   $flagsrequired = '*';                                 # Any permission at all
2097   $flagsrequired = 'a_flag';                            # a_flag must be satisfied (all subpermissions)
2098   $flagsrequired = [ 'a_flag', 'b_flag' ];              # a_flag OR b_flag must be satisfied
2099   $flagsrequired = { 'a_flag => 1, 'b_flag' => 1 };     # a_flag AND b_flag must be satisfied
2100   $flagsrequired = { 'a_flag' => 'sub_a' };             # sub_a of a_flag must be satisfied
2101   $flagsrequired = { 'a_flag' => [ 'sub_a, 'sub_b' ] }; # sub_a OR sub_b of a_flag must be satisfied
2102
2103   $flags = ($userid, $flagsrequired);
2104
2105 C<$userid> the userid of the member
2106 C<$flags> is a query structure similar to that used by SQL::Abstract that
2107 denotes the combination of flags required. It is a required parameter.
2108
2109 The main logic of this method is that things in arrays are OR'ed, and things
2110 in hashes are AND'ed. The `*` character can be used, at any depth, to denote `ANY`
2111
2112 Returns member's flags or 0 if a permission is not met.
2113
2114 =cut
2115
2116 sub _dispatch {
2117     my ($required, $flags) = @_;
2118
2119     my $ref = ref($required);
2120     if ($ref eq '') {
2121         if ($required eq '*') {
2122             return 0 unless ( $flags or ref( $flags ) );
2123         } else {
2124             return 0 unless ( $flags and (!ref( $flags ) || $flags->{$required} ));
2125         }
2126     } elsif ($ref eq 'HASH') {
2127         foreach my $key (keys %{$required}) {
2128             next if $flags == 1;
2129             my $require = $required->{$key};
2130             my $rflags  = $flags->{$key};
2131             return 0 unless _dispatch($require, $rflags);
2132         }
2133     } elsif ($ref eq 'ARRAY') {
2134         my $satisfied = 0;
2135         foreach my $require ( @{$required} ) {
2136             my $rflags =
2137               ( ref($flags) && !ref($require) && ( $require ne '*' ) )
2138               ? $flags->{$require}
2139               : $flags;
2140             $satisfied++ if _dispatch( $require, $rflags );
2141         }
2142         return 0 unless $satisfied;
2143     } else {
2144         croak "Unexpected structure found: $ref";
2145     }
2146
2147     return $flags;
2148 };
2149
2150 sub haspermission {
2151     my ( $userid, $flagsrequired ) = @_;
2152
2153     #Koha::Exceptions::WrongParameter->throw('$flagsrequired should not be undef')
2154     #  unless defined($flagsrequired);
2155
2156     my $sth = C4::Context->dbh->prepare("SELECT flags FROM borrowers WHERE userid=?");
2157     $sth->execute($userid);
2158     my $row = $sth->fetchrow();
2159     my $flags = getuserflags( $row, $userid );
2160
2161     return $flags unless defined($flagsrequired);
2162     return $flags if $flags->{superlibrarian};
2163     return _dispatch($flagsrequired, $flags);
2164
2165     #FIXME - This fcn should return the failed permission so a suitable error msg can be delivered.
2166 }
2167
2168 =head2 in_iprange
2169
2170   $flags = ($iprange);
2171
2172 C<$iprange> A space separated string describing an IP range. Can include single IPs or ranges
2173
2174 Returns 1 if the remote address is in the provided iprange, or 0 otherwise.
2175
2176 =cut
2177
2178 sub in_iprange {
2179     my ($iprange) = @_;
2180     my $result = 1;
2181     my @allowedipranges = $iprange ? split(' ', $iprange) : ();
2182     if (scalar @allowedipranges > 0) {
2183         my @rangelist;
2184         eval { @rangelist = Net::CIDR::range2cidr(@allowedipranges); }; return 0 if $@;
2185         eval { $result = Net::CIDR::cidrlookup($ENV{'REMOTE_ADDR'}, @rangelist) } || ( $ENV{DEBUG} && warn 'cidrlookup failed for ' . join(' ',@rangelist) );
2186      }
2187      return $result ? 1 : 0;
2188 }
2189
2190 sub getborrowernumber {
2191     my ($userid) = @_;
2192     my $userenv = C4::Context->userenv;
2193     if ( defined($userenv) && ref($userenv) eq 'HASH' && $userenv->{number} ) {
2194         return $userenv->{number};
2195     }
2196     my $dbh = C4::Context->dbh;
2197     for my $field ( 'userid', 'cardnumber' ) {
2198         my $sth =
2199           $dbh->prepare("select borrowernumber from borrowers where $field=?");
2200         $sth->execute($userid);
2201         if ( $sth->rows ) {
2202             my ($bnumber) = $sth->fetchrow;
2203             return $bnumber;
2204         }
2205     }
2206     return 0;
2207 }
2208
2209 =head2 track_login_daily
2210
2211     track_login_daily( $userid );
2212
2213 Wraps the call to $patron->track_login, the method used to update borrowers.lastseen. We only call track_login once a day.
2214
2215 =cut
2216
2217 sub track_login_daily {
2218     my $userid = shift;
2219     return if !$userid || !C4::Context->preference('TrackLastPatronActivity');
2220
2221     my $cache     = Koha::Caches->get_instance();
2222     my $cache_key = "track_login_" . $userid;
2223     my $cached    = $cache->get_from_cache($cache_key);
2224     my $today = dt_from_string()->ymd;
2225     return if $cached && $cached eq $today;
2226
2227     my $patron = Koha::Patrons->find({ userid => $userid });
2228     return unless $patron;
2229     $patron->track_login;
2230     $cache->set_in_cache( $cache_key, $today );
2231 }
2232
2233 END { }    # module clean-up code here (global destructor)
2234 1;
2235 __END__
2236
2237 =head1 SEE ALSO
2238
2239 CGI(3)
2240
2241 C4::Output(3)
2242
2243 Crypt::Eksblowfish::Bcrypt(3)
2244
2245 Digest::MD5(3)
2246
2247 =cut