Bug 30199: Do not generate jwt if patron does not exist
[koha.git] / opac / sco / sco-main.pl
1 #!/usr/bin/perl
2 #
3 # This code has been modified by Trendsetters (originally from opac-user.pl)
4 # This code has been modified by rch
5 # Parts Copyright 2010-2011, ByWater Solutions (those related to username/password auth)
6 #
7 # This file is part of Koha.
8 #
9 # Koha is free software; you can redistribute it and/or modify it
10 # under the terms of the GNU General Public License as published by
11 # the Free Software Foundation; either version 3 of the License, or
12 # (at your option) any later version.
13 #
14 # Koha is distributed in the hope that it will be useful, but
15 # WITHOUT ANY WARRANTY; without even the implied warranty of
16 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 # GNU General Public License for more details.
18 #
19 # You should have received a copy of the GNU General Public License
20 # along with Koha; if not, see <http://www.gnu.org/licenses>.
21
22 # We're going to authenticate a self-check user.  we'll add a flag to borrowers 'selfcheck'
23 #
24 # We're not in a controlled environment; we never trust the user.
25 #
26 # The checkout permission comes form the CGI cookie/session of a staff user.
27 # The patron is not really logging in here in the same way as they do on the
28 # rest of the OPAC.  So don't confuse loggedinuser with the patron user.
29 # The patron id/cardnumber is retrieved from the JWT
30
31 use Modern::Perl;
32
33 use CGI qw ( -utf8 );
34
35 use C4::Auth qw( in_iprange get_template_and_user checkpw );
36 use C4::Circulation qw( barcodedecode AddReturn CanBookBeIssued AddIssue CanBookBeRenewed AddRenewal );
37 use C4::Reserves;
38 use C4::Output qw( output_html_with_http_headers );
39 use C4::Members;
40 use Koha::DateUtils qw( dt_from_string );
41 use Koha::Acquisition::Currencies;
42 use Koha::Items;
43 use Koha::Patrons;
44 use Koha::Patron::Images;
45 use Koha::Patron::Messages;
46 use Koha::Plugins;
47 use Koha::Token;
48
49 my $query = CGI->new;
50
51 unless (C4::Context->preference('WebBasedSelfCheck')) {
52     # redirect to OPAC home if self-check is not enabled
53     print $query->redirect("/cgi-bin/koha/opac-main.pl");
54     exit;
55 }
56
57 unless ( in_iprange(C4::Context->preference('SelfCheckAllowByIPRanges')) ) {
58     # redirect to OPAC home if self-checkout not permitted from current IP
59     print $query->redirect("/cgi-bin/koha/opac-main.pl");
60     exit;
61 }
62
63 if (C4::Context->preference('AutoSelfCheckAllowed'))
64 {
65     my $AutoSelfCheckID = C4::Context->preference('AutoSelfCheckID');
66     my $AutoSelfCheckPass = C4::Context->preference('AutoSelfCheckPass');
67     $query->param(-name=>'userid',-values=>[$AutoSelfCheckID]);
68     $query->param(-name=>'password',-values=>[$AutoSelfCheckPass]);
69     $query->param(-name=>'koha_login_context',-values=>['sco']);
70 }
71 $query->param(-name=>'sco_user_login',-values=>[1]);
72
73 my ( $template, $loggedinuser, $cookie ) = get_template_and_user(
74     {
75         template_name   => "sco/sco-main.tt",
76         flagsrequired   => { self_check => "self_checkout_module" },
77         query           => $query,
78         type            => "opac",
79     }
80 );
81
82 # Get the self checkout timeout preference, or use 120 seconds as a default
83 my $selfchecktimeout = 120000;
84 if (C4::Context->preference('SelfCheckTimeout')) { 
85     $selfchecktimeout = C4::Context->preference('SelfCheckTimeout') * 1000;
86 }
87 $template->param( SelfCheckTimeout => $selfchecktimeout );
88
89 # Checks policy laid out by SCOAllowCheckin, defaults to 'on' if preference is undefined
90 my $allowselfcheckreturns = 1;
91 if (defined C4::Context->preference('SCOAllowCheckin')) {
92     $allowselfcheckreturns = C4::Context->preference('SCOAllowCheckin');
93 }
94
95 my $issuerid = $loggedinuser;
96 my ($op, $patronlogin, $patronpw, $barcode, $confirmed, $newissues) = (
97     $query->param("op")         || '',
98     $query->param("patronlogin")|| '',
99     $query->param("patronpw")   || '',
100     $query->param("barcode")    || '',
101     $query->param("confirmed")  || '',
102     $query->param("newissues")  || '',
103 );
104
105 my $jwt = $query->cookie('JWT');
106 if ($op eq "logout") {
107     $template->param( loggedout => 1 );
108     $query->param( patronlogin => undef, patronpw => undef );
109     undef $jwt;
110 }
111
112 $barcode = barcodedecode( $barcode ) if $barcode;
113
114 my @newissueslist = split /,/, $newissues;
115 my $issuenoconfirm = 1; #don't need to confirm on issue.
116 my $issuer   = Koha::Patrons->find( $issuerid )->unblessed;
117
118 my $patronid = $jwt ? Koha::Token->new->decode_jwt({ token => $jwt }) : undef;
119 unless ( $patronid ) {
120     if ( C4::Context->preference('SelfCheckoutByLogin') ) {
121         my $dbh = C4::Context->dbh;
122         ( undef, $patronid ) = checkpw( $dbh, $patronlogin, $patronpw );
123     }
124     else {    # People should not do that unless they know what they are doing!
125               # SelfCheckAllowByIPRanges MUST be configured
126         $patronid = $query->param('patronid');
127     }
128     $jwt = Koha::Token->new->generate_jwt({ id => $patronid }) if $patronid;
129 }
130
131 my $patron;
132 if ( $patronid ) {
133     Koha::Plugins->call( 'patron_barcode_transform', \$patronid );
134     $patron = Koha::Patrons->find( { cardnumber => $patronid } );
135 }
136
137 undef $jwt unless $patron;
138
139 my $branch = $issuer->{branchcode};
140 my $confirm_required = 0;
141 my $return_only = 0;
142
143 if ( $patron && $op eq "returnbook" && $allowselfcheckreturns ) {
144     my $success = 1;
145
146
147     my $item = Koha::Items->find( { barcode => $barcode } );
148     if ( $success && C4::Context->preference("CircConfirmItemParts") ) {
149         if ( defined($item)
150             && $item->materials )
151         {
152             $success = 0;
153         }
154     }
155
156     if ($success) {
157         # Patron cannot checkin an item they don't own
158         $success = 0
159           unless $patron->checkouts->find( { itemnumber => $item->itemnumber } );
160     }
161
162     if ( $success ) {
163         ($success) = AddReturn( $barcode, $branch )
164     }
165
166     $template->param( returned => $success );
167 }
168 elsif ( $patron && ( $op eq 'checkout' ) ) {
169
170     my $item = Koha::Items->find( { barcode => $barcode } );
171     my $impossible  = {};
172     my $needconfirm = {};
173     ( $impossible, $needconfirm ) = CanBookBeIssued(
174         $patron,
175         $barcode,
176         undef,
177         0,
178         C4::Context->preference("AllowItemsOnHoldCheckoutSCO")
179     );
180     my $issue_error;
181     if ( $confirm_required = scalar keys %$needconfirm ) {
182         for my $error ( qw( UNKNOWN_BARCODE max_loans_allowed ISSUED_TO_ANOTHER NO_MORE_RENEWALS NOT_FOR_LOAN DEBT WTHDRAWN RESTRICTED RESERVED ITEMNOTSAMEBRANCH EXPIRED DEBARRED CARD_LOST GNA INVALID_DATE UNKNOWN_BARCODE TOO_MANY DEBT_GUARANTEES DEBT_GUARANTORS USERBLOCKEDOVERDUE PATRON_CANT PREVISSUE NOT_FOR_LOAN_FORCING ITEM_LOST ADDITIONAL_MATERIALS ) ) {
183             if ( $needconfirm->{$error} ) {
184                 $issue_error = $error;
185                 $confirmed = 0;
186                 last;
187             }
188         }
189     }
190
191     if (scalar keys %$impossible) {
192
193         my $issue_error = (keys %$impossible)[0]; # FIXME This is wrong, we assume only one error and keys are not ordered
194         my $title = ( $item ) ? $item->biblio->title : '';
195
196         $template->param(
197             impossible                => $issue_error,
198             "circ_error_$issue_error" => 1,
199             title                     => $title,
200             hide_main                 => 1,
201         );
202         if ($issue_error eq 'DEBT') {
203             $template->param(DEBT => $impossible->{DEBT});
204         }
205         if ( $issue_error eq "NO_MORE_RENEWALS" ) {
206             $return_only = 1;
207             $template->param(
208                 returnitem => 1,
209                 barcode    => $barcode,
210             );
211         }
212     } elsif ( $needconfirm->{RENEW_ISSUE} ){
213         $template->param(
214                 renew               => 1,
215                 barcode             => $barcode,
216                 confirm             => 1,
217                 confirm_renew_issue => 1,
218                 hide_main           => 1,
219         );
220     } elsif ( $confirm_required && !$confirmed ) {
221         $template->param(
222             impossible                => 1,
223             "circ_error_$issue_error" => 1,
224             hide_main                 => 1,
225         );
226         if ($issue_error eq 'DEBT') {
227             $template->param(DEBT => $needconfirm->{DEBT});
228         }
229     } else {
230         if ( $confirmed || $issuenoconfirm ) {    # we'll want to call getpatroninfo again to get updated issues.
231             my ( $hold_existed, $item );
232             if ( C4::Context->preference('HoldFeeMode') eq 'any_time_is_collected' ) {
233                 # There is no easy way to know if the patron has been charged for this item.
234                 # So we check if a hold existed for this item before the check in
235                 $item = Koha::Items->find({ barcode => $barcode });
236                 $hold_existed = Koha::Holds->search(
237                     {
238                         -and => {
239                             borrowernumber => $patron->borrowernumber,
240                             -or            => {
241                                 biblionumber => $item->biblionumber,
242                                 itemnumber   => $item->itemnumber
243                             }
244                         }
245                     }
246                 )->count;
247             }
248
249             AddIssue( $patron->unblessed, $barcode );
250             $template->param( issued => 1 );
251             push @newissueslist, $barcode;
252
253             if ( $hold_existed ) {
254                 my $dtf = Koha::Database->new->schema->storage->datetime_parser;
255                 $template->param(
256                     # If the hold existed before the check in, let's confirm that the charge line exists
257                     # Note that this should not be needed but since we do not have proper exception handling here we do it this way
258                     patron_has_hold_fee => Koha::Account::Lines->search(
259                         {
260                             borrowernumber  => $patron->borrowernumber,
261                             debit_type_code => 'RESERVE',
262                             description     => $item->biblio->title,
263                             date            => $dtf->format_date(dt_from_string)
264                         }
265                       )->count,
266                 );
267             }
268         } else {
269             $confirm_required = 1;
270             $template->param(
271                 confirm    => "Issuing title: " . $item->biblio->title,
272                 barcode    => $barcode,
273                 hide_main  => 1,
274             );
275         }
276     }
277 } # $op
278
279 if ( $patron && ( $op eq 'renew' ) ) {
280     my $item = Koha::Items->find({ barcode => $barcode });
281
282     if ( $patron->checkouts->find( { itemnumber => $item->itemnumber } ) ) {
283         my ($status,$renewerror) = CanBookBeRenewed( $patron->borrowernumber, $item->itemnumber );
284         if ($status) {
285             AddRenewal( $patron->borrowernumber, $item->itemnumber, undef, undef, undef, undef, 1 );
286             push @newissueslist, $barcode;
287             $template->param( renewed => 1 );
288         }
289     } else {
290         $template->param( renewed => 0 );
291     }
292 }
293
294 if ( $patron) {
295     my $borrowername = sprintf "%s %s", ($patron->firstname || ''), ($patron->surname || '');
296     my $pending_checkouts = $patron->pending_checkouts;
297     my @checkouts;
298     while ( my $c = $pending_checkouts->next ) {
299         my $checkout = $c->unblessed_all_relateds;
300         my ($can_be_renewed, $renew_error) = CanBookBeRenewed(
301             $patron->borrowernumber,
302             $checkout->{itemnumber},
303         );
304         $checkout->{can_be_renewed} = $can_be_renewed; # In the future this will be $checkout->can_be_renewed
305         $checkout->{renew_error} = $renew_error;
306         $checkout->{overdue} = $c->is_overdue;
307         push @checkouts, $checkout;
308     }
309
310     my $show_priority;
311     for ( C4::Context->preference("OPACShowHoldQueueDetails") ) {
312         m/priority/ and $show_priority = 1;
313     }
314
315     my $account = $patron->account;
316     my $total = $account->balance;
317     my $accountlines = $account->lines;
318
319     my $holds = $patron->holds;
320     my $waiting_holds_count = 0;
321
322     while(my $hold = $holds->next) {
323         $waiting_holds_count++ if $hold->is_waiting;
324     }
325
326     $template->param(
327         validuser => 1,
328         borrowername => $borrowername,
329         issues_count => scalar(@checkouts),
330         ISSUES => \@checkouts,
331         HOLDS => $holds,
332         newissues => join(',',@newissueslist),
333         patronlogin => $patronlogin,
334         patronpw => $patronpw,
335         waiting_holds_count => $waiting_holds_count,
336         noitemlinks => 1 ,
337         borrowernumber => $patron->borrowernumber,
338         SuspendHoldsOpac => C4::Context->preference('SuspendHoldsOpac'),
339         AutoResumeSuspendedHolds => C4::Context->preference('AutoResumeSuspendedHolds'),
340         howpriority   => $show_priority,
341         ACCOUNT_LINES => $accountlines,
342         total => $total,
343     );
344
345     my $patron_messages = Koha::Patron::Messages->search(
346         {
347             borrowernumber => $patron->borrowernumber,
348             message_type => 'B',
349         }
350     );
351     $template->param(
352         patron_messages => $patron_messages,
353         opacnote => $patron->opacnote,
354     );
355
356     $template->param(
357         nofines => 1,
358
359     );
360     if (C4::Context->preference('ShowPatronImageInWebBasedSelfCheck')) {
361         my $patron_image = $patron->image;
362         $template->param(
363             display_patron_image => 1,
364             csrf_token           => Koha::Token->new->generate_csrf( { session_id => scalar $query->cookie('CGISESSID') . $patron->cardnumber, id => $patron->userid } ),
365         ) if $patron_image;
366     }
367 } else {
368     $template->param(
369         nouser     => $patronid,
370     );
371 }
372
373 $cookie = $query->cookie(
374     -name => 'JWT',
375     -value => $jwt // '',
376     -expires => $jwt ? '+1d' : '',
377     -HttpOnly => 1,
378     -secure => ( C4::Context->https_enabled() ? 1 : 0 ),
379 );
380
381 $template->param(patronid => $patronid);
382
383 output_html_with_http_headers $query, $cookie, $template->output, undef, { force_no_caching => 1 };