Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

symfony

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.

like image 933
Md Mehedi Hasan Avatar asked Sep 03 '25 01:09

Md Mehedi Hasan


2 Answers

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)) {
    //...
}
like image 77
xdazz Avatar answered Sep 06 '25 12:09

xdazz


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

like image 25
Jordan S Avatar answered Sep 06 '25 11:09

Jordan S