|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Bdf\Form\Csrf; |
|
4
|
|
|
|
|
5
|
|
|
use Bdf\Form\ElementInterface; |
|
6
|
|
|
use Bdf\Form\Error\FormError; |
|
7
|
|
|
use Bdf\Form\Validator\ConstraintValueValidator; |
|
8
|
|
|
use Bdf\Form\Validator\ValueValidatorInterface; |
|
9
|
|
|
use Exception; |
|
10
|
|
|
|
|
11
|
|
|
/** |
|
12
|
|
|
* Class CsrfValueValidator |
|
13
|
|
|
* |
|
14
|
|
|
* @implements ValueValidatorInterface<\Symfony\Component\Security\Csrf\CsrfToken> |
|
15
|
|
|
*/ |
|
16
|
|
|
final class CsrfValueValidator implements ValueValidatorInterface |
|
17
|
|
|
{ |
|
18
|
|
|
/** |
|
19
|
|
|
* Invalidate the token after verification ? |
|
20
|
|
|
* |
|
21
|
|
|
* @var boolean |
|
22
|
|
|
*/ |
|
23
|
|
|
private $invalidate; |
|
24
|
|
|
|
|
25
|
|
|
/** |
|
26
|
|
|
* The constraint options |
|
27
|
|
|
* |
|
28
|
|
|
* @var array |
|
29
|
|
|
*/ |
|
30
|
|
|
private $options; |
|
31
|
|
|
|
|
32
|
|
|
/** |
|
33
|
|
|
* CsrfValueValidator constructor. |
|
34
|
|
|
* |
|
35
|
|
|
* @param bool $invalidate Always invalidate the token after validation |
|
36
|
|
|
* @param array $options Constraints options |
|
37
|
|
|
*/ |
|
38
|
22 |
|
public function __construct(bool $invalidate = false, array $options = []) |
|
39
|
|
|
{ |
|
40
|
22 |
|
$this->invalidate = $invalidate; |
|
41
|
22 |
|
$this->options = $options; |
|
42
|
22 |
|
} |
|
43
|
|
|
|
|
44
|
|
|
/** |
|
45
|
|
|
* {@inheritdoc} |
|
46
|
|
|
* |
|
47
|
|
|
* @param CsrfElement $element |
|
48
|
|
|
* @psalm-suppress MoreSpecificImplementedParamType |
|
49
|
|
|
*/ |
|
50
|
12 |
|
public function validate($value, ElementInterface $element): FormError |
|
51
|
|
|
{ |
|
52
|
|
|
try { |
|
53
|
12 |
|
return (new ConstraintValueValidator([new CsrfConstraint($this->options + ['manager' => $element->getTokenManager()])]))->validate($value, $element); |
|
|
|
|
|
|
54
|
|
|
} finally { |
|
55
|
12 |
|
if ($this->invalidate) { |
|
56
|
12 |
|
$element->invalidateToken(); |
|
|
|
|
|
|
57
|
|
|
} |
|
58
|
|
|
} |
|
59
|
|
|
} |
|
60
|
|
|
|
|
61
|
|
|
/** |
|
62
|
|
|
* {@inheritdoc} |
|
63
|
|
|
*/ |
|
64
|
|
|
public function onTransformerException(Exception $exception, $value, ElementInterface $element): FormError |
|
65
|
|
|
{ |
|
66
|
|
|
// Ignore transformer exception: the CSRF token will be validated after |
|
67
|
|
|
return FormError::null(); |
|
68
|
|
|
} |
|
69
|
|
|
|
|
70
|
|
|
/** |
|
71
|
|
|
* {@inheritdoc} |
|
72
|
|
|
*/ |
|
73
|
|
|
public function constraints(): array |
|
74
|
|
|
{ |
|
75
|
|
|
return []; // Does CsrfConstraint should be returns ? |
|
76
|
|
|
} |
|
77
|
|
|
} |
|
78
|
|
|
|