问题
I'm using FOS User Bundle to manage access to my app. As i need a group notion, i've implemented what i need as described in the doc group .
Everything's fine for creating users and groups BUT when i'm logging in with a user, and trying to get his role, he has none but USER_ROLE.
Here is my User
use FOS\UserBundle\Entity\User as BaseUser;
class RegistredUser extends BaseUser
{
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* @ORM\ManyToOne(targetEntity="myBundle\Entity\RegistredUserGroup")
*/
protected $group;
[...]
}
Here is my Group class
use FOS\UserBundle\Entity\Group as BaseGroup;
class RegistredUserGroup extends BaseGroup
{
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
[...]
}
My User has none roles setted in the RegistredUser table, but has a groupId setted. This group have the ROLE_ADMIN role.
In my layout, i try to check role like this :
{% if is_granted('ROLE_ADMIN') %}
<dl class="menuIcon">
<dd><img src="{{ asset('bundles/bundle/images/user.png') }}" alt=""></dd>
<dd>{{ "menu.gererReferentiel"|trans }}</dd>
</dl>
{% endif %}
But Symfony doesn't display anything.
Am i using a bad function for checking groupe roles ? Or am i doing something else wrong ?
A solution is getting groups_role by
{% if app.user != null and app.user.group.hasRole('ROLE_ADMIN') %}
But is there any other way for doing this ?
回答1:
FOSUserBundle allows you to associate groups to your users. Groups are a way to group a collection of roles. The roles of a group will be granted to all users belonging to it.
From Using Groups With FOSUserBundle
In your case you should not check
app.user.group.hasRole('ROLE_ADMIN')
if a user has a group which has the role admin, but check if the current user is member of a certain group, e.g.
app.user.hasGroup('ADMIN')
来源:https://stackoverflow.com/questions/12056583/symfony-2-fos-userbundle-users-doesnt-get-groups-role