Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validating a password in Symfony2

Tags:

symfony

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?

like image 208
Jason Swett Avatar asked Apr 01 '12 15:04

Jason Swett


1 Answers

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\Model namespace 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:

<?php
namespace Vendor\Bundle\AppBundle\Validator\Constraints\User;

use Symfony\Component\Validator\Constraint;

/**
 * @Annotation
 */
class CurrentPassword extends Constraint
{
    public $message = "Your current password is not valid";

    /**
     * @return string
     */
    public function validatedBy()
    {
        return 'user.validator.current_password';
    }
}

And its validator:

<?php
namespace Vendor\Bundle\AppBundle\Validator\Constraints\User;

use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Security\Core\Encoder\EncoderFactoryInterface;
use Symfony\Component\Security\Core\SecurityContextInterface;
use JMS\DiExtraBundle\Annotation\Validator;
use JMS\DiExtraBundle\Annotation\InjectParams;
use JMS\DiExtraBundle\Annotation\Inject;

/**
 * @Validator("user.validator.current_password")
 */
class CurrentPasswordValidator extends ConstraintValidator
{
    /**
     * @var EncoderFactoryInterface
     */
    private $encoderFactory;

    /**
     * @var SecurityContextInterface
     */
    private $securityContext;

    /**
     * @InjectParams({
     *     "encoderFactory"  = @Inject("security.encoder_factory"),
     *     "securityContext" = @Inject("security.context")
     * })
     *
     * @param EncoderFactoryInterface  $encoderFactory
     * @param SecurityContextInterface $securityContext
     */
    public function __construct(EncoderFactoryInterface  $encoderFactory,
                                SecurityContextInterface $securityContext)
    {
        $this->encoderFactory  = $encoderFactory;
        $this->securityContext = $securityContext;
    }

    /**
     * @param string     $currentPassword
     * @param Constraint $constraint
     * @return boolean
     */
    public function isValid($currentPassword, Constraint $constraint)
    {
        $currentUser = $this->securityContext->getToken()->getUser();
        $encoder = $this->encoderFactory->getEncoder($currentUser);
        $isValid = $encoder->isPasswordValid(
            $currentUser->getPassword(), $currentPassword, null
        );

        if (!$isValid) {
            $this->setMessage($constraint->message);
            return false;
        }

        return true;
    }
}

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 JMSDiExtraBundle to simplify development, but you can of course use the classical service container configuration way.

like image 135
Elnur Abdurrakhimov Avatar answered Sep 22 '22 20:09

Elnur Abdurrakhimov