feature #28656 When a CSRF occures on a Form submit add a cause on the FormError object (gmponos)

This PR was merged into the 4.2-dev branch.

Discussion
----------

When a CSRF occures on a Form submit add a cause on the FormError object

| Q             | A
| ------------- | ---
| Branch?       | master
| Bug fix?      | no
| New feature?  | yes
| BC breaks?    | no
| Deprecations? | no
| Tests pass?   | yes
| Fixed tickets | #28427
| License       | MIT
| Doc PR        | symfony/symfony-docs

This is a resubmitted PR of this: https://github.com/symfony/symfony/pull/28564

> Something went wrong when merging this PR. @gmponos Can you resubmit it again? Sorry for the trouble.

Commits
-------

e54e94c7fe When a CSRF occures on a Form submit add a cause on the FormError object
This commit is contained in:
Fabien Potencier 2018-10-01 09:31:13 +02:00
commit 9610d10034
3 changed files with 7 additions and 4 deletions

View File

@ -7,6 +7,7 @@ CHANGELOG
* deprecated the `$scale` argument of the `IntegerToLocalizedStringTransformer`
* added `Symfony\Component\Form\ClearableErrorsInterface`
* deprecated calling `FormRenderer::searchAndRenderBlock` for fields which were already rendered
* added a cause when a CSRF error has occurred
* deprecated the `scale` option of the `IntegerType`
4.1.0

View File

@ -59,14 +59,15 @@ class CsrfValidationListener implements EventSubscriberInterface
if ($form->isRoot() && $form->getConfig()->getOption('compound') && !$postRequestSizeExceeded) {
$data = $event->getData();
if (!isset($data[$this->fieldName]) || !$this->tokenManager->isTokenValid(new CsrfToken($this->tokenId, $data[$this->fieldName]))) {
$csrfToken = new CsrfToken($this->tokenId, $data[$this->fieldName] ?? null);
if (!isset($data[$this->fieldName]) || !$this->tokenManager->isTokenValid($csrfToken)) {
$errorMessage = $this->errorMessage;
if (null !== $this->translator) {
$errorMessage = $this->translator->trans($errorMessage, array(), $this->translationDomain);
}
$form->addError(new FormError($errorMessage));
$form->addError(new FormError($errorMessage, $errorMessage, array(), null, $csrfToken));
}
if (\is_array($data)) {

View File

@ -365,9 +365,10 @@ class FormTypeCsrfExtensionTest extends TypeTestCase
public function testsTranslateCustomErrorMessage()
{
$csrfToken = new CsrfToken('TOKEN_ID', 'token');
$this->tokenManager->expects($this->once())
->method('isTokenValid')
->with(new CsrfToken('TOKEN_ID', 'token'))
->with($csrfToken)
->will($this->returnValue(false));
$this->translator->expects($this->once())
@ -390,7 +391,7 @@ class FormTypeCsrfExtensionTest extends TypeTestCase
));
$errors = $form->getErrors();
$expected = new FormError('[trans]Foobar[/trans]');
$expected = new FormError('[trans]Foobar[/trans]', null, array(), null, $csrfToken);
$expected->setOrigin($form);
$this->assertGreaterThan(0, \count($errors));