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