3 # This is part of CGI::Auth::Flexible, a perl CGI authentication module.
4 # Copyright (C) 2012 Ian Jackson.
5 # Copyright (C) 2012 Citrix.
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.
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.
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/>.
21 use warnings FATAL => 'all';
23 package CGI::Auth::Flexible;
28 our ($VERSION, @ISA, @EXPORT, @EXPORT_OK, %EXPORT_TAGS);
33 %EXPORT_TAGS = ( ); # eg: TAG => [ qw!name1 name2! ],
35 @EXPORT_OK = qw(setup);
40 use CGI qw/escapeHTML/;
51 #---------- public utilities ----------
53 sub flatten_params ($) {
56 foreach my $k (keys %$p) {
57 foreach my $v (@{ $p->{$k} }) {
64 #---------- default callbacks ----------
66 sub has_a_param ($$) {
68 foreach my $pn (@{ $r->{S}{$cn} }) {
69 return 1 if $r->_ch('get_param',$pn);
78 foreach my $name ($c->param()) {
79 $p{$name} = [ $c->param($name) ];
84 sub get_cookie_domain ($$$) {
86 my $uri = new URI $r->_ch('get_url');
90 sub login_ok_password ($$) {
92 my $username_params = $r->{S}{username_param_names};
93 my $username = $r->_ch('get_param',$username_params->[0]);
94 my $password = $r->_rp('password_param_name');
95 return undef unless $r->_ch('username_password_ok', $username, $password);
99 sub do_redirect_cgi ($$$$) {
100 my ($c, $r, $new_url, $cookie) = @_;
101 $r->_print($c->header($r->_cgi_header_args($cookie,
102 -status => '303 See other',
103 -location => $new_url)),
104 $r->_ch('gen_start_html',$r->_gt('Redirection')),
105 '<a href="'.escapeHTML($new_url).'">',
106 $r->_gt("If you aren't redirected, click to continue."),
108 $c->_ch('gen_end_html'));
111 sub gen_plain_login_form ($$) {
112 my ($c,$r, $params) = @_;
114 push @form, ('<form method="POST" action="'.
115 escapeHTML($r->_ch('get_url')).'">'.
117 my $sz = 'size="'.$r->{S}{form_entry_size}.'"';
118 foreach my $up (@{ $r->{S}{username_param_names}}) {
119 push @form, ('<tr><td>',$r->_gt(ucfirst $up),'</td>',
120 '<td><input type="text" '.$sz.
121 ' name='.$up.'></td></tr>');
123 push @form, ('<tr><td>'.$r->_gt('Password').'</td>',
124 '<td><input type="password" '.$sz.
125 ' name="'.$r->{S}{password_param_name}.'"></td></tr>');
126 push @form, ('<tr><td colspan="2">',
127 '<input type="submit"'.
128 ' name="'.$r->{S}{login_submit_name}[0].'"'.
129 ' value="'.$r->_gt('Login').'"></td></tr>',
131 foreach my $n (keys %$params) {
132 push @form, ('<input type="hidden"'.
134 ' value="'.$params->{$n}.'">');
136 push @form, ('</form>');
137 return join "\n", @form;
140 sub gen_login_link ($$) {
141 my ($c,$r, $params) = @_;
142 my $url = $r->url_with_query_params($params);
143 return ('<a href="'.escapeHTML($url).'">'.
144 $r->_gt('Log in again to continue.').
148 #---------- verifier object methods ----------
155 assocdb_path => 'caf-assocs.db',
156 keys_path => 'caf-keys',
157 assocdb_dsn => undef,
159 assocdb_password => '',
160 assocdb_table => 'caf_assocs',
161 random_source => '/dev/urandom',
162 secretbits => 128, # bits
163 hash_algorithm => "SHA-256",
164 login_timeout => 86400, # seconds
165 login_form_timeout => 3600, # seconds
166 key_rollover => 86400, # seconds
167 assoc_param_name => 'caf_assochash',
168 cookie_name => "caf_assocsecret",
169 password_param_name => 'password',
170 username_param_names => [qw(username)],
171 form_entry_size => 60,
172 logout_param_names => [qw(caf_logout)],
173 login_submit_name => [qw(caf_login)],
174 loggedout_param_names => [qw(caf_loggedout)],
175 promise_check_mutate => 0,
176 get_param => sub { $_[0]->param($_[2]) },
177 get_params => sub { $_[1]->get_params() },
178 get_cookie => sub { $_[0]->cookie($_[1]->{S}{cookie_name}) },
179 get_method => sub { $_[0]->request_method() },
180 get_url => sub { $_[0]->url(); },
181 is_login => sub { defined $_[1]->_rp('password_param_name') },
182 login_ok => \&login_ok_password,
183 username_password_ok => sub { die },
184 is_logout => sub { $_[1]->has_a_param('logout_param_names') },
185 is_loggedout => sub { $_[1]->has_a_param('loggedout_param_names') },
186 is_page => sub { return 1 },
187 handle_divert => sub { return 0 },
188 do_redirect => \&do_redirect_cgi, # this hook is allowed to throw
190 get_cookie_domain => \&get_cookie_domain,
192 gen_start_html => sub { $_[0]->start_html($_[2]); },
193 gen_end_html => sub { $_[0]->end_html(); },
194 gen_login_form => \&gen_plain_login_form,
195 gen_login_link => \&gen_plain_login_link,
196 gettext => sub { gettext($_[2]); },
197 print => sub { print $_[2] or die $!; },
202 while (($k,$v,@_) = @_) {
203 die "unknown setting $k" unless exists $verifier->{S}{$k};
204 $verifier->{S}{$k} = $v;
206 bless $verifier, $class;
207 $verifier->_dbopen();
211 sub _db_setup_do ($$) {
215 $v->_db_transaction(sub {
216 local ($dbh->{PrintError}) = 0;
227 $v->{S}{assocdb_dsn} ||= "dbi:SQLite:dbname=".$v->_get_path('assocdb');
228 my $dsn = $v->{S}{assocdb_dsn};
231 $dbh = DBI->connect($dsn, $v->{S}{assocdb_user},
232 $v->{S}{assocdb_password}, {
235 ShowErrorStatement => 1,
237 die "$dsn $! ?" unless $dbh;
240 $v->_db_setup_do("CREATE TABLE $v->{S}{assocdb_table} (".
241 " assochash VARCHAR PRIMARY KEY,".
242 " username VARCHAR NOT NULL,".
243 " last INTEGER NOT NULL".
245 $v->_db_setup_do("CREATE INDEX $v->{S}{assocdb_table}_timeout_index".
246 " ON $v->{S}{assocdb_table}".
258 sub _db_transaction ($$) {
263 print STDERR "DT entry\n";
265 print STDERR "DT loop\n";
268 print STDERR "DT fn ok\n";
271 print STDERR "DT fn error\n";
272 { local ($@); $dbh->rollback(); }
273 print STDERR "DT fn throwing\n";
276 print STDERR "DT fn eval ok\n";
279 print STDERR "DT commit ok\n";
282 print STDERR "DT commit eval ok $rv\n";
285 print STDERR "DT commit throw?\n";
286 die $@ if !--$retries;
287 print STDERR "DT loop again\n";
291 #---------- request object methods ----------
294 my ($classbase, $cgi, @extra) = @_;
295 if (!ref $classbase) {
296 $classbase = $classbase->new_verifier(@extra);
302 S => $classbase->{S},
303 Dbh => $classbase->{Dbh},
306 bless $r, ref $classbase;
309 sub _ch ($$@) { # calls an application hook
310 my ($r,$methname, @args) = @_;
311 my $methfunc = $r->{S}{$methname};
312 die "$methname ?" unless $methfunc;
313 return $methfunc->($r->{Cgi}, $r, @args);
318 my $pn = $r->{S}{$pnvb};
319 my $p = scalar $r->_ch('get_param',$pn)
323 my ($v,$keybase) = @_;
324 my $leaf = $v->{S}{"${keybase}_path"};
325 my $dir = $v->{S}{dir};
326 return $leaf if $leaf =~ m,^/,;
327 die "relying on cwd by default ?! set dir" unless defined $dir;
331 sub _gt ($$) { my ($r, $t) = @_; return $r->_ch('gettext',$t); }
332 sub _print ($$) { my ($r, @t) = @_; return $r->_ch('print', join '', @t); }
334 sub construct_cookie ($$$) {
335 my ($r, $cooks) = @_;
336 return undef unless $cooks;
338 my @ca = (-name => $r->{S}{cookie_name},
340 -path => $r->{S}{cookie_path},
341 -domain => $r->_ch('get_cookie_domain'),
342 -expires => '+'.$r->{S}{login_timeout}.'s',
343 -secure => $r->{S}{encrypted_only});
344 my $cookie = $c->cookie(@ca);
345 print STDERR "CC $r $c $cooks $cookie (@ca).\n";
349 # pages/param-sets are
350 # n normal non-mutating page
351 # r retrieval of information for JS, non-mutating
353 # u update of information by JS, mutating
356 # O "you have just logged out" page load
359 # - no value supplied (represented in code as $cookt='')
360 # n, nN value not in our db
361 # t, tN temporary value (in our db, no logged in user yet)
362 # y, yN value corresponds to logged-in user
363 # and, aggregated conditions:
364 # a, aN anything including -
366 # if N differs the case applies only when the two values differ
367 # (eg, a1 y2 does not apply when the logged-in value is supplied twice)
369 # "stale session" means request originates from a page from a login
370 # session which has been revoked (eg by logout); "cleared session"
371 # means request originates from a browser which has a different (or
374 # Case analysis, cookie mode, app promises re mutate:
375 # cook parm meth form
377 # any - POST nrmuoi bug or attack, fail
378 # any - GET rmuoi bug or attack, fail
379 # any any GET muoi bug or attack, fail
380 # any t any nrmu bug or attack, fail
382 # - - GET O "just logged out" page
383 # (any other) O bug or attack, fail
385 # a1 a2 POST o logout
386 # if a1 is valid, revoke it
387 # if a2 is valid, revoke it
389 # redirect to "just logged out" page
390 # (which contains link to login form)
392 # - t POST i complain about cookies being disabled
393 # (with link to login form)
395 # t1 t1 POST i login (or switch user)
397 # show new login form
399 # upgrade t1 to y1 in our db (setting username)
400 # redirect to GET of remaining params
402 # y1 a2 POST i complain about stale login form
404 # show new login form
406 # (other) POST i complain about stale login form
407 # show new login form
409 # t1 a2 ANY nrmu treat as - a2 ANY
411 # y - GET n cross-site link
414 # y y GET nr fine, show page or send data
415 # y y POST nrmu mutation is OK, do operation
417 # y1 y2 GET nr request from stale page
418 # do not revoke y2 as not RESTful
421 # y1 y2 POST nrmu request from stale page
425 # y n GET n intra-site link from stale page,
426 # treat as cross-site link, show data
428 # y n POST n m intra-site form submission from stale page
429 # show "session interrupted"
430 # with link to main data page
432 # y n GET r intra-site request from stale page
435 # y n POST r u intra-site request from stale page
438 # -/n y2 GET nr intra-site link from cleared session
439 # do not revoke y2 as not RESTful
442 # -/n y2 POST nrmu request from cleared session
444 # treat as -/n n POST
446 # -/n -/n GET n cross-site link but user not logged in
447 # show login form with redirect to orig params
448 # generate fresh cookie
450 # -/n n GET rmu user not logged in
453 # -/n n POST n m user not logged in
456 # -/n n POST r u user not logged in
459 sub _check_divert_core ($) {
462 my $meth = $r->_ch('get_method');
463 my $cooks = $r->_ch('get_cookie');
464 my $parmh = $r->_rp('assoc_param_name');
465 my $cookh = defined $cooks ? $r->hash($cooks) : undef;
467 my ($cookt,$cooku) = $r->_identify($cookh, $cooks);
468 my $parms = (defined $cooks && defined $parmh && $parmh eq $cookh)
470 my ($parmt) = $r->_identify($parmh, $parms);
472 print STDERR "_c_d_c cookt=$cookt parmt=$parmt\n";
474 if ($r->_ch('is_logout')) {
477 $r->_db_revoke($cookh);
478 $r->_db_revoke($parmh);
479 return ({ Kind => 'REDIRECT-LOGGEDOUT',
480 Message => "Logging out...",
484 if ($r->_ch('is_loggedout')) {
485 die unless $meth eq 'GET';
488 return ({ Kind => 'SMALLPAGE-LOGGEDOUT',
489 Message => "You have been logged out.",
493 if ($r->_ch('is_login')) {
496 if (!$cookt && $parmt eq 't') {
497 return ({ Kind => 'SMALLPAGE-NOCOOKIE',
498 Message => "You do not seem to have cookies enabled. ".
499 "You must enable cookies as we use them for login.",
500 CookieSecret => $r->_fresh_secret(),
501 Params => $r->_chain_params() })
503 if (!$cookt || $cookt eq 'n' || $cookh ne $parmh) {
504 $r->_db_revoke($cookh);
505 return ({ Kind => 'LOGIN-STALE',
506 Message => "Stale session; you need to log in again.",
507 CookieSecret => $r->_fresh_secret(),
510 die unless $parmt eq 't' || $parmt eq 'y';
511 my $username = $r->_ch('login_ok');
512 unless (defined $username && length $username) {
513 return ({ Kind => 'LOGIN-BAD',
514 Message => "Incorrect username/password.",
515 CookieSecret => $cooks,
516 Params => $r->_chain_params() })
518 $r->_db_record_login_ok($parmh,$username);
519 return ({ Kind => 'REDIRECT-LOGGEDIN',
520 Message => "Logging in...",
521 CookieSecret => $cooks,
522 Params => $r->_chain_params() });
527 die if $parmt eq 't';
529 if ($cookt eq 'y' && $parmt eq 'y' && $cookh ne $parmh) {
530 $r->_db_revoke($parmh) if $meth eq 'POST';
535 die unless !$cookt || $cookt eq 'n';
536 die unless !$parmt || $parmt eq 'n' || $parmt eq 'y';
537 my $news = $r->_fresh_secret();
538 if ($meth eq 'GET') {
539 return ({ Kind => 'LOGIN-INCOMINGLINK',
540 Message => "You need to log in.",
541 CookieSecret => $news,
542 Params => $r->_chain_params() });
544 $r->_db_revoke($parmh);
545 return ({ Kind => 'LOGIN-FRESH',
546 Message => "You need to log in.",
547 CookieSecret => $news,
552 if (!$r->{S}{promise_check_mutate}) {
553 if ($meth ne 'POST') {
554 return ({ Kind => 'MAINPAGEONLY',
555 Message => 'Entering via cross-site link.',
556 CookieSecret => $cooks,
558 # NB caller must then ignore params & path!
559 # if this is too hard they can spit out a small form
560 # with a "click to continue"
564 die unless $cookt eq 'y';
565 die unless $parmt eq 'y';
566 die unless $cookh eq $parmh;
567 $r->{AssocSecret} = $cooks;
568 $r->{UserOK} = $cooku;
569 print STDERR "C-D-C OK\n";
573 sub _chain_params ($) {
575 my %p = %{ $r->_ch('get_params') };
576 foreach my $pncn (keys %{ $r->{S} }) {
578 if ($pncn =~ m/_param_name$/) {
579 my $name = $r->{S}{$pncn};
580 die "$pncn ?" if ref $name;
582 } elsif ($pncn =~ m/_param_names$/) {
583 $names = $r->{S}{$pncn};
587 foreach my $name (@$names) {
596 # returns ($t,$username)
597 # where $t is one of "t" "y" "n", or "" (for -)
598 # either $s must be undef, or $h eq $r->hash($s)
600 print STDERR "_identify\n";
601 return '' unless defined $h && length $h;
602 print STDERR "_identify h=$h s=".(defined $s ? $s : '<undef>')."\n";
606 $dbh->do("DELETE FROM $r->{S}{assocdb_table}".
607 " WHERE last < ?", {},
608 time - $r->{S}{login_timeout});
610 my $row = $dbh->selectrow_arrayref("SELECT username, last".
611 " FROM $r->{S}{assocdb_table}".
612 " WHERE assochash = ?", {}, $h);
614 print STDERR "_identify h=$h s=$s YES @$row\n";
615 my ($nusername, $nlast) = @$row;
616 return ('y', $nusername);
619 # Well, it's not in the database. But maybe it's a hash of a
622 return 'n' unless defined $s;
624 my ($keyt, $signature, $message, $noncet, $nonce) =
625 $s =~ m/^(\d+)\.(\w+)\.((\d+)\.(\w+))$/ or die;
627 return 'n' if time > $noncet + $r->{S}{login_form_timeout};
629 print STDERR "_identify noncet=$noncet ok\n";
631 my $keys = $r->_open_keys();
632 while (my ($rkeyt, $rkey, $line) = $r->_read_key($keys)) {
633 print STDERR "_identify search rkeyt=$rkeyt rkey=$rkey\n";
634 last if $rkeyt < $keyt; # too far down in the file
635 my $trysignature = $r->_hmac($rkey, $message);
636 print STDERR "_identify search rkeyt=$rkeyt rkey=$rkey trysig=$trysignature\n";
637 return 't' if $trysignature eq $signature;
640 print STDERR "_identify NO\n";
642 $keys->error and die $!;
646 sub _db_revoke ($$) {
647 # revokes $h if it's valid; no-op if it's not
652 $dbh->do("DELETE FROM $r->{S}{assocdb_table}".
653 " WHERE assochash = ?", {}, $h);
656 sub _db_record_login_ok ($$$) {
657 my ($r,$h,$user) = @_;
660 $dbh->do("INSERT INTO $r->{S}{assocdb_table}".
661 " (assochash, username, last) VALUES (?,?,?)", {},
665 sub check_divert ($) {
667 if (exists $r->{Divert}) {
671 $r->{Divert} = $r->_db_transaction(sub { $r->_check_divert_core(); });
673 print STDERR Dumper($r->{Divert});
679 die "unchecked" unless exists $r->{Divert};
683 sub get_username ($) {
685 my $divert = $r->get_divert();
686 return undef if $divert;
690 sub url_with_query_params ($$) {
691 my ($r, $params) = @_;
692 print STDERR "PARAMS ",Dumper($params);
693 my $uri = URI->new($r->_ch('get_url'));
694 $uri->query_form(flatten_params($params));
695 return $uri->as_string();
698 sub _cgi_header_args ($$@) {
699 my ($r, $cookie, @ha) = @_;
700 unshift @ha, qw(-type text/html);
701 push @ha, (-cookie => $cookie) if defined $cookie;
702 print STDERR "_cgi_header_args ",join('|',@ha),".\n";
709 my ($divert) = $r->check_divert();
710 return 1 if !$divert;
712 my $handled = $r->_ch('handle_divert',$divert);
713 return 0 if $handled;
715 my $kind = $divert->{Kind};
716 my $cookiesecret = $divert->{CookieSecret};
717 my $params = $divert->{Params};
718 my $cookie = $r->construct_cookie($cookiesecret);
720 if (defined $cookiesecret) {
721 $params->{$r->{S}{assoc_param_name}} = $r->hash($cookiesecret);
724 if ($kind =~ m/^REDIRECT-/) {
725 # for redirects, we honour stored NextParams and SetCookie,
726 # as we would for non-divert
727 if ($kind eq 'REDIRECT-LOGGEDOUT') {
728 $params->{$r->{S}{loggedout_param_names}[0]} = 1;
729 } elsif ($kind eq 'REDIRECT-LOGOUT') {
730 $params->{$r->{S}{logout_param_names}[0]} = 1;
731 } elsif ($kind eq 'REDIRECT-LOGGEDIN') {
735 my $new_url = $r->url_with_query_params($params);
736 $r->_ch('do_redirect',$new_url, $cookie);
741 if ($kind =~ m/^LOGIN-/) {
742 $title = $r->_gt('Login');
743 push @body, $r->_gt($divert->{Message});
744 push @body, $r->_ch('gen_login_form', $params);
745 } elsif ($kind =~ m/^SMALLPAGE-/) {
746 $title = $r->_gt('Not logged in');
747 push @body, $r->_gt($divert->{Message});
748 push @body, $r->_ch('gen_login_link');
753 $r->_print($r->{Cgi}->header($r->_cgi_header_args($cookie)),
754 $r->_ch('gen_start_html',$title),
756 $r->_ch('gen_end_html'));
761 my ($r, $bytes) = @_;
763 my $rsf = $v->{RandomHandle};
764 my $rsp = $r->{S}{random_source};
766 $v->{RandomHandle} = $rsf = new IO::File $rsp, '<' or die "$rsp $!";
767 print STDERR "RH $rsf\n";
771 read($rsf,$bin,$bytes) == $bytes or die "$rsp $!";
772 my $out = unpack "H*", $bin;
773 print STDERR "_random out $out\n";
777 sub _random_key ($) {
779 print STDERR "_random_key\n";
780 my $bytes = ($r->{S}{secretbits} + 7) >> 3;
781 return $r->_random($bytes);
786 # returns $gen_time_t, $key_value_in_hex, $complete_line
788 my ($gen, $k) = m/^(\d+) (\S+)$/ or die "$_ ?";
789 my $age = time - $gen;
790 next if $age > $r->{S}{key_rollover} &&
791 $age > $r->{S}{login_form_timeout}*2;
792 return ($gen, $k, $_);
799 my $spath = $r->_get_path('keys');
801 print STDERR "_open_keys\n";
802 my $keys = new IO::File $spath, 'r+';
804 print STDERR "_open_keys open\n";
805 stat $keys or die $!; # NB must not disturb stat _
806 my $size = (stat _)[7];
807 my $age = time - (stat _)[9];
808 print STDERR "_open_keys open size=$size age=$age\n";
810 if $size && $age <= $r->{S}{key_rollover} / 2;
811 print STDERR "_open_keys open bad\n";
813 # file doesn't exist, or is empty or too old
815 print STDERR "_open_keys closed\n";
816 die "$spath $!" unless $!==&ENOENT;
817 # doesn't exist, so create it just so we can lock it
818 $keys = new IO::File $spath, 'a+';
819 die "$keys $!" unless $keys;
820 stat $keys or die $!; # NB must not disturb stat _
821 my $size = (stat _)[7];
822 print STDERR "_open_keys created size=$size\n";
823 next if $size; # oh someone else has done it, reopen and read it
825 # file now exists is empty or too old, we must try to replace it
826 my $our_inum = (stat _)[1]; # last use of that stat _
827 flock $keys, LOCK_EX or die "$spath $!";
828 stat $spath or die "$spath $!";
829 my $path_inum = (stat _)[1];
830 print STDERR "_open_keys locked our=$our_inum path=$path_inum\n";
831 next if $our_inum != $path_inum; # someone else has done it
832 # We now hold the lock!
833 print STDERR "_open_keys creating\n";
834 my $newkeys = new IO::Handle;
835 sysopen $newkeys, "$spath.new", O_CREAT|O_TRUNC|O_WRONLY, 0600
836 or die "$spath.new $!";
837 # we add the new key to the front which means it's always sorted
838 print $newkeys time, ' ', $r->_random_key(), "\n" or die $!;
839 while (my ($gen,$key,$line) = $r->_read_key($keys)) {
840 print STDERR "_open_keys copy1\n";
841 print $newkeys, $line or die $!;
843 $keys->error and die $!;
844 close $newkeys or die "$spath.new $!";
845 rename "$spath.new", "$spath" or die "$spath: $!";
846 print STDERR "_open_keys installed\n";
847 # that rename effective unlocks, since it makes the name refer
848 # to the new file which we haven't locked
849 # we go round again opening the file at the beginning
850 # so that our caller gets a fresh handle onto the existing key file
854 sub _fresh_secret ($) {
856 print STDERR "_fresh_secret\n";
858 my $keys = $r->_open_keys();
859 my ($keyt, $key) = $r->_read_key($keys);
860 die unless defined $keyt;
862 my $nonce = $r->_random_key();
864 my $message = "$noncet.$nonce";
866 my $signature = $r->_hmac($key, $message);
867 my $secret = "$keyt.$signature.$message";
868 print STDERR "FRESH $secret\n";
873 my ($r, $keyhex, $message) = @_;
874 my $keybin = pack "H*", $keyhex;
875 my $alg = $r->{S}{hash_algorithm};
876 print STDERR "hmac $alg\n";
877 my $base = new Digest $alg;
878 print STDERR "hmac $alg $base\n";
879 my $digest = new Digest::HMAC $keybin, $base;
880 print STDERR "hmac $alg $base $digest\n";
881 $digest->add($message);
882 return $digest->hexdigest();
886 my ($r, $message) = @_;
887 my $alg = $r->{S}{hash_algorithm};
888 print STDERR "hash $alg\n";
889 my $digest = new Digest $alg;
890 $digest->add($message);
891 return $digest->hexdigest();
894 sub _assert_checked ($) {
896 die "unchecked" unless exists $r->{Divert};
899 sub _must_be_post ($) {
901 my $meth = $r->_ch('get_method');
902 die "mutating non-POST" if $meth ne 'POST';
905 sub check_mutate ($) {
907 $r->_assert_checked();
912 #---------- output ----------
914 sub secret_cookie_val ($) {
916 $r->_assert_checked();
917 return defined $r->{AssocSecret} ? $r->{AssocSecret} : '';
920 sub secret_hidden_val ($) {
922 $r->_assert_checked();
923 return defined $r->{AssocSecret} ? r->hash($r->{AssocSecret}) : '';
926 sub secret_hidden_html ($) {
928 return $r->{Cgi}->hidden(-name => $r->{S}{assoc_param_name},
929 -default => $r->secret_hidden_val());
932 sub secret_cookie ($) {
934 my $secret = $r->secret_cookie_val();
935 return undef if !defined $secret;
936 #print STDERR "SC\n";
937 my $cookv = $r->construct_cookie($secret);
938 #print STDERR "SC=$cookv\n";
946 CGI::Auth::Flexible - web authentication optionally using cookies
950 my $verifier = CGI::Auth::Flexible->new_verifier(setting => value,...);
951 my $authreq = $verifier->new_request($cgi_request_object);
953 my $authreq = CGI::Auth::Flexible->new_request($cgi_request_object,
954 setting => value,...);
956 =head1 USAGE PATTERN FOR SIMPLE APPLICATIONS
958 $authreq->check_ok() or return;
961 $authreq->check_mutate();
964 =head1 USAGE PATTERN FOR FANCY APPLICATIONS
966 my $divert_kind = $authreq->check_divert();
968 if ($divert_kind eq 'LOGGEDOUT') {
969 print "goodbye you are now logged out" and quit
970 } elsif ($divert_kind eq 'NOCOOKIES') {
971 print "you need cookies" and quit
977 $authreq->check_mutate();