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