]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/src/perlmods/lib/OpenILS/WWW/EGCatLoader.pm
Fix TPAC recognition of logged-in users via http
[working/Evergreen.git] / Open-ILS / src / perlmods / lib / OpenILS / WWW / EGCatLoader.pm
1 package OpenILS::WWW::EGCatLoader;
2 use strict; use warnings;
3 use XML::LibXML;
4 use URI::Escape;
5 use Digest::MD5 qw(md5_hex);
6 use Apache2::Const -compile => qw(OK DECLINED FORBIDDEN HTTP_INTERNAL_SERVER_ERROR REDIRECT HTTP_BAD_REQUEST);
7 use OpenSRF::AppSession;
8 use OpenSRF::EX qw/:try/;
9 use OpenSRF::Utils qw/:datetime/;
10 use OpenSRF::Utils::JSON;
11 use OpenSRF::Utils::Logger qw/$logger/;
12 use OpenILS::Application::AppUtils;
13 use OpenILS::Utils::CStoreEditor qw/:funcs/;
14 use OpenILS::Utils::Fieldmapper;
15 use DateTime::Format::ISO8601;
16 use CGI qw(:all -utf8);
17 use Time::HiRes;
18
19 # EGCatLoader sub-modules 
20 use OpenILS::WWW::EGCatLoader::Util;
21 use OpenILS::WWW::EGCatLoader::Account;
22 use OpenILS::WWW::EGCatLoader::Search;
23 use OpenILS::WWW::EGCatLoader::Record;
24 use OpenILS::WWW::EGCatLoader::Container;
25 use OpenILS::WWW::EGCatLoader::SMS;
26
27 my $U = 'OpenILS::Application::AppUtils';
28
29 use constant COOKIE_SES => 'ses';
30 use constant COOKIE_LOGGEDIN => 'eg_loggedin';
31 use constant COOKIE_PHYSICAL_LOC => 'eg_physical_loc';
32 use constant COOKIE_SSS_EXPAND => 'eg_sss_expand';
33
34 use constant COOKIE_ANON_CACHE => 'anoncache';
35 use constant ANON_CACHE_MYLIST => 'mylist';
36 use constant ANON_CACHE_STAFF_SEARCH => 'staffsearch';
37
38 use constant DEBUG_TIMING => 0;
39
40 sub new {
41     my($class, $apache, $ctx) = @_;
42
43     my $self = bless({}, ref($class) || $class);
44
45     $self->apache($apache);
46     $self->ctx($ctx);
47     $self->cgi(new CGI);
48     $self->timelog("New page");
49
50     OpenILS::Utils::CStoreEditor->init; # just in case
51     $self->editor(new_editor());
52
53     return $self;
54 }
55
56
57 # current Apache2::RequestRec;
58 sub apache {
59     my($self, $apache) = @_;
60     $self->{apache} = $apache if $apache;
61     return $self->{apache};
62 }
63
64 # runtime / template context
65 sub ctx {
66     my($self, $ctx) = @_;
67     $self->{ctx} = $ctx if $ctx;
68     return $self->{ctx};
69 }
70
71 # cstore editor
72 sub editor {
73     my($self, $editor) = @_;
74     $self->{editor} = $editor if $editor;
75     return $self->{editor};
76 }
77
78 # CGI handle
79 sub cgi {
80     my($self, $cgi) = @_;
81     $self->{cgi} = $cgi if $cgi;
82     return $self->{cgi};
83 }
84
85 sub timelog {
86     my($self, $description) = @_;
87
88     return unless DEBUG_TIMING;
89     return unless $description;
90     $self->ctx->{timing} ||= [];
91     
92     my $timer = [Time::HiRes::gettimeofday()];
93     $self->ctx->{time_begin} ||= $timer;
94
95     push @{$self->ctx->{timing}}, [
96         Time::HiRes::tv_interval($self->ctx->{time_begin}, $timer), $description
97     ];
98 }
99
100 # -----------------------------------------------------------------------------
101 # Perform initial setup, load common data, then load page data
102 # -----------------------------------------------------------------------------
103 sub load {
104     my $self = shift;
105
106     $self->init_ro_object_cache;
107     $self->timelog("Initial load");
108
109     my $stat = $self->load_common;
110     return $stat unless $stat == Apache2::Const::OK;
111
112     my $path = $self->apache->path_info;
113
114     (undef, $self->ctx->{mylist}) = $self->fetch_mylist unless
115         $path =~ /opac\/my(opac\/lists|list)/;
116
117     return $self->load_simple("home") if $path =~ m|opac/home|;
118     return $self->load_simple("advanced") if
119         $path =~ m:opac/(advanced|numeric|expert):;
120
121     return $self->load_rresults if $path =~ m|opac/results|;
122     return $self->load_print_record if $path =~ m|opac/record/print|;
123     return $self->load_record if $path =~ m|opac/record/\d|;
124     return $self->load_cnbrowse if $path =~ m|opac/cnbrowse|;
125
126     return $self->load_mylist_add if $path =~ m|opac/mylist/add|;
127     return $self->load_mylist_delete if $path =~ m|opac/mylist/delete|;
128     return $self->load_mylist_move if $path =~ m|opac/mylist/move|;
129     return $self->load_mylist if $path =~ m|opac/mylist|;
130     return $self->load_cache_clear if $path =~ m|opac/cache/clear|;
131     return $self->load_temp_warn_post if $path =~ m|opac/temp_warn/post|;
132     return $self->load_temp_warn if $path =~ m|opac/temp_warn|;
133
134     # ----------------------------------------------------------------
135     #  Everything below here requires SSL
136     # ----------------------------------------------------------------
137     return $self->redirect_ssl unless $self->cgi->https;
138     return $self->load_password_reset if $path =~ m|opac/password_reset|;
139     return $self->load_logout if $path =~ m|opac/logout|;
140
141     if($path =~ m|opac/login|) {
142         return $self->load_login unless $self->editor->requestor; # already logged in?
143
144         # This will be less confusing to users than to be shown a login form
145         # when they're already logged in.
146         return $self->generic_redirect(
147             sprintf(
148                 "https://%s%s/myopac/main",
149                 $self->apache->hostname, $self->ctx->{opac_root}
150             )
151         );
152     }
153
154     if ($path =~ m|opac/sms_cn| and !$self->editor->requestor) {
155         my $org_unit = $self->ctx->{physical_loc} || $self->cgi->param('loc') || $self->ctx->{aou_tree}->()->id;
156         my $skip_sms_auth = $self->ctx->{get_org_setting}->($org_unit, 'sms.disable_authentication_requirement.callnumbers');
157         return $self->load_sms_cn if $skip_sms_auth;
158     }
159
160     # ----------------------------------------------------------------
161     #  Everything below here requires authentication
162     # ----------------------------------------------------------------
163     return $self->redirect_auth unless $self->editor->requestor;
164
165     # Don't cache anything requiring auth for security reasons
166     $self->apache->headers_out->add("cache-control" => "no-store, no-cache, must-revalidate");
167     $self->apache->headers_out->add("expires" => "-1");
168
169     return $self->load_email_record if $path =~ m|opac/record/email|;
170
171     return $self->load_place_hold if $path =~ m|opac/place_hold|;
172     return $self->load_myopac_holds if $path =~ m|opac/myopac/holds|;
173     return $self->load_myopac_circs if $path =~ m|opac/myopac/circs|;
174     return $self->load_myopac_payment_form if $path =~ m|opac/myopac/main_payment_form|;
175     return $self->load_myopac_payments if $path =~ m|opac/myopac/main_payments|;
176     return $self->load_myopac_pay_init if $path =~ m|opac/myopac/main_pay_init|;
177     return $self->load_myopac_pay if $path =~ m|opac/myopac/main_pay|;
178     return $self->load_myopac_main if $path =~ m|opac/myopac/main|;
179     return $self->load_myopac_receipt_email if $path =~ m|opac/myopac/receipt_email|;
180     return $self->load_myopac_receipt_print if $path =~ m|opac/myopac/receipt_print|;
181     return $self->load_myopac_update_email if $path =~ m|opac/myopac/update_email|;
182     return $self->load_myopac_update_password if $path =~ m|opac/myopac/update_password|;
183     return $self->load_myopac_update_username if $path =~ m|opac/myopac/update_username|;
184     return $self->load_myopac_bookbags if $path =~ m|opac/myopac/lists|;
185     return $self->load_myopac_bookbag_print if $path =~ m|opac/myopac/list/print|;
186     return $self->load_myopac_bookbag_update if $path =~ m|opac/myopac/list/update|;
187     return $self->load_myopac_circ_history_export if $path =~ m|opac/myopac/circ_history/export|;
188     return $self->load_myopac_circ_history if $path =~ m|opac/myopac/circ_history|;
189     return $self->load_myopac_hold_history if $path =~ m|opac/myopac/hold_history|;
190     return $self->load_myopac_prefs_notify if $path =~ m|opac/myopac/prefs_notify|;
191     return $self->load_myopac_prefs_settings if $path =~ m|opac/myopac/prefs_settings|;
192     return $self->load_myopac_prefs if $path =~ m|opac/myopac/prefs|;
193     return $self->load_sms_cn if $path =~ m|opac/sms_cn|;
194
195     return Apache2::Const::OK;
196 }
197
198
199 # -----------------------------------------------------------------------------
200 # Redirect to SSL equivalent of a given page
201 # -----------------------------------------------------------------------------
202 sub redirect_ssl {
203     my $self = shift;
204     my $new_page = sprintf('https://%s%s', $self->apache->hostname, $self->apache->unparsed_uri);
205     return $self->generic_redirect($new_page);
206 }
207
208 # -----------------------------------------------------------------------------
209 # If an authnticated resource is requested w/o auth, redirect to the login page,
210 # then return to the originally requrested resource upon successful login.
211 # -----------------------------------------------------------------------------
212 sub redirect_auth {
213     my $self = shift;
214     my $login_page = sprintf('https://%s%s/login', $self->apache->hostname, $self->ctx->{opac_root});
215     my $redirect_to = uri_escape($self->apache->unparsed_uri);
216     return $self->generic_redirect("$login_page?redirect_to=$redirect_to");
217 }
218
219 # -----------------------------------------------------------------------------
220 # Fall-through for loading a basic page
221 # -----------------------------------------------------------------------------
222 sub load_simple {
223     my ($self, $page) = @_;
224     $self->ctx->{page} = $page;
225     $self->ctx->{search_ou} = $self->_get_search_lib();
226
227     return Apache2::Const::OK;
228 }
229
230 # -----------------------------------------------------------------------------
231 # Tests to see if the user is authenticated and sets some common context values
232 # -----------------------------------------------------------------------------
233 sub load_common {
234     my $self = shift;
235
236     my $e = $self->editor;
237     my $ctx = $self->ctx;
238
239     # redirect non-https to https if we think we are already logged in
240     if ($self->cgi->cookie(COOKIE_LOGGEDIN)) {
241         return $self->redirect_ssl unless $self->cgi->https;
242     }
243
244     $ctx->{referer} = $self->cgi->referer;
245     $ctx->{path_info} = $self->cgi->path_info;
246     $ctx->{full_path} = $ctx->{base_path} . $self->cgi->path_info;
247     $ctx->{unparsed_uri} = $self->apache->unparsed_uri;
248     $ctx->{opac_root} = $ctx->{base_path} . "/opac"; # absolute base url
249     $ctx->{is_staff} = 0; # Assume false, check for workstation id later.  Was: ($self->apache->headers_in->get('User-Agent') =~ /oils_xulrunner/);
250     $ctx->{physical_loc} = $self->get_physical_loc;
251
252     # capture some commonly accessed pages
253     $ctx->{home_page} = 'http://' . $self->apache->hostname . $self->ctx->{opac_root} . "/home";
254     $ctx->{logout_page} = 'https://' . $self->apache->hostname . $self->ctx->{opac_root} . "/logout";
255
256     if($e->authtoken($self->cgi->cookie(COOKIE_SES))) {
257
258         if($e->checkauth) {
259
260             $ctx->{authtoken} = $e->authtoken;
261             $ctx->{authtime} = $e->authtime;
262             $ctx->{user} = $e->requestor;
263
264             $ctx->{user_stats} = $U->simplereq(
265                 'open-ils.actor', 
266                 'open-ils.actor.user.opac.vital_stats', 
267                 $e->authtoken, $e->requestor->id);
268             $ctx->{is_staff} = 1 if $e->requestor->wsid;
269
270         } else {
271
272             # if we encounter a stale authtoken, call load_logout 
273             # to clean up the cookie, then redirect the user to the
274             # originally requested page
275             return $self->load_logout($self->apache->unparsed_uri);
276         }
277     }
278
279     $self->extract_copy_location_group_info;
280     $ctx->{search_ou} = $self->_get_search_lib();
281     $self->staff_saved_searches_set_expansion_state if $ctx->{is_staff};
282     $self->load_eg_cache_hash;
283     $self->load_copy_location_groups;
284     $self->staff_saved_searches_set_expansion_state if $ctx->{is_staff};
285     $self->load_search_filter_groups($ctx->{search_ou});
286
287     return Apache2::Const::OK;
288 }
289
290 sub staff_saved_searches_set_expansion_state {
291     my $self = shift;
292
293     my $param = $self->cgi->param('sss_expand');
294     my $value;
295     
296     if (defined $param) {
297         $value = ($param ? 1 : 0);
298         $self->apache->headers_out->add(
299             "Set-Cookie" => $self->cgi->cookie(
300                 -name => COOKIE_SSS_EXPAND,
301                 -path => $self->ctx->{base_path},
302                 -secure => 1,   # not strictly necessary, but this feature is staff-only, so may as well
303                 -value => $value,
304                 -expires => undef
305             )
306         );
307     } else {
308         $value = $self->cgi->cookie(COOKIE_SSS_EXPAND);
309     }
310
311     $self->ctx->{saved_searches_expanded} = $value;
312 }
313
314 # physical_loc (i.e. "original location") passed in as a URL 
315 # param will replace any existing physical_loc stored as a cookie.
316 sub get_physical_loc {
317     my $self = shift;
318
319     if(my $physical_loc = $self->cgi->param('physical_loc')) {
320         $self->apache->headers_out->add(
321             "Set-Cookie" => $self->cgi->cookie(
322                 -name => COOKIE_PHYSICAL_LOC,
323                 -path => $self->ctx->{base_path},
324                 -value => $physical_loc,
325                 -expires => undef
326             )
327         );
328         return $physical_loc;
329     }
330
331     return $self->cgi->cookie(COOKIE_PHYSICAL_LOC);
332 }
333
334 # -----------------------------------------------------------------------------
335 # Log in and redirect to the redirect_to URL (or home)
336 # -----------------------------------------------------------------------------
337 sub load_login {
338     my $self = shift;
339     my $cgi = $self->cgi;
340     my $ctx = $self->ctx;
341
342     $ctx->{page} = 'login';
343
344     my $username = $cgi->param('username');
345     my $password = $cgi->param('password');
346     my $org_unit = $cgi->param('loc') || $ctx->{aou_tree}->()->id;
347     my $persist = $cgi->param('persist');
348
349     # initial log form only
350     return Apache2::Const::OK unless $username and $password;
351
352         my $seed = $U->simplereq(
353         'open-ils.auth', 
354                 'open-ils.auth.authenticate.init', $username);
355
356     my $args = {        
357         username => $username, 
358         password => md5_hex($seed . md5_hex($password)), 
359         type => ($persist) ? 'persist' : 'opac',
360         agent => 'opac'
361     };
362
363     my $bc_regex = $ctx->{get_org_setting}->($org_unit, 'opac.barcode_regex');
364
365     # To avoid surprises, default to "Barcodes start with digits"
366     $bc_regex = '^\d' unless $bc_regex;
367
368     $args->{barcode} = delete $args->{username} 
369         if $bc_regex and ($username =~ /$bc_regex/);
370
371         my $response = $U->simplereq(
372         'open-ils.auth', 'open-ils.auth.authenticate.complete', $args);
373
374     if($U->event_code($response)) { 
375         # login failed, report the reason to the template
376         $ctx->{login_failed_event} = $response;
377         return Apache2::Const::OK;
378     }
379
380     # login succeeded, redirect as necessary
381
382     my $acct = $self->apache->unparsed_uri;
383     $acct =~ s|/login|/myopac/main|;
384
385     # both login-related cookies should expire at the same time
386     my $login_cookie_expires = ($persist) ? CORE::time + $response->{payload}->{authtime} : undef;
387
388     return $self->generic_redirect(
389         $cgi->param('redirect_to') || $acct,
390         [
391             # contains the actual auth token and should be sent only over https
392             $cgi->cookie(
393                 -name => COOKIE_SES,
394                 -path => '/',
395                 -secure => 1,
396                 -value => $response->{payload}->{authtoken},
397                 -expires => $login_cookie_expires
398             ),
399             # contains only a hint that we are logged in, and is used to
400             # trigger a redirect to https
401             $cgi->cookie(
402                 -name => COOKIE_LOGGEDIN,
403                 -path => '/',
404                 -secure => 0,
405                 -value => '1',
406                 -expires => $login_cookie_expires
407             )
408         ]
409     );
410 }
411
412 # -----------------------------------------------------------------------------
413 # Log out and redirect to the home page
414 # -----------------------------------------------------------------------------
415 sub load_logout {
416     my $self = shift;
417     my $redirect_to = shift;
418
419     # If the user was adding anyting to an anonymous cache 
420     # while logged in, go ahead and clear it out.
421     $self->clear_anon_cache;
422
423     return $self->generic_redirect(
424         $redirect_to || $self->ctx->{home_page},
425         [
426             # clear value of and expire both of these login-related cookies
427             $self->cgi->cookie(
428                 -name => COOKIE_SES,
429                 -path => '/',
430                 -value => '',
431                 -expires => '-1h'
432             ),
433             $self->cgi->cookie(
434                 -name => COOKIE_LOGGEDIN,
435                 -path => '/',
436                 -value => '',
437                 -expires => '-1h'
438             )
439         ]
440     );
441 }
442
443 1;
444