Timestamp validation.
authorGunnar Wrobel <p@rdus.de>
Wed, 3 Nov 2010 20:01:46 +0000 (21:01 +0100)
committerGunnar Wrobel <p@rdus.de>
Tue, 30 Nov 2010 12:48:24 +0000 (13:48 +0100)
framework/Nonce/lib/Horde/Nonce.php
framework/Nonce/test/Horde/Nonce/Integration/NonceTest.php
framework/Nonce/test/Horde/Nonce/StoryTestCase.php

index 836045a..a17b89c 100644 (file)
@@ -36,4 +36,21 @@ class Horde_Nonce
     {
         return pack('Nn2', time(), mt_rand(), mt_rand());
     }
+
+    /**
+     * Validate a nonce.
+     *
+     * @param string $nonce   The nonce that should be validate.
+     * @param float  $timeout The nonce should be invalid after this amount of time.
+     *
+     * @return boolean True if the nonce is still valid.
+     */
+    public function isValid($nonce, $timeout)
+    {
+        $timestamp = unpack('N', substr($nonce, 0, 4));
+        if (array_pop($timestamp) < (time() - $timeout)) {
+            return false;
+        }
+        return true;
+    }
 }
index f02a6eb..b727d17 100644 (file)
@@ -52,7 +52,7 @@ extends Horde_Nonce_StoryTestCase
     {
         $this->given('the default nonce setup')
             ->when('retrieving a nonce')
-            ->and('waiting for the tenth of a second')
-            ->then('the nonce is invalid given a timeout of a twentieth of a second');
+            ->and('waiting for two seconds')
+            ->then('the nonce is invalid given a timeout of one second');
     }
 }
\ No newline at end of file
index 12cb12d..306f099 100644 (file)
@@ -65,6 +65,9 @@ extends PHPUnit_Extensions_Story_TestCase
         case 'retrieving a nonce':
             $world['nonce'] = $world['nonce_handler']->get();
             break;
+        case 'waiting for two seconds':
+            sleep(2);
+            break;
         default:
             return $this->notImplemented($action);
         }
@@ -85,6 +88,9 @@ extends PHPUnit_Extensions_Story_TestCase
         case 'the nonce has a length of 8 bytes':
             $this->assertEquals(8, strlen($world['nonce']));
             break;
+        case 'the nonce is invalid given a timeout of one second':
+            $this->assertFalse($world['nonce_handler']->isValid($world['nonce'], 1));
+            break;
         default:
             return $this->notImplemented($action);
         }