2013-10-06 49 views
2

我想檢查用戶的角色是否已經改變。如何檢查用戶角色是否已更改?

看看這個例子:我是管理員,我想更改另一個管理員(ROLE_MEMBER_ADMINROLE_USER)的角色。但是成員的角色只有在他斷開連接並重新連接時纔會改變。

isEqualTo方法EquatableInterface是解決方案嗎?我怎樣才能實現它?

回答

0

我想你應該自己實施它。這聽起來有點像用戶日誌。

您可以創建一個新表,記錄所有與用戶標識相關的事件。然後你可以記錄每一個事件。

之後,您可以編寫一個函數,檢查是否有更改的用戶。

+0

我會設置一個監聽器來檢查角色是否已經改變......你有想法嗎? –

0

在用戶實體:

use Symfony\Component\Security\Core\User\EquatableInterface; 
use Symfony\Component\Security\Core\User\UserInterface; 

class User implements UserInterface, \Serializable, EquatableInterface { 

    /* took out getters/setters/ members declaration for clarity */ 

    /** 
    * @see \Serializable::serialize() 
    */ 
    public function serialize() { 
     return serialize(array(
      $this->id, 
      $this->username, 
      $this->email, 
      $this->password, 
      $this->isActive, 
      $this->roles 
     )); 
    } 

    /** 
    * @see \Serializable::unserialize() 
    */ 
    public function unserialize($serialized) { 
     list (
      $this->id, 
      $this->username, 
      $this->email, 
      $this->password, 
      $this->isActive, 
      $this->roles 
     ) = unserialize($serialized); 
    } 

    public function isEqualTo(UserInterface $user) { 
     if (!$user instanceof User) { 
      return false; 
     } 

     if ($this->password !== $user->getPassword()) { 
      return false; 
     } 

     if ($this->username !== $user->getUsername()) { 
      return false; 
     } 

     if ($this->email !== $user->getEmail()) { 
      return false; 
     } 

     if ($this->isActive !== $user->isEnabled()) { 
      return false; 
     } 

     // check roles 
     // http://www.metod.si/symfony2-reload-user-roles/ 
     if (md5(serialize($this->getRoles())) !== md5(serialize($user->getRoles()))) { 
      return false; 
     } 

     return true; 
    } 
} 

它應該這樣做,用PHP 27年5月3日進行測試,PHP 5.4.x版本與序列化的一些問題。

希望這會有所幫助。