Reputation: 27
I have been trying to assign dynamic roles to users in my application. I tried to use an event listener to do that, but it just added the dynamic role for that one http request.
This is the function in my custom event listener that adds the role.
public function onSecurityInteractiveLogin(InteractiveLoginEvent $event) {
$user = $this->security->getToken()->getUser();
$role = new Role;
$role->setId('ROLE_NEW');
$user->addRole($role);
}
But I am not sure if this is even possible to do with event listeners. I just need to find a nice way how to add the roles for the whole time the user is logged. I would appreciate any help and suggestions.
Upvotes: 0
Views: 2755
Reputation: 3622
I haven't tested this yet, but reading the cookbook this could work.
This example is a modified version of the example in the cookbook to accomodate for your requirements.
class DynamicRoleRequestListener
{
public function __construct($session, $security)
{
$this->session = $session;
$this->security = $security;
}
public function onKernelRequest(GetResponseEvent $event)
{
if (HttpKernel::MASTER_REQUEST != $event->getRequestType()) {
// don't do anything if it's not the master request
return;
}
if ($this->session->has('_is_dynamic_role_auth') && $this->session->get('_is_dynamic_role_auth') === true) {
$role = new Role("ROLE_NEW"); //I'm assuming this implements RoleInterface
$this->security->getRoles()[] = $role; //You might have to add credentials, too.
$this->security->getUser()->addRole($role);
}
// ...
}
private $session;
private $security;
}
And then you declare it as a service.
services:
kernel.listener.dynamicrolerequest:
class: Your\DemoBundle\EventListener\DynamicRoleRequestListener
arguments: [@session, @security.context]
tags:
- { name: kernel.event_listener, event: kernel.request, method: onKernelRequest }
A similar question is here: how to add user roles dynamically upon login with symfony2 (and fosUserBundle)?
Upvotes: 1