1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace mindplay\kissform\Framework; |
4
|
|
|
|
5
|
|
|
use mindplay\kissform\Facets\TokenStoreInterface; |
6
|
|
|
use RuntimeException; |
7
|
|
|
|
8
|
|
|
/** |
9
|
|
|
* This class implements a token store using `$_SESSION`. |
10
|
|
|
*/ |
11
|
|
|
class SessionTokenStore implements TokenStoreInterface |
12
|
|
|
{ |
13
|
|
|
/** |
14
|
|
|
* @var int hard limit for unique tokens stored per user session |
15
|
|
|
*/ |
16
|
|
|
const HARD_LIMIT = 10; |
17
|
|
|
|
18
|
|
|
/** |
19
|
|
|
* @var bool[] map of tokens validated and consumed during the lifetime of this object |
20
|
|
|
*/ |
21
|
|
|
private $valid = []; |
22
|
|
|
|
23
|
|
|
/** |
24
|
|
|
* @inheritdoc |
25
|
|
|
* |
26
|
|
|
* @throws RuntimeException |
27
|
|
|
* |
28
|
|
|
* @SuppressWarnings(Superglobals) |
29
|
|
|
*/ |
30
|
|
|
public function registerToken($token) |
31
|
|
|
{ |
32
|
|
|
if (!session_id()) { |
33
|
|
|
throw new RuntimeException("no active session"); |
34
|
|
|
} |
35
|
|
|
|
36
|
|
|
if (!isset($_SESSION[__CLASS__])) { |
37
|
|
|
$_SESSION[__CLASS__] = []; |
38
|
|
|
} |
39
|
|
|
|
40
|
|
|
$_SESSION[__CLASS__][$token] = true; |
41
|
|
|
|
42
|
|
|
if (count($_SESSION[__CLASS__]) > self::HARD_LIMIT) { |
43
|
|
|
// truncate garbage tokens (which may accummulate if the user keeps hitting "refresh") |
44
|
|
|
|
45
|
|
|
$_SESSION[__CLASS__] = array_slice($_SESSION[__CLASS__], -self::HARD_LIMIT, null, true); |
46
|
|
|
} |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
/** |
50
|
|
|
* @inheritdoc |
51
|
|
|
* |
52
|
|
|
* @throws RuntimeException |
53
|
|
|
* |
54
|
|
|
* @SuppressWarnings(Superglobals) |
55
|
|
|
*/ |
56
|
|
|
public function verifyToken($token) |
57
|
|
|
{ |
58
|
|
|
if (!session_id()) { |
59
|
|
|
throw new RuntimeException("no active session"); |
60
|
|
|
} |
61
|
|
|
|
62
|
|
|
if (isset($_SESSION[__CLASS__][$token])) { |
63
|
|
|
unset($_SESSION[__CLASS__][$token]); |
64
|
|
|
|
65
|
|
|
$this->valid[$token] = true; |
66
|
|
|
} |
67
|
|
|
|
68
|
|
|
return isset($this->valid[$token]); |
69
|
|
|
} |
70
|
|
|
|
71
|
|
|
/** |
72
|
|
|
* @inheritdoc |
73
|
|
|
* |
74
|
|
|
* @SuppressWarnings(Superglobals) |
75
|
|
|
*/ |
76
|
|
|
public function getClientSalt() |
77
|
|
|
{ |
78
|
|
|
return @$_SERVER['REMOTE_ADDR'] . @$_SERVER['HTTP_USER_AGENT'] . session_id(); |
79
|
|
|
} |
80
|
|
|
} |
81
|
|
|
|