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