如果用户已登录,则重定向 [英] Redirect if the user is logged in

查看:32
本文介绍了如果用户已登录,则重定向的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Symfony 2 构建一个 Web 应用程序,使用 FOSUserBundle 包.
用户创建一个帐户,登录并开始使用该应用程序.

I am building a web application with Symfony 2, using the FOSUserBundle bundle.
Users create an account, login and start using the application.

我现在想要实现的是让用户从他们登录后可能所在的任何页面重定向到他们的帐户.
这包括:

What I want to achieve now is to have the user redirected to their account from any page they may be at if they are logged in.
This includes:

  • 如果他们返回登录页面
  • 如果他们回到注册页面
  • 如果他们访问网站的主页
  • 他们确认电子邮件后
  • 一旦他们重置密码

基本上代码是这样的:

$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 中,我会使用过滤器.

The problem is I don't know where that code should go.
It should be executed for any request. In Symfony 1 I would have used a filter.

推荐答案

我自己找到了解决方案:

I found the solution myself:

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

然后,在我的包的 services.yml 文件中:

And then, in the services.yml file of my bundle:

services:
    kernel.listener.logged_in_user_listener:
            class: Danyuki\UserBundle\Listener\LoggedInUserListener
            tags:
                - { name: kernel.event_listener, event: kernel.request, method: onKernelRequest }
            arguments: [ @router, @service_container ]  

这篇关于如果用户已登录,则重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆