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