Search code examples
phpsymfonyroles

How can I check if a non-logged in user has a role?


I have a situation where I need to check the roles for a user who isn't logged in.

I was originally simply querying the users table's roles field to see if the role in question was contained, but this does not take into account role heirarchy. For example, if a user has been granted ROLE_ADMIN they would also have ROLE_USER. However, you won't see ROLE_USER in the database, since in this case it's included in ROLE_ADMIN.

I'm a bit unfamiliar with the inner workings of Symfony2's security mechanism - I'd like to possibly "mock" a token for a user (based on their username) but I'm not sure how to, or if it's even possible. I've been digging around the Security component, but haven't found a solution yet.

Is it possible to check the roles of a user that is not logged in?


Solution

  • To get the list of roles users have, have a look at this code

    use Symfony\Component\Security\Core\Role\Role;
    use Symfony\Component\Security\Core\Role\RoleHierarchy;
    
    //....
    $roleHierarchy = new RoleHierarchy($this->container->getParameter('security.role_hierarchy.roles'));
    $userRoles = array(new Role('ROLE_ADMIN')); // Or $securityContext->getToken()->getRoles()
    $reachableRoles = $roleHierarchy->getReachableRoles($userRoles);
    

    Notice: Those methods are deprecated since Symfony 4.3