-
Notifications
You must be signed in to change notification settings - Fork 257
/
Auth.pm
2408 lines (2042 loc) · 98.3 KB
/
Auth.pm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package C4::Auth;
# Copyright 2000-2002 Katipo Communications
#
# This file is part of Koha.
#
# Koha is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# Koha is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Koha; if not, see <http://www.gnu.org/licenses>.
use strict;
use warnings;
use Carp qw( croak );
use Digest::MD5 qw( md5_base64 );
use CGI::Session;
use CGI::Session::ErrorHandler;
use URI;
use URI::QueryParam;
use List::MoreUtils qw( uniq );
use C4::Context;
use C4::Templates; # to get the template
use C4::Languages;
use C4::Search::History;
use C4::Output qw( output_and_exit );
use Koha;
use Koha::Logger;
use Koha::Caches;
use Koha::AuthUtils qw( get_script_name hash_password );
use Koha::Auth::TwoFactorAuth;
use Koha::Checkouts;
use Koha::DateUtils qw( dt_from_string );
use Koha::Library::Groups;
use Koha::Libraries;
use Koha::Cash::Registers;
use Koha::Desks;
use Koha::Patrons;
use Koha::Patron::Consents;
use List::MoreUtils qw( any );
use Encode;
use C4::Auth_with_shibboleth qw( shib_ok get_login_shib login_shib_url logout_shib checkpw_shib );
use Net::CIDR;
use C4::Log qw( logaction );
use Koha::CookieManager;
use Koha::Auth::Permissions;
use Koha::Token;
use Koha::Exceptions::Token;
use Koha::Session;
# use utf8;
use vars qw($ldap $cas $caslogout);
our (@ISA, @EXPORT_OK);
#NOTE: The utility of keeping the safe_exit function is that it can be easily re-defined in unit tests and plugins
sub safe_exit {
# It's fine for us to "exit" because CGI::Compile (used in Plack::App::WrapCGI) redefines "exit" for us automatically.
# Since we only seem to use C4::Auth::safe_exit in a CGI context, we don't actually need PSGI detection at all here.
exit;
}
BEGIN {
C4::Context->set_remote_address;
require Exporter;
@ISA = qw(Exporter);
@EXPORT_OK = qw(
checkauth check_api_auth get_session check_cookie_auth checkpw checkpw_internal checkpw_hash
get_all_subpermissions get_cataloguing_page_permissions get_user_subpermissions in_iprange
get_template_and_user haspermission create_basic_session
);
$cas = C4::Context->preference('casAuthentication');
$caslogout = C4::Context->preference('casLogout');
if ($cas) {
require C4::Auth_with_cas; # no import
import C4::Auth_with_cas qw(check_api_auth_cas checkpw_cas login_cas logout_cas login_cas_url logout_if_required multipleAuth getMultipleAuth);
}
}
=head1 NAME
C4::Auth - Authenticates Koha users
=head1 SYNOPSIS
use CGI qw ( -utf8 );
use C4::Auth;
use C4::Output;
my $query = CGI->new;
my ($template, $borrowernumber, $cookie)
= get_template_and_user(
{
template_name => "opac-main.tt",
query => $query,
type => "opac",
authnotrequired => 0,
flagsrequired => { catalogue => '*', tools => 'import_patrons' },
}
);
output_html_with_http_headers $query, $cookie, $template->output;
=head1 DESCRIPTION
The main function of this module is to provide
authentification. However the get_template_and_user function has
been provided so that a users login information is passed along
automatically. This gets loaded into the template.
=head1 FUNCTIONS
=head2 get_template_and_user
my ($template, $borrowernumber, $cookie)
= get_template_and_user(
{
template_name => "opac-main.tt",
query => $query,
type => "opac",
authnotrequired => 0,
flagsrequired => { catalogue => '*', tools => 'import_patrons' },
}
);
This call passes the C<query>, C<flagsrequired> and C<authnotrequired>
to C<&checkauth> (in this module) to perform authentification.
See C<&checkauth> for an explanation of these parameters.
The C<template_name> is then used to find the correct template for
the page. The authenticated users details are loaded onto the
template in the logged_in_user variable (which is a Koha::Patron object). Also the
C<sessionID> is passed to the template. This can be used in templates
if cookies are disabled. It needs to be put as and input to every
authenticated page.
More information on the C<gettemplate> sub can be found in the
Output.pm module.
=cut
sub get_template_and_user {
my $in = shift;
my ( $user, $cookie, $sessionID, $flags );
$cookie = [];
my $cookie_mgr = Koha::CookieManager->new;
# Get shibboleth login attribute
my $shib = C4::Context->config('useshibboleth') && shib_ok();
my $shib_login = $shib ? get_login_shib() : undef;
C4::Context->interface( $in->{type} );
$in->{'authnotrequired'} ||= 0;
# the following call includes a bad template check; might croak
my $template = C4::Templates::gettemplate(
$in->{'template_name'},
$in->{'type'},
$in->{'query'},
);
if ( C4::Context->preference('AutoSelfCheckAllowed') && $in->{template_name} =~ m|sco/| ) {
my $AutoSelfCheckID = C4::Context->preference('AutoSelfCheckID');
my $AutoSelfCheckPass = C4::Context->preference('AutoSelfCheckPass');
$in->{query}->param( -name => 'login_userid', -values => [$AutoSelfCheckID] );
$in->{query}->param( -name => 'login_password', -values => [$AutoSelfCheckPass] );
$in->{query}->param( -name => 'koha_login_context', -values => ['sco'] );
} else {
my $request_method = $in->{query}->request_method // q{};
unless ( $request_method eq 'POST' && $in->{query}->param('op') eq 'cud-login' ) {
for my $v (qw( login_userid login_password )) {
$in->{query}->param( $v, '' )
if $in->{query}->param($v);
}
}
}
if ( $in->{'template_name'} !~ m/maintenance/ ) {
( $user, $cookie, $sessionID, $flags ) = checkauth(
$in->{'query'},
$in->{'authnotrequired'},
$in->{'flagsrequired'},
$in->{'type'},
undef,
$in->{template_name},
{ skip_csrf_check => 1 },
);
}
my $session = get_session($sessionID);
# If we enforce GDPR and the user did not consent, redirect
# Exceptions for consent page itself and SCI/SCO system
if( $in->{type} eq 'opac' && $user &&
$in->{'template_name'} !~ /^(opac-page|opac-patron-consent|sc[io]\/)/ &&
C4::Context->preference('PrivacyPolicyConsent') eq 'Enforced' )
{
my $consent = Koha::Patron::Consents->search({
borrowernumber => getborrowernumber($user),
type => 'GDPR_PROCESSING',
given_on => { '!=', undef },
})->next;
if( !$consent ) {
print $in->{query}->redirect(-uri => '/cgi-bin/koha/opac-patron-consent.pl', -cookie => $cookie);
safe_exit;
}
}
if ( $in->{type} eq 'opac' && $user ) {
my $is_sco_user;
if ($session){
$is_sco_user = $session->param('sco_user');
}
my $kick_out;
if (
# If the user logged in is the SCO user and they try to go out of the SCO module,
# log the user out removing the CGISESSID cookie
$in->{template_name} !~ m|sco/| && $in->{template_name} !~ m|errors/errorpage.tt|
&& (
$is_sco_user ||
(
C4::Context->preference('AutoSelfCheckID')
&& $user eq C4::Context->preference('AutoSelfCheckID')
)
)
)
{
$kick_out = 1;
}
elsif (
# If the user logged in is the SCI user and they try to go out of the SCI module,
# kick them out unless it is SCO with a valid permission
# or they are a superlibrarian
$in->{template_name} !~ m|sci/| && $in->{template_name} !~ m|errors/errorpage.tt|
&& haspermission( $user, { self_check => 'self_checkin_module' } )
&& !(
$in->{template_name} =~ m|sco/| && haspermission(
$user, { self_check => 'self_checkout_module' }
)
)
&& $flags && $flags->{superlibrarian} != 1
)
{
$kick_out = 1;
}
if ($kick_out) {
$template = C4::Templates::gettemplate( 'opac-auth.tt', 'opac',
$in->{query} );
$cookie = $cookie_mgr->replace_in_list( $cookie, $in->{query}->cookie(
-name => 'CGISESSID',
-value => '',
-HttpOnly => 1,
-secure => ( C4::Context->https_enabled() ? 1 : 0 ),
-sameSite => 'Lax',
));
#NOTE: This JWT should only be used by the self-check controllers
$cookie = $cookie_mgr->replace_in_list( $cookie, $in->{query}->cookie(
-name => 'JWT',
-value => '',
-HttpOnly => 1,
-secure => ( C4::Context->https_enabled() ? 1 : 0 ),
-sameSite => 'Lax',
));
my $auth_error = $in->{query}->param('auth_error');
$template->param(
loginprompt => 1,
script_name => get_script_name(),
auth_error => $auth_error,
);
print $in->{query}->header(
{
type => 'text/html',
charset => 'utf-8',
cookie => $cookie,
'X-Frame-Options' => 'SAMEORIGIN'
}
),
$template->output;
safe_exit;
}
}
my $borrowernumber;
my $patron;
if ($user) {
# It's possible for $user to be the borrowernumber if they don't have a
# userid defined (and are logging in through some other method, such
# as SSL certs against an email address)
$borrowernumber = getborrowernumber($user) if defined($user);
if ( !defined($borrowernumber) && defined($user) ) {
$patron = Koha::Patrons->find( $user );
if ($patron) {
$borrowernumber = $user;
# A bit of a hack, but I don't know there's a nicer way
# to do it.
$user = $patron->firstname . ' ' . $patron->surname;
}
} else {
$patron = Koha::Patrons->find( $borrowernumber );
# FIXME What to do if $patron does not exist?
}
if ( $in->{'type'} eq 'opac' ) {
require Koha::Virtualshelves;
my $some_private_shelves = Koha::Virtualshelves->get_some_shelves(
{
borrowernumber => $borrowernumber,
public => 0,
}
);
my $some_public_shelves = Koha::Virtualshelves->get_some_shelves(
{
public => 1,
}
);
$template->param(
some_private_shelves => $some_private_shelves,
some_public_shelves => $some_public_shelves,
);
}
# We are going to use the $flags returned by checkauth
# to create the template's parameters that will indicate
# which menus the user can access.
my $authz = Koha::Auth::Permissions->get_authz_from_flags({ flags => $flags });
foreach my $permission ( keys %{ $authz } ){
$template->param( $permission => $authz->{$permission} );
}
# Logged-in opac search history
# If the requested template is an opac one and opac search history is enabled
if ( $in->{type} eq 'opac' && C4::Context->preference('EnableOpacSearchHistory') ) {
my $dbh = C4::Context->dbh;
my $query = "SELECT COUNT(*) FROM search_history WHERE userid=?";
my $sth = $dbh->prepare($query);
$sth->execute($borrowernumber);
# If at least one search has already been performed
if ( $sth->fetchrow_array > 0 ) {
# We show the link in opac
$template->param( EnableOpacSearchHistory => 1 );
}
if (C4::Context->preference('LoadSearchHistoryToTheFirstLoggedUser'))
{
# And if there are searches performed when the user was not logged in,
# we add them to the logged-in search history
my @recentSearches = C4::Search::History::get_from_session( { cgi => $in->{'query'} } );
if (@recentSearches) {
my $query = q{
INSERT INTO search_history(userid, sessionid, query_desc, query_cgi, type, total, time )
VALUES (?, ?, ?, ?, ?, ?, ?)
};
my $sth = $dbh->prepare($query);
$sth->execute( $borrowernumber,
$in->{query}->cookie("CGISESSID"),
$_->{query_desc},
$_->{query_cgi},
$_->{type} || 'biblio',
$_->{total},
$_->{time},
) foreach @recentSearches;
# clear out the search history from the session now that
# we've saved it to the database
}
}
C4::Search::History::set_to_session( { cgi => $in->{'query'}, search_history => [] } );
} elsif ( $in->{type} eq 'intranet' and C4::Context->preference('EnableSearchHistory') ) {
$template->param( EnableSearchHistory => 1 );
}
}
else { # if this is an anonymous session, setup to display public lists...
# If shibboleth is enabled, and we're in an anonymous session, we should allow
# the user to attempt login via shibboleth.
if ($shib) {
$template->param( shibbolethAuthentication => $shib,
shibbolethLoginUrl => login_shib_url( $in->{'query'} ),
);
# If shibboleth is enabled and we have a shibboleth login attribute,
# but we are in an anonymous session, then we clearly have an invalid
# shibboleth koha account.
if ($shib_login) {
$template->param( invalidShibLogin => '1' );
}
}
if ( $in->{'type'} eq 'opac' ){
require Koha::Virtualshelves;
my $some_public_shelves = Koha::Virtualshelves->get_some_shelves(
{
public => 1,
}
);
$template->param(
some_public_shelves => $some_public_shelves,
);
# Set default branch if one has been passed by the environment.
$template->param( default_branch => $ENV{OPAC_BRANCH_DEFAULT} ) if $ENV{OPAC_BRANCH_DEFAULT};
}
}
# Sysprefs disabled via URL param
# Note that value must be defined in order to override via ENV
foreach my $syspref (
qw(
OPACUserCSS
OPACUserJS
IntranetUserCSS
IntranetUserJS
OpacAdditionalStylesheet
opaclayoutstylesheet
intranetcolorstylesheet
intranetstylesheet
)
)
{
$ENV{"OVERRIDE_SYSPREF_$syspref"} = q{}
if $in->{'query'}->param("DISABLE_SYSPREF_$syspref");
}
# Anonymous opac search history
# If opac search history is enabled and at least one search has already been performed
if ( C4::Context->preference('EnableOpacSearchHistory') ) {
my @recentSearches = C4::Search::History::get_from_session( { cgi => $in->{'query'} } );
if (@recentSearches) {
$template->param( EnableOpacSearchHistory => 1 );
}
}
if ( C4::Context->preference('dateformat') ) {
$template->param( dateformat => C4::Context->preference('dateformat') );
}
$template->param(auth_forwarded_hash => scalar $in->{'query'}->param('auth_forwarded_hash'));
# these template parameters are set the same regardless of $in->{'type'}
my $minPasswordLength = C4::Context->preference('minPasswordLength');
$minPasswordLength = 3 if not $minPasswordLength or $minPasswordLength < 3;
$template->param(
EnhancedMessagingPreferences => C4::Context->preference('EnhancedMessagingPreferences'),
GoogleJackets => C4::Context->preference("GoogleJackets"),
OpenLibraryCovers => C4::Context->preference("OpenLibraryCovers"),
KohaAdminEmailAddress => "" . C4::Context->preference("KohaAdminEmailAddress"),
LoginFirstname => ( C4::Context->userenv ? C4::Context->userenv->{"firstname"} : "Bel" ),
LoginSurname => C4::Context->userenv ? C4::Context->userenv->{"surname"} : "Inconnu",
emailaddress => C4::Context->userenv ? C4::Context->userenv->{"emailaddress"} : undef,
TagsEnabled => C4::Context->preference("TagsEnabled"),
hide_marc => C4::Context->preference("hide_marc"),
item_level_itypes => C4::Context->preference('item-level_itypes'),
patronimages => C4::Context->preference("patronimages"),
singleBranchMode => ( Koha::Libraries->search->count == 1 ),
noItemTypeImages => C4::Context->preference("noItemTypeImages"),
marcflavour => C4::Context->preference("marcflavour"),
OPACBaseURL => C4::Context->preference('OPACBaseURL'),
minPasswordLength => $minPasswordLength,
);
if ( $in->{'type'} eq "intranet" ) {
$template->param(
advancedMARCEditor => C4::Context->preference("advancedMARCEditor"),
AllowMultipleCovers => C4::Context->preference('AllowMultipleCovers'),
AmazonCoverImages => C4::Context->preference("AmazonCoverImages"),
StaffLoginRestrictLibraryByIP => C4::Context->preference("StaffLoginRestrictLibraryByIP"),
can_see_cataloguing_module => haspermission( $user, get_cataloguing_page_permissions() ) ? 1 : 0,
canreservefromotherbranches => C4::Context->preference('canreservefromotherbranches'),
EasyAnalyticalRecords => C4::Context->preference('EasyAnalyticalRecords'),
EnableBorrowerFiles => C4::Context->preference('EnableBorrowerFiles'),
FRBRizeEditions => C4::Context->preference("FRBRizeEditions"),
IndependentBranches => C4::Context->preference("IndependentBranches"),
intranetcolorstylesheet => C4::Context->preference("intranetcolorstylesheet"),
IntranetFavicon => C4::Context->preference("IntranetFavicon"),
IntranetmainUserblock => C4::Context->preference("IntranetmainUserblock"),
IntranetNav => C4::Context->preference("IntranetNav"),
intranetreadinghistory => C4::Context->preference("intranetreadinghistory"),
IntranetReadingHistoryHolds => C4::Context->preference("IntranetReadingHistoryHolds"),
intranetstylesheet => C4::Context->preference("intranetstylesheet"),
IntranetUserCSS => C4::Context->preference("IntranetUserCSS"),
IntranetUserJS => C4::Context->preference("IntranetUserJS"),
LibraryName => C4::Context->preference("LibraryName"),
LocalCoverImages => C4::Context->preference('LocalCoverImages'),
OPACLocalCoverImages => C4::Context->preference('OPACLocalCoverImages'),
PatronAutoComplete => C4::Context->preference("PatronAutoComplete"),
pending_checkout_notes => Koha::Checkouts->search( { noteseen => 0 } ),
plugins_enabled => C4::Context->config("enable_plugins"),
StaffSerialIssueDisplayCount => C4::Context->preference("StaffSerialIssueDisplayCount"),
UseCourseReserves => C4::Context->preference("UseCourseReserves"),
useDischarge => C4::Context->preference('useDischarge'),
virtualshelves => C4::Context->preference("virtualshelves"),
);
}
else {
warn "template type should be OPAC, here it is=[" . $in->{'type'} . "]" unless ( $in->{'type'} eq 'opac' );
#TODO : replace LibraryName syspref with 'system name', and remove this html processing
my $LibraryNameTitle = C4::Context->preference("LibraryName");
$LibraryNameTitle =~ s/<(?:\/?)(?:br|p)\s*(?:\/?)>/ /sgi;
$LibraryNameTitle =~ s/<(?:[^<>'"]|'(?:[^']*)'|"(?:[^"]*)")*>//sg;
# clean up the busc param in the session
# if the page is not opac-detail and not the "add to list" page
# and not the "edit comments" page
if ( C4::Context->preference("OpacBrowseResults")
&& $in->{'template_name'} =~ /opac-(.+)\.(?:tt|tmpl)$/ ) {
my $pagename = $1;
unless ( $pagename =~ /^(?:MARC|ISBD)?detail$/
or $pagename =~ /^showmarc$/
or $pagename =~ /^addbybiblionumber$/
or $pagename =~ /^review$/ )
{
$session->clear( ["busc"] ) if $session;
}
}
# variables passed from CGI: opac_css_override and opac_search_limits.
my $opac_search_limit = $ENV{'OPAC_SEARCH_LIMIT'};
my $opac_limit_override = $ENV{'OPAC_LIMIT_OVERRIDE'};
my $opac_name = '';
if (
( $opac_limit_override && $opac_search_limit && $opac_search_limit =~ /^branch:([\w-]+)/ ) ||
( $in->{'query'}->param('limit') && $in->{'query'}->param('limit') =~ /^branch:([\w-]+)/ ) ||
( $in->{'query'}->param('limit') && $in->{'query'}->param('limit') =~ /^multibranchlimit:(\w+)/ )
) {
$opac_name = $1; # opac_search_limit is a branch, so we use it.
} elsif ( $in->{'query'}->param('multibranchlimit') ) {
$opac_name = $in->{'query'}->param('multibranchlimit');
} elsif ( C4::Context->preference("SearchMyLibraryFirst") && C4::Context->userenv && C4::Context->userenv->{'branch'} ) {
$opac_name = C4::Context->userenv->{'branch'};
}
# Decide if the patron can make suggestions in the OPAC
my $can_make_suggestions;
if ( C4::Context->preference('Suggestion') && C4::Context->preference('AnonSuggestions') ) {
$can_make_suggestions = 1;
} elsif ( C4::Context->userenv && C4::Context->userenv->{'number'} ) {
$can_make_suggestions = Koha::Patrons->find(C4::Context->userenv->{'number'})->category->can_make_suggestions;
}
my @search_groups = Koha::Library::Groups->get_search_groups({ interface => 'opac' })->as_list;
$template->param(
AnonSuggestions => "" . C4::Context->preference("AnonSuggestions"),
LibrarySearchGroups => \@search_groups,
opac_name => $opac_name,
LibraryName => "" . C4::Context->preference("LibraryName"),
LibraryNameTitle => "" . $LibraryNameTitle,
OPACAmazonCoverImages => C4::Context->preference("OPACAmazonCoverImages"),
OPACFRBRizeEditions => C4::Context->preference("OPACFRBRizeEditions"),
OpacHighlightedWords => C4::Context->preference("OpacHighlightedWords"),
OPACShelfBrowser => "" . C4::Context->preference("OPACShelfBrowser"),
OPACURLOpenInNewWindow => "" . C4::Context->preference("OPACURLOpenInNewWindow"),
OpacAuthorities => C4::Context->preference("OpacAuthorities"),
opac_css_override => $ENV{'OPAC_CSS_OVERRIDE'},
opac_search_limit => $opac_search_limit,
opac_limit_override => $opac_limit_override,
OpacBrowser => C4::Context->preference("OpacBrowser"),
OpacCloud => C4::Context->preference("OpacCloud"),
OpacKohaUrl => C4::Context->preference("OpacKohaUrl"),
OpacPasswordChange => C4::Context->preference("OpacPasswordChange"),
OPACPatronDetails => C4::Context->preference("OPACPatronDetails"),
OPACPrivacy => C4::Context->preference("OPACPrivacy"),
OPACFinesTab => C4::Context->preference("OPACFinesTab"),
OpacTopissue => C4::Context->preference("OpacTopissue"),
'Version' => C4::Context->preference('Version'),
hidelostitems => C4::Context->preference("hidelostitems"),
mylibraryfirst => ( C4::Context->preference("SearchMyLibraryFirst") && C4::Context->userenv ) ? C4::Context->userenv->{'branch'} : '',
opacbookbag => "" . C4::Context->preference("opacbookbag"),
OpacFavicon => C4::Context->preference("OpacFavicon"),
opaclanguagesdisplay => "" . C4::Context->preference("opaclanguagesdisplay"),
opacreadinghistory => C4::Context->preference("opacreadinghistory"),
opacuserlogin => "" . C4::Context->preference("opacuserlogin"),
OpenLibrarySearch => C4::Context->preference("OpenLibrarySearch"),
ShowReviewer => C4::Context->preference("ShowReviewer"),
ShowReviewerPhoto => C4::Context->preference("ShowReviewerPhoto"),
suggestion => $can_make_suggestions,
virtualshelves => "" . C4::Context->preference("virtualshelves"),
OPACSerialIssueDisplayCount => C4::Context->preference("OPACSerialIssueDisplayCount"),
SyndeticsClientCode => C4::Context->preference("SyndeticsClientCode"),
SyndeticsEnabled => C4::Context->preference("SyndeticsEnabled"),
SyndeticsCoverImages => C4::Context->preference("SyndeticsCoverImages"),
SyndeticsTOC => C4::Context->preference("SyndeticsTOC"),
SyndeticsSummary => C4::Context->preference("SyndeticsSummary"),
SyndeticsEditions => C4::Context->preference("SyndeticsEditions"),
SyndeticsExcerpt => C4::Context->preference("SyndeticsExcerpt"),
SyndeticsReviews => C4::Context->preference("SyndeticsReviews"),
SyndeticsAuthorNotes => C4::Context->preference("SyndeticsAuthorNotes"),
SyndeticsAwards => C4::Context->preference("SyndeticsAwards"),
SyndeticsSeries => C4::Context->preference("SyndeticsSeries"),
SyndeticsCoverImageSize => C4::Context->preference("SyndeticsCoverImageSize"),
OPACLocalCoverImages => C4::Context->preference("OPACLocalCoverImages"),
PatronSelfRegistration => C4::Context->preference("PatronSelfRegistration"),
PatronSelfRegistrationDefaultCategory => C4::Context->preference("PatronSelfRegistrationDefaultCategory"),
useDischarge => C4::Context->preference('useDischarge'),
);
$template->param( OpacPublic => '1' ) if ( $user || C4::Context->preference("OpacPublic") );
}
# Check if we were asked using parameters to force a specific language
if ( defined $in->{'query'}->param('language') ) {
# Extract the language, let C4::Languages::getlanguage choose
# what to do
my $language = C4::Languages::getlanguage( $in->{'query'} );
my $languagecookie = C4::Templates::getlanguagecookie( $in->{'query'}, $language );
$cookie = $cookie_mgr->replace_in_list( $cookie, $languagecookie );
}
# user info
$template->param( loggedinusername => $user ); # OBSOLETE - Do not reuse this in template, use logged_in_user.userid instead
$template->param( loggedinusernumber => $borrowernumber ); # FIXME Should be replaced with logged_in_user.borrowernumber
$template->param( logged_in_user => $patron );
$template->param( sessionID => $sessionID );
return ( $template, $borrowernumber, $cookie, $flags );
}
=head2 checkauth
($userid, $cookie, $sessionID) = &checkauth($query, $noauth, $flagsrequired, $type);
Verifies that the user is authorized to run this script. If
the user is authorized, a (userid, cookie, session-id, flags)
quadruple is returned. If the user is not authorized but does
not have the required privilege (see $flagsrequired below), it
displays an error page and exits. Otherwise, it displays the
login page and exits.
Note that C<&checkauth> will return if and only if the user
is authorized, so it should be called early on, before any
unfinished operations (e.g., if you've opened a file, then
C<&checkauth> won't close it for you).
C<$query> is the CGI object for the script calling C<&checkauth>.
The C<$noauth> argument is optional. If it is set, then no
authorization is required for the script.
C<&checkauth> fetches user and session information from C<$query> and
ensures that the user is authorized to run scripts that require
authorization.
The C<$flagsrequired> argument specifies the required privileges
the user must have if the username and password are correct.
It should be specified as a reference-to-hash; keys in the hash
should be the "flags" for the user, as specified in the Members
intranet module. Any key specified must correspond to a "flag"
in the userflags table. E.g., { circulate => 1 } would specify
that the user must have the "circulate" privilege in order to
proceed. To make sure that access control is correct, the
C<$flagsrequired> parameter must be specified correctly.
Koha also has a concept of sub-permissions, also known as
granular permissions. This makes the value of each key
in the C<flagsrequired> hash take on an additional
meaning, i.e.,
1
The user must have access to all subfunctions of the module
specified by the hash key.
*
The user must have access to at least one subfunction of the module
specified by the hash key.
specific permission, e.g., 'export_catalog'
The user must have access to the specific subfunction list, which
must correspond to a row in the permissions table.
The C<$type> argument specifies whether the template should be
retrieved from the opac or intranet directory tree. "opac" is
assumed if it is not specified; however, if C<$type> is specified,
"intranet" is assumed if it is not "opac".
If C<$query> does not have a valid session ID associated with it
(i.e., the user has not logged in) or if the session has expired,
C<&checkauth> presents the user with a login page (from the point of
view of the original script, C<&checkauth> does not return). Once the
user has authenticated, C<&checkauth> restarts the original script
(this time, C<&checkauth> returns).
The login page is provided using a HTML::Template, which is set in the
systempreferences table or at the top of this file. The variable C<$type>
selects which template to use, either the opac or the intranet
authentification template.
C<&checkauth> returns a user ID, a cookie, and a session ID. The
cookie should be sent back to the browser; it verifies that the user
has authenticated.
=cut
sub _version_check {
my $type = shift;
my $query = shift;
my $version;
# If version syspref is unavailable, it means Koha is being installed,
# and so we must redirect to OPAC maintenance page or to the WebInstaller
# also, if OpacMaintenance is ON, OPAC should redirect to maintenance
if ( C4::Context->preference('OpacMaintenance') && $type eq 'opac' ) {
warn "OPAC Install required, redirecting to maintenance";
print $query->redirect("/cgi-bin/koha/maintenance.pl");
safe_exit;
}
unless ( $version = C4::Context->preference('Version') ) { # assignment, not comparison
if ( $type ne 'opac' ) {
warn "Install required, redirecting to Installer";
print $query->redirect("/cgi-bin/koha/installer/install.pl");
} else {
warn "OPAC Install required, redirecting to maintenance";
print $query->redirect("/cgi-bin/koha/maintenance.pl");
}
safe_exit;
}
# check that database and koha version are the same
# there is no DB version, it's a fresh install,
# go to web installer
# there is a DB version, compare it to the code version
my $kohaversion = Koha::version();
# remove the 3 last . to have a Perl number
$kohaversion =~ s/(.*\..*)\.(.*)\.(.*)/$1$2$3/;
Koha::Logger->get->debug("kohaversion : $kohaversion");
if ( $version < $kohaversion ) {
my $warning = "Database update needed, redirecting to %s. Database is $version and Koha is $kohaversion";
if ( $type ne 'opac' ) {
warn sprintf( $warning, 'Installer' );
print $query->redirect("/cgi-bin/koha/installer/install.pl");
} else {
warn sprintf( "OPAC: " . $warning, 'maintenance' );
print $query->redirect("/cgi-bin/koha/maintenance.pl");
}
safe_exit;
}
}
sub _timeout_syspref {
my $default_timeout = 600;
my $timeout = C4::Context->preference('timeout') || $default_timeout;
# value in days, convert in seconds
if ( $timeout =~ /^(\d+)[dD]$/ ) {
$timeout = $1 * 86400;
}
# value in hours, convert in seconds
elsif ( $timeout =~ /^(\d+)[hH]$/ ) {
$timeout = $1 * 3600;
}
elsif ( $timeout !~ m/^\d+$/ ) {
warn "The value of the system preference 'timeout' is not correct, defaulting to $default_timeout";
$timeout = $default_timeout;
}
return $timeout;
}
sub checkauth {
my $query = shift;
# Get shibboleth login attribute
my $shib = C4::Context->config('useshibboleth') && shib_ok();
my $shib_login = $shib ? get_login_shib() : undef;
# $authnotrequired will be set for scripts which will run without authentication
my $authnotrequired = shift;
my $flagsrequired = shift;
my $type = shift;
my $emailaddress = shift;
my $template_name = shift;
my $params = shift || {}; # do_not_print, skip_csrf_check
my $skip_csrf_check = $params->{skip_csrf_check} || 0;
$type = 'opac' unless $type;
if ( $type eq 'opac' && !C4::Context->preference("OpacPublic") ) {
my @allowed_scripts_for_private_opac = qw(
opac-memberentry.tt
opac-registration-email-sent.tt
opac-registration-confirmation.tt
opac-memberentry-update-submitted.tt
opac-password-recovery.tt
opac-reset-password.tt
ilsdi.tt
);
$authnotrequired = 0 unless grep { $_ eq $template_name }
@allowed_scripts_for_private_opac;
}
my $timeout = _timeout_syspref();
my $cookie_mgr = Koha::CookieManager->new;
_version_check( $type, $query );
# state variables
my $auth_state = 'failed';
my %info;
my ( $userid, $cookie, $sessionID, $flags );
$cookie = [];
my $logout = $query->param('logout.x');
my $anon_search_history;
my $cas_ticket = '';
# This parameter is the name of the CAS server we want to authenticate against,
# when using authentication against multiple CAS servers, as configured in Auth_cas_servers.yaml
my $casparam = $query->param('cas');
my $q_userid = $query->param('login_userid') // '';
my $session;
my $invalid_otp_token;
my $require_2FA =
( $type ne "opac" # Only available for the staff interface
&& C4::Context->preference('TwoFactorAuthentication') ne "disabled" ) # If "enabled" or "enforced"
? 1 : 0;
# Basic authentication is incompatible with the use of Shibboleth,
# as Shibboleth may return REMOTE_USER as a Shibboleth attribute,
# and it may not be the attribute we want to use to match the koha login.
#
# Also, do not consider an empty REMOTE_USER.
#
# Finally, after those tests, we can assume (although if it would be better with
# a syspref) that if we get a REMOTE_USER, that's from basic authentication,
# and we can affect it to $userid.
if ( !$shib and defined( $ENV{'REMOTE_USER'} ) and $ENV{'REMOTE_USER'} ne '' and $userid = $ENV{'REMOTE_USER'} ) {
# Using Basic Authentication, no cookies required
$cookie = $cookie_mgr->replace_in_list( $cookie, $query->cookie(
-name => 'CGISESSID',
-value => '',
-HttpOnly => 1,
-secure => ( C4::Context->https_enabled() ? 1 : 0 ),
-sameSite => 'Lax',
));
}
elsif ( $emailaddress) {
# the Google OpenID Connect passes an email address
}
elsif ( $sessionID = $query->cookie("CGISESSID") ) { # assignment, not comparison
my ( $return, $more_info );
# NOTE: $flags in the following call is still undefined !
( $return, $session, $more_info ) = check_cookie_auth( $sessionID, $flags,
{ remote_addr => $ENV{REMOTE_ADDR}, skip_version_check => 1 }
);
if ( $return eq 'ok' || $return eq 'additional-auth-needed' ) {
$userid = $session->param('id');
}
$auth_state =
$return eq 'ok' ? 'completed'
: $return eq 'additional-auth-needed' ? 'additional-auth-needed'
: 'failed';
# We are at the second screen if the waiting-for-2FA is set in session
# and otp_token param has been passed
if ( $require_2FA
&& $auth_state eq 'additional-auth-needed'
&& ( my $otp_token = $query->param('otp_token') ) )
{
my $patron = Koha::Patrons->find( { userid => $userid } );
my $auth = Koha::Auth::TwoFactorAuth->new( { patron => $patron } );
my $verified = $auth->verify($otp_token);
$auth->clear;
if ( $verified ) {
# The token is correct, the user is fully logged in!
$auth_state = 'completed';
$session->param( 'waiting-for-2FA', 0 );
$session->param( 'waiting-for-2FA-setup', 0 );
# This is an ugly trick to pass the test
# $query->param('koha_login_context') && ( $q_userid ne $userid )
# few lines later
$q_userid = $userid;
}
else {
$invalid_otp_token = 1;
}
}
if ( $auth_state eq 'completed' ) {
Koha::Logger->get->debug(sprintf "AUTH_SESSION: (%s)\t%s %s - %s", map { $session->param($_) || q{} } qw(cardnumber firstname surname branch));
if ( ( $query->param('koha_login_context') && ( $q_userid ne $userid ) )
|| ( $cas && $query->param('ticket') && !C4::Context->userenv->{'id'} )
|| ( $shib && $shib_login && !$logout && !C4::Context->userenv->{'id'} )
) {
#if a user enters an id ne to the id in the current session, we need to log them in...
#first we need to clear the anonymous session...
$anon_search_history = $session->param('search_history');
$session->delete();
$session->flush;
$cookie = $cookie_mgr->clear_unless( $query->cookie, @$cookie );
C4::Context::unset_userenv();
$sessionID = undef;
undef $userid; # IMPORTANT: this assures us a new session in code below
$auth_state = 'failed';
} elsif (!$logout) {
$cookie = $cookie_mgr->replace_in_list( $cookie, $query->cookie(
-name => 'CGISESSID',
-value => $session->id,
-HttpOnly => 1,
-secure => ( C4::Context->https_enabled() ? 1 : 0 ),
-sameSite => 'Lax',
));
$flags = haspermission( $userid, $flagsrequired );
unless ( $flags ) {
$auth_state = 'failed';
$info{'nopermission'} = 1;
}
}
} elsif ( !$logout ) {
if ( $return eq 'expired' ) {
$info{timed_out} = 1;
} elsif ( $return eq 'restricted' ) {
$info{oldip} = $more_info->{old_ip};
$info{newip} = $more_info->{new_ip};
$info{different_ip} = 1;
} elsif ( $return eq 'password_expired' ) {
$info{password_has_expired} = 1;
}
}
}
my $request_method = $query->request_method // q{};
if ( $auth_state eq 'failed' || $logout ) {
$sessionID = undef;
$userid = undef;
}
if ($logout) {
# voluntary logout the user
# check wether the user was using their shibboleth session or a local one
my $shibSuccess = C4::Context->userenv ? C4::Context->userenv->{'shibboleth'} : undef;
if ( $session ) {
$session->delete();
$session->flush;
}
C4::Context::unset_userenv();
$cookie = $cookie_mgr->clear_unless( $query->cookie, @$cookie );
if ($cas and $caslogout) {
logout_cas($query, $type);
}
# If we are in a shibboleth session (shibboleth is enabled, a shibboleth match attribute is set and matches koha matchpoint)
if ( $shib and $shib_login and $shibSuccess) {
logout_shib($query);
}
$session = undef;
$auth_state = 'logout';
}
unless ( $userid ) {
#we initiate a session prior to checking for a username to allow for anonymous sessions...
if( !$session or !$sessionID ) { # if we cleared sessionID, we need a new session
$session = get_session() or die "Auth ERROR: Cannot get_session()";
}