Symfony route redirection based on roles

Viewed 857

I am trying to redirect the route based on the Role after registration / login. After the registration, I am redirecting the route to this secure_area, to route according to the user roles.

/**
 * @Route("/secure", name="secure_area")
 *
 * @throws \Exception
 */
public function indexAction()
{
    if ($this->isGranted('ROLE_USER1')) {
        return $this->redirectToRoute('user1');
    }

    if ($this->isGranted('ROLE_USER2')) {
        return $this->redirectToRoute('user2');
    }
    throw new \Exception(AccessDeniedException::class);
}

In both cases, I am landing to the route user1. How can I make it redirect the route according to the user roles?

security.yaml

role_hierarchy: 
    ROLE_ADMIN: ROLE_USER2 
    ROLE_USER2: ROLE_USER1 
    ROLE_USER1: ROLE_USER1 
access_control: 
    - { path: ^/admin, roles: ROLE_ADMIN } 
    - { path: ^/user2, roles: ROLE_USER2 } 
    - { path: ^/user1, roles: ROLE_USER1 }
1 Answers
<?php 

// Change the namespace according to the location of this class in your bundle
namespace AppBundle\Listeners;

use FOS\UserBundle\Model\UserManagerInterface;
use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
use Symfony\Component\Routing\Router;
use Symfony\Component\Security\Core\SecurityContext;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
use Symfony\Component\HttpFoundation\RedirectResponse;

class LoginListener
{
    protected $userManager;
    protected $router;
    protected $security;
    protected $dispatcher;

    public function __construct(UserManagerInterface $userManager, Router $router, SecurityContext $security, EventDispatcher $dispatcher)
    {
        $this->userManager = $userManager;
        $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)
    {
        // Important: redirect according to user Role
        if ($this->security->isGranted('ROLE_ADMIN')) {
            $event->setResponse(new RedirectResponse($this->router->generate("admin_homepage")));
        } elseif ($this->security->isGranted('ROLE_MANAGER')) {
            $event->setResponse(new RedirectResponse($this->router->generate("manager_homepage")));
        } else {
            $event->setResponse(new RedirectResponse($this->router->generate("default_homepage")));
        }  
    }
}

You can implement LoginListener like this that will handle your role based redirection.

Related