FRED™  3.0
FRED™: Framework for Rapid and Easy Development
Token.php
Go to the documentation of this file.
1 <?php
2 
3 namespace Rsi\Fred;
4 
5 /**
6  * Unique token generator/validator.
7  */
8 class Token extends Component{
9 
10  public $length = 50;
11 
12  protected function hash($context,$token){
13  return substr(base_convert(sha1(serialize($context) . $this->component('encrypt')->key . $token),16,36),0,$this->length / 2);
14  }
15  /**
16  * Generate a token.
17  * @param mixed $context Context for the token.
18  * @param int $ttl Time-to-live in seconds (empty = indefinitely).
19  * @return string Random token for this context.
20  */
21  public function generate($context = null,$ttl = null){
22  $token = $ttl ? base_convert(time() + $ttl,10,36) . '-' : '';
23  $token .= \Rsi\Str::random($this->length / 2 - strlen($token) - 1,'[0-9][a-z]');
24  return $token . '-' . $this->hash($context,$token);
25  }
26  /**
27  * Check if a token is (still) valid.
28  * @param string $token Token to check.
29  * @param mixed $context Context for the token.
30  * @return bool True if the token is valid.
31  */
32  public function valid($token,$context = null){
33  $result = false;
34  try{
35  if(strlen($token) == $this->length) switch(count($token = explode('-',$token))){
36  case 3:
37  if(base_convert($token[0],36,10) < time()) break;
38  case 2:
39  $hash = array_pop($token);
40  $result = hash_equals($this->hash($context,implode('-',$token)),$hash);
41  }
42  }
43  catch(\Exception $e){
44  if($this->_fred->debug) throw $e;
45  }
46  $this->component('security')->bruteForceDelay($result,'token');
47  return $result;
48  }
49  /**
50  * Delete a token.
51  * @return bool True on success.
52  */
53  public function delete($token){
54  return false;
55  }
56 
57 }
hash($context, $token)
Definition: Token.php:12
valid($token, $context=null)
Check if a token is (still) valid.
Definition: Token.php:32
Unique token generator/validator.
Definition: Token.php:8
Basic component class.
Definition: Component.php:8
generate($context=null, $ttl=null)
Generate a token.
Definition: Token.php:21
component($name)
Get a component (local or default).
Definition: Component.php:80