我有一个使用FOSUSerBundle在Symfony2.0上运行的应用程序。 连接该应用程序的用户每3个月必须更改其密码,该密码已就位且正常工作。
今天每3个月如果用户写入与前一个密码相同的新密码则没有验证,他可以再使用3个月。
我想在密码重置时添加约束,并强制用户提供与前一个密码不同的密码。 我不知道该怎么做。我试图创建一个验证器但我在验证器中没有我的用户ID ......
有任何线索吗?
答案 0 :(得分:1)
我找到了一个解决方案,它正在运行,但我还有一个小问题:当我提交新密码时,如果我尝试输入与前一个密码相同的密码,我的表单无效(&# 39;太棒了!),但我的树枝没有显示错误信息,而我正在使用:
{{ form_widget(edit_form) }}
知道为什么吗?
无论如何,这是我的解决方案:
我在类级别添加了验证器来验证密码。为此,我在User类中添加了一个验证器:
// \src\Acme\UserBundle\Resources\config\validation.xml
<class name="Acme\UserBundle\Entity\User">
<constraint name="Acme\UserBundle\Validator\Constraints\IsDifferentPassword">
<option name="message">Password has to be different from the previous one</option>
</constraint>
<property name="plainPassword">
<constraint name="NotBlank">
<option name="message">fos_user.password.blank</option>
</constraint>
</property>
</class>
我在班级创建了一个验证器:
// \src\Acme\UserBundle\Validator\Constraints\IsDifferentPassword.php
namespace Acme\UserBundle\Validator\Constraints;
use Symfony\Component\Validator\Constraint;
/**
* @Annotation
*/
class IsDifferentPassword extends Constraint
{
public $message = 'Password has to be different from the previous one';
public function getTargets()
{
return Constraint::CLASS_CONSTRAINT;
}
}
并且:
// \src\Acme\UserBundle\Validator\Constraints\IsDifferentPasswordValidator.php
namespace Acme\UserBundle\Validator\Constraints;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Security\Core\Encoder\MessageDigestPasswordEncoder;
class IsDifferentPasswordValidator extends ConstraintValidator
{
public function isValid($value, Constraint $constraint)
{
$encoder = new MessageDigestPasswordEncoder();
$password = $encoder->encodePassword($value->getPlainPassword(), $value->getSalt());
$oldPassword = $value->getPassword();
if($password == $oldPassword){
return false;
}
return true;
}
}
答案 1 :(得分:0)
我在symfony 3.4上也遇到了同样的问题。我解决了(symfony doc)替换为“ return false”的问题:
if ($password == $oldPassword) {
$this->context->buildViolation($constraint->message)
->atPath('current_password')
->addViolation();
}
其中
atPath()方法定义验证错误为的属性 关联到。使用任何有效的PropertyAccess语法来定义 属性。
删除“返回真实”; isValid函数末尾的行。
另一个区别是,我使用validate()函数代替了isValid()