Check if a role is granted for a specific user in Symfony2 ACL

后端 未结 3 1426
忘了有多久
忘了有多久 2020-12-10 19:03

I want to check if a role is granted for a specific user in Symfony2 (not the logged user). I know that I can check it for the logged user by:

$securityCont         


        
3条回答
  •  死守一世寂寞
    2020-12-10 19:48

    Checking roles for another user can not be done via the SecurityContext as this will always hold the current user's session token. Your task can be achieved for example via the getRoles method, if the user you need to check implements the UserInterface.

    $otherUser = $this->get('doctrine')->...   // fetch the user
    
    if( $otherUser instanceof \Symfony\Component\Security\Core\User\UserInterface  )
    { 
         $roles = $otherUser->getRoles();
    
         // your role could be VIEW or ROLE_VIEW, check the $roles array above. 
         if ( in_array( 'VIEW' , $roles ) )
         {
          // do something else
         }
    }
    

    If your user entity implement the FosUserBundle UserInterFace, that has a dedicated method hasRole. In that case you could use a one-liner:

    $otherUser = $this->get('doctrine')->...   // fetch the user
    
    if( $otherUser instanceof \FOS\UserBundle\Model\UserInterface  )
    { 
         // your role could be VIEW or ROLE_VIEW, check the proper role names
         if ( $otherUser->hasRole( 'VIEW' ) )
         {
          // do something else
         }
    }
    

提交回复
热议问题