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