symfony2 : user password set to empty after running this method

前端 未结 3 1602
闹比i
闹比i 2020-12-21 22:09

this methodi use it to add a new job but when i add a job the password of the that current user get its password set to empty cus the user object that i retrieve has no pass

相关标签:
3条回答
  • 2020-12-21 22:52

    It does seem strange, but you could always retrieve User object prior to binding it to a newly created job:

    $token = $this->get('security.context')->getToken();
    $user_repo = $this->getDoctrine()->getRepository('**NAMESPACE**:User');
    $user = $user_repo->find($token->getUser()->getId());
    
    $job->setAnnouncer($user);
    $em = $this->getDoctrine()->getEntityManager();
    $em->persist($job) ;
    $em->flush();
    

    Also, I'm not really sure but I read somewhere that token isn't supposed to carry password due to it's security nature.... maybe that is your problem...

    0 讨论(0)
  • 2020-12-21 23:01

    well i found the issue it was caused by that eraseCredential method of the UserInterface in my User entity

    <?php 
    public function eraseCredential(){    
     $this->password = null ;
    }
    

    i just had to empty it as it was doin to my password by commenting that line ; ]

    0 讨论(0)
  • 2020-12-21 23:10

    2 kosaidpo

    Your solution works because eraseCredentials() method is used to clear user sensitive data (means NOT secret, but the one that can be restored, the sense is like __sleep()) when serializing user object or saving it to database (that is what manual says). So when you attach user to job object and call #flush(), doctrine will check for changes in all objects connected with job and find that user object has changed because eraseCredentials() has erased password. That is why your user gets updated.

    There is one more solution which could help you:

    The Solution:

    Change Tracking Policies from Doctrine documentation.

    In short, you can add @ChangeTrackingPolicy("DEFERRED_EXPLICIT") annotation (as I did, because I'm using annotations. Captain Obvious =) ) to UserInterface implementation (in my case I'm using User class) and this will tell Doctrine not to check all 'connected' to job objects.

    In this case doctrine will not check user object and save it with erased password, unless you will force it to do it with calling #persist(User object) manually.

    But anyway, you should not do $this->password = null in your eraseCredentials() method.

    0 讨论(0)
提交回复
热议问题