Symfony перенаправление маршрута на основе ролей - PullRequest
1 голос
/ 30 мая 2020

Я пытаюсь перенаправить маршрут в зависимости от роли после регистрации / входа в систему. После регистрации я перенаправляю маршрут в эту защищенную_зону для маршрутизации в соответствии с ролями пользователей.

   /**
     * @Route("/secure", name="secure_area")
     * @throws \Exception
     */

public function indexAction(){
    if ($this->isGranted('ROLE_USER1'))
        return $this->redirectToRoute('user1');
    elseif ($this->isGranted('ROLE_USER2'))
        return $this->redirectToRoute('user2');
    throw new \Exception(AccessDeniedException::class);

}

В обоих случаях я приземляюсь на маршрут user1. Как я могу сделать так, чтобы он перенаправлял маршрут в соответствии с ролями пользователей?

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 Ответ

4 голосов
/ 30 мая 2020
<?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")));
        }  
    }
}

Вы можете реализовать LoginListener таким образом, чтобы обрабатывать перенаправление на основе вашей роли.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...