]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/perlmods/lib/OpenILS/WWW/EGCatLoader.pm
lp1849212 Course Browse
[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 OpenILS::Utils::DateTime 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 OpenSRF::Utils::Cache;
16 use DateTime::Format::ISO8601;
17 use CGI qw(:all -utf8);
18 use Time::HiRes;
19
20 # EGCatLoader sub-modules 
21 use OpenILS::WWW::EGCatLoader::Util;
22 use OpenILS::WWW::EGCatLoader::Account;
23 use OpenILS::WWW::EGCatLoader::Browse;
24 use OpenILS::WWW::EGCatLoader::Library;
25 use OpenILS::WWW::EGCatLoader::Search;
26 use OpenILS::WWW::EGCatLoader::Record;
27 use OpenILS::WWW::EGCatLoader::Course;
28 use OpenILS::WWW::EGCatLoader::Container;
29 use OpenILS::WWW::EGCatLoader::SMS;
30 use OpenILS::WWW::EGCatLoader::Register;
31
32 my $U = 'OpenILS::Application::AppUtils';
33
34 use constant COOKIE_SES => 'ses';
35 use constant COOKIE_LOGGEDIN => 'eg_loggedin';
36 use constant COOKIE_TZ => 'client_tz';
37 use constant COOKIE_PHYSICAL_LOC => 'eg_physical_loc';
38 use constant COOKIE_SSS_EXPAND => 'eg_sss_expand';
39
40 use constant COOKIE_ANON_CACHE => 'anoncache';
41 use constant COOKIE_CART_CACHE => 'cartcache';
42 use constant CART_CACHE_MYLIST => 'mylist';
43 use constant ANON_CACHE_STAFF_SEARCH => 'staffsearch';
44
45 use constant DEBUG_TIMING => 0;
46
47 sub new {
48     my($class, $apache, $ctx) = @_;
49
50     my $self = bless({}, ref($class) || $class);
51
52     $self->apache($apache);
53     $self->ctx($ctx);
54     $self->cgi(new CGI);
55     $self->timelog("New page");
56
57     # Add a timelog helper to the context
58     $self->ctx->{timelog} = sub { return $self->timelog(@_) };
59
60     OpenILS::Utils::CStoreEditor->init; # just in case
61     $self->editor(new_editor());
62
63     return $self;
64 }
65
66 sub DESTROY {
67     my $self = shift;
68     $ENV{TZ} = $self->ctx->{original_tz}
69         if ($self->ctx && exists $self->ctx->{original_tz});
70 }
71
72 # current Apache2::RequestRec;
73 sub apache {
74     my($self, $apache) = @_;
75     $self->{apache} = $apache if $apache;
76     return $self->{apache};
77 }
78
79 # runtime / template context
80 sub ctx {
81     my($self, $ctx) = @_;
82     $self->{ctx} = $ctx if $ctx;
83     return $self->{ctx};
84 }
85
86 # cstore editor
87 sub editor {
88     my($self, $editor) = @_;
89     $self->{editor} = $editor if $editor;
90     return $self->{editor};
91 }
92
93 # CGI handle
94 sub cgi {
95     my($self, $cgi) = @_;
96     $self->{cgi} = $cgi if $cgi;
97     return $self->{cgi};
98 }
99
100 sub timelog {
101     my($self, $description) = @_;
102
103     return unless DEBUG_TIMING;
104     return unless $description;
105     $self->ctx->{timing} ||= [];
106     
107     my $timer = [Time::HiRes::gettimeofday()];
108     $self->ctx->{time_begin} ||= $timer;
109
110     push @{$self->ctx->{timing}}, [
111         Time::HiRes::tv_interval($self->ctx->{time_begin}, $timer), $description
112     ];
113 }
114
115 # -----------------------------------------------------------------------------
116 # Perform initial setup, load common data, then load page data
117 # -----------------------------------------------------------------------------
118 sub load {
119     my $self = shift;
120
121     $self->init_ro_object_cache;
122     $self->timelog("Initial load");
123
124     my $stat = $self->load_common;
125     return $stat unless $stat == Apache2::Const::OK;
126
127     my $path = $self->apache->path_info;
128
129     if ($path =~ m|opac/?$|) {
130         # nowhere specified, just go home
131         return $self->generic_redirect($self->ctx->{home_page});
132     }
133
134     (undef, $self->ctx->{mylist}) = $self->fetch_mylist unless
135         $path =~ /opac\/my(opac\/lists|list)/ ||
136         $path =~ m!opac/api/mylist!;
137
138     my $org_unit = $self->ctx->{physical_loc} || $self->cgi->param('context_org') || $self->_get_search_lib;
139     $self->ctx->{selected_print_email_loc} = $org_unit;
140
141     return $self->load_api_mylist_retrieve if $path =~ m|opac/api/mylist/retrieve|;
142     return $self->load_api_mylist_add if $path =~ m|opac/api/mylist/add|;
143     return $self->load_api_mylist_delete if $path =~ m|opac/api/mylist/delete|;
144     return $self->load_api_mylist_clear if $path =~ m|opac/api/mylist/clear|;
145
146     return $self->load_simple("home") if $path =~ m|opac/home|;
147     return $self->load_simple("css") if $path =~ m|opac/css|;
148     return $self->load_cresults if $path =~ m|opac/course/results|;
149     return $self->load_simple("course_search") if $path =~ m|opac/course_search|;
150     return $self->load_simple("advanced") if
151         $path =~ m:opac/(advanced|numeric|expert):;
152
153     return $self->load_library if $path =~ m|opac/library|;
154     return $self->load_rresults if $path =~ m|opac/results|;
155     return $self->load_print_or_email_preview('print') if $path =~ m|opac/record/print_preview|;
156     return $self->load_print_record if $path =~ m|opac/record/print|;
157     return $self->load_record if $path =~ m|opac/record/\d|;
158     return $self->load_cnbrowse if $path =~ m|opac/cnbrowse|;
159     return $self->load_browse if $path =~ m|opac/browse|;
160     return $self->load_course_browse if $path =~ m|opac/course_browse|;
161     return $self->load_course if $path =~ m|opac/course|;
162
163     return $self->load_mylist_add if $path =~ m|opac/mylist/add|;
164     return $self->load_mylist_delete if $path =~ m|opac/mylist/delete|;
165     return $self->load_mylist_move if $path =~ m|opac/mylist/move|;
166     return $self->load_mylist_print if $path =~ m|opac/mylist/doprint|;
167     return $self->load_mylist if $path =~ m|opac/mylist| && $path !~ m|opac/mylist/email| && $path !~ m|opac/mylist/doemail|;
168     return $self->load_cache_clear if $path =~ m|opac/cache/clear|;
169     return $self->load_temp_warn_post if $path =~ m|opac/temp_warn/post|;
170     return $self->load_temp_warn if $path =~ m|opac/temp_warn|;
171
172     # ----------------------------------------------------------------
173     #  Everything below here requires SSL
174     # ----------------------------------------------------------------
175     return $self->redirect_ssl unless $self->cgi->https;
176     return $self->load_password_reset if $path =~ m|opac/password_reset|;
177     return $self->load_logout if $path =~ m|opac/logout|;
178     return $self->load_patron_reg if $path =~ m|opac/register|;
179
180     $self->load_simple("myopac") if $path =~ m:opac/myopac:; # A default page for myopac parts
181
182     if($path =~ m|opac/login|) {
183         return $self->load_login unless $self->editor->requestor; # already logged in?
184
185         # This will be less confusing to users than to be shown a login form
186         # when they're already logged in.
187         return $self->generic_redirect(
188             sprintf(
189                 "%s://%s%s/myopac/main",
190                 $self->ctx->{proto},
191                 $self->ctx->{hostname}, $self->ctx->{opac_root}
192             )
193         );
194     }
195
196     if ($path =~ m|opac/sms_cn| and !$self->editor->requestor) {
197         my $skip_sms_auth = $self->ctx->{get_org_setting}->($org_unit, 'sms.disable_authentication_requirement.callnumbers');
198         return $self->load_sms_cn if $skip_sms_auth;
199     }
200
201     if (!$self->editor->requestor && $path =~ m|opac/record/email|) {
202         if ($self->ctx->{get_org_setting}->($org_unit, 'opac.email_record.allow_without_login')) {
203             my $cache = OpenSRF::Utils::Cache->new('global');
204
205             if ($path !~ m|preview|) { # the real thing!
206                 $logger->info("not preview");
207                 my $cap_key = $self->ctx->{cap}->{key} = $self->cgi->param('capkey');
208                 $logger->info("got cap_key $cap_key");
209                 if ($cap_key) {
210                     my $cap_answer = $self->ctx->{cap_answer} = $self->cgi->param('capanswer');
211                     my $real_answer = $self->ctx->{real_answer} = $cache->get_cache(md5_hex($cap_key));
212                     $logger->info("got answers $cap_answer $real_answer");
213                     return $self->load_email_record(1) if ( $cap_answer eq $real_answer );
214                 }
215             }
216
217             my $captcha = {};
218             $$captcha{key} = time() . $$ . rand();
219             $$captcha{left} = int(rand(10));
220             $$captcha{right} = int(rand(10));
221             $cache->put_cache(md5_hex($$captcha{key}), $$captcha{left} + $$captcha{right});
222             $self->ctx->{captcha} = $captcha;
223             return $self->load_print_or_email_preview('email', 1) if $path =~ m|opac/record/email_preview|;
224         }
225     }
226
227     # ----------------------------------------------------------------
228     #  Everything below here requires authentication
229     # ----------------------------------------------------------------
230     return $self->redirect_auth unless $self->editor->requestor;
231
232     # Don't cache anything requiring auth for security reasons
233     $self->apache->headers_out->add("cache-control" => "no-store, no-cache, must-revalidate");
234     $self->apache->headers_out->add("expires" => "-1");
235
236     if ($path =~ m|opac/mylist/email|) {
237         (undef, $self->ctx->{mylist}) = $self->fetch_mylist;
238     }
239     $self->load_simple("mylist/email") if $path =~ m|opac/mylist/email|;
240     return $self->load_print_or_email_preview('email') if $path =~ m|opac/mylist/doemail_preview|;
241     return $self->load_mylist_email if $path =~ m|opac/mylist/doemail|;
242     return $self->load_print_or_email_preview('email') if $path =~ m|opac/record/email_preview|;
243     return $self->load_email_record if $path =~ m|opac/record/email|;
244
245     return $self->load_place_hold if $path =~ m|opac/place_hold|;
246     return $self->load_myopac_holds if $path =~ m|opac/myopac/holds|;
247     return $self->load_myopac_circs if $path =~ m|opac/myopac/circs|;
248     return $self->load_myopac_messages if $path =~ m|opac/myopac/messages|;
249     return $self->load_myopac_payment_form if $path =~ m|opac/myopac/main_payment_form|;
250     return $self->load_myopac_payments if $path =~ m|opac/myopac/main_payments|;
251     return $self->load_myopac_pay_init if $path =~ m|opac/myopac/main_pay_init|;
252     return $self->load_myopac_pay if $path =~ m|opac/myopac/main_pay|;
253     return $self->load_myopac_main if $path =~ m|opac/myopac/charges|;
254     return $self->load_myopac_main if $path =~ m|opac/myopac/main|;
255     return $self->load_myopac_receipt_email if $path =~ m|opac/myopac/receipt_email|;
256     return $self->load_myopac_receipt_print if $path =~ m|opac/myopac/receipt_print|;
257     return $self->load_myopac_update_email if $path =~ m|opac/myopac/update_email|;
258     return $self->load_myopac_update_password if $path =~ m|opac/myopac/update_password|;
259     return $self->load_myopac_update_username if $path =~ m|opac/myopac/update_username|;
260     return $self->load_myopac_bookbags if $path =~ m|opac/myopac/lists|;
261     return $self->load_myopac_bookbag_print if $path =~ m|opac/myopac/list/print|;
262     return $self->load_myopac_bookbag_update if $path =~ m|opac/myopac/list/update|;
263     return $self->load_myopac_circ_history_export if $path =~ m|opac/myopac/circ_history/export|;
264     return $self->load_myopac_circ_history if $path =~ m|opac/myopac/circ_history|;
265     return $self->load_myopac_hold_history if $path =~ m|opac/myopac/hold_history|;
266     return $self->load_myopac_prefs_notify_changed_holds if $path =~ m|opac/myopac/prefs_notify_changed_holds|;
267     return $self->load_myopac_prefs_notify if $path =~ m|opac/myopac/prefs_notify|;
268     return $self->load_myopac_prefs_settings if $path =~ m|opac/myopac/prefs_settings|;
269     return $self->load_myopac_prefs_my_lists if $path =~ m|opac/myopac/prefs_my_lists|;
270     return $self->load_myopac_prefs if $path =~ m|opac/myopac/prefs|;
271     return $self->load_myopac_reservations if $path =~ m|opac/myopac/reservations|;
272     return $self->load_sms_cn if $path =~ m|opac/sms_cn|;
273
274     return Apache2::Const::OK;
275 }
276
277
278 # -----------------------------------------------------------------------------
279 # Redirect to SSL equivalent of a given page
280 # -----------------------------------------------------------------------------
281 sub redirect_ssl {
282     my $self = shift;
283     my $new_page = sprintf('%s://%s%s', ($self->ctx->{is_staff} ? 'oils' : 'https'), $self->ctx->{hostname}, $self->apache->unparsed_uri);
284     return $self->generic_redirect($new_page);
285 }
286
287 # -----------------------------------------------------------------------------
288 # If an authnticated resource is requested w/o auth, redirect to the login page,
289 # then return to the originally requrested resource upon successful login.
290 # -----------------------------------------------------------------------------
291 sub redirect_auth {
292     my $self = shift;
293     my $login_page = sprintf('%s://%s%s/login',($self->ctx->{is_staff} ? 'oils' : 'https'), $self->ctx->{hostname}, $self->ctx->{opac_root});
294     my $redirect_to = uri_escape_utf8($self->apache->unparsed_uri);
295     return $self->generic_redirect("$login_page?redirect_to=$redirect_to");
296 }
297
298 # -----------------------------------------------------------------------------
299 # Fall-through for loading a basic page
300 # -----------------------------------------------------------------------------
301 sub load_simple {
302     my ($self, $page) = @_;
303     $self->ctx->{page} = $page;
304     $self->ctx->{search_ou} = $self->_get_search_lib();
305
306     return Apache2::Const::OK;
307 }
308
309 # -----------------------------------------------------------------------------
310 # Tests to see if the user is authenticated and sets some common context values
311 # -----------------------------------------------------------------------------
312 sub load_common {
313     my $self = shift;
314
315     my $e = $self->editor;
316     my $ctx = $self->ctx;
317
318     # redirect non-https to https if we think we are already logged in
319     if ($self->cgi->cookie(COOKIE_LOGGEDIN)) {
320         return $self->redirect_ssl unless $self->cgi->https;
321     }
322
323     # XXX Cache this? Makes testing difficult as apache needs a restart.
324     my $default_sort = $e->retrieve_config_global_flag('opac.default_sort');
325     $ctx->{default_sort} =
326         ($default_sort && $U->is_true($default_sort->enabled)) ? $default_sort->value : '';
327
328     $ctx->{client_tz} = $self->cgi->cookie(COOKIE_TZ) || $ENV{TZ};
329     $ctx->{referer} = $self->cgi->referer;
330     $ctx->{path_info} = $self->cgi->path_info;
331     $ctx->{full_path} = $ctx->{base_path} . $self->cgi->path_info;
332     $ctx->{unparsed_uri} = $self->apache->unparsed_uri;
333     $ctx->{opac_root} = $ctx->{base_path} . "/opac"; # absolute base url
334
335     $ctx->{original_tz} = $ENV{TZ};
336     $ENV{TZ} = $ctx->{client_tz};
337
338     my $xul_wrapper = 
339         ($self->apache->headers_in->get('OILS-Wrapper') || '') =~ /true/;
340
341     if ($xul_wrapper) {
342         # XUL client
343         $ctx->{is_staff} = 1;
344         $ctx->{proto} = 'oils';
345         $ctx->{hostname} = 'remote';
346     }
347
348     $ctx->{physical_loc} = $self->get_physical_loc;
349
350     # capture some commonly accessed pages
351     $ctx->{home_page} = $ctx->{proto} . '://' . $ctx->{hostname} . $self->ctx->{opac_root} . "/home";
352     $ctx->{logout_page} = ($ctx->{proto} eq 'http' ? 'https' : $ctx->{proto} ) . '://' . $ctx->{hostname} . $self->ctx->{opac_root} . "/logout";
353
354     if($e->authtoken($self->cgi->cookie(COOKIE_SES))) {
355
356         if($e->checkauth) {
357
358             $ctx->{authtoken} = $e->authtoken;
359             $ctx->{authtime} = $e->authtime;
360             $ctx->{user} = $e->requestor;
361             my $card = $self->editor->retrieve_actor_card($ctx->{user}->card);
362             $ctx->{active_card} = (ref $card) ? $card->barcode : undef;
363             $ctx->{place_unfillable} = 1 if $e->requestor->wsid && $e->allowed('PLACE_UNFILLABLE_HOLD', $e->requestor->ws_ou);
364
365             # The browser client does not set an OILS-Wrapper header (above).
366             # The presence of a workstation and no header indicates staff mode.
367             # FIXME: this approach leaves un-wrapped TPAC's within the same
368             # browser (and hence same ses cookie) in an unnatural is_staff
369             # state.  Consider alternatives for determining is_staff / 
370             # is_browser_staff when $xul_wrapper is false.
371             if (!$xul_wrapper and $e->requestor->wsid) {
372                 $ctx->{is_staff} = 1;
373                 $ctx->{is_browser_staff} = 1;
374             }
375
376             $self->update_dashboard_stats();
377
378         } else {
379
380             # if we encounter a stale authtoken, call load_logout 
381             # to clean up the cookie, then redirect the user to the
382             # originally requested page
383             return $self->load_logout($self->apache->unparsed_uri);
384         }
385     }
386
387     # List of <meta> and <link> elements to populate
388     $ctx->{metalinks} = [];
389
390     $self->extract_copy_location_group_info;
391     $ctx->{search_ou} = $self->_get_search_lib();
392     $self->staff_saved_searches_set_expansion_state if $ctx->{is_staff};
393     $self->load_eg_cache_hash;
394     $self->load_copy_location_groups;
395     $self->staff_saved_searches_set_expansion_state if $ctx->{is_staff};
396     $self->load_search_filter_groups($ctx->{search_ou});
397     $self->load_org_util_funcs;
398     $self->load_perm_funcs;
399
400     # FIXME - move carousel helpers to a separate file
401     $ctx->{get_visible_carousels} = sub {
402         my $org_unit = $self->ctx->{physical_loc} || $self->cgi->param('loc') || $self->ctx->{aou_tree}->()->id;
403         return $U->simplereq(
404             'open-ils.actor',
405             'open-ils.actor.carousel.retrieve_by_org',
406             $org_unit
407         );
408     };
409     $ctx->{get_carousel} = sub {
410         my $id = shift;
411
412         my $carousel = $e->retrieve_container_carousel($id);
413         my $ret = {
414             id   => $id,
415             name => $carousel->name
416         };
417         my $q = {
418             select => { bre => ['id'], mfde => [{ column => 'value', alias => 'title' }] },
419             from   => {
420                 bre => {
421                     cbrebi => {
422                         join => {
423                             cbreb => {
424                                 join => { cc => {} }
425                             }
426                         }
427                     },
428                     mfde => {}
429                 }
430             },
431             where  => {
432                 '+cc' => { id => $id },
433                 '+bre' => { deleted => 'f' },
434                 '+mfde' => { name => 'title' }
435             }
436         };
437         my $r = $e->json_query($q);
438         $ret->{bibs} = $r;
439         return $ret;
440     };
441
442     $ctx->{fetch_display_fields} = sub {
443         my $id = shift;
444
445         if (@$id == 1) {
446             return $ctx->{_hl_data}{''.$$id[0]}
447                 if ($ctx->{_hl_data}{''.$$id[0]});
448         }
449
450         $self->timelog("HL data not cached, fetching from server.");
451
452         my $rows = $U->simplereq(
453             'open-ils.search', 
454             'open-ils.search.fetch.metabib.display_field.highlight',
455             $ctx->{query_struct}{additional_data}{highlight_map},
456             map {int($_)} @$id
457         );
458
459         $ctx->{_hl_data}{''.$$id[0]} = $rows if (@$id == 1);
460
461         return $rows;
462     };
463
464     return Apache2::Const::OK;
465 }
466
467 sub update_dashboard_stats {
468     my $self = shift;
469
470     my $e = $self->editor;
471     my $ctx = $self->ctx;
472
473     $ctx->{user_stats} = $U->simplereq(
474         'open-ils.actor', 
475         'open-ils.actor.user.opac.vital_stats', 
476         $e->authtoken, $e->requestor->id);
477 }
478
479 sub staff_saved_searches_set_expansion_state {
480     my $self = shift;
481
482     my $param = $self->cgi->param('sss_expand');
483     my $value;
484     
485     if (defined $param) {
486         $value = ($param ? 1 : 0);
487         $self->apache->headers_out->add(
488             "Set-Cookie" => $self->cgi->cookie(
489                 -name => COOKIE_SSS_EXPAND,
490                 -path => $self->ctx->{base_path},
491                 -secure => 1,   # not strictly necessary, but this feature is staff-only, so may as well
492                 -value => $value,
493                 -expires => undef
494             )
495         );
496     } else {
497         $value = $self->cgi->cookie(COOKIE_SSS_EXPAND);
498     }
499
500     $self->ctx->{saved_searches_expanded} = $value;
501 }
502
503 # physical_loc (i.e. "original location") passed in as a URL 
504 # param will replace any existing physical_loc stored as a cookie.
505 # If specified via ENV that rules over all and we don't set cookies.
506 sub get_physical_loc {
507     my $self = shift;
508
509     return $ENV{physical_loc} if($ENV{physical_loc});
510
511     if(my $physical_loc = $self->cgi->param('physical_loc')) {
512         $self->apache->headers_out->add(
513             "Set-Cookie" => $self->cgi->cookie(
514                 -name => COOKIE_PHYSICAL_LOC,
515                 -path => $self->ctx->{base_path},
516                 -value => $physical_loc,
517                 -expires => undef
518             )
519         );
520         return $physical_loc;
521     }
522
523     return $self->cgi->cookie(COOKIE_PHYSICAL_LOC);
524 }
525
526 # -----------------------------------------------------------------------------
527 # Log in and redirect to the redirect_to URL (or home)
528 # -----------------------------------------------------------------------------
529 sub load_login {
530     my $self = shift;
531     my $cgi = $self->cgi;
532     my $ctx = $self->ctx;
533
534     $self->timelog("Load login begins");
535
536     $ctx->{page} = 'login';
537
538     my $username = $cgi->param('username') || '';
539     $username =~ s/\s//g;  # Remove blanks
540     my $password = $cgi->param('password');
541     my $org_unit = $ctx->{physical_loc} || $ctx->{aou_tree}->()->id;
542     my $persist = $cgi->param('persist');
543     my $client_tz = $cgi->param('client_tz');
544
545     # initial log form only
546     return Apache2::Const::OK unless $username and $password;
547
548     my $auth_proxy_enabled = 0; # default false
549     try { # if the service is not running, just let this fail silently
550         $auth_proxy_enabled = $U->simplereq(
551             'open-ils.auth_proxy',
552             'open-ils.auth_proxy.enabled');
553     } catch Error with {};
554
555     $self->timelog("Checked for auth proxy: $auth_proxy_enabled; org = $org_unit; username = $username");
556
557     my $args = {
558         type => ($persist) ? 'persist' : 'opac',
559         org => $org_unit,
560         agent => 'opac'
561     };
562
563     my $bc_regex = $ctx->{get_org_setting}->($org_unit, 'opac.barcode_regex');
564
565     # To avoid surprises, default to "Barcodes start with digits"
566     $bc_regex = '^\d' unless $bc_regex;
567
568     if ($bc_regex and ($username =~ /$bc_regex/)) {
569         $args->{barcode} = $username;
570     } else {
571         $args->{username} = $username;
572     }
573
574     my $response;
575     if (!$auth_proxy_enabled) {
576         my $seed = $U->simplereq(
577             'open-ils.auth',
578             'open-ils.auth.authenticate.init', $username);
579         $args->{password} = md5_hex($seed . md5_hex($password));
580         $response = $U->simplereq(
581             'open-ils.auth', 'open-ils.auth.authenticate.complete', $args);
582     } else {
583         $args->{password} = $password;
584         $response = $U->simplereq(
585             'open-ils.auth_proxy',
586             'open-ils.auth_proxy.login', $args);
587     }
588     $self->timelog("Checked password");
589
590     if($U->event_code($response)) { 
591         # login failed, report the reason to the template
592         $ctx->{login_failed_event} = $response;
593         return Apache2::Const::OK;
594     }
595
596     # login succeeded, redirect as necessary
597
598     my $acct = $self->apache->unparsed_uri;
599     $acct =~ s|/login|/myopac/main|;
600
601     # both login-related cookies should expire at the same time
602     my $login_cookie_expires = ($persist) ? CORE::time + $response->{payload}->{authtime} : undef;
603
604     my $cookie_list = [
605         # contains the actual auth token and should be sent only over https
606         $cgi->cookie(
607             -name => COOKIE_SES,
608             -path => '/',
609             -secure => 1,
610             -value => $response->{payload}->{authtoken},
611             -expires => $login_cookie_expires
612         ),
613         # contains only a hint that we are logged in, and is used to
614         # trigger a redirect to https
615         $cgi->cookie(
616             -name => COOKIE_LOGGEDIN,
617             -path => '/',
618             -secure => 0,
619             -value => '1',
620             -expires => $login_cookie_expires
621         )
622     ];
623
624     if ($client_tz) {
625         # contains the client's tz, as passed by the client
626         # trigger a redirect to https
627         push @$cookie_list, $cgi->cookie(
628             -name => COOKIE_TZ,
629             -path => '/',
630             -secure => 0,
631             -value => $client_tz,
632             -expires => $login_cookie_expires
633         );
634     }
635
636     return $self->generic_redirect(
637         $cgi->param('redirect_to') || $acct,
638         $cookie_list
639     );
640 }
641
642 # -----------------------------------------------------------------------------
643 # Log out and redirect to the home page
644 # -----------------------------------------------------------------------------
645 sub load_logout {
646     my $self = shift;
647     my $redirect_to = shift || $self->cgi->param('redirect_to');
648
649     # If the user was adding anyting to an anonymous cache 
650     # while logged in, go ahead and clear it out.
651     $self->clear_anon_cache;
652
653     try { # a missing auth token will cause an ugly explosion
654         $U->simplereq(
655             'open-ils.auth',
656             'open-ils.auth.session.delete',
657             $self->cgi->cookie(COOKIE_SES)
658         );
659     } catch Error with {};
660
661     return $self->generic_redirect(
662         $redirect_to || $self->ctx->{home_page},
663         [
664             # clear value of and expire both of these login-related cookies
665             $self->cgi->cookie(
666                 -name => COOKIE_SES,
667                 -path => '/',
668                 -value => '',
669                 -expires => '-1h'
670             ),
671             $self->cgi->cookie(
672                 -name => COOKIE_LOGGEDIN,
673                 -path => '/',
674                 -value => '',
675                 -expires => '-1h'
676             )
677         ]
678     );
679 }
680
681 1;
682