Symfony2 UserPassword约束获取NULL密码

时间:2015-03-24 11:27:54

标签: forms validation symfony constraints

我想让用户在我的应用程序中更改密码。我已经构建了一个用于编辑密码的表单,但验证从未通过,因为UserPassword约束中当前用户的密码始终为NULL:

<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Security\Core\Validator\Constraints;

use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\SecurityContextInterface;
use Symfony\Component\Security\Core\Encoder\EncoderFactoryInterface;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\Exception\ConstraintDefinitionException;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;

class UserPasswordValidator extends ConstraintValidator
{
    private $securityContext;
    private $encoderFactory;

    public function __construct(SecurityContextInterface $securityContext, EncoderFactoryInterface $encoderFactory)
    {
        $this->securityContext = $securityContext;
        $this->encoderFactory = $encoderFactory;
    }

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

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

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

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

        //I tried to print $user->getPassword from here and it is always NULL
        if (!$encoder->isPasswordValid($user->getPassword(), $password, $user->getSalt())) {
            $this->context->addViolation($constraint->message);
        }
    }
}

这是我用来更改密码的形式:

class UserPasswordEditType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('oldPassword', 'password', array(
            'constraints' => array(
                new UserPassword(array(
                        'message' => 'password_current.invalid',
                        'groups' => 'user-password-edit'
                    )
                ),
                new NotBlank(array(
                    'message' => 'not_blank',
                    'groups' => 'user-password-edit'
                ))
            ),
            'mapped' => false,
            'required' => true,
        ))
            ->add('password', 'repeated', array(
                'type' => 'password',
                'invalid_message' => 'password_repeat.invalid',
                'required' => true,
                'first_options' => array('label' => 'password.label'),
                'second_options' => array('label' => 'password_repeat.label'),
            ))
            ->add('save', 'submit', array(
                'label' => 'save.label'
            ));
    }

    public function getName()
    {
        return 'user_edit_password';
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'validation_groups' => array('user-password-edit'),
        ));
    }
}

这是security.yml的一部分

  security:
      encoders: 
          Symfony\Component\Security\Core\User\User: plaintext
          XXX\PrivateApplication\Bundle\UserBundle\Entity\User: plaintext

  role_hierarchy:
      ROLE_ADMIN:       ROLE_USER
      ROLE_SUPER_ADMIN: [ROLE_USER, ROLE_ADMIN, ROLE_ALLOWED_TO_SWITCH]

  providers:
      chain_provider:
        chain:
            providers: [in_memory, user_db]
      in_memory:
          memory:
              users:
                  API_DOC:  { password: @aaa, roles: [ 'ROLE_API_DOC' ] }
      user_db:
          entity: { class: XXX\PrivateApplication\Bundle\UserBundle\Entity\User, property: username }

为什么记录用户的密码始终为约束的NULL?如果我从控制器打印它可以工作......我不使用FOSUserBundle。

谢谢

PS: 我发现了一个类似的问题Using Symfony2 UserPassword validator in form type,但没有回复......

1 个答案:

答案 0 :(得分:0)

  

为什么记录用户的密码始终为约束的NULL?如果我从控制器打印它可以工作......

问题是,在$password中,您是来自表单的普通密码,而不是getPassword()!您从安全上下文的标记中检索“已登录”用户,并且编码的密码为NULL。这意味着,getUsername()可能也是NULL,getRoles()只是匿名或访客(现在不知道)。

然后登录根本不起作用,令牌只是匿名的。