|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace App\ViewRenderer; |
|
6
|
|
|
|
|
7
|
|
|
use Yiisoft\Router\UrlMatcherInterface; |
|
8
|
|
|
use Yiisoft\Yii\Web\Middleware\Csrf; |
|
9
|
|
|
|
|
10
|
|
|
class CsrfInjection extends AbstractInjection |
|
11
|
|
|
{ |
|
12
|
|
|
public const DEFAULT_META_ATTRIBUTE = 'csrf'; |
|
13
|
|
|
public const DEFAULT_PARAMETER = 'csrf'; |
|
14
|
|
|
|
|
15
|
|
|
private UrlMatcherInterface $urlMatcher; |
|
16
|
|
|
|
|
17
|
|
|
private string $requestAttribute = Csrf::REQUEST_NAME; |
|
18
|
|
|
private string $metaAttribute = self::DEFAULT_META_ATTRIBUTE; |
|
19
|
|
|
private string $parameter = self::DEFAULT_PARAMETER; |
|
20
|
|
|
|
|
21
|
|
|
public function __construct(UrlMatcherInterface $urlMatcher) |
|
22
|
|
|
{ |
|
23
|
|
|
$this->urlMatcher = $urlMatcher; |
|
24
|
|
|
} |
|
25
|
|
|
|
|
26
|
|
|
public function withRequestAttribute(string $requestAttribute): self |
|
27
|
|
|
{ |
|
28
|
|
|
$clone = clone $this; |
|
29
|
|
|
$clone->requestAttribute = $requestAttribute; |
|
30
|
|
|
return $clone; |
|
31
|
|
|
} |
|
32
|
|
|
|
|
33
|
|
|
public function withParameter(string $parameter): self |
|
34
|
|
|
{ |
|
35
|
|
|
$clone = clone $this; |
|
36
|
|
|
$clone->parameter = $parameter; |
|
37
|
|
|
return $clone; |
|
38
|
|
|
} |
|
39
|
|
|
|
|
40
|
|
|
public function withMetaAttribute(string $metaAttribute): self |
|
41
|
|
|
{ |
|
42
|
|
|
$clone = clone $this; |
|
43
|
|
|
$clone->metaAttribute = $metaAttribute; |
|
44
|
|
|
return $clone; |
|
45
|
|
|
} |
|
46
|
|
|
|
|
47
|
|
|
public function getParams(): array |
|
48
|
|
|
{ |
|
49
|
|
|
return [$this->parameter => $this->getCsrfToken()]; |
|
50
|
|
|
} |
|
51
|
|
|
|
|
52
|
|
|
public function getMetaTags(): array |
|
53
|
|
|
{ |
|
54
|
|
|
return [ |
|
55
|
|
|
[ |
|
56
|
|
|
'__key' => 'csrf_meta_tags', |
|
57
|
|
|
'name' => $this->metaAttribute, |
|
58
|
|
|
'content' => $this->getCsrfToken(), |
|
59
|
|
|
] |
|
60
|
|
|
]; |
|
61
|
|
|
} |
|
62
|
|
|
|
|
63
|
|
|
private ?string $csrfToken = null; |
|
64
|
|
|
|
|
65
|
|
|
private function getCsrfToken(): string |
|
66
|
|
|
{ |
|
67
|
|
|
if ($this->csrfToken === null) { |
|
68
|
|
|
$this->csrfToken = $this->urlMatcher->getLastMatchedRequest()->getAttribute($this->requestAttribute); |
|
69
|
|
|
} |
|
70
|
|
|
return $this->csrfToken; |
|
|
|
|
|
|
71
|
|
|
} |
|
72
|
|
|
} |
|
73
|
|
|
|