views:

1277

answers:

3

Hi,

Can anyone tell me where/how to customise the CSRF token error message for forms in Symfony 1.4. I'm using sfDoctrineGuard for logins and in this form particularly, whenever a session runs out and you still have the page open, it throws a very user-unfriendly error: "CSRF attack detected". Something like "This session has expired. Please return to the home page and try again" sounds better.

What's the right way to do this in the form class?

Thanks.

+1  A: 

The only way seems to be to overwrite sfForm::addCSRFProtection().

In /lib/form/BaseForm.class.php you can add this piece of code:

class BaseForm extends sfFormSymfony
{
    public function addCSRFProtection($secret = null)
    {
        parent::addCSRFProtection($secret);
        if (array_key_exists(self::$CSRFFieldName, $this->getValidatorSchema())) {
            $this->getValidator(self::$CSRFFieldName)->setMessage('csrf_attack', 'This session has expired. Please return to the home page and try again.');
        }
    }
}

After calling the parent method, you retrieve the validator associated with the CSRF field and change the message for the code csrf_attack.

Edit: You also need to check whether or not the validator exists. Some forms might have their CSRF protection disabled!

Hope this helps!

naag
@naag: thanks very much. Tried a few things but not that, will have a play. Seems like a minor oversight from the symfony guys.
Tom
I edited my answer to include a check for the existence of the CSRF validator :-)
naag
A: 

In 1.4.4 I had to modify naag's code like so...

public function addCSRFProtection($secret = null) { parent::addCSRFProtection($secret); if (isset($this->validatorSchema[self::$CSRFFieldName])) { $this->validatorSchema[self::$CSRFFieldName]->setMessage('csrf_attack', 'This session has expired. Please refresh and try again.'); } }

This got it working, the 'csrf token:' bit still appears in the error message though.

Dave Reed
A: 

Use event dispatcher. Check this out http://bluehorn.co.nz/2010/07/15/how-to-change-csrf-attack-message-in-symfony-1-2/

I wrote it for Symfony 1.2, but using event dispatcher, so it still might work for Symfony 1.4.

Sid Bachtiar