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

361

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 ?

598

Answer

Solution:

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

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

People are also looking for solutions to the problem: php - How to access service container in symfony2 global helper function (service)?

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.