Md Mehedi Hasan
Md Mehedi Hasan

Reputation: 1792

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

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

Answers (3)

Jordan S
Jordan S

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

xdazz
xdazz

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

Tom Tom
Tom Tom

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

Related Questions