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.
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)) {
//...
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With