我有一个具有 plainPassword 和密码属性的实体。在表单中,我映射到 plainPassword。之后,当用户验证表单时,我对 plainPassword 进行密码验证。
为了对密码进行编码,我使用了监听 prePersist 和 preUpdate 的 EventSubscriber。它适用于注册表单,因为它是一个新实体,用户填写一些持久的属性,然后教条将其持久化并刷新。
但是,当我只想编辑密码时,它不起作用,我认为这是因为用户只是编辑了非持久属性。那么教义就不会试图坚持它。但我需要它来输入订阅者。
有人知道该怎么做吗? (我在其他实体中也有类似的问题)目前,我在控制器中进行操作......
多谢。
我的用户订阅者
class UserSubscriber implements EventSubscriber
{
private $passwordEncoder;
private $tokenGenerator;
public function __construct(UserPasswordEncoder $passwordEncoder, TokenGenerator $tokenGenerator)
{
$this->passwordEncoder = $passwordEncoder;
$this->tokenGenerator = $tokenGenerator;
}
public function getSubscribedEvents()
{
return array(
'prePersist',
'preUpdate',
);
}
public function prePersist(LifecycleEventArgs $args)
{
$object = $args->getObject();
if ($object instanceof User) {
$this->createActivationToken($object);
$this->encodePassword($object);
}
}
public function preUpdate(LifecycleEventArgs $args)
{
$object = $args->getObject();
if ($object instanceof User) {
$this->encodePassword($object);
}
}
private function createActivationToken(User $user)
{
// If it's not a new object, return
if (null !== $user->getId()) {
return;
}
$token = $this->tokenGenerator->generateToken();
$user->setConfirmationToken($token);
}
private function encodePassword(User $user)
{
if (null === $user->getPlainPassword()) {
return;
}
$encodedPassword = $this->passwordEncoder->encodePassword($user, $user->getPlainPassword());
$user->setPassword($encodedPassword);
}
我的用户实体:
class User implements AdvancedUserInterface, \Serializable
{
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* @ORM\Column(name="email", type="string", length=255, unique=true)
* @Assert\NotBlank()
* @Assert\Email()
*/
private $email;
/**
* @Assert\Length(max=4096)
*/
private $plainPassword;
/**
* @ORM\Column(name="password", type="string", length=64)
*/
private $password;
配置文件控制器:
class ProfileController extends Controller
{
/**
* @Route("/my-profile/password/edit", name="user_password_edit")
* @Security("is_granted('IS_AUTHENTICATED_REMEMBERED')")
*/
public function editPasswordAction(Request $request)
{
$user = $this->getUser();
$form = $this->createForm(ChangePasswordType::class, $user);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
// Encode the password
// If I decomment it, it's work, but I want to do it autmaticlally, but in the form I just change the plainPassword, that is not persisted in database
//$password = $this->get('security.password_encoder')->encodePassword($user, $user->getPlainPassword());
//$user->setPassword($password);
$em = $this->getDoctrine()->getManager();
$em->flush();
$this->addFlash('success', 'Your password have been successfully changed.');
return $this->redirectToRoute('user_profile');
}
return $this->render('user/password/edit.html.twig', [
'form' => $form->createView(),
]);
}
}