Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Twig/Symfony2 : multiples roles with is_granted

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

If I use in a 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've tried to logging in and out, emptying symfony's cache.
I also tried to switch the order of roles in the array returned by the method getRoles() of my User : the function is_granted will only take into account the first role of the array

like image 736
Laurent W. Avatar asked Jun 12 '13 13:06

Laurent W.


1 Answers

If you are expecting Symfony2 to handle your roles, then your roles need to start with "ROLE_".

Change

'VIEW_GEOLOC_DATA' 

to

'ROLE_VIEW_GEOLOC_DATA'

Of course, you'll need to change this in your config and add the new role.

This answer does not apply, if you are using a dedicated Role class.

like image 184
JonnyS Avatar answered Oct 11 '22 18:10

JonnyS