我知道这个答案要晚几年才出现,但是当我遇到同样的问题时,我想提出我的解决方案:
问题是在我用于 FormMapping 的 $user 实体和来自 security.context 的 User 之间存在连接。
请参阅以下内容:(密码更改 - 控制器)
$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(...);
isValid() 函数正在触发 UserPassword 约束验证器:
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);
}
}
感兴趣的线路是: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')
感兴趣的线路是'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();
}
一些我无法完全理解的问题的解决方法。如果有人能解释数据库对象和 security.context 对象之间的联系,我会很高兴听到它!