1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Schnittstabil\Csrf; |
4
|
|
|
|
5
|
|
|
/** |
6
|
|
|
* A TokenService. |
7
|
|
|
*/ |
8
|
|
|
class TokenService implements TokenServiceInterface |
9
|
|
|
{ |
10
|
|
|
protected $generator; |
11
|
|
|
protected $validator; |
12
|
|
|
|
13
|
|
|
/** |
14
|
|
|
* Create a new TokenService. |
15
|
|
|
* |
16
|
|
|
* @param string $key Shared secret key used for generating token signatures. |
17
|
|
|
* @param int $ttl Default Time to Live in seconds used for calculating the expiration time of the tokens (1440sec === 24min === default of session.gc_maxlifetime). |
18
|
|
|
* @param string $algo Name of hashing algorithm. See hash_algos() for a list of supported algorithms. |
19
|
|
|
*/ |
20
|
|
|
public function __construct($key, $ttl = 1440, $algo = 'SHA512') |
21
|
|
|
{ |
22
|
|
|
$signatory = new TokenSignatory($key, $algo); |
23
|
|
|
$this->generator = new TokenGenerator($signatory, $ttl); |
24
|
|
|
$this->validator = new TokenValidator($signatory); |
25
|
|
|
} |
26
|
|
|
|
27
|
|
|
/** |
28
|
|
|
* Generate a Csrf Token. |
29
|
|
|
* |
30
|
|
|
* @param int $iat The time that the token was issued, defaults to `time()` |
31
|
|
|
* @param int $exp The expiration time, defaults to `$iat + $this->ttl` |
32
|
|
|
* |
33
|
|
|
* @return string |
34
|
|
|
* |
35
|
|
|
* @throws \InvalidArgumentException For invalid $iat and $exp arguments. |
36
|
|
|
*/ |
37
|
|
|
public function generate($iat = null, $exp = null) |
38
|
|
|
{ |
39
|
|
|
$generator = $this->generator; |
40
|
|
|
|
41
|
|
|
return $generator($iat, $exp); |
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
/** |
45
|
|
|
* Determine constraint violations of Csrf tokens. |
46
|
|
|
* |
47
|
|
|
* @param string $token The token to validate. |
48
|
|
|
* @param int $now The current time, defaults to `time()`. |
49
|
|
|
* |
50
|
|
|
* @return InvalidArgumentException[] Constraint violations; if $token is valid, an empty array. |
51
|
|
|
*/ |
52
|
|
|
public function getConstraintViolations($token, $now = null) |
53
|
|
|
{ |
54
|
|
|
$validator = $this->validator; |
55
|
|
|
|
56
|
|
|
return $validator($token, $now); |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
/** |
60
|
|
|
* Validate Csrf tokens. |
61
|
|
|
* |
62
|
|
|
* @param string $token The token to validate. |
63
|
|
|
* @param int $now The current time, defaults to `time()`. |
64
|
|
|
* |
65
|
|
|
* @return bool true iff $token is valid. |
66
|
|
|
*/ |
67
|
|
|
public function validate($token, $now = null) |
68
|
|
|
{ |
69
|
|
|
return count($this->getConstraintViolations($token, $now)) === 0; |
70
|
|
|
} |
71
|
|
|
} |
72
|
|
|
|