How do I check if a user has one role exactly in symfony2?

8.9k views Asked by At

Suppose in my system there are four user roles-

1. ROLE_SUPER_ADMIN
2. ROLE_ADMIN
3. ROLE_EDITOR
4. ROLE_AUTHOR

Now think, a user has role ROLE_AUTHOR. He can access a specific document but none other user can access it. So I want permit only user who has ROLE_AUTHOR. I got some solution when searching which has like is_granted('ROLE_AUTHOR') but this return a hierarchical result. Because in my config file I set hierarchy. So how can I give permission only ROLE_AUTHOR user.

3

There are 3 answers

0
xdazz On BEST ANSWER

You could check the user has the role exactly.

In twig:

{% if 'ROLE_AUTHOR' in app.user.roles %}
...
{% endif %}

In controller:

if (in_array('ROLE_AUTHOR', $this->getUser()->getRoles(), true)) {
    //...
}
0
Jordan S On

Note the accepted answer here doesn't take into account role hierarchy. It only checks for specific roles that are assigned, not roles which might be inherited by configuration.

The following is the best code to use (for controllers).

if($this->isGranted('ROLE_ADMIN'))
{
    // your code
}

Source: https://symfony.com/doc/current/security.html#roles

0
Tom Tom On

Well you are probably storing the user role in your user entity so you should just have to call the getter for the your roles field (ie: getRoles()) and check that.