Validating a password in Symfony2

后端 未结 4 849
我寻月下人不归
我寻月下人不归 2020-12-31 12:08

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 th

相关标签:
4条回答
  • 2020-12-31 12:28

    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.

    0 讨论(0)
  • 2020-12-31 12:42

    I ended up cutting the Gordian knot. I bypassed all of Symfony's form stuff and did all the logic in the controller.

    0 讨论(0)
  • 2020-12-31 12:47

    FOSUserBundle uses a ModelManager class which is separate from the base Model. You can check their implementation.

    0 讨论(0)
  • 2020-12-31 12:48

    In Symfony 2.1 you can use the built-in validator: http://symfony.com/doc/master/reference/constraints/UserPassword.html

    So for instance in your form builder:

    // declare
    use Symfony\Component\Security\Core\Validator\Constraints\UserPassword;
    
    // mapped=>false (new in 2.1) is to let the builder know this is not an entity field
    ->add('currentpassword', 'password', array('label'=>'Current password', 'mapped' => false, 'constraints' => new UserPassword()))
    

    Apparently there's a bug right now with that validator so might or might now work https://github.com/symfony/symfony/issues/5460

    0 讨论(0)
提交回复
热议问题