Reputation: 1792
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.
Upvotes: 4
Views: 10568
Reputation: 51
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
Upvotes: 2
Reputation: 160963
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)) {
//...
}
Upvotes: 15
Reputation: 3698
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.
Upvotes: 0