I’m trying to put together a change password feature in Symfony2. I have a “current password” field, a “new password” field and a “confirm new password” field, and the part I’m currently focusing on is validating the “current password” field.
(By the way, I realize now that things like FOSUserBundle exist that would take care of a lot of these things for me, but I already built my authentication system based on the official Symfony documentation, and I don’t have time right now to redo all my authentication code.)
What I’m imagining/hoping I can do is create a validation callback that says something like this:
// Entity/User.php
public function currentPasswordIsValid(ExecutionContext $context)
{
$currentPassword = $whatever; // whatever the user submitted as their current password
$factory = $this->get('security.encoder_factory'); // Getting the factory this way doesn't work in this context.
$encoder = $factory->getEncoder($this);
$encryptedCurrentPassword = $encoder->encodePassword($this->getPassword(), $this->getSalt());
if ($encyptedCurrentPassword != $this->getPassword() {
$context->addViolation('Current password is not valid', array(), null);
}
}
As you can see in my comments, there are at least a couple reasons why the above code doesn’t work. I would just post specific questions about those particular issues, but maybe I’m barking up the wrong tree altogether. That’s why I’m asking the overall question.
So, how can I validate a user’s password?
There’s a built-in constraint for that since Symfony 2.1.
First, you should create a custom validation constraint. You can register the validator as a service and inject whatever you need in it.
Second, since you probably don’t want to add a field for the current password to the User class just to stick the constraint to it, you could use what is called a form model. Essentially, you create a class in the
Form\Modelnamespace that holds the current password field and a reference to the user object. You can stick your custom constraint to that password field then. Then you create your password change form type against this form model.Here’s an example of a constraint from one of my projects:
And its validator:
I use my Blofwish password encoder bundle, so I don’t pass salt as the third argument to the
$encoder->isPasswordValid()method, but I think you’ll be able to adapt this example to your needs yourself.Also, I’m using
JMSDiExtraBundleto simplify development, but you can of course use the classical service container configuration way.