|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace PSR7Csrf; |
|
6
|
|
|
|
|
7
|
|
|
use Lcobucci\JWT\Builder; |
|
8
|
|
|
use Lcobucci\JWT\Signer; |
|
9
|
|
|
use Lcobucci\JWT\Token; |
|
10
|
|
|
use Psr\Http\Message\ServerRequestInterface; |
|
11
|
|
|
use PSR7Csrf\Exception\InvalidExpirationTimeException; |
|
12
|
|
|
use PSR7Csrf\Exception\SessionAttributeNotFoundException; |
|
13
|
|
|
use PSR7Csrf\Session\ExtractUniqueKeyFromSessionInterface; |
|
14
|
|
|
use PSR7Sessions\Storageless\Session\SessionInterface; |
|
15
|
|
|
|
|
16
|
|
|
final class TokenGenerator implements TokenGeneratorInterface |
|
17
|
|
|
{ |
|
18
|
|
|
/** |
|
19
|
|
|
* @var Signer |
|
20
|
|
|
*/ |
|
21
|
|
|
private $signer; |
|
22
|
|
|
|
|
23
|
|
|
/** |
|
24
|
|
|
* @var ExtractUniqueKeyFromSessionInterface |
|
25
|
|
|
*/ |
|
26
|
|
|
private $extractUniqueKeyFromSession; |
|
27
|
|
|
|
|
28
|
|
|
/** |
|
29
|
|
|
* @var int |
|
30
|
|
|
*/ |
|
31
|
|
|
private $expirationTime; |
|
32
|
|
|
|
|
33
|
|
|
/** |
|
34
|
|
|
* @var string |
|
35
|
|
|
*/ |
|
36
|
|
|
private $sessionAttribute; |
|
37
|
|
|
|
|
38
|
|
|
/** |
|
39
|
|
|
* @param Signer $signer |
|
40
|
|
|
* @param ExtractUniqueKeyFromSessionInterface $extractUniqueKeyFromSession |
|
41
|
|
|
* @param int $expirationTime |
|
42
|
|
|
* @param string $sessionAttribute |
|
43
|
|
|
* |
|
44
|
|
|
* @throws InvalidExpirationTimeException |
|
45
|
|
|
*/ |
|
46
|
8 |
|
public function __construct( |
|
47
|
|
|
Signer $signer, |
|
48
|
|
|
ExtractUniqueKeyFromSessionInterface $extractUniqueKeyFromSession, |
|
49
|
|
|
int $expirationTime, |
|
50
|
|
|
string $sessionAttribute |
|
51
|
|
|
) { |
|
52
|
8 |
|
if ($expirationTime <= 0) { |
|
53
|
3 |
|
throw InvalidExpirationTimeException::fromInvalidExpirationTime($expirationTime); |
|
54
|
|
|
} |
|
55
|
|
|
|
|
56
|
5 |
|
$this->signer = $signer; |
|
57
|
5 |
|
$this->extractUniqueKeyFromSession = $extractUniqueKeyFromSession; |
|
58
|
5 |
|
$this->expirationTime = $expirationTime; |
|
59
|
5 |
|
$this->sessionAttribute = $sessionAttribute; |
|
60
|
5 |
|
} |
|
61
|
|
|
|
|
62
|
3 |
|
public function __invoke(ServerRequestInterface $request) : Token |
|
63
|
|
|
{ |
|
64
|
3 |
|
$session = $request->getAttribute($this->sessionAttribute); |
|
65
|
|
|
|
|
66
|
3 |
|
if (! $session instanceof SessionInterface) { |
|
67
|
1 |
|
throw SessionAttributeNotFoundException::fromAttributeNameAndRequest($this->sessionAttribute, $request); |
|
68
|
|
|
} |
|
69
|
|
|
|
|
70
|
2 |
|
$timestamp = (new \DateTime())->getTimestamp(); |
|
71
|
|
|
|
|
72
|
2 |
|
return (new Builder()) |
|
73
|
2 |
|
->setIssuedAt($timestamp) |
|
74
|
2 |
|
->setExpiration($timestamp + $this->expirationTime) |
|
75
|
2 |
|
->sign($this->signer, $this->extractUniqueKeyFromSession->__invoke($session)) |
|
76
|
2 |
|
->getToken(); |
|
77
|
|
|
} |
|
78
|
|
|
} |
|
79
|
|
|
|