Symfony 如果用户已登录,则重定向

Symfony 如果用户已登录,则重定向,symfony,Symfony,我正在使用Symfony 2构建一个web应用程序,使用FOSUserBundle捆绑包。 用户创建帐户,登录并开始使用应用程序 我现在想要实现的是,如果用户登录,他们可以从任何页面重定向到他们的帐户。 这包括: 如果他们回到登录页面 如果他们回到注册页面 如果他们进入网站的主页 一旦他们确认他们的电子邮件 一旦他们重置了密码 基本上,代码是这样的: $container = $this->container; $accountRouteName = "DanyukiWebappBun

我正在使用Symfony 2构建一个web应用程序,使用FOSUserBundle捆绑包。
用户创建帐户,登录并开始使用应用程序

我现在想要实现的是,如果用户登录,他们可以从任何页面重定向到他们的帐户。
这包括:

  • 如果他们回到登录页面
  • 如果他们回到注册页面
  • 如果他们进入网站的主页
  • 一旦他们确认他们的电子邮件
  • 一旦他们重置了密码
基本上,代码是这样的:

$container = $this->container;
$accountRouteName = "DanyukiWebappBundle_account";
if( $container->get('security.context')->isGranted('IS_AUTHENTICATED_FULLY') ){
    // authenticated (NON anonymous)
    $routeName = $container->get('request')->get('_route');
    if ($routeName != $accountRouteName) {
        return $this->redirect($this->generateUrl($accountRouteName));
    }
}
问题是我不知道代码应该放在哪里。

任何请求都应该执行它。在Symfony 1中,我会使用过滤器。

我自己找到了解决方案:

<?php

namespace Danyuki\UserBundle\Listener;

use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpFoundation\RedirectResponse;

class LoggedInUserListener
{
    private $router;
    private $container;

    public function __construct($router, $container)
    {
        $this->router = $router;
        $this->container = $container;
    }    

    public function onKernelRequest(GetResponseEvent $event)
    {
        $container = $this->container;
        $accountRouteName = "DanyukiWebappBundle_account";
        if( $container->get('security.context')->isGranted('IS_AUTHENTICATED_FULLY') ){
            // authenticated (NON anonymous)
            $routeName = $container->get('request')->get('_route');
            if ($routeName != $accountRouteName) {
                $url = $this->router->generate($accountRouteName);
                $event->setResponse(new RedirectResponse($url));
            }
        }
    }
}

如果只需检查一次,也可以执行此解决方案:

每次成功登录时都会触发一个事件。 事件名称为:

use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;

public function onLoginSuccess(InteractiveLoginEvent $event) {
   if ($this->_security->isGranted('IS_AUTHENTICATED_FULLY')) {
      //your code here...
   }
}
security.interactive\u登录

为了订阅此事件,您必须使用创建的类创建一个服务容器,比如说“LoginListener.php”,并使用事件“security.interactive\u login”注入标记“kernel.even\u listener”:

您还可以添加其他依赖项并将其注入构造函数,在我的例子中,我必须注入安全性、会话和容器:

public function __construct(SecurityContext $security, Session $session,            ContainerInterface $container) {

}

不建议在服务中注入容器,您可以注入security.context服务,甚至比这更简单。由于@dan需要请求对象,他可以通过
$event->getRequest()
从事件中检索它。见:,或
use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;

public function onLoginSuccess(InteractiveLoginEvent $event) {
   if ($this->_security->isGranted('IS_AUTHENTICATED_FULLY')) {
      //your code here...
   }
}
public function __construct(SecurityContext $security, Session $session,            ContainerInterface $container) {

}