SteveM
SteveM

Reputation: 53

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

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 ?

Upvotes: 3

Views: 3562

Answers (1)

DarkLeafyGreen
DarkLeafyGreen

Reputation: 70406

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')

Upvotes: 1

Related Questions