1

I am using FOSUserBundle for handling my users. For them I have 2 roles ROLE_CUSTOMER and ROLE_MANUFACTURER. The problem is that I need to be able switch these roles when I am logged in. Is it possible? I have read this documentation:

http://symfony.com/doc/current/cookbook/security/impersonating_user.html

There is said how I can switch user to other user without relog, but nothing about role switching.

Maybe someone has any code examples or something? I have read too lot documentations which are hard to understand.

RydelHouse
  • 362
  • 1
  • 4
  • 23
  • Looking at the FOSUserBundle User class ([link](https://github.com/FriendsOfSymfony/FOSUserBundle/blob/master/Model/User.php)): It has addRole() and removeRole() - what exactly is stopping you? – ccKep Aug 06 '14 at 20:34
  • I know how to add roles during user registration, but how to switch them? – RydelHouse Aug 06 '14 at 20:38
  • You can call `$user->removeRole('ROLE_FOO'); $user->addRole('ROLE_BAR');` anywhere (eg. your controller(s)) as long as you have the user object (which you can get from the fos usermanager) and vice versa. Although I don't think roles are meant for temporary switching. – ccKep Aug 06 '14 at 20:40
  • Ok, I will try removing and adding roles - not bad idea. What solution you could suggest for switching users? I need to switch them because each group has different functionality... – RydelHouse Aug 06 '14 at 20:45
  • 1
    If you allow the user(s) to switch between those roles at will you could aswell just give them both roles at the same time? It would probably help if you told us a bit about your project / intentions in more detail so we can help you with specific tips. – ccKep Aug 06 '14 at 20:46
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/58832/discussion-between-cckep-and-rydelhouse). – ccKep Aug 06 '14 at 20:48
  • "For them I have 2 roles ROLE_CUSTOMER and ROLE_CUSTOMER." `ROLE_CUSTOMER === ROLE_CUSTOMER` – qooplmao Aug 07 '14 at 08:43
  • @Qoop just corrected, thank you! – RydelHouse Aug 07 '14 at 09:06

1 Answers1

4

Look at my answer here - Symfony 2.3: How do I refresh the authenticated user from the database?

The key is you need to reset a token after you switched roles.

Something like this:

$loggedInUser = $this->get('security.context')->getToken()->getUser();
$loggedInUser->removeRole('ROLE_ABC');
$loggedInUser->addRole('ROLE_XYZ');

$token = new \Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken(
  $loggedInUser,
  null,
  'main',
  $loggedInUser->getRoles()
);

$this->container->get('security.context')->setToken($token);
Community
  • 1
  • 1
dmnptr
  • 4,258
  • 1
  • 20
  • 19