2

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?

hakre
  • 193,403
  • 52
  • 435
  • 836
Steven Mercatante
  • 24,757
  • 9
  • 65
  • 109
  • I don't have a solution for you but try looking at `RoleHierarchyVoter` which is what the security system uses to resolve current roles. Last time I looked at it this class actually reads the security config for its own purposes and there wasn't a central location that you could query role hierarchy from. – Kasheen Mar 02 '12 at 21:06

1 Answers1

5

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

Serhii Smirnov
  • 1,338
  • 1
  • 16
  • 24
Mun Mun Das
  • 14,992
  • 2
  • 44
  • 43
  • Is this code written in a controller or can I use it directly on my `User` class?? I ask for the container, which is not always accessible... I don't understand the container object yet. – Throoze Apr 21 '12 at 04:49
  • Yes it is applicable for controller or any `ContainerAware` object. You can create a method in `User` class and pass the roles and parameter to use it. But I think `User` class is not right place for it. It would be better to create a service and place the method there. You can check [this](http://stackoverflow.com/questions/6124444/how-can-i-access-a-service-outside-of-a-controller-with-symfony2) question. – Mun Mun Das Apr 21 '12 at 05:13