From 50c2557a48ba86085cf98ece6b9ddce78da285c8 Mon Sep 17 00:00:00 2001 From: Gunnar Wrobel Date: Wed, 3 Nov 2010 21:01:46 +0100 Subject: [PATCH] Timestamp validation. --- framework/Nonce/lib/Horde/Nonce.php | 17 +++++++++++++++++ .../Nonce/test/Horde/Nonce/Integration/NonceTest.php | 4 ++-- framework/Nonce/test/Horde/Nonce/StoryTestCase.php | 6 ++++++ 3 files changed, 25 insertions(+), 2 deletions(-) diff --git a/framework/Nonce/lib/Horde/Nonce.php b/framework/Nonce/lib/Horde/Nonce.php index 836045ac7..a17b89c80 100644 --- a/framework/Nonce/lib/Horde/Nonce.php +++ b/framework/Nonce/lib/Horde/Nonce.php @@ -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; + } } diff --git a/framework/Nonce/test/Horde/Nonce/Integration/NonceTest.php b/framework/Nonce/test/Horde/Nonce/Integration/NonceTest.php index f02a6eb61..b727d17c6 100644 --- a/framework/Nonce/test/Horde/Nonce/Integration/NonceTest.php +++ b/framework/Nonce/test/Horde/Nonce/Integration/NonceTest.php @@ -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 diff --git a/framework/Nonce/test/Horde/Nonce/StoryTestCase.php b/framework/Nonce/test/Horde/Nonce/StoryTestCase.php index 12cb12dc7..306f09958 100644 --- a/framework/Nonce/test/Horde/Nonce/StoryTestCase.php +++ b/framework/Nonce/test/Horde/Nonce/StoryTestCase.php @@ -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); } -- 2.11.0