2014-01-22 40 views
0

我沒有使用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?分隔「編輯」中的密碼字段,以便字段不會被覆蓋?

+0

我會用密碼另一個屬性(FOSUserBundle使用'plainPassword'),然後,在prePersist /更新前的聽衆,如果plainPassword不爲空做的編碼和更新的實際密碼字段。 – qooplmao

回答

1

嘗試使用repeated Field Type設置密碼。如果您以用戶編輯的形式錯過了它們,則該原則不會在數據庫中更新它們,並且不會被覆蓋。

  • 而且也不要使用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')); 
    } 
    
+0

你好,雖然編輯時不顯示密碼,如果我修改任何其他領域的空白密碼存儲。 – Splendonia

+0

還使用preUpdate進行密碼編碼。你使用什麼版本的Symfony? –

+0

檢查更新我的回答,請 –