编辑用户时出现问题,如何存储正确编码的密码?

时间:2014-01-22 22:20:12

标签: symfony

我没有使用FOSUserBundle,我自己创建了实体用户,角色等。配置如下:

security:
    encoders:
          Bundle\UserBundle\Entity\User: 
            algorithm: sha512
            encode-as-base64: true
            iterations: 10

在创建时我这样做:

if ($form->isValid()) {
            $factory = $this->get('security.encoder_factory');
            $encoder = $factory->getEncoder($entity);
            $entity->setSalt(md5(time()));
            $entity->setCompany($company);
            $encoded_password = $encoder->encodePassword($entity->getPassword(), $entity->getSalt());
            $entity->setPassword($encoded_password);
            $em = $this->getDoctrine()->getManager();
            $em->persist($entity);
            $em->flush();

            return $this->redirect($this->generateUrl('user'));
        }

但是,在编辑任何用户时,密码显示为:

2cp/D6OTBEx4m2Y9xM/ku6rOtgODhrXK7//3Pd8D0jnZkOuusPB120Jwb6x+kan/52qSQuQxcUYDP1T6q6zqbw== 

但如果我保存任何其他更改,密码将被覆盖,我无法再访问,如果我输入新密码,它也不会被编码(显然是因为我没有对updateAction做任何事情)但是我我想知道什么是正确的方法来实现这个目标?

使用preUpdate?在“编辑”中分隔密码字段,以便不会覆盖该字段?

1 个答案:

答案 0 :(得分:1)

尝试使用repeated Field Type设置密码。如果您在用户编辑表单中错过了它们,则该原则不会在DB中更新它们并且不会覆盖它们。

  • 并且不要使用notBlank验证码作为密码!

    $oldPass = $entity->getPassword();
    // Handle form from request
    if ($form->isValid()) {
        if ($entity->getPassword() == '' || $entity->getPassword() == NULL) {
            $entity->setPassword($oldPass);
        } else {
            $factory = $this->get('security.encoder_factory');
            $encoder = $factory->getEncoder($entity);
            $entity->setSalt(md5(time()));
            $entity->setCompany($company);
            $encoded_password = $encoder->encodePassword($entity->getPassword(), $entity->getSalt());
            $entity->setPassword($encoded_password);
        }
        $em = $this->getDoctrine()->getManager();
        $em->persist($entity);
        $em->flush();
    
        return $this->redirect($this->generateUrl('user'));
    }