chiark / gitweb /
wip
authorIan Jackson <ijackson@chiark.greenend.org.uk>
Fri, 31 Aug 2012 20:33:20 +0000 (21:33 +0100)
committerIan Jackson <ijackson@chiark.greenend.org.uk>
Fri, 31 Aug 2012 20:33:20 +0000 (21:33 +0100)
cgi-auth-hybrid.pm

index a5630428b13d3551cab3b0ba2ad39432829f3dac..e258bdc2b613a26ff95e14702e251e06e25fa0c8 100644 (file)
@@ -26,6 +26,7 @@ sub new {
            assocdb_table => 'assocs',
            random_source => '/dev/urandom',
            associdlen => 128, # bits
+           login_timeout => 86400, # seconds
            param_name => 'cah_associd',
            cookie_name => 'cah_associd', # make undef to disable cookie
            cgi => undef,
@@ -71,7 +72,8 @@ sub _dbopen ($) {
     eval {
        $dbh->do("CREATE TABLE $s->{S}{assocdb_table} (".
                 " associd VARCHAR PRIMARY KEY,".
-                 " username VARCHAR".
+                 " username VARCHAR,".
+                " last INTEGER"
                 ")");
     };
     return $dbh;
@@ -89,18 +91,55 @@ sub record_login ($$) {
     my $nassoc = unpack "H*", $nassocbin;
     my $dbh = $s->_dbopen();
     $dbh->do("INSERT INTO $s->{S}{assocdb_table}".
-            " (associd, username) VALUES (?,?)", {},
-            $nassoc, $nusername);
+            " (associd, username, last) VALUES (?,?,?)", {},
+            $nassoc, $nusername, time);
     $dbh->do("COMMIT");
     $username = $nusername;
     $assoc =    $nassoc;
 }
 
-sub check () {
-    my $qassocid = $s->{S}{param_get}();
-    if (!defined $qassocid) {
-       $qassocid = $s->{S}{cookie_get}();
-       return 0 unless defined $qassocid;
-       return 0 unless $s->{S}{get_method}() eq 'GET';
+sub _check ($) {
+    my ($s) = @_;
+    my $qassoc = $s->{S}{param_get}();
+    if (!defined $qassoc) {
+       $qassoc = $s->{S}{cookie_get}();
+       return undef unless defined $qassoc;
+       return undef unless $s->{S}{get_method}() eq 'GET';
     }
-    
+    my $dbh = $s->_dbopen();
+    my ($nusername, $nlast) =
+       $dbh->selectrow_array("SELECT username, last".
+                             " FROM $s->{S}{assocdb_table}".
+                             " WHERE associd = ?", {}, $qassoc);
+    return undef unless defined $nusername;
+    my $timeout = $s->{S}{login_timeout};
+    return undef unless !defined $timeout || time <= $nlast + $timeout;
+
+    return ($nusername, $qassoc);
+}
+
+sub check ($) {
+    my ($s) = @_;
+
+    my ($nusername, $qassoc) = $s->_check() or return undef;
+
+    # hooray
+    $dbh->do("UPDATE $s->{S}{assocdb_table}".
+            " SET last = ?".
+            " WHERE associd = ?", {}, time, $qassoc);
+    $dbh->do("COMMIT");
+
+    $username = $nusername;
+    $assoc =    $qassoc;
+    return $username;
+}
+
+sub logout ($) {
+    my ($s) = @_;
+
+    if (my ($nusername, $qassoc) = $s->_check()) {
+       $dbh->do("DELETE FROM $s->{S}{assocdb_table}".
+                " WHERE associd = ?", {}, $qassoc);
+       $dbh->do("COMMIT");
+    }
+}