在表单类型中使用Symfony2 UserPassword验证程序

the*_*ids 5 php passwords validation formbuilder symfony

我试图在表单中使用特定的验证器。

该表格供用户重新定义其密码,他还必须输入其当前密码。为此,我使用来自symfony的内置验证器

以我的形式:

use Symfony\Component\Security\Core\Validator\Constraints\UserPassword;
Run Code Online (Sandbox Code Playgroud)

表单类型如下所示:

 /**
 * @param FormBuilderInterface $builder
 * @param array $options
 */
public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('currentpassword', 'password', array('label'=>'Current password',
            'mapped' => false,
            'constraints' => new UserPassword(array('message' => 'you wot m8?')),
            'required' => true
        ))
        ->add('password', 'repeated', array(
            'first_name' => 'new',
            'second_name' => 'confirm',
            'type' => 'password',
            'required' => true
        ))
    ;
}
Run Code Online (Sandbox Code Playgroud)

我知道我可以在控制器中获取数据表格,获取当前密码值,调用security.encoder_factory等,但是该验证程序很方便。

我的问题是表单总是返回错误(在这里:“ you wot m8?”),就像我输入了错误的当前密码一样。

知道我在做什么错吗?

Mar*_*tin 5

我知道这个答案迟到了几年,但是当我遇到同样的问题时,我想提出我的解决方案:

问题是,在我的案例中,$user我用于 FormMapping的实体与User来自security.context.

请参阅以下内容:(密码更改 - 控制器)

    $username = $this->getUser()->getUsername();
    $user = $this->getDoctrine()->getRepository("BlueChordCmsBaseBundle:User")->findOneBy(array("username"=>$username));
    // Equal to $user = $this->getUser();

    $form = $this->createForm(new ChangePasswordType(), $user);
    //ChangePasswordType equals the one 'thesearentthedroids' posted


    $form->handleRequest($request);
    if($request->getMethod() === "POST" && $form->isValid()) {
        $manager = $this->getDoctrine()->getManager();
        $user->setPassword(password_hash($user->getPassword(), PASSWORD_BCRYPT));
        [...]
    }

    return array(...);
Run Code Online (Sandbox Code Playgroud)

isValid()函数正在触发 UserPassword Constraint Validator:

public function validate($password, Constraint $constraint)
{
    if (!$constraint instanceof UserPassword) {
        throw new UnexpectedTypeException($constraint, __NAMESPACE__.'\UserPassword');
    }

    $user = $this->tokenStorage->getToken()->getUser();

    if (!$user instanceof UserInterface) {
        throw new ConstraintDefinitionException('The User object must implement the UserInterface interface.');
    }

    $encoder = $this->encoderFactory->getEncoder($user);

    if (!$encoder->isPasswordValid($user->getPassword(), $password, $user->getSalt())) {
        $this->context->addViolation($constraint->message);
    }
}
Run Code Online (Sandbox Code Playgroud)

感兴趣的线路是: if (!$encoder->isPasswordValid($user->getPassword(), $password, $user->getSalt()))

在我的情况下,$user->getPassword()正在返回我刚刚在表单中输入的新密码作为我的新密码。 这就是为什么测试总是失败的原因! 我不明白为什么 tokenStorage 中的用户和我从数据库加载的用户之间可能存在连接。感觉这两个对象(MyDatabase 一个和 tokenStorage 一个)共享相同的处理器地址并且实际上是相同的......

奇怪的!

我的解决方案是还将 ChangePasswordType 中的(新)密码字段与 EntityMapping 分离:参见

        ->add('currentpassword', 'password', array('label'=>'Current password', 'mapped' => false, 'constraints' => new UserPassword()))
        ->add('password', 'repeated', array(
            'mapped'          => false,
            'type'            => 'password',
            'invalid_message' => 'The password fields must match.',
            'required'        => true,
            'first_options'   => array('label' => 'Password'),
            'second_options'  => array('label' => 'Repeat Password'),
            ))
        ->add('Send', 'submit')
        ->add('Reset','reset')
Run Code Online (Sandbox Code Playgroud)

感兴趣的线是 'mapped' => false,

这样,在表单中输入的新密码将不会自动映射到给定的$user实体。相反,您现在需要从form. 看

    $form->handleRequest($request);
    if($request->getMethod() === "POST" && $form->isValid()) {
        $data = $form->getData();
        $manager = $this->getDoctrine()->getManager();
        $user->setPassword(password_hash($data->getPassword(), PASSWORD_BCRYPT));
        $manager->persist($user);
        $manager->flush();
    }
Run Code Online (Sandbox Code Playgroud)

一些我无法完全理解的问题的解决方法。如果有人能解释数据库对象和 security.context 对象之间的联系,我会很高兴听到的!