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