Question

I'd like to set some Roles to the user after the loginSuccess happen according parameters that depends on user behaviour.

I had a look and it looks like the Roles are stored in the security.content.token which is accessible through the container:

$this->container->get('security.context')->getToken()

I can see that the roles are stored in this token (in my case a FacebookUserToken from FOSFacebookBundle)

The other requirement I have is that I cannot set the Roles and logout the user, it has to be in the same session.

Is that possible?

Was it helpful?

Solution

I've found this question: Get security token for non-logged user with Symfony

Which help me think that I could set a new Security token (instead to try to update the roles in the existing one). The roles of my users are not stored in the User table so it would make sense.

public function strangeAction()
{
    // Get your User, however you normally get it
    $user = $userRepository->find($id);

    // Save the original token in the session (just in case I need to reverse it)
    $originalToken = $this->get("security.context")->getToken();
    $this->getRequest()->getSession()->set('original.security.token', $originalToken);

    // Create my new custom token (loading the roles of the user)
    $token = new UsernamePasswordToken($user, null, "main", $user->getRolesMagically());

    // Update the security context with the new token
    $this->get("security.context")->setToken($token);

    // Now you have access to isGranted()
    if ($this->get("security.context")->isGranted("ROLE_SOMETHING"))
}

I feel confident about this solution but I'd like some more input if possible.

ie. Why should I not do it like this?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top