symfony 3.4 根据用户的状态在页面上重定向用户

symfony 3.4 redirect a user on a page depending on his status

目标:根据状态重定向用户,当用户登录时在整个网站上。

我需要强制用户在一个页面上,直到他更改了个人资料 所以我尝试使用事件内核进行重定向,但我遇到了无限循环。但是我试图避免在页面需要时进行这种重定向

所以请找到我尝试做的事情

class TokenSubscriber implements EventSubscriberInterface {

    private $user;
    private $tokenStorage;
    private $router;
    protected $redirect;

    public function __construct(TokenStorageInterface $tokenStorage, RouterInterface $router
    ) {
        $this->tokenStorage = $tokenStorage;
        $this->router = $router;
    }

    public function onKernelController(FilterControllerEvent $event) {
        $controller = $event->getController();


        if (!is_array($controller)) {
            return;
        }

        $this->user = $this->tokenStorage->getToken()->getUser();


        if ($this->user->getValider() == 3 && $controller[1] == 'indexUserAction' && $controller[0] instanceof DefaultUserController) {
            $this->redirect = null;
        } else {
            $this->redirect = 'user_index';
        }
    }

    public function onKernelResponse(FilterResponseEvent $event) {
        if (null !== $this->redirect) {
            $url = $this->router->generate($this->redirect);
            $event->setResponse(new RedirectResponse($url));
        }
    }

    public static function getSubscribedEvents() {
        return array(
            KernelEvents::CONTROLLER => 'onKernelController',
            KernelEvents::RESPONSE => 'onKernelResponse',
        );
    }

}

您可以试试这个,但是使用 ->get('_route') 通常应该只用于调试。您应该转储事件和响应以了解您还可以使用什么。

public function onKernelRequest(GetResponseEvent $event)
    if($event->getRequest()->get('_route') != 'user_index'){
        $event->setResponse(new Response('[NOT_ALLOWED]'));
    }
}

这应该可以解决您的问题

public function onKernelController(FilterControllerEvent $event) {
    $controller = $event->getController();

    if (!is_array($controller)) {
        return;
    }

    $this->user = $this->tokenStorage->getToken()->getUser();

    if ($this->user->getValider() == 3 && $controller[1] == 'indexUserAction' && $controller[0] instanceof DefaultUserController) {
        $this->redirect = null;
    } else {
        $this->redirect = 'user_index';
    }

    // Add this to Empty redirect if on already same page
    if($event->getRequest()->get('_route') == 'user_index'){
        $this->redirect = null;
    }
}

现在重定向有效,但是当页面加载时,我的所有 css 和 javascript 都不是加载程序,因为我认为是重定向。 我只在内核响应中工作。

public function onKernelResponse(FilterResponseEvent $event){
    if ($event->getRequest()->get('_route') != null &&  $event->getRequest()->get('_route') != 'user_index') {

        $url = $this->router->generate('user_index');
        $event->setResponse(new RedirectResponse($url));

    }
}