1

I tried so far,

Path CoreBundle / DependencyInjection / configuration.php

namespace Funstaff\CoreBundle\DependencyInjection;

use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;

class Configuration implements ConfigurationInterface
{
    /**
     * {@inheritDoc}
     */
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder();
        $rootNode = $treeBuilder->root('funstaff_core');

        $rootNode
            ->children()
                ->scalarNode('timeout')->defaultValue(900)
                ->isRequired()->end()
            ->end();

        return $treeBuilder;
    }
}

we will add this code in the file FunstaffCoreExtension.php

namespace Funstaff\CoreBundle\DependencyInjection;

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
use Symfony\Component\DependencyInjection\Loader;

class FunstaffCoreExtension extends Extension
{
    /**
     * {@inheritDoc}
     */
    public function load(array $configs, ContainerBuilder $container)
    {
        $configuration = new Configuration();
        $config = $this->processConfiguration($configuration, $configs);

        $loader = new Loader\XmlFileLoader($container,
                         new FileLocator(__DIR__.'/../Resources/config'));
        $loader->load('services.yml');

        $container->setParameter('core.timeout', $config['timeout']);
    }
}

In config.yml.

funstaff_core:
    timeout:    600 

I created my RequestListener.php file in the following path: FunstaffCoreBundle / Request / Listener.

namespace Funstaff\CoreBundle\Request\Listener;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\Security\Core\SecurityContext;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\HttpKernelInterface;

class RequestListener implements EventSubscriberInterface
{
    protected $session;

    protected $securityContext;

    protected $timeout;

    /**
     * Construct
     * 
     * @param Session $session
     */
    public function __construct(Session $session,
                                SecurityContext $securityContext,
                                $timeout)
    {
        $this->session = $session;
        $this->securityContext = $securityContext;
        $this->timeout = $timeout;
    }

    /**
     * Get Subscribed Events
     * 
     * @return array event list
     */
    public static function getSubscribedEvents()
    {
        return array(
            'kernel.request' => 'onKernelRequest',
        );
    }

    /**
     * On Kernel Request
     */
    public function onKernelRequest(GetResponseEvent $event)
    {

        if (HttpKernelInterface::MASTER_REQUEST !== $event->getRequestType()) {
            return;
        }

        $meta = $this->session->getMetadataBag();
        $lastused = $meta->getLastUsed();

        if (null !== $lastused && (time() - $lastused) > $this->timeout) {
            $this->securityContext->setToken(null);
            $this->session->invalidate();
        }
    }
}

& in Resources / config / services.yml

services:
    timeout.request.listener:
        class: Funstaff\CoreBundle\Request\Listener\RequestListener
        arguments: [ @session, @security.context, %funstaff.timeout% ]
        tags: 
            - { name: kernel.event_subscriber }    

But its not working session timeout. Anything left me? Please Anyone have idea then let me know.

Chiku
  • 107
  • 11
  • Why you haven't done this? http://stackoverflow.com/questions/5933774/symfony2-session-lifetime – pabgaran May 15 '15 at 13:27
  • I used symfony2.3 . It working by adding cookie_lifetime: 7200 gc_maxlifetime: 3600 but it logout after 2nd request. should logout on 1st request. – Chiku May 15 '15 at 14:04

1 Answers1

3

I found the solution.

Create folder Handler & in handler create file .php

<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
namespace my\DemoBundle\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;

/**
 * Description of SessionIdleHandler
 *
 */
class SessionIdleHandler {
    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;
        }

        if ($this->maxIdleTime > 0) {

            $this->session->start();
            $lapse = time() - $this->session->getMetadataBag()->getLastUsed();

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

                $this->securityContext->setToken(null);
                $this->session->getFlashBag()->set('info', 'You have been logged out due to inactivity.');

                //Redirect URL to logout               
                $event->setResponse(new RedirectResponse($this->router->generate('logout')));
            }
        }
    }
}

In service.yml file

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

Set parameter (in second) in parameter.yml

session_max_idle_time: 600

Its works perfectly.

Chiku
  • 107
  • 11