0

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

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

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

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',
        );
    }

}
4

3 回答 3

1

现在重定向有效,但是当页面加载时,我所有的 css et 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));

    }
}
于 2018-10-17T15:49:47.327 回答
0

你可以试试这个,但使用 ->get('_route') 通常应该只用于调试。您应该转储事件和响应以找出您可以使用的其他内容。

public function onKernelRequest(GetResponseEvent $event)
    if($event->getRequest()->get('_route') != 'user_index'){
        $event->setResponse(new Response('[NOT_ALLOWED]'));
    }
}
于 2018-10-17T07:29:41.570 回答
0

这应该可以解决您的问题

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;
    }
}
于 2018-10-17T10:21:18.387 回答