user825904 user825904 - 1 year ago 78
PHP Question

How to redirect to different url based on roles in symfony 2

I have one login page on site.
I have 4 different tye of users and i want that when they login they go to different page based on their role assigned.

Is there any way

Answer Source

One way to solve this is to use an event listener on the security.interactive_login event. In this case I simply attach another listener in that event listener so it will fire on the response. This lets the authentication still happen but still perform a redirect once complete.

<service id="sotb_core.listener.login" class="SOTB\CoreBundle\EventListener\SecurityListener" scope="request">
    <tag name="kernel.event_listener" event="security.interactive_login" method="onSecurityInteractiveLogin"/>
    <argument type="service" id="router"/>
    <argument type="service" id="security.context"/>
    <argument type="service" id="event_dispatcher"/>

And the class...

class SecurityListener
    protected $router;
    protected $security;
    protected $dispatcher;

    public function __construct(Router $router, SecurityContext $security, EventDispatcher $dispatcher)
        $this->router = $router;
        $this->security = $security;
        $this->dispatcher = $dispatcher;

    public function onSecurityInteractiveLogin(InteractiveLoginEvent $event)
        $this->dispatcher->addListener(KernelEvents::RESPONSE, array($this, 'onKernelResponse'));

    public function onKernelResponse(FilterResponseEvent $event)
        if ($this->security->isGranted('ROLE_TEAM')) {
            $response = new RedirectResponse($this->router->generate('team_homepage'));
        } elseif ($this->security->isGranted('ROLE_VENDOR')) {
            $response = new RedirectResponse($this->router->generate('vendor_homepage'));
        } else {
            $response = new RedirectResponse($this->router->generate('homepage'));