Symfony 2 FOS UserBundle users doesn't get group's role

允我心安 提交于 2019-12-21 05:39:12

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!