chiark / gitweb /
6453779c2a6d7234930b4944a33613e09aa81599
[cgi-auth-flexible.git] / cgi-auth-hybrid.pm
1 # -*- perl -*-
2
3 # This is part of CGI::Auth::Hybrid, a perl CGI authentication module.
4 # Copyright (C) 2012 Ian Jackson.
5 # Copyright (C) 2012 Citrix.
6
7 # This program is free software: you can redistribute it and/or modify
8 # it under the terms of the GNU Affero General Public License as published by
9 # the Free Software Foundation, either version 3 of the License, or
10 # (at your option) any later version.
11
12 # This program is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 # GNU Affero General Public License for more details.
16
17 # You should have received a copy of the GNU Affero General Public License
18 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
19
20 use strict;
21 use warnings;
22
23 package CGI::Auth::Hybrid;
24 require Exporter;
25
26 BEGIN {
27     use Exporter   ();
28     our ($VERSION, @ISA, @EXPORT, @EXPORT_OK, %EXPORT_TAGS);
29
30     $VERSION     = 1.00;
31     @ISA         = qw(Exporter);
32     @EXPORT      = qw();
33     %EXPORT_TAGS = ( );     # eg: TAG => [ qw!name1 name2! ],
34
35     @EXPORT_OK   = qw(setup);
36 }
37 our @EXPORT_OK;
38
39 use DBI;
40 use CGI qw/escapeHTML/;
41 use Locale::gettext;
42 use URI;
43 use IO::File;
44 use Data::Dumper;
45
46 #---------- public utilities ----------
47
48 sub flatten_params ($) {
49     my ($p) = @_;
50     my @p;
51     foreach my $k (keys %$p) {
52         foreach my $v (@{ $p->{$k} }) {
53             push @p, $k, $v;
54         }
55     }
56     return @p;
57 }
58
59 #---------- default callbacks ----------
60
61 sub has_a_param ($$) {
62     my ($r,$cn) = @_;
63     foreach my $pn (@{ $r->{S}{$cn} }) {
64         return 1 if $r->_ch('get_param',$pn);
65     }
66     return 0;
67 }
68
69 sub get_params ($) {
70     my ($r) = @_;
71     my %p;
72     my $c = $r->{Cgi};
73     foreach my $name ($c->param()) {
74         $p{$name} = [ $c->param($name) ];
75     }
76     return \%p;
77 }
78
79 sub get_cookie_domain ($$$) {
80     my ($c,$r) = @_;
81     my $uri = new URI $r->_ch('get_url');
82     return $uri->host();
83 }
84
85 sub login_ok_password ($$) {
86     my ($c, $r) = @_;
87     my $username_params = $r->{S}{username_param_names};
88     my $username = $r->_ch('get_param',$username_params->[0]);
89     my $password = $r->_rp('password_param_name');
90     return $r->_ch('username_password_ok', $username, $password);
91 }
92
93 sub do_redirect_cgi ($$$$) {
94     my ($c, $r, $new_url, $cookie) = @_;
95     $r->_print($c->header($r->_cgi_header_args($cookie,
96                                                -status => '303 See other',
97                                                -location => $new_url)),
98                $r->_ch('gen_start_html',$r->_gt('Redirection')),
99                '<a href="'.escapeHTML($new_url).'">',
100                $r->_gt("If you aren't redirected, click to continue."),
101                "</a>",
102                $c->_ch('gen_end_html'));
103 }
104
105 sub gen_plain_login_form ($$) {
106     my ($c,$r, $params) = @_;
107     my @form;
108     push @form, ('<form method="POST" action="'.
109                  escapeHTML($r->_ch('get_url')).'">'.
110                  '<table>');
111     my $sz = 'size="'.$r->{S}{form_entry_size}.'"';
112     foreach my $up (@{ $r->{S}{username_param_names}}) {
113         push @form, ('<tr><td>',$r->_gt(ucfirst $up),'</td>',
114                      '<td><input type="text" '.$sz.
115                      ' name='.$up.'></td></tr>');
116     }
117     push @form, ('<tr><td>'.$r->_gt('Password'),'</td>',
118                  '<td><input type="password" '.$sz.
119                  ' name="'.$r->{S}{password_param_name}.'"></td></tr>');
120     push @form, ('<tr><td colspan="2">',
121                  '<input type="submit"'.
122                  ' name="'.$r->{S}{login_submit_name}.'"'.
123                  ' value="'.$r->_gt('Login').'"></td></tr>',
124                  '</table>');
125     foreach my $n (keys %$params) {
126         push @form, ('<input type="hidden"'.
127                      ' name="'.$n.'"'.
128                      ' value="'.$params->{$n}.'">');
129     }
130     push @form, ('</form>');
131     return join "\n", @form;
132 }
133
134 sub gen_login_link ($$) {
135     my ($c,$r, $params) = @_;
136     my $url = $r->url_with_query_params($params);
137     return ('<a href="'.escapeHTML($url).'">'.
138             $r->_gt('Log in again to continue.').
139             '</a>');
140 }
141
142 #---------- verifier object methods ----------
143
144 sub new_verifier {
145     my $class = shift;
146     my $verifier = {
147         S => {
148             assocdb_path => 'cah-assocs.db',
149             assocdb_dsn => undef,
150             assocdb_user => '',
151             assocdb_password => '',
152             assocdb_table => 'assocs',
153             random_source => '/dev/urandom',
154             associdlen => 128, # bits
155             login_timeout => 86400, # seconds
156             assoc_param_name => 'cah_associd',
157             password_param_name => 'password',
158             username_param_names => [qw(username)],
159             form_entry_size => 60,
160             logout_param_names => [qw(cah_logout)],
161             login_submit_name => [qw(cah_login)],
162             loggedout_param_names => [qw(cah_loggedout)],
163             promise_check_mutate => 0,
164             get_param => sub { $_[0]->param($_[2]) },
165             get_params => sub { $_[1]->get_params() },
166             get_cookie => sub { $_[0]->cookie($_[1]->{S}{cookie_name}) },
167             get_method => sub { $_[0]->request_method() },
168             get_url => sub { $_[0]->url(); },
169             is_login => sub { defined $_[1]->_rp('password_param_name') },
170             login_ok => \&login_ok_password,
171             username_password_ok => sub { die },
172             is_logout => sub { $_[1]->has_a_param('logout_param_names') },
173             is_loggedout => sub { $_[1]->has_a_param('loggedout_param_names') },
174             is_page => sub { return 1 },
175             handle_divert => sub { return 0 },
176             do_redirect => \&do_redirect_cgi, # this hook is allowed to throw
177             cookie_path => "/",
178             get_cookie_domain => \&get_cookie_domain,
179             encrypted_only => 0,
180             gen_start_html => sub { $_[0]->start_html($_[2]); },
181             gen_end_html => sub { $_[0]->end_html(); },
182             gen_login_form => \&gen_plain_login_form,
183             gen_login_link => \&gen_plain_login_link,
184             gettext => sub { gettext($_[2]); },
185             print => sub { print $_[2] or die $!; },
186         },
187         Dbh => undef,
188     };
189     my ($k,$v);
190     while (($k,$v,@_) = @_) {
191         die "unknown setting $k" unless exists $verifier->{S}{$k};
192         $verifier->{S}{$k} = $v;
193     }
194     bless $verifier, $class;
195     $verifier->_dbopen();
196     return $verifier;
197 }
198
199 sub _dbopen ($) {
200     my ($v) = @_;
201     my $dbh = $v->{Dbh};
202     return $dbh if $dbh; 
203
204     $v->{S}{assocdb_dsn} ||= "dbi:SQLite:dbname=$v->{S}{assocdb_path}";
205     my $dsn = $v->{S}{assocdb_dsn};
206
207     my $u = umask 077;
208     $dbh = DBI->connect($dsn, $v->{S}{assocdb_user}, 
209                         $v->{S}{assocdb_password}, { 
210                             AutoCommit => 0,
211                             RaiseError => 1,
212                             ShowErrorStatement => 1,
213                         });
214     die "$dsn $! ?" unless $dbh;
215     $v->{Dbh} = $dbh;
216
217     eval {
218         $v->_db_transaction(sub {
219             local ($dbh->{PrintError}) = 0;
220             $dbh->do("CREATE TABLE $v->{S}{assocdb_table} (".
221                      " associd VARCHAR PRIMARY KEY,".
222                      " username VARCHAR,".
223                      " last INTEGER NOT NULL".
224                      ")");
225         });
226     };
227     return $dbh;
228 }
229
230 sub disconnect ($) {
231     my ($v) = @_;
232     my $dbh = $v->{Dbh};
233     return unless $dbh;
234     $dbh->disconnect();
235 }
236
237 sub _db_transaction ($$) {
238     my ($v, $fn) = @_;
239     my $retries = 10;
240     my $rv;
241     my $dbh = $v->{Dbh};
242 print STDERR "DT entry\n";
243     for (;;) {
244 print STDERR "DT loop\n";
245         if (!eval {
246             $rv = $fn->();
247 print STDERR "DT fn ok\n";
248             1;
249         }) {
250 print STDERR "DT fn error\n";
251             { local ($@); $dbh->rollback(); }
252 print STDERR "DT fn throwing\n";
253             die $@;
254         }
255 print STDERR "DT fn eval ok\n";
256         if (eval {
257             $dbh->commit();
258 print STDERR "DT commit ok\n";
259             1;
260         }) {
261 print STDERR "DT commit eval ok $rv\n";
262             return $rv;
263         }
264 print STDERR "DT commit throw?\n";
265         die $@ if !--$retries;
266 print STDERR "DT loop again\n";
267     }
268 }
269
270 #---------- request object methods ----------
271
272 sub new_request {
273     my ($classbase, $cgi, @extra) = @_;
274     if (!ref $classbase) {
275         $classbase = $classbase->new_verifier(@extra);
276     } else {
277         die if @extra;
278     }
279     my $r = {
280         V => $classbase,
281         S => $classbase->{S},
282         Dbh => $classbase->{Dbh},
283         Cgi => $cgi,
284     };
285     bless $r, ref $classbase;
286 }
287
288 sub _ch ($$@) { # calls an application hook
289     my ($r,$methname, @args) = @_;
290     my $methfunc = $r->{S}{$methname};
291     die "$methname ?" unless $methfunc;
292     return $methfunc->($r->{Cgi}, $r, @args);
293 }
294
295 sub _rp ($$@) {
296     my ($r,$pnvb) = @_;
297     my $pn = $r->{S}{$pnvb};
298     my $p = scalar $r->_ch('get_param',$pn)
299 }
300
301 sub _gt ($$) { my ($r, $t) = @_; return $r->_ch('gettext',$t); }
302 sub _print ($$) { my ($r, @t) = @_; return $r->_ch('print', join '', @t); }
303
304 sub construct_cookie ($$$) {
305     my ($r, $cookv) = @_;
306     return undef unless $cookv;
307     my $c = $r->{Cgi};
308     my $cookie = $c->cookie(-name => $r->{S}{cookie_name},
309                              -value => $cookv,
310                              -path => $r->{S}{cookie_path},
311                              -domain => $r->_ch('get_cookie_domain'),
312                              -expires => '+'.$r->{S}{login_timeout}.'s',
313                              -secure => $r->{S}{encrypted_only});
314 print STDERR "CC $r $c $cookv $cookie\n";
315     return $cookie;
316 }
317
318 # pages/param-sets are
319 #   n normal non-mutating page
320 #   r retrieval of information for JS, non-mutating
321 #   m mutating page
322 #   u update of information by JS, mutating
323 #   i login
324 #   o logout
325 #   O "you have just logged out" page load
326
327 # in cook and par,
328 #    a, aN     anything including -
329 #    t, tN     temporary value (in our db, no logged in user yet)
330 #    y, yN     value corresponds to logged-in user
331 #    n, nN     value not in our db
332 #    x, xN     t or y
333 #    -         no value supplied (represented in code as $cookt='')
334 # if N differs the case applies only when the two values differ
335 # (eg,   a1 y2   does not apply when the logged-in value is supplied twice)
336
337 # "stale session" means request originates from a page from a login
338 # session which has been revoked (eg by logout); "cleared session"
339 # means request originates from a browser which has a different (or
340 # no) cookie.
341
342     # Case analysis, cookie mode, app promises re mutate:
343     # cook parm meth form
344     #                      
345     #  any -   POST  nrmuoi   bug or attack, fail
346     #  any -   GET    rmuoi   bug or attack, fail
347     #  any any GET     muoi   bug or attack, fail
348     #  any t   any   nrmu     bug or attack, fail
349     #
350     #  -   -   GET         O  "just logged out" page
351     #  (any other)         O  bug or attack, fail
352     #
353     #  a1  a2  POST      o    logout
354     #                           if a1 is valid, revoke it
355     #                           if a2 is valid, revoke it
356     #                           delete cookie
357     #                           redirect to "just logged out" page
358     #                             (which contains link to login form)
359     #
360     #  -   t   POST       i   complain about cookies being disabled
361     #                           (with link to login form)
362     #
363     #  any n   POST       i   complain about stale login form
364     #                           show new login form
365     #
366     #  x1  t2  POST       i   login (or switch user)
367     #                           if bad
368     #                             show new login form
369     #                           if good
370     #                             revoke x1 if it was valid and !=t2
371     #                             upgrade t2 to y2 in our db (setting username)
372     #                             set cookie to t2
373     #                             redirect to GET of remaining params
374     #
375     #  t1  a2  ANY   nrmu     treat as  - a2 ANY
376     #
377     #  y   -   GET   n        cross-site link
378     #                           show data
379     #
380     #  y   y   GET   nr       fine, show page or send data
381     #  y   y   POST  nrmu     mutation is OK, do operation
382     #
383     #  y1  y2  GET   nr       request from stale page
384     #                           do not revoke y2 as not RESTful
385     #                           treat as   y1 n GET
386     #
387     #  y1  y2  POST  nrmu     request from stale page
388     #                           revoke y2
389     #                           treat as   y1 n POST
390     #
391     #  y   n   GET   n        intra-site link from stale page,
392     #                           treat as cross-site link, show data
393     #
394     #  y   n   POST  n m      intra-site form submission from stale page
395     #                           show "session interrupted"
396     #                           with link to main data page
397     #
398     #  y   n   GET    r       intra-site request from stale page
399     #                           fail
400     #
401     #  y   n   POST   r u     intra-site request from stale page
402     #                           fail
403     #
404     #  -/n y2  GET   nr       intra-site link from cleared session
405     #                           do not revoke y2 as not RESTful
406     #                           treat as   -/n n GET
407     #
408     #  -/n y2  POST  nrmu     request from cleared session
409     #                           revoke y2
410     #                           treat as   -/n n POST
411     #
412     #  -/n -/n GET   n        cross-site link but user not logged in
413     #                           show login form with redirect to orig params
414     #                           generate fresh cookie
415     #
416     #  -/n n   GET    rmu     user not logged in
417     #                           fail
418     #
419     #  -/n n   POST  n m      user not logged in
420     #                           show login form
421     #
422     #  -/n n   POST   r u     user not logged in
423     #                           fail
424
425 sub _check_divert_core ($) {
426     my ($r) = @_;
427
428     my $meth = $r->_ch('get_method');
429     my $cookv = $r->_ch('get_cookie');
430     my $parmv = $r->_rp('assoc_param_name');
431
432     my ($cookt,$cooku) = $r->_db_lookup($cookv);
433     my $parmt = $r->_db_lookup($parmv);
434
435     print STDERR "_c_d_c cookt=$cookt parmt=$parmt\n";
436
437     if ($r->_ch('is_logout')) {
438         $r->_must_be_post();
439         die unless $parmt;
440         $r->_db_revoke($cookv);
441         $r->_db_revoke($parmv);
442         return ({ Kind => 'REDIRECT-LOGGEDOUT',
443                   Message => "Logging out...",
444                   CookieVal => '',
445                   Params => { } });
446     }
447     if ($r->_ch('is_loggedout')) {
448         die unless $meth eq 'GET';
449         die unless $cookt;
450         die unless $parmt;
451         return ({ Kind => 'SMALLPAGE-LOGGEDOUT',
452                   Message => "You have been logged out.",
453                   CookieVal => '',
454                   Params => { } });
455     }
456     if ($r->_ch('is_login')) {
457         $r->_must_be_post();
458         return ({ Kind => 'LOGIN-STALE',
459                   Message => "Stale session; you need to log in again.",
460                   CookieVal => $r->_fresh_cookie(),
461                   Params => { } })
462             if $parmt eq 'n';
463         die unless $parmt eq 't' || $parmt eq 'y';
464         return ({ Kind => 'SMALLPAGE-NOCOOKIE',
465                   Message => "You do not seem to have cookies enabled.  ".
466                       "You must enable cookies as we use them for login.",
467                   CookieVal => $r->_fresh_cookie(),
468                   Params => $r->_chain_params() })
469             if !$cookt && $parmt eq 't';
470         my $username = $r->_ch('login_ok');
471         return ({ Kind => 'LOGIN-BAD',
472                   Message => "Incorrect username/password.",
473                   CookieVal => $cookv,
474                   Params => $r->_chain_params() })
475             unless defined $username && length $username;
476         $r->_db_revoke($cookv) 
477             if defined $cookv && !(defined $parmv && $cookv eq $parmv);
478         $r->_db_record_login_ok($parmv,$username);
479         return ({ Kind => 'REDIRECT-LOGGEDIN',
480                   Message => "Logging in...",
481                   CookieVal => $parmv,
482                   Params => $r->_chain_params() });
483     }
484     if ($cookt eq 't') {
485         $cookt = '';
486     }
487     die if $parmt eq 't';
488
489     if ($cookt eq 'y' && $parmt eq 'y' && $cookv ne $parmv) {
490         $r->_db_revoke($parmv) if $meth eq 'POST';
491         $parmt = 'n';
492     }
493
494     if ($cookt ne 'y') {
495         die unless !$cookt || $cookt eq 'n';
496         die unless !$parmt || $parmt eq 'n' || $parmt eq 'y';
497         my $newv = $r->_fresh_cookie();
498         if ($meth eq 'GET') {
499             return ({ Kind => 'LOGIN-INCOMINGLINK',
500                       Message => "You need to log in again.",
501                       CookieVal => $newv,
502                       Params => $r->_chain_params() });
503         } else {
504             $r->_db_revoke($parmv);
505             return ({ Kind => 'LOGIN-FRESH',
506                       Message => "You need to log in again.",
507                       CookieVal => $newv,
508                       Params => { } });
509         }
510     }
511
512     if (!$r->{S}{promise_check_mutate}) {
513         if ($meth ne 'POST') {
514             return ({ Kind => 'MAINPAGEONLY',
515                       Message => 'Entering via cross-site link.',
516                       CookieVal => $cookv,
517                       Params => { } });
518             # NB caller must then ignore params & path!
519             # if this is too hard they can spit out a small form
520             # with a "click to continue"
521         }
522     }
523
524     die unless $cookt eq 'y';
525     die unless $parmt eq 'y';
526     die unless $cookv eq $parmv;
527     $r->{Assoc} = $cookv;
528     $r->{UserOK} = $cooku;
529     print STDERR "C-D-C OK\n";
530     return undef;
531 }
532
533 sub _chain_params ($) {
534     my ($r) = @_;
535     my %p = %{ $r->_ch('get_params') };
536     foreach my $pncn (keys %{ $r->{S} }) {
537         my $names;
538         if ($pncn =~ m/_param_name$/) {
539             my $name = $r->{S}{$pncn};
540             die "$pncn ?" if ref $name;
541             $names = [ $name ];
542         } elsif ($pncn =~ m/_param_names$/) {
543             $names = $r->{S}{$pncn};
544         } else {
545             next;
546         }
547         foreach my $name (@$names) {
548             delete $p{$name};
549         }
550     }
551     return \%p;
552 }
553
554 sub _db_lookup ($$) {
555     my ($r,$v) = @_;
556     # returns ($t,$username)
557     # where $t is one of "t" "y" "n", or "" (for -)
558
559     my $dbh = $r->{Dbh};
560
561     my $row = $dbh->selectrow_arrayref("SELECT username, last".
562                               " FROM $r->{S}{assocdb_table}".
563                               " WHERE associd = ?", {}, $v);
564     return ('') unless defined $row;
565
566     my ($nusername, $nlast) = @$row;
567
568     my $timeout = $r->{S}{login_timeout};
569     return ('n') unless !defined $timeout || time <= $nlast + $timeout;
570
571     return ('t') unless defined $nusername;
572
573     # hooray
574     return ('y', $nusername);
575 }
576
577 sub _db_revoke ($$) {
578     # revokes $v if it's valid; no-op if it's not
579     my ($r,$v) = @_;
580
581     my $dbh = $r->{Dbh};
582
583     $dbh->do("DELETE FROM $r->{S}{assocdb_table}".
584              " WHERE associd = ?", {}, $v);
585 }
586
587 sub _db_record_login_ok ($$$) {
588     my ($r,$v,$user) = @_;
589     $r->_db_revoke($v);
590     my $dbh = $r->{Dbh};
591     $dbh->do("INSERT INTO $r->{S}{assocdb_table}".
592              " (associd, username, last) VALUES (?,?,?)", {},
593              $v, $user, time);
594 }
595
596 sub check_divert ($) {
597     my ($r) = @_;
598     if (exists $r->{Divert}) {
599         return $r->{Divert};
600     }
601     my $dbh = $r->{Dbh};
602     $r->{Divert} = $r->_db_transaction(sub { $r->_check_divert_core(); });
603     $dbh->commit();
604     print STDERR Dumper($r->{Divert});
605     return $r->{Divert};
606 }
607
608 sub get_divert ($) {
609     my ($r) = @_;
610     die "unchecked" unless exists $r->{Divert};
611     return $r->{Divert};
612 }
613
614 sub get_username ($) {
615     my ($r) = @_;
616     my $divert = $r->get_divert();
617     return undef if $divert;
618     return $r->{UserOK};
619 }
620
621 sub url_with_query_params ($$) {
622     my ($r, $params) = @_;
623     my $uri = URI->new($r->_ch('get_url'));
624     $uri->query_form(flatten_params($params));
625     return $uri->as_string();
626 }
627
628 sub _cgi_header_args ($$@) {
629     my ($r, $cookie, @ha) = @_;
630     unshift @ha, qw(-type text/html);
631     push @ha, (-cookie => $cookie) if defined $cookie;
632     print STDERR "_cgi_header_args ",join('|',@ha),".\n";
633     return @ha;
634 }
635
636 sub check_ok ($) {
637     my ($r) = @_;
638
639     my ($divert) = $r->check_divert();
640     return 1 if !$divert;
641
642     my $handled = $r->_ch('handle_divert',$divert);
643     return 0 if $handled;
644
645     my $kind = $divert->{Kind};
646     my $cookieval = $divert->{CookieVal};
647     my $params = $divert->{Params};
648     my $cookie = $r->construct_cookie($cookieval);
649
650     if ($kind =~ m/^REDIRECT-/) {
651         # for redirects, we honour stored NextParams and SetCookie,
652         # as we would for non-divert
653         if ($kind eq 'REDIRECT-LOGGEDOUT') {
654             $params->{$r->{S}{loggedout_param_names}[0]} = 1;
655         } elsif ($kind eq 'REDIRECT-LOGOUT') {
656             $params->{$r->{S}{logout_param_names}[0]} = 1;
657         } elsif ($kind eq 'REDIRECT-LOGGEDIN') {
658         } else {
659             die;
660         }
661         my $new_url = $r->url_with_query_params($params);
662         $r->_ch('do_redirect',$new_url, $cookie);
663         return 0;
664     }
665
666     my ($title, @body);
667     if ($kind =~ m/^LOGIN-/) {
668         $title = $r->_gt('Login');
669         push @body, $r->_gt($divert->{Message});
670         push @body, $r->_ch('gen_login_form', $params);
671     } elsif ($kind =~ m/^SMALLPAGE-/) {
672         $title = $r->_gt('Not logged in');
673         push @body, $r->_gt($divert->{Message});
674         push @body, $r->_ch('gen_login_link');
675     } else {
676         die $kind;
677     }
678
679     $r->_print($r->{Cgi}->header($r->_cgi_header_args($cookie)),
680                $r->_ch('gen_start_html',$title),
681                @body,
682                $r->_ch('gen_end_html'));
683     return 0;
684 }
685
686 sub _random ($$) {
687     my ($r, $bytes) = @_;
688     my $v = $r->{V};
689     my $rsf = $v->{RandomHandle};
690     my $rsp = $r->{S}{random_source};
691     if (!$rsf) {
692         $v->{RandomHandle} = $rsf = new IO::File $rsp, '<' or die "$rsp $!";
693     }
694     my $bin;
695     $!=0;
696     read($rsf,$bin,$bytes) == $bytes or die "$rsp $!";
697     close $rsf;
698     my $out = unpack "H*", $bin;
699     print STDERR "_random out $out\n";
700     return $out;
701 }
702
703 sub _fresh_cookie ($) {
704     my ($r) = @_;
705     print STDERR "_fresh_cookie\n";
706     my $bytes = ($r->{S}{associdlen} + 7) >> 3;
707     return $r->_random($bytes);
708 }
709
710 sub _assert_checked ($) {
711     my ($r) = @_;
712     die "unchecked" unless exists $r->{Divert};
713 }
714
715 sub check_mutate ($) {
716     my ($r) = @_;
717     $r->_assert_checked();
718     die if $r->{Divert};
719     my $meth = $r->_ch('get_method');
720     die "mutating non-POST" if $meth ne 'POST';
721 }
722
723 #---------- output ----------
724
725 sub secret_val ($) {
726     my ($r) = @_;
727     $r->_assert_checked();
728     return defined $r->{Assoc} ? $r->{Assoc} : '';
729 }
730
731 sub secret_hidden_html ($) {
732     my ($r) = @_;
733     return $r->{Cgi}->hidden(-name => $r->{S}{assoc_param_name},
734                              -default => $r->secret_val());
735 }
736
737 sub secret_cookie ($) {
738     my ($r) = @_;
739 #print STDERR "SC\n";
740     my $cookv = $r->construct_cookie($r->secret_val()); 
741 #print STDERR "SC=$cookv\n";
742     return $cookv;
743 }
744
745 __END__
746
747 =head1 NAME
748
749 CGI::Auth::Hybrid - web authentication optionally using cookies
750
751 =head1 SYNOPSYS
752
753  my $verifier = CGI::Auth::Hybrid->new_verifier(setting => value,...);
754  my $authreq = $verifier->new_request($cgi_request_object);
755
756  my $authreq = CGI::Auth::Hybrid->new_request($cgi_request_object,
757                                               setting => value,...);
758
759 =head1 USAGE PATTERN FOR SIMPLE APPLICATIONS
760
761  $authreq->check_ok() or return;
762
763  blah blah blah
764  $authreq->check_mutate();
765  blah blah blah
766
767 =head1 USAGE PATTERN FOR FANCY APPLICATIONS
768
769  my $divert_kind = $authreq->check_divert();
770  if ($divert_kind) {
771      if ($divert_kind eq 'LOGGEDOUT') {
772          print "goodbye you are now logged out" and quit
773      } elsif ($divert_kind eq 'NOCOOKIES') {
774          print "you need cookies" and quit
775      ... etc.
776      }
777  }
778
779  blah blah blah
780  $authreq->check_mutate();
781  blah blah blah