chiark / gitweb /
automatic agpl compliance: fixes
[cgi-auth-flexible.git] / cgi-auth-flexible.pm
1 # -*- perl -*-
2
3 # This is part of CGI::Auth::Flexible, 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 FATAL => 'all';
22
23 package CGI::Auth::Flexible;
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();
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 Fcntl qw(:flock);
45 use POSIX;
46 use Digest;
47 use Digest::HMAC;
48 use Digest::SHA;
49 use Data::Dumper;
50 use File::Copy;
51
52 #---------- public utilities ----------
53
54 sub flatten_params ($) {
55     my ($p) = @_;
56     my @p;
57     foreach my $k (keys %$p) {
58         next if $k eq '';
59         foreach my $v (@{ $p->{$k} }) {
60             push @p, $k, $v;
61         }
62     }
63     return @p;
64 }
65
66 #---------- default callbacks ----------
67
68 sub has_a_param ($$) {
69     my ($r,$cn) = @_;
70     foreach my $pn (@{ $r->{S}{$cn} }) {
71         return 1 if $r->_ch('get_param',$pn);
72     }
73     return 0;
74 }
75
76 sub get_params ($) {
77     my ($r) = @_;
78     my %p;
79     my $c = $r->{Cgi};
80     foreach my $name ($c->param()) {
81         $p{$name} = [ $c->param($name) ];
82     }
83     return \%p;
84 }
85
86 sub get_cookie_domain ($$$) {
87     my ($c,$r) = @_;
88     my $uri = new URI $r->_ch('get_url');
89     return $uri->host();
90 }
91
92 sub login_ok_password ($$) {
93     my ($c, $r) = @_;
94     my $username_params = $r->{S}{username_param_names};
95     my $username = $r->_ch('get_param',$username_params->[0]);
96     my $password = $r->_rp('password_param_name');
97     my $error = $r->_ch('username_password_error', $username, $password);
98     return defined($error) ? (undef,$error) : ($username,undef);
99 }
100
101 sub do_redirect_cgi ($$$$) {
102     my ($c, $r, $new_url, $cookie) = @_;
103     $r->_print($c->header($r->_cgi_header_args($cookie,
104                                                -status => '303 See other',
105                                                -location => $new_url)),
106                $r->_ch('gen_start_html',$r->_gt('Redirection')),
107                '<a href="'.escapeHTML($new_url).'">',
108                $r->_gt("If you aren't redirected, click to continue."),
109                "</a>",
110                $r->_ch('gen_end_html'));
111 }
112
113 sub gen_some_form ($$) {
114     my ($r, $params, $bodyfn) = @_;
115     # Calls $bodyfn->($c,$r) which returns @formbits
116     my $c = $r->{Cgi};
117     my @form;
118     my $pathinfo = '';
119     $pathinfo .= $params->{''}[0] if $params->{''};
120     push @form, ('<form method="POST" action="'.
121                  escapeHTML($r->_ch('get_url').$pathinfo).'">');
122     push @form, $bodyfn->($c,$r);
123     foreach my $n (keys %$params) {
124         next if $n eq '';
125         foreach my $val (@{ $params->{$n} }) {
126             push @form, ('<input type="hidden"'.
127                          ' name="'.escapeHTML($n).'"'.
128                          ' value="'.escapeHTML($val).'">');
129         }
130     }
131     push @form, ('</form>');
132     return join "\n", @form;
133 }
134
135 sub gen_plain_login_form ($$) {
136     my ($c,$r, $params) = @_;
137     return $r->gen_some_form($params, sub {
138         my @form;
139         push @form, ('<table>');
140         my $sz = 'size="'.$r->{S}{form_entry_size}.'"';
141         foreach my $up (@{ $r->{S}{username_param_names}}) {
142             push @form, ('<tr><td>',$r->_gt(ucfirst $up),'</td>',
143                          '<td><input type="text" '.$sz.
144                          ' name='.$up.'></td></tr>');
145         }
146         push @form, ('<tr><td>'.$r->_gt('Password').'</td>',
147                      '<td><input type="password" '.$sz.
148                      ' name="'.$r->{S}{password_param_name}.'"></td></tr>');
149         push @form, ('<tr><td colspan="2">',
150                      '<input type="submit"'.
151                      ' name="'.$r->{S}{dummy_param_name_prefix}.'login"'.
152                      ' value="'.$r->_gt('Login').'"></td></tr>',
153                      '</table>');
154         return @form;
155     });
156 }
157
158 sub gen_postmainpage_form ($$$) {
159     my ($c,$r, $params) = @_;
160     return $r->gen_some_form($params, sub {
161         my @form;
162         push @form, ('<input type="submit"',
163                      ' name="'.$r->{S}{dummy_param_name_prefix}.'submit"'.
164                      ' value="'.$r->_gt('Continue').'">');
165         return @form;
166     });
167 }
168
169 sub gen_plain_login_link ($$) {
170     my ($c,$r, $params) = @_;
171     my $url = $r->url_with_query_params($params);
172     return ('<a href="'.escapeHTML($url).'">'.
173             $r->_gt('Log in again to continue.').
174             '</a>');
175 }
176
177 sub gen_srcdump_link_html ($$$$) {
178     my ($c,$r,$anchor,$specval) = @_;
179     my %params = ($r->{S}{srcdump_param_name} => [ $specval ]);
180     return '<a href="'.escapeHTML($r->url_with_query_params(\%params)).'">'.
181         $anchor."</a>";
182 }
183 sub gen_plain_licence_link_html ($$) {
184     my ($c,$r) = @_;
185     gen_srcdump_link_html($c,$r, 'GNU Affero GPL', 'licence');
186 }
187 sub gen_plain_source_link_html ($$) {
188     my ($c,$r) = @_;
189     gen_srcdump_link_html($c,$r, 'Source available', 'source');
190 }
191
192 sub gen_plain_footer_html ($$) {
193     my ($c,$r) = @_;
194     return ('<hr><address>',
195             ("Powered by Free / Libre / Open Source Software".
196              " according to the ".$r->_ch('gen_licence_link_html')."."),
197             $r->_ch('gen_source_link_html').".",
198             '</address>');
199 }
200
201 #---------- licence and source code ----------
202
203 sub srcdump_dump ($$$) {
204     my ($c,$r, $thing) = @_;
205     die if $thing =~ m/\W/ || $thing !~ m/\w/;
206     my $path = $r->_get_path('srcdump');
207     my $ctf = new IO::File "$path/$thing.ctype", 'r'
208         or die "$path/$thing.ctype $!";
209     my $ct = <$ctf>;
210     chomp $ct or die "$path/$thing ?";
211     $ctf->close or die "$path/$thing $!";
212     my $df = new IO::File "$path/$thing.data", 'r'
213         or die "$path/$thing.data $!";
214     $r->_ch('dump', $ct, $df);
215 }
216
217 sub dump_plain ($$$$) {
218     my ($c, $r, $ct, $df) = @_;
219     $r->_print($c->header('-type' => $ct));
220     my $buffer;
221     for (;;) {
222         my $got = read $df, $buffer, 65536;
223         die $! unless defined $got;
224         return if !$got;
225         $r->_print($buffer);
226     }
227 }
228
229 sub srcdump_process_dir ($$$$$$) {
230     my ($c, $v, $dumpdir, $incdir, $tarballcounter,
231         $needlicence, $dirsdone) = @_;
232     return () if $v->_ch('srcdump_system_dir', $incdir);
233     my $upwards = $incdir;
234     for (;;) {
235         $upwards =~ s#/+$##;
236         last unless $upwards =~ m#[^/]#;
237         foreach my $try (@{ $v->{S}{srcdump_vcs_dirs} }) {
238 #print STDERR "TRY $incdir $upwards $try\n";
239             if (!stat "$upwards/$try") {
240                 $!==&ENOENT or die "check $upwards/$try $!";
241                 next;
242             }
243 #print STDERR "VCS $incdir $upwards $try\n";
244             return if $dirsdone->{$upwards}++;
245 #print STDERR "VCS $incdir $upwards $try GO\n";
246             $try =~ m/\w+/ or die;
247             return $v->_ch(('srcdump_byvcs_'.lc $&),
248                            $dumpdir, $upwards, $tarballcounter);
249         }
250         $upwards =~ s#/*[^/]+##;
251     }
252     return $v->_ch('srcdump_novcs', $dumpdir, $incdir, $tarballcounter);
253 }
254
255 sub srcdump_novcs ($$$$$) {
256     my ($c, $v, $dumpdir, $dir, $tarballcounter) = @_;
257     my $script = 'find -type f -perm +004';
258     foreach my $excl (@{ $v->{S}{srcdump_excludes} }) {
259         $script .= " \\! -name '$excl'";
260     }
261     $script .= " -print0";
262     return srcdump_dir_cpio($c,$v,$dumpdir,$dir,$tarballcounter,$script);
263 }
264
265 sub srcdump_byvcs_git ($$$$$) {
266     my ($c, $v, $dumpdir, $dir, $tarballcounter) = @_;
267 #print STDERR "BYVCS GIT $dir\n";
268     return srcdump_dir_cpio($c,$v,$dumpdir,$dir,$tarballcounter,"
269                  git ls-files -z
270                  git ls-files -z --others --exclude-from=.gitignore
271                  find .git -print0
272                             ");
273 }
274
275 sub srcdump_dir_cpio ($$$$$) {
276     my ($c,$v,$dumpdir,$dir,$tarballcounter,$script) = @_;
277     my $outfile = "$dumpdir/$$tarballcounter.tar";
278 #print STDERR "CPIO $dir >$script<\n";
279     my $pid = fork();
280     defined $pid or die $!;
281     if (!$pid) {
282         $SIG{__DIE__} = sub {
283             print STDERR "CGI::Auth::Flexible srcdump error: $@\n";
284             exit 127;
285         };
286         open STDOUT, ">", $outfile or die "$outfile $!";
287         chdir $dir or die "chdir $dir: $!";
288         exec '/bin/bash','-ec',"
289             set -o pipefail
290             (
291              $script
292             ) | (
293              cpio -Hustar -o --quiet -0 -R 1000:1000 || \
294              cpio -Hustar -o --quiet -0
295             )
296             ";
297         die $!;
298     }
299     $!=0; (waitpid $pid, 0) == $pid or die "$!";
300     die "$dir ($script) $outfile $?" if $?;
301     print STDERR
302         "CGI::Auth::Flexible srcdump_dir_cpio saved $dir into $outfile\n"
303         or die $!;
304     $$tarballcounter++;
305     return $outfile;
306 }
307
308 sub srcdump_dirscan_prepare ($$) {
309     my ($c, $v) = @_;
310     my $dumpdir = $v->_get_path('srcdump');
311     mkdir $dumpdir or $!==&EEXIST or die "mkdir $dumpdir $!";
312     my $lockf = new IO::File "$dumpdir/generate.lock", 'w+'
313         or die "$dumpdir/generate.lock $!";
314     flock $lockf, LOCK_EX or die "$dumpdir/generate.lock $!";
315     my $needlicence = "$dumpdir/licence.tmp";
316     unlink $needlicence or $!==&ENOENT or die "rm $needlicence $!";
317     if (defined $v->{S}{srcdump_licence_path}) {
318         copy($v->{S}{srcdump_licence_path}, $needlicence)
319             or die "$v->{S}{srcdump_licence_path} $!";
320         $needlicence = undef;
321     }
322     unlink <"$dumpdir/[a-z][a-z][a-z].tar">;
323     my $srctarballcounter = 'aaa';
324     my %dirsdone;
325     my @srcfiles = ("$dumpdir/licence.data");
326     foreach my $incdir ($v->_ch('srcdump_includedirs')) {
327         if ($incdir eq '.' && $v->{S}{srcdump_filter_cwd}) {
328             my @bad = grep { !m#^/# } values %INC;
329             die "filtering . from srcdump dirs and \@INC but already".
330                 " included @bad " if @bad;
331             @INC = grep { $_ ne '.' } @INC;
332             next;
333         }
334         if (!stat "$incdir/.") {
335             next if $!==&ENOENT;
336             die "stat $incdir $!";
337         };
338         if (defined $needlicence) {
339             foreach my $try (@{ $v->{S}{srcdump_licence_files} }) {
340                 last if copy("$incdir/$try", $needlicence);
341                 $!==&ENOENT or die "copy $incdir/$try $!";
342             }
343         }
344         push @srcfiles, $v->_ch('srcdump_process_dir', $dumpdir, $incdir,
345                                 \$srctarballcounter, \$needlicence, \%dirsdone);
346         $dirsdone{$incdir}++;
347     }
348     $!=0;
349     my $r = system qw(tar -zvvc -f), "$dumpdir/source.tmp", '--', @srcfiles;
350     die "tar $r $!" if $r;
351     die "licence file not found" unless defined $needlicence;
352     srcdump_install($c,$v, $dumpdir, 'licence', 'text/plain');
353     srcdump_install($c,$v, $dumpdir, 'source', 'application/octet-stream');
354     close $lockf or die $!;
355 }
356
357 sub srcdump_install ($$$$$) {
358     my ($c,$v, $dumpdir, $which, $ctype) = @_;
359     rename "$dumpdir/$which.tmp", "$dumpdir/$which.data"
360         or die "$dumpdir/$which.data $!";
361     my $ctf = new IO::File "$dumpdir/$which.tmp", 'w'
362         or die "$dumpdir/$which.tmp $!";
363     print $ctf $ctype, "\n" or die $!;
364     close $ctf or die $!;
365     rename "$dumpdir/$which.tmp", "$dumpdir/$which.ctype"
366         or die "$dumpdir/$which.ctype $!";
367 }
368
369 #---------- verifier object methods ----------
370
371 sub new_verifier {
372     my $class = shift;
373     my $verifier = {
374         S => {
375             dir => undef,
376             assocdb_dbh => undef, # must have AutoCommit=0, RaiseError=1
377             assocdb_path => 'caf-assocs.db',
378             keys_path => 'caf-keys',
379             srcdump_path => 'caf-srcdump',
380             assocdb_dsn => undef,
381             assocdb_user => '',
382             assocdb_password => '',
383             assocdb_table => 'caf_assocs',
384             random_source => '/dev/urandom',
385             secretbits => 128, # bits
386             hash_algorithm => "SHA-256",
387             login_timeout => 86400, # seconds
388             login_form_timeout => 3600, # seconds
389             key_rollover => 86400, # seconds
390             assoc_param_name => 'caf_assochash',
391             dummy_param_name_prefix => 'caf__',
392             cookie_name => "caf_assocsecret",
393             password_param_name => 'password',
394             srcdump_param_name => 'caf_srcdump',
395             username_param_names => [qw(username)],
396             form_entry_size => 60,
397             logout_param_names => [qw(caf_logout)],
398             loggedout_param_names => [qw(caf_loggedout)],
399             promise_check_mutate => 0,
400             get_param => sub { $_[0]->param($_[2]) },
401             get_params => sub { $_[1]->get_params() },
402             get_path_info => sub { $_[0]->path_info() },
403             get_cookie => sub { $_[0]->cookie($_[1]->{S}{cookie_name}) },
404             get_method => sub { $_[0]->request_method() },
405             check_https => sub { !!$_[0]->https() },
406             get_url => sub { $_[0]->url(); },
407             is_login => sub { defined $_[1]->_rp('password_param_name') },
408             login_ok => \&login_ok_password,
409             username_password_error => sub { die },
410             is_logout => sub { $_[1]->has_a_param('logout_param_names') },
411             is_loggedout => sub { $_[1]->has_a_param('loggedout_param_names') },
412             is_page => sub { return 1 },
413             handle_divert => sub { return 0 },
414             do_redirect => \&do_redirect_cgi, # this hook is allowed to throw
415             cookie_path => "/",
416             get_cookie_domain => \&get_cookie_domain,
417             encrypted_only => 1,
418             gen_start_html => sub { $_[0]->start_html($_[2]); },
419             gen_footer_html => \&gen_plain_footer_html,
420             gen_licence_link_html => \&gen_plain_licence_link_html,
421             gen_source_link_html => \&gen_plain_source_link_html,
422             gen_end_html => sub { $_[0]->end_html(); },
423             gen_login_form => \&gen_plain_login_form,
424             gen_login_link => \&gen_plain_login_link,
425             gen_postmainpage_form => \&gen_postmainpage_form,
426             srcdump_dump => \&srcdump_dump,
427             srcdump_prepare => \&srcdump_dirscan_prepare,
428             srcdump_licence_path => undef,
429             srcdump_licence_files => [qw(AGPLv3 CGI/Auth/Flexible/AGPLv3)],
430             srcdump_includedirs => sub { return @INC; },
431             srcdump_filter_cwd => 1,
432             srcdump_system_dir => sub { $_[2] =~ m#^/etc/|^/usr/(?!local/)#; },
433             srcdump_process_dir => \&srcdump_process_dir,
434             srcdump_vcs_dirs => [qw(.git .hg .svn CVS)],
435             srcdump_byvcs_git => \&srcdump_byvcs_git,
436             srcdump_byvcs_hg => \&srcdump_byvcs_hg,
437             srcdump_byvcs_svn => \&srcdump_byvcs_svn,
438             srcdump_byvcs_cvs => \&srcdump_byvcs_cvs,
439             srcdump_novcs => \&srcdump_novcs,
440             srcdump_excludes => [qw(*~ *.bak *.tmp), '#*#'],
441             dump => \&dump_plain,
442             gettext => sub { gettext($_[2]); },
443             print => sub { print $_[2] or die $!; },
444             debug => sub { }, # like print; msgs contain trailing \n
445         },
446         Dbh => undef,
447     };
448     my ($k,$v);
449     while (($k,$v,@_) = @_) {
450         die "unknown setting $k" unless exists $verifier->{S}{$k};
451         $verifier->{S}{$k} = $v;
452     }
453     bless $verifier, $class;
454     $verifier->_dbopen();
455     $verifier->_ch('srcdump_prepare');
456     return $verifier;
457 }
458
459 sub _db_setup_do ($$) {
460     my ($v, $sql) = @_;
461     my $dbh = $v->{Dbh};
462     eval {
463         $v->_db_transaction(sub {
464             local ($dbh->{PrintError}) = 0;
465             $dbh->do($sql);
466         });
467     };
468 }
469
470 sub _dbopen ($) {
471     my ($v) = @_;
472     my $dbh = $v->{Dbh};
473     return $dbh if $dbh; 
474
475     $dbh = $v->{S}{assocdb_dbh};
476     if ($dbh) {
477         die if $dbh->{AutoCommit};
478         die unless $dbh->{RaiseError};
479     } else {
480         $v->{S}{assocdb_dsn} ||= "dbi:SQLite:dbname=".$v->_get_path('assocdb');
481         my $dsn = $v->{S}{assocdb_dsn};
482
483         my $u = umask 077;
484         $dbh = DBI->connect($dsn, $v->{S}{assocdb_user},
485                             $v->{S}{assocdb_password}, {
486                                 AutoCommit => 0,
487                                 RaiseError => 1,
488                                 ShowErrorStatement => 1,
489                             });
490         umask $u;
491         die "$dsn $! ?" unless $dbh;
492     }
493     $v->{Dbh} = $dbh;
494
495     $v->_db_setup_do("CREATE TABLE $v->{S}{assocdb_table} (".
496                      " assochash VARCHAR PRIMARY KEY,".
497                      " username VARCHAR NOT NULL,".
498                      " last INTEGER NOT NULL".
499                      ")");
500     $v->_db_setup_do("CREATE INDEX $v->{S}{assocdb_table}_timeout_index".
501                      " ON $v->{S}{assocdb_table}".
502                      " (last)");
503     return $dbh;
504 }
505
506 sub disconnect ($) {
507     my ($v) = @_;
508     my $dbh = $v->{Dbh};
509     return unless $dbh;
510     $dbh->disconnect();
511 }
512
513 sub _db_transaction ($$) {
514     my ($v, $fn) = @_;
515     my $retries = 10;
516     my $rv;
517     my $dbh = $v->{Dbh};
518 #print STDERR "DT entry\n";
519     for (;;) {
520 #print STDERR "DT loop\n";
521         if (!eval {
522             $rv = $fn->();
523 #print STDERR "DT fn ok\n";
524             1;
525         }) {
526 #print STDERR "DT fn error\n";
527             { local ($@); $dbh->rollback(); }
528 #print STDERR "DT fn throwing\n";
529             die $@;
530         }
531 #print STDERR "DT fn eval ok\n";
532         if (eval {
533             $dbh->commit();
534 #print STDERR "DT commit ok\n";
535             1;
536         }) {
537 #print STDERR "DT commit eval ok ",Dumper($rv);
538             return $rv;
539         }
540 #print STDERR "DT commit throw?\n";
541         die $@ if !--$retries;
542 #print STDERR "DT loop again\n";
543     }
544 }
545
546 #---------- request object methods ----------
547
548 sub new_request {
549     my ($classbase, $cgi, @extra) = @_;
550     if (!ref $classbase) {
551         $classbase = $classbase->new_verifier(@extra);
552     } else {
553         die if @extra;
554     }
555     my $r = {
556         V => $classbase,
557         S => $classbase->{S},
558         Dbh => $classbase->{Dbh},
559         Cgi => $cgi,
560     };
561     bless $r, ref $classbase;
562 }
563
564 sub _ch ($$@) { # calls an application hook
565     my ($r,$methname, @args) = @_;
566     my $methfunc = $r->{S}{$methname};
567     die "$methname ?" unless $methfunc;
568     return $methfunc->($r->{Cgi}, $r, @args);
569 }
570
571 sub _rp ($$@) {
572     my ($r,$pnvb) = @_;
573     my $pn = $r->{S}{$pnvb};
574     my $p = scalar $r->_ch('get_param',$pn)
575 }
576
577 sub _debug ($@) {
578     my ($r,@args) = @_;
579     $r->_ch('debug',@args);
580 }
581
582 sub _get_path ($$) {
583     my ($r,$keybase) = @_;
584     my $leaf = $r->{S}{"${keybase}_path"};
585     return $r->_absify_path($leaf);
586 }
587
588 sub _absify_path ($$) {
589     my ($v,$leaf) = @_;
590     return $leaf if $leaf =~ m,^/,;
591     my $dir = $v->{S}{dir};
592     die "relying on cwd by default ?!  set dir" unless defined $dir;
593     return "$dir/$leaf";
594 }
595
596 sub _gt ($$) { my ($r, $t) = @_; return $r->_ch('gettext',$t); }
597 sub _print ($$) { my ($r, @t) = @_; return $r->_ch('print', join '', @t); }
598
599 sub construct_cookie ($$$) {
600     my ($r, $cooks) = @_;
601     return undef unless $cooks;
602     my $c = $r->{Cgi};
603 my @ca = (-name => $r->{S}{cookie_name},
604                              -value => $cooks,
605                              -path => $r->{S}{cookie_path},
606                              -domain => $r->_ch('get_cookie_domain'),
607                              -expires => '+'.$r->{S}{login_timeout}.'s',
608                              -secure => $r->{S}{encrypted_only});
609     my $cookie = $c->cookie(@ca);
610 #print STDERR "CC $r $c $cooks $cookie (@ca).\n";
611     return $cookie;
612 }
613
614 # pages/param-sets are
615 #   n normal non-mutating page
616 #   r retrieval of information for JS, non-mutating
617 #   m mutating page
618 #   u update of information by JS, mutating
619 #   i login
620 #   o logout
621 #   O "you have just logged out" page load
622
623 # in cook and par,
624 #    -         no value supplied (represented in code as $cookt='')
625 #    n, nN     value not in our db
626 #    t, tN     temporary value (in our db, no logged in user yet)
627 #    y, yN     value corresponds to logged-in user
628 # and, aggregated conditions:
629 #    a, aN     anything including -
630 #    x, xN     t or y
631 # if N differs the case applies only when the two values differ
632 # (eg,   a1 y2   does not apply when the logged-in value is supplied twice)
633
634 # "stale session" means request originates from a page from a login
635 # session which has been revoked (eg by logout); "cleared session"
636 # means request originates from a browser which has a different (or
637 # no) cookie.
638
639     # Case analysis, cookie mode, app promises re mutate:
640     # cook parm meth form
641     #                      
642     #  any -   POST  nrmuoi   bug or attack, fail
643     #  any -   GET    rmuoi   bug or attack, fail
644     #  any any GET     muoi   bug or attack, fail
645     #  any t   any   nrmu     bug or attack, fail
646     #
647     #  -   -   GET         O  "just logged out" page
648     #  (any other)         O  bug or attack, fail
649     #
650     #  a1  a2  POST      o    logout
651     #                           if a1 is valid, revoke it
652     #                           if a2 is valid, revoke it
653     #                           delete cookie
654     #                           redirect to "just logged out" page
655     #                             (which contains link to login form)
656     #
657     #  -   t   POST       i   complain about cookies being disabled
658     #                           (with link to login form)
659     #
660     #  t1  t1  POST       i   login (or switch user)
661     #                           if bad
662     #                             show new login form
663     #                           if good
664     #                             upgrade t1 to y1 in our db (setting username)
665     #                             redirect to GET of remaining params
666     #
667     #  y1  a2  POST       i   complain about stale login form
668     #                           revoke y1
669     #                           show new login form
670     #                           
671     #  (other) POST       i   complain about stale login form
672     #                           show new login form
673     #
674     #  t1  a2  ANY   nrmu     treat as  - a2 ANY
675     #
676     #  y   -   GET   n        cross-site link
677     #                           show data
678     #
679     #  y   y   GET   nr       fine, show page or send data
680     #  y   y   POST  nrmu     mutation is OK, do operation
681     #
682     #  y1  y2  GET   nr       request from stale page
683     #                           do not revoke y2 as not RESTful
684     #                           treat as   y1 n GET
685     #
686     #  y1  y2  POST  nrmu     request from stale page
687     #                           revoke y2
688     #                           treat as   y1 n POST
689     #
690     #  y   n   GET   n        intra-site link from stale page,
691     #                           treat as cross-site link, show data
692     #
693     #  y   n   POST  n m      intra-site form submission from stale page
694     #                           show "session interrupted"
695     #                           with link to main data page
696     #
697     #  y   n   GET    r       intra-site request from stale page
698     #                           fail
699     #
700     #  y   n   POST   r u     intra-site request from stale page
701     #                           fail
702     #
703     #  -/n y2  GET   nr       intra-site link from cleared session
704     #                           do not revoke y2 as not RESTful
705     #                           treat as   -/n n GET
706     #
707     #  -/n y2  POST  nrmu     request from cleared session
708     #                           revoke y2
709     #                           treat as   -/n n POST
710     #
711     #  -/n -/n GET   n        cross-site link but user not logged in
712     #                           show login form with redirect to orig params
713     #                           generate fresh cookie
714     #
715     #  -/n n   GET    rmu     user not logged in
716     #                           fail
717     #
718     #  -/n n   POST  n m      user not logged in
719     #                           show login form
720     #
721     #  -/n n   POST   r u     user not logged in
722     #                           fail
723
724 sub _check_divert_core ($) {
725     my ($r) = @_;
726
727     my $srcdump = $r->_rp('srcdump_param_name');
728     if ($srcdump) {
729         die if $srcdump =~ m/\W/;
730         return ({ Kind => 'SRCDUMP-'.uc $srcdump,
731                   Message => undef,
732                   CookieSecret => undef,
733                   Params => { } });
734     }
735
736     my $cooks = $r->_ch('get_cookie');
737
738     if ($r->{S}{encrypted_only} && !$r->_ch('check_https')) {
739         return ({ Kind => 'REDIRECT-HTTPS',
740                   Message => $r->_gt("Redirecting to secure server..."),
741                   CookieSecret => undef,
742                   Params => { } });
743     }
744
745     my $meth = $r->_ch('get_method');
746     my $parmh = $r->_rp('assoc_param_name');
747     my $cookh = defined $cooks ? $r->hash($cooks) : undef;
748
749     my ($cookt,$cooku) = $r->_identify($cookh, $cooks);
750     my $parms = (defined $cooks && defined $parmh && $parmh eq $cookh)
751         ? $cooks : undef;
752     my ($parmt) = $r->_identify($parmh, $parms);
753
754     $r->_debug("_c_d_c cookt=$cookt parmt=$parmt\n");
755
756     if ($r->_ch('is_logout')) {
757         $r->_must_be_post();
758         die unless $parmt;
759         $r->_db_revoke($cookh);
760         $r->_db_revoke($parmh);
761         return ({ Kind => 'REDIRECT-LOGGEDOUT',
762                   Message => $r->_gt("Logging out..."),
763                   CookieSecret => '',
764                   Params => { } });
765     }
766     if ($r->_ch('is_loggedout')) {
767         die unless $meth eq 'GET';
768         die if $cookt eq 'y';
769         die if $parmt;
770         return ({ Kind => 'SMALLPAGE-LOGGEDOUT',
771                   Message => $r->_gt("You have been logged out."),
772                   CookieSecret => '',
773                   Params => { } });
774     }
775     if ($r->_ch('is_login')) {
776         $r->_must_be_post();
777         die unless $parmt;
778         if (!$cookt && $parmt eq 'n') {
779             return ({ Kind => 'SMALLPAGE-NOCOOKIE',
780                       Message => $r->_gt("You do not seem to have cookies".
781                                          " enabled.  You must enable cookies".
782                                          " as we use them for login."),
783                       CookieSecret => $r->_fresh_secret(),
784                       Params => $r->chain_params() })
785         }
786         if (!$cookt || $cookt eq 'n' || $cookh ne $parmh) {
787             $r->_db_revoke($cookh);
788             return ({ Kind => 'LOGIN-STALE',
789                       Message => $r->_gt("Stale session;".
790                                          " you need to log in again."),
791                       CookieSecret => $r->_fresh_secret(),
792                       Params => { } })
793         }
794         die unless $parmt eq 't' || $parmt eq 'y';
795         my ($username, $login_errormessage) = $r->_ch('login_ok');
796         unless (defined $username && length $username) {
797             $login_errormessage = $r->_gt("Incorrect username/password.")
798                 if !$login_errormessage;
799             return ({ Kind => 'LOGIN-BAD',
800                       Message => $login_errormessage,
801                       CookieSecret => $cooks,
802                       Params => $r->chain_params() })
803         }
804         $r->_db_record_login_ok($parmh,$username);
805         return ({ Kind => 'REDIRECT-LOGGEDIN',
806                   Message => $r->_gt("Logging in..."),
807                   CookieSecret => $cooks,
808                   Params => $r->chain_params() });
809     }
810     if ($cookt eq 't') {
811         $cookt = '';
812     }
813     die if $parmt eq 't';
814
815     if ($cookt eq 'y' && $parmt eq 'y' && $cookh ne $parmh) {
816         $r->_db_revoke($parmh) if $meth eq 'POST';
817         $parmt = 'n';
818     }
819
820     if ($cookt ne 'y') {
821         die unless !$cookt || $cookt eq 'n';
822         die unless !$parmt || $parmt eq 'n' || $parmt eq 'y';
823         my $news = $r->_fresh_secret();
824         if ($meth eq 'GET') {
825             return ({ Kind => 'LOGIN-INCOMINGLINK',
826                       Message => $r->_gt("You need to log in."),
827                       CookieSecret => $news,
828                       Params => $r->chain_params() });
829         } else {
830             $r->_db_revoke($parmh);
831             return ({ Kind => 'LOGIN-FRESH',
832                       Message => $r->_gt("You need to log in."),
833                       CookieSecret => $news,
834                       Params => { } });
835         }
836     }
837
838     if (!$r->{S}{promise_check_mutate}) {
839         if ($meth ne 'POST') {
840             return ({ Kind => 'MAINPAGEONLY',
841                       Message => $r->_gt('Entering via cross-site link.'),
842                       CookieSecret => $cooks,
843                       Params => { } });
844             # NB caller must then ignore params & path!
845             # if this is too hard they can spit out a small form
846             # with a "click to continue"
847         }
848     }
849
850     die unless $cookt eq 'y';
851     unless ($r->{S}{promise_check_mutate} && $meth eq 'GET') {
852         die unless $parmt eq 'y';
853         die unless $cookh eq $parmh;
854     }
855     $r->{AssocSecret} = $cooks;
856     $r->{UserOK} = $cooku;
857 #print STDERR "C-D-C OK\n";
858     return undef;
859 }
860
861 sub chain_params ($) {
862     my ($r) = @_;
863     my %p = %{ $r->_ch('get_params') };
864     foreach my $pncn (keys %{ $r->{S} }) {
865         my $names;
866         if ($pncn =~ m/_param_name$/) {
867             my $name = $r->{S}{$pncn};
868             die "$pncn ?" if ref $name;
869             $names = [ $name ];
870         } elsif ($pncn =~ m/_param_names$/) {
871             $names = $r->{S}{$pncn};
872         } else {
873             next;
874         }
875         foreach my $name (@$names) {
876             delete $p{$name};
877         }
878     }
879     my $dummy_prefix = $r->{S}{dummy_param_name_prefix};
880     foreach my $name (grep /^$dummy_prefix/, keys %p) {
881         delete $p{$name};
882     }
883     die if exists $p{''};
884     $p{''} = [ $r->_ch('get_path_info') ];
885     return \%p;
886 }
887
888 sub _identify ($$) {
889     my ($r,$h,$s) = @_;
890     # returns ($t,$username)
891     # where $t is one of "t" "y" "n", or "" (for -)
892     # either $s must be undef, or $h eq $r->hash($s)
893
894 #print STDERR "_identify\n";
895     return '' unless defined $h && length $h;
896 #print STDERR "_identify h=$h s=".(defined $s ? $s : '<undef>')."\n";
897
898     my $dbh = $r->{Dbh};
899
900     $dbh->do("DELETE FROM $r->{S}{assocdb_table}".
901              " WHERE last < ?", {},
902              time - $r->{S}{login_timeout});
903
904     my $row = $dbh->selectrow_arrayref("SELECT username, last".
905                               " FROM $r->{S}{assocdb_table}".
906                               " WHERE assochash = ?", {}, $h);
907     if (defined $row) {
908 #print STDERR "_identify h=$h s=$s YES @$row\n";
909         my ($nusername, $nlast) = @$row;
910         return ('y', $nusername);
911     }
912
913     # Well, it's not in the database.  But maybe it's a hash of a
914     # temporary secret.
915
916     return 'n' unless defined $s;
917
918     my ($keyt, $signature, $message, $noncet, $nonce) =
919         $s =~ m/^(\d+)\.(\w+)\.((\d+)\.(\w+))$/ or die;
920
921     return 'n' if time > $noncet + $r->{S}{login_form_timeout};
922
923 #print STDERR "_identify noncet=$noncet ok\n";
924
925     my $keys = $r->_open_keys();
926     while (my ($rkeyt, $rkey, $line) = $r->_read_key($keys)) {
927 #print STDERR "_identify  search rkeyt=$rkeyt rkey=$rkey\n";
928         last if $rkeyt < $keyt; # too far down in the file
929         my $trysignature = $r->_hmac($rkey, $message);
930 #print STDERR "_identify  search rkeyt=$rkeyt rkey=$rkey try=$trysignature\n";
931         return 't' if $trysignature eq $signature;
932     }
933     # oh well
934 #print STDERR "_identify NO\n";
935
936     $keys->error and die $!;
937     return 'n';
938 }
939
940 sub _db_revoke ($$) {
941     # revokes $h if it's valid; no-op if it's not
942     my ($r,$h) = @_;
943
944     my $dbh = $r->{Dbh};
945
946     $dbh->do("DELETE FROM $r->{S}{assocdb_table}".
947              " WHERE assochash = ?", {}, $h);
948 }
949
950 sub _db_record_login_ok ($$$) {
951     my ($r,$h,$user) = @_;
952     $r->_db_revoke($h);
953     my $dbh = $r->{Dbh};
954     $dbh->do("INSERT INTO $r->{S}{assocdb_table}".
955              " (assochash, username, last) VALUES (?,?,?)", {},
956              $h, $user, time);
957 }
958
959 sub check_divert ($) {
960     my ($r) = @_;
961     if (exists $r->{Divert}) {
962         return $r->{Divert};
963     }
964     my $dbh = $r->{Dbh};
965     $r->{Divert} = $r->_db_transaction(sub { $r->_check_divert_core(); });
966     $dbh->commit();
967     $r->_debug(Data::Dumper->Dump([$r->{Divert}],[qw(divert)]));
968     return $r->{Divert};
969 }
970
971 sub get_divert ($) {
972     my ($r) = @_;
973     die "unchecked" unless exists $r->{Divert};
974     return $r->{Divert};
975 }
976
977 sub get_username ($) {
978     my ($r) = @_;
979     my $divert = $r->get_divert();
980     return undef if $divert;
981     return $r->{UserOK};
982 }
983
984 sub url_with_query_params ($$) {
985     my ($r, $params) = @_;
986 #print STDERR "PARAMS ",Dumper($params);
987     my $uri = URI->new($r->_ch('get_url'));
988     $uri->path($uri->path() . $params->{''}[0]) if $params->{''};
989     $uri->query_form(flatten_params($params));
990     return $uri->as_string();
991 }
992
993 sub _cgi_header_args ($$@) {
994     my ($r, $cookie, @ha) = @_;
995     unshift @ha, qw(-type text/html);
996     push @ha, (-cookie => $cookie) if defined $cookie;
997 #print STDERR "_cgi_header_args ",join('|',@ha),".\n";
998     return @ha;
999 }
1000
1001 sub check_ok ($) {
1002     my ($r) = @_;
1003
1004     my ($divert) = $r->check_divert();
1005     return 1 if !$divert;
1006
1007     my $handled = $r->_ch('handle_divert',$divert);
1008     return 0 if $handled;
1009
1010     my $kind = $divert->{Kind};
1011     my $cookiesecret = $divert->{CookieSecret};
1012     my $params = $divert->{Params};
1013     my $cookie = $r->construct_cookie($cookiesecret);
1014
1015     if ($kind =~ m/^SRCDUMP-(\w+)$/) {
1016         $r->_ch('srcdump_dump', (lc $1));
1017         return 0;
1018     }
1019
1020     if ($kind =~ m/^REDIRECT-/) {
1021         # for redirects, we honour stored NextParams and SetCookie,
1022         # as we would for non-divert
1023         if ($kind eq 'REDIRECT-LOGGEDOUT') {
1024             $params->{$r->{S}{loggedout_param_names}[0]} = [ 1 ];
1025         } elsif ($kind eq 'REDIRECT-LOGOUT') {
1026             $params->{$r->{S}{logout_param_names}[0]} = [ 1 ];
1027         } elsif ($kind =~ m/REDIRECT-(?:LOGGEDIN|HTTPS)/) {
1028         } else {
1029             die;
1030         }
1031         my $new_url = $r->url_with_query_params($params);
1032         if ($kind eq 'REDIRECT-HTTPS') {
1033             my $uri = URI->new($new_url);
1034             die unless $uri->scheme eq 'http';
1035             $uri->scheme('https');
1036             $new_url = $uri->as_string();
1037         }
1038         $r->_ch('do_redirect',$new_url, $cookie);
1039         return 0;
1040     }
1041
1042     if (defined $cookiesecret) {
1043         $params->{$r->{S}{assoc_param_name}} = [ $r->hash($cookiesecret) ];
1044     }
1045
1046     my ($title, @body);
1047     if ($kind =~ m/^LOGIN-/) {
1048         $title = $r->_gt('Login');
1049         push @body, $divert->{Message};
1050         push @body, $r->_ch('gen_login_form', $params);
1051     } elsif ($kind =~ m/^SMALLPAGE-/) {
1052         $title = $r->_gt('Not logged in');
1053         push @body, $divert->{Message};
1054         push @body, $r->_ch('gen_login_link', $params);
1055     } elsif ($kind =~ m/^MAINPAGEONLY$/) {
1056         $title = $r->_gt('Entering secure site.');
1057         push @body, $divert->{Message};
1058         push @body, $r->_ch('gen_postmainpage_form', $params);
1059     } else {
1060         die $kind;
1061     }
1062
1063     $r->_print($r->{Cgi}->header($r->_cgi_header_args($cookie)),
1064                $r->_ch('gen_start_html',$title),
1065                (join "\n", (@body,
1066                             $r->_ch('gen_footer_html'),
1067                             $r->_ch('gen_end_html'))));
1068     return 0;
1069 }
1070
1071 sub _random ($$) {
1072     my ($r, $bytes) = @_;
1073     my $v = $r->{V};
1074     my $rsf = $v->{RandomHandle};
1075     my $rsp = $r->{S}{random_source};
1076     if (!$rsf) {
1077         $v->{RandomHandle} = $rsf = new IO::File $rsp, '<' or die "$rsp $!";
1078 #print STDERR "RH $rsf\n";
1079     }
1080     my $bin;
1081     $!=0;
1082     read($rsf,$bin,$bytes) == $bytes or die "$rsp $!";
1083     my $out = unpack "H*", $bin;
1084 #print STDERR "_random out $out\n";
1085     return $out;
1086 }
1087
1088 sub _random_key ($) {
1089     my ($r) = @_;
1090 #print STDERR "_random_key\n";
1091     my $bytes = ($r->{S}{secretbits} + 7) >> 3;
1092     return $r->_random($bytes);
1093 }
1094
1095 sub _read_key ($$) {
1096     my ($r, $keys) = @_;
1097     # returns $gen_time_t, $key_value_in_hex, $complete_line
1098     while (<$keys>) {
1099         my ($gen, $k) = m/^(\d+) (\S+)$/ or die "$_ ?";
1100         my $age = time - $gen;
1101         next if $age > $r->{S}{key_rollover} &&
1102             $age > $r->{S}{login_form_timeout}*2;
1103         return ($gen, $k, $_);
1104     }
1105     return ();
1106 }
1107
1108 sub _open_keys ($) {
1109     my ($r) = @_;
1110     my $spath = $r->_get_path('keys');
1111     for (;;) {
1112 #print STDERR "_open_keys\n";
1113         my $keys = new IO::File $spath, 'r+';
1114         if ($keys) {
1115 #print STDERR "_open_keys open\n";
1116             stat $keys or die $!; # NB must not disturb stat _
1117             my $size = (stat _)[7];
1118             my $age = time - (stat _)[9];
1119 #print STDERR "_open_keys open size=$size age=$age\n";
1120             return $keys
1121                 if $size && $age <= $r->{S}{key_rollover} / 2;
1122 #print STDERR "_open_keys open bad\n";
1123         }
1124         # file doesn't exist, or is empty or too old
1125         if (!$keys) {
1126 #print STDERR "_open_keys closed\n";
1127             die "$spath $!" unless $!==&ENOENT;
1128             # doesn't exist, so create it just so we can lock it
1129             $keys = new IO::File $spath, 'a+';
1130             die "$keys $!" unless $keys;
1131             stat $keys or die $!; # NB must not disturb stat _
1132             my $size = (stat _)[7];
1133 #print STDERR "_open_keys created size=$size\n";
1134             next if $size; # oh someone else has done it, reopen and read it
1135         }
1136         # file now exists is empty or too old, we must try to replace it
1137         my $our_inum = (stat _)[1]; # last use of that stat _
1138         flock $keys, LOCK_EX or die "$spath $!";
1139         stat $spath or die "$spath $!";
1140         my $path_inum = (stat _)[1];
1141 #print STDERR "_open_keys locked our=$our_inum path=$path_inum\n";
1142         next if $our_inum != $path_inum; # someone else has done it
1143         # We now hold the lock!
1144 #print STDERR "_open_keys creating\n";
1145         my $newkeys = new IO::Handle;
1146         sysopen $newkeys, "$spath.new", O_CREAT|O_TRUNC|O_WRONLY, 0600
1147             or die "$spath.new $!";
1148         # we add the new key to the front which means it's always sorted
1149         print $newkeys time, ' ', $r->_random_key(), "\n" or die $!;
1150         while (my ($gen,$key,$line) = $r->_read_key($keys)) {
1151 #print STDERR "_open_keys copy1\n";
1152             print $newkeys, $line or die $!;
1153         }
1154         $keys->error and die $!;
1155         close $newkeys or die "$spath.new $!";
1156         rename "$spath.new", "$spath" or die "$spath: $!";
1157 #print STDERR "_open_keys installed\n";
1158         # that rename effective unlocks, since it makes the name refer
1159         #  to the new file which we haven't locked
1160         # we go round again opening the file at the beginning
1161         #  so that our caller gets a fresh handle onto the existing key file
1162     }
1163 }
1164
1165 sub _fresh_secret ($) {
1166     my ($r) = @_;
1167 #print STDERR "_fresh_secret\n";
1168
1169     my $keys = $r->_open_keys();
1170     my ($keyt, $key) = $r->_read_key($keys);
1171     die unless defined $keyt;
1172
1173     my $nonce = $r->_random_key();
1174     my $noncet = time;
1175     my $message = "$noncet.$nonce";
1176
1177     my $signature = $r->_hmac($key, $message);
1178     my $secret = "$keyt.$signature.$message";
1179 #print STDERR "FRESH $secret\n";
1180     return $secret;
1181 }
1182
1183 sub _hmac ($$$) {
1184     my ($r, $keyhex, $message) = @_;
1185     my $keybin = pack "H*", $keyhex;
1186     my $alg = $r->{S}{hash_algorithm};
1187 #print STDERR "hmac $alg\n";
1188     my $base = new Digest $alg;
1189 #print STDERR "hmac $alg $base\n";
1190     my $digest = new Digest::HMAC $keybin, $base;
1191 #print STDERR "hmac $alg $base $digest\n";
1192     $digest->add($message);
1193     return $digest->hexdigest();
1194 }
1195
1196 sub hash ($$) {
1197     my ($r, $message) = @_;
1198     my $alg = $r->{S}{hash_algorithm};
1199 #print STDERR "hash $alg\n";
1200     my $digest = new Digest $alg;
1201     $digest->add($message);
1202     return $digest->hexdigest();
1203 }
1204
1205 sub _assert_checked ($) {
1206     my ($r) = @_;
1207     die "unchecked" unless exists $r->{Divert};
1208 }
1209
1210 sub _is_post ($) {
1211     my ($r) = @_;
1212     my $meth = $r->_ch('get_method');
1213     return $meth eq 'POST';
1214 }
1215
1216 sub _must_be_post ($) {
1217     my ($r) = @_;
1218     my $meth = $r->_ch('get_method');
1219     die "mutating non-POST" if $meth ne 'POST';
1220 }
1221
1222 sub check_mutate ($) {
1223     my ($r) = @_;
1224     $r->_assert_checked();
1225     die if $r->{Divert};
1226     $r->_must_be_post();
1227 }
1228
1229 sub mutate_ok ($) {
1230     my ($r) = @_;
1231     $r->_assert_checked();
1232     die if $r->{Divert};
1233     return $r->_is_post();
1234 }
1235
1236 #---------- output ----------
1237
1238 sub secret_cookie_val ($) {
1239     my ($r) = @_;
1240     $r->_assert_checked();
1241     return defined $r->{AssocSecret} ? $r->{AssocSecret} : '';
1242 }
1243
1244 sub secret_hidden_val ($) {
1245     my ($r) = @_;
1246     $r->_assert_checked();
1247     return defined $r->{AssocSecret} ? $r->hash($r->{AssocSecret}) : '';
1248 }
1249
1250 sub secret_hidden_html ($) {
1251     my ($r) = @_;
1252     return $r->{Cgi}->hidden(-name => $r->{S}{assoc_param_name},
1253                              -default => $r->secret_hidden_val());
1254 }
1255
1256 sub secret_cookie ($) {
1257     my ($r) = @_;
1258     my $secret = $r->secret_cookie_val();
1259     return undef if !defined $secret;
1260 #print STDERR "SC\n";
1261     my $cookv = $r->construct_cookie($secret); 
1262 #print STDERR "SC=$cookv\n";
1263     return $cookv;
1264 }
1265
1266 1;
1267
1268 __END__
1269
1270 =head1 NAME
1271
1272 CGI::Auth::Flexible - web authentication optionally using cookies
1273
1274 =head1 SYNOPSYS
1275
1276  my $verifier = CGI::Auth::Flexible->new_verifier(setting => value,...);
1277  my $authreq = $verifier->new_request($cgi_request_object);
1278
1279  my $authreq = CGI::Auth::Flexible->new_request($cgi_request_object,
1280                                               setting => value,...);
1281
1282 =head1 USAGE PATTERN FOR SIMPLE APPLICATIONS
1283
1284  $authreq->check_ok() or return;
1285
1286  blah blah blah
1287  $authreq->check_mutate();
1288  blah blah blah
1289
1290 =head1 USAGE PATTERN FOR FANCY APPLICATIONS
1291
1292  my $divert_kind = $authreq->check_divert();
1293  if ($divert_kind) {
1294      if ($divert_kind eq 'LOGGEDOUT') {
1295          print "goodbye you are now logged out" and quit
1296      } elsif ($divert_kind eq 'NOCOOKIES') {
1297          print "you need cookies" and quit
1298      ... etc.
1299      }
1300  }
1301
1302  blah blah blah
1303  $authreq->check_mutate();
1304  blah blah blah