Search code examples
phpsymfonytwiguser-roles

Can't check if a role is granted


I've to set dynamic role to an user when he logs in, so I've created a service LoginSuccessHanlder with this function on login success :

public function onAuthenticationSuccess(Request $request, TokenInterface $token) {
    $response = null;

    $user = $this->token->getToken()->getUser();
    $poste = $request->get('_poste');
    $user->addRole('ROLE_'.strtoupper($poste));
    $this->em->persist($user);
    $this->em->flush();
    if ($this->authorizationChecker->isGranted('ROLE_USER')) {
        $response = new RedirectResponse($this->router->generate('homepage'));
        $response->headers->setCookie(new Cookie('poste', $poste));
    }

    return $response;
}

So here, I add a new role to the user thanks to a field in the login form _poste . Once I'm logged in I should be able to do :

{% if is_granted("ROLE_FLEX") %}
    message
{% endif %}

But there is no message

But if I do this :

{{ dump(app.user.roles) }}

I have in the array the role ROLE_FLEX, why I can't check the role with is_granted function ? What did I missed ?

For information, I'm using FOSUserBundle

EDIT

I remove the role each time that the user logout so when a user logout he doesn't have the ROLE_FLEX anymore but the role will be added if he check this role on log in. Basically the user has a role for each session


Solution

  • The RoleVoter class that is used by the Symfony Security layer when you pass a role to the is_granted() function reads the roles from the token and not the user object. This means that you will have to update the token accordingly too.