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

时间:2018-10-16 20:09:08

标签: symfony redirect events controller kernel

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

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

所以请找到我想做的事情

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

}

3 个答案:

答案 0 :(得分:0)

您可以尝试执行此操作,但是使用-> get('_ route')通常仅应用于调试。您应该转储事件和响应,以了解还可以使用什么。

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

答案 1 :(得分: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;
    }
}

答案 2 :(得分:0)

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

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));

    }
}