会话注销处理程序是错误的

时间:2015-07-09 21:38:56

标签: php symfony session-timeout symfony-2.3

我正在尝试实现会话注销功能,我似乎有一个错误的实现。对于初学者来说,超时不一致,并且似乎在不同时间注销用户。此外,当用户注销时,它不会将它们重定向到我指定的登录URL,而只是停留在屏幕上,用户知道他们退出的唯一方式是他们点击链接时。

请提前协助,并提前多多感谢您的建议:

<?php

namespace Main\UserBundle\Component\Session\Handler;

use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\Security\Core\SecurityContextInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\KernelEvents;

class SessionIdleHandler implements EventSubscriberInterface {

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

    public function onKernelRequest(GetResponseEvent $event) {
        if (HttpKernelInterface::MASTER_REQUEST != $event->getRequestType()) {

            return;
        }


        $request = $event->getRequest();
        if (!$request->hasSession()) {
            return;
        }

        $session = $this->session;
        $session->start(); //on every page request the session is restarted
        $session_data = $session->getMetadataBag();

        $lapse = time() - $session_data->getLastUsed();

        if ($lapse > $this->maxIdleTime) {

                $session->invalidate();
                $this->securityContext->setToken(null);
                $this->session->getFlashBag()->set('info', 'You have been logged out due to inactivity.');
                $event->setResponse(new RedirectResponse($this->router->generate('fos_user_security_login')));

        }
    }

    public static function getSubscribedEvents() {
        return array(
            KernelEvents::REQUEST => array('onKernelRequest', 127),
        );
    }

}

另请参阅我的services.yml

my.user.component.session.handler.session_idle:
        class: Main\UserBundle\Component\Session\Handler\SessionIdleHandler
        arguments: ["@session", "@security.context", "@router", %session_max_idle_time%]
        tags:
            - { name: kernel.event_listener, event: kernel.request, method: onKernelRequest }    

在我的parameters.yml

session_max_idle_time: 3600

0 个答案:

没有答案