【发布时间】:2017-03-02 10:15:36
【问题描述】:
我有一个集成了 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? 的建议,但想知道是否有另一种更好的方法来不时触发刷新事件?
【问题讨论】:
标签: redirect refresh php-5.6 symfony-2.5 event-listener