Symfony 2.5 - 一段时间不活动后自动重定向

时间:2017-03-02 10:15:36

标签: redirect refresh php-5.6 symfony-2.5 event-listener

我有一个集成了FOSUserBundle的Symfony 2.5项目。我希望任何登录用户在应用程序上有X个空闲时间自动注销并重定向到登录页面。

到目前为止,我已经实施了一个解决方案,这与此处的建议非常相似How to log users off automatically after a period of inactivity?

<?php
namespace MyProject\UserBundle\EventListener;

use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\Security\Core\SecurityContextInterface;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpKernel\Event\FilterControllerEvent;


class UserInactivityListener
{

    protected $session;
    protected $securityContext;
    protected $router;
    protected $maxIdleTime;

    public function __construct(
        SessionInterface $session, 
        SecurityContextInterface $securityContext, 
        RouterInterface $router, 
        $maxIdleTime = 0)
    {
        $this->session = $session;
        $this->securityContext = $securityContext;
        $this->router = $router;
        $this->maxIdleTime = $maxIdleTime;
    }

    /**
     * user will be logged out after 30 minutes of inactivity
     * 
     * @param FilterControllerEvent $event
     * @return type
     */
    public function onKernelController(FilterControllerEvent $event)
    {
        if (HttpKernelInterface::MASTER_REQUEST != $event-  >getRequestType()) {
            return;
        }

        if ($this->maxIdleTime > 0) {
            try {
                $this->session->start();
                $lapse = time() - $this->session->getMetadataBag()->getLastUsed();
                $isFullyAuthenticated = $this->securityContext->isGranted('IS_AUTHENTICATED_FULLY');

                if (($lapse > $this->maxIdleTime) && $isFullyAuthenticated == true) {
                    $this->securityContext->setToken(null);
                    $url = $this->router->generate('fos_user_security_login');

                    $event->setController(function() use ($url) {
                        return new RedirectResponse($url);

                    });
                }
            } catch (\Exception $ex) {
                return;
            }
        }
    }
}

问题是此事件将被触发,只有当用户在空闲时间后尝试在应用程序中加载任何内容时才会发生重定向。我想要的是让应用程序自动重定向到注册页面,而无需用户进行任何交互。

我遇到这个建议使用刷新元标记How to auto redirect a user in Symfony after a session time out?,但是想知道是否还有另一种更好的方法来不时地触发刷新事件?

1 个答案:

答案 0 :(得分:1)

如果定期页面重新加载不会让您的用户烦恼,那么元刷新就可以了。它可能是最可靠的。您还可以实现JavaScript / jQuery代码段,以便重复ping服务器:

setTimeout(checkIdleTime, 2000);

在这种情况下,每2000毫秒或每两秒。

function checkIdleTime() {
    $.get('/idle', function()) {
        // If HTTP_OK response, do nothing, otherwise handle error
    }
}

/idle网址映射到检查&#34;空闲&#34;的操作。当然,行动必须忽略对自己的要求。如果没有空闲则返回成功,否则强制注销用户并返回某种错误。处理jQuery响应中的错误;可能只需要一个简单的重定向:window.location.href = '/login';

查看FOSJsRoutingBundle以优雅地使用来自jQuery的Symfony路由,这样您就不必对URL进行硬编码。

相关问题