Twig / Symfony2: multiple roles with is_granted

I want to know if the user has the role "VIEW_GEOLOC_DATA", but I have a problem using the twig is_granted() function.

If I use in the template:

 Roles : {{ dump(app.user.getRoles()) }} is_granted('ROLE_SUPER_ADMIN') : {{ dump(is_granted('ROLE_SUPER_ADMIN')) }} is_granted('VIEW_GEOLOC_DATA') : {{ dump(is_granted('VIEW_GEOLOC_DATA')) }} 

This is what I get when rendering:

 array(2) { [0]=> string(16) "ROLE_SUPER_ADMIN" [1]=> string(16) "VIEW_GEOLOC_DATA" } is_granted('ROLE_SUPER_ADMIN') : bool(true) is_granted('VIEW_GEOLOC_DATA') : bool(false) 

I tried to log in and out, omitting the symfony cache.
I also tried to switch the order of the roles in the array returned by my user’s getRoles () method: the is_granted function only considers the first role of the array

+6
source share
3 answers

I ended up creating a new hasRole method in my User class:

 public function hasRole($role) { return in_array($role, $this->getRoles()); } 

Then in the template I use:

 {% if app.user.hasRole('ROLE_VIEW_GEOLOC_DATA') %} {# do something #} {% endif %} 

EDIT: As @JonnyS explained, it is possible that roles should start with ROLE_ to work with the is_granted Symfony function. Not tested.

+8
source

If you expect Symfony2 to handle your roles, your roles should begin with "ROLE _".

Change

 'VIEW_GEOLOC_DATA' 

to

 'ROLE_VIEW_GEOLOC_DATA' 

Of course, you need to change this in your configuration and add a new role.

This answer does not apply if you use a dedicated Role class.

+8
source

Create an advocate who checks this out. http://symfony.com/doc/current/cookbook/security/voters_data_permission.html

This is much cleaner than creating a method for an object to do this.

+1
source

Source: https://habr.com/ru/post/947113/


All Articles