dongren4147 2016-01-13 20:31
浏览 20
已采纳

更新symfony2用户而不会丢失密码

How can I update the symfony2 user without losing his password?

This is the custom User entity:

namespace Nbois\UserBundle\Entity;

use Symfony\Component\Security\Core\User\AdvancedUserInterface;
use Symfony\Component\Validator\Constraints as Assert;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity
 * @ORM\Table(name="system_user")
 * @ORM\Entity(repositoryClass="Nbois\UserBundle\Repository\UserRepository")
 */
class User implements AdvancedUserInterface, \Serializable
{
  /**
   * @ORM\Column(type="integer")
   * @ORM\Id
   * @ORM\GeneratedValue(strategy="AUTO")
   */
  private $id;

  /**
   * @ORM\Column(name="username", type="string", length=25, unique=true)
   * @Assert\NotBlank()
   * @Assert\Length(min=3)
   */
  private $username;

  /**
   * @ORM\Column(name="salt", type="string", length=40)
   */
  private $salt;

  /**
   * @ORM\Column(name="password", type="string", length=255)
   * @Assert\Length(min=6)
   */
  private $password;

  /**
   * @Assert\NotBlank()
   * @Assert\Length(max = 4096)
   */
  private $plainPassword;

  /**
   * @ORM\Column(name="email", type="string", length=60, unique=true)
   * @Assert\NotBlank()
   */
  private $email;

  /**
   * @ORM\Column(type="string", length=25)
   * @Assert\NotBlank()
   */
  private $firstName;

  /**
   * @ORM\Column(type="string", length=25)
   * @Assert\NotBlank()
   */
  private $lastName;

  /**
   * @ORM\Column(type="string", length=12, unique=true)
   * @Assert\NotBlank()
   */
  private $phone;

  /**
   * @ORM\Column(type="string", length=2)
   */
  private $defaultLanguage;

  /**
   * @ORM\Column(name="is_active", type="boolean")
   */
  private $isActive;

  /**
   * @ORM\Column(type="string", length=255, nullable=true)
   */
  private $confirmationToken;

  /**
   * @ORM\Column(type="datetime")
   */
  private $createdAt;

  /**
   * @ORM\Column(type="datetime")
   */
  private $updatedAt;

  /**
  * @ORM\OneToMany(targetEntity="RoleUser", mappedBy="user")
  */
  private $roles;

  // constructor
  public function __construct()
  {
    $this->isActive = true;
    $this->roles = new ArrayCollection();
    $this->salt = base_convert(sha1(uniqid(mt_rand(), true)), 16, 36);
  }

//----- GET METHODS
  public function getId(){
    return $this->id;
  }

  public function getUsername() {
    return $this->username;
  }

  public function getPassword() {
    return $this->password;
  }

  public function getSalt() {
    return $this->salt;
  }

  public function getEmail()
  {
      return $this->email;
  }

  public function getPlainPassword()
  {
      return $this->plainPassword;
  }

  public function getFirstName()
  {
      return $this->firstName;
  }

  public function getLastName(){
      return $this->lastName;
  }

  public function getPhone(){
      return $this->phone;
  }

  public function getDefaultLanguage(){
      return $this->defaultLanguage;
  }

  public function getCreatedAt(){
      return $this->createdAt;
  }

  public function getUpdatedAt(){
      return $this->updatedAt;
  }

  public function getIsActive(){
    return $this->isActive;
  }

  public function getConfirmationToken(){
    return $this->confirmationToken;
  }

  public function getRoles()
  {
    if(count($this->roles) == 0){
      return array("ROLE_USER");
    }else{

      $result = array();
      foreach($this->roles as $ru){
        array_push($result, $ru->getRole());
      }

      return $result;
    }
  }


//------ SET METHODS

  public function setUsername($username){
    $this->username = $username;
    return $this;
  }

  public function setPassword($password){
    $this->password = $password;
  }

  public function setFirstName($firstName){
      $this->firstName = $firstName;
      return $this;
  }

  public function setLastName($lastName){
      $this->lastName = $lastName;
      return $this;
  }

  public function setEmail($email){
    $this->email = $email;
    return $this;
  }

  public function setPlainPassword($password)
  {
      $this->plainPassword = $password;
  }

  public function setPhone($phone){
      $this->phone = $phone;
      return $this;
  }

  public function setDefaultLanguage($language){
      $this->defaultLanguage = $language;
      return $this;
  }

  public function setCreatedAt(\DateTime $createdAt){
      $this->createdAt = $createdAt;
      return $this;
  }

  public function setUpdatedAt(\DateTime $updatedAt){
      $this->updatedAt = $updatedAt;
      return $this;
  }

  public function setConfirmationToken($token){
    $this->confirmationToken = md5($token);
    return $this;
  }

  public function addRole(Role $role){
    $roles = $this->getRoles();
    array_push($roles, $role);
  }


  /** @see \Serializable::serialize() */
  public function serialize()
  {
    return serialize(array(
      $this->id,
      $this->username,
      $this->email,
      $this->password,
      $this->salt,
      $this->firstName,
      $this->lastName,
      $this->phone,
      $this->defaultLanguage,
      $this->isActive,
      $this->confirmationToken,
      $this->createdAt,
      $this->updatedAt
    ));
  }

  /** @see \Serializable::unserialize() */
  public function unserialize($serialized)
  {
    list (
        $this->id,
        $this->username,
        $this->email,
        $this->password,
        $this->salt,
        $this->firstName,
        $this->lastName,
        $this->phone,
        $this->defaultLanguage,
        $this->isActive,
        $this->confirmationToken,
        $this->createdAt,
        $this->updatedAt
      ) = unserialize($serialized);
  }

  public function eraseCredentials() {
    $this->password = null;
  }

  public function __toString() {
    return $this->username;
  }

  public function isAccountNonExpired() {
    return true;
  }

  public function isAccountNonLocked() {
    return true;
  }

  public function isCredentialsNonExpired() {
    return true;
  }

  public function isEnabled() {
    return $this->isActive;
  }

}

And this is how I update the defaultLanguage field:

$em = $this->getDoctrine()->getEntityManager();
$user= $em->getRepository('NboisUserBundle:User')->find(2);
$user->setDefaultLanguage('en');
$em->persist($user);
$em->flush();

The problem is when I execute this code and look in the database for the changes in notice the password field is empty. I think this happens because the password is not stored in the user object for some security measures.

This is the symfony profiler log:

UPDATE system_user SET password = ?, default_language = ? WHERE id = ?
Parameters: [null, nb, 2]  
  • 写回答

1条回答 默认 最新

  • dpd3982 2016-01-15 18:45
    关注

    The problem was that the password is set to null by a method in the user entity:

    public function eraseCredentials() {
        $this->password = null;
      }
    

    I found the answer here: symfony2 : user password set to empty after running this method

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探