Add initial steps of the token validation.
authorGunnar Wrobel <p@rdus.de>
Tue, 30 Nov 2010 05:49:46 +0000 (06:49 +0100)
committerGunnar Wrobel <p@rdus.de>
Tue, 30 Nov 2010 12:48:27 +0000 (13:48 +0100)
framework/Token/lib/Horde/Token/Base.php
framework/Token/test/Horde/Token/Unit/FileTest.php

index aac281a..7be77b0 100644 (file)
@@ -108,17 +108,43 @@ abstract class Horde_Token_Base
      *
      * @param string $seed  A unique ID to be included in the token.
      *
-     * @return string A string of 6 bytes.
+     * @return string The new token.
      */
     public function get($seed = '')
     {
         $nonce = $this->getNonce();
         return Horde_Url::uriB64Encode(
-            $nonce . hash('sha256', $nonce . $this->_params['secret'] . $seed, true)
+            $nonce . $this->_hash($nonce . $seed)
         );
     }
 
     /**
+     * Validate a signed token.
+     *
+     * @param string  $token    The signed token.
+     * @param string  $seed     The unique ID of the token.
+     * @param int     $timeout  Timout of the token in seconds.
+     * @param boolean $unique   Can the token be used more than once?
+     *
+     * @return boolean True if the token was valid.
+     */
+    public function validate($token, $seed = '', $timeout = 0, $unique = false)
+    {
+        $b = Horde_Url::uriB64Decode($token);
+        $nonce = substr($b, 0, 6);
+        $hash = substr($b, 6);
+        if ($hash != $this->_hash($nonce . $seed)) {
+            return false;
+        }
+        return true;
+    }
+
+    private function _hash($text)
+    {
+        return hash('sha256', $text . $this->_params['secret'], true);
+    }
+
+    /**
      * Return a "number used once" (a concatenation of a timestamp and a random
      * numer).
      *
index 3e4ac81..a458bed 100644 (file)
@@ -45,6 +45,36 @@ class Horde_Token_Unit_Storage_FileTest extends PHPUnit_Framework_TestCase
         $this->assertEquals(51, strlen($t->get()));
     }
 
+    public function testValidation()
+    {
+        $t = new Horde_Token_File(array('secret' => 'abc'));
+        $this->assertTrue($t->validate($t->get()));
+    }
+
+    public function testValidationWithSeed()
+    {
+        $t = new Horde_Token_File(array('secret' => 'abc'));
+        $this->assertTrue($t->validate($t->get('a'), 'a'));
+    }
+
+    public function testInvalidToken()
+    {
+        $t = new Horde_Token_File(array('secret' => 'abc'));
+        $this->assertFalse($t->validate('something'));
+    }
+
+    public function testInvalidEmptyToken()
+    {
+        $t = new Horde_Token_File(array('secret' => 'abc'));
+        $this->assertFalse($t->validate(''));
+    }
+
+    public function testInvalidSeed()
+    {
+        $t = new Horde_Token_File(array('secret' => 'abc'));
+        $this->assertFalse($t->validate($t->get('a'), 'b'));
+    }
+
     public function testNonces()
     {
         $t = new Horde_Token_File(array('secret' => 'abc'));