How to prevent CakePHP 3.0 from extending session timeout with ajax requests?

僤鯓⒐⒋嵵緔 提交于 2020-02-08 02:28:09

问题


How can I prevent CakePHP 3.x from extending my users session when background ajax calls are made to the server? I am using jquery's $.ajax() as well.

I have a setInterval running once a minute to get some user notifications. My application is an EHR and I need to maintain strict session timeout. My get notifications Javascript basically just made my sessions unlimited because the ajax calls are extending the sessions.

I thought a saw something in the CakePHP book about this a few weeks ago but I can't seem to find it today.

Thanks, Daren


回答1:


Generally this is something that you need to handle on your own, ie implement your own timeout mechanism. How to handle it, depends.

You want to exclude AJAX background activity only, so you need to have access to the request object, and you most probably want to handle this as early as possible. Given this prerequisites, I'd probably use a dispatcher filter, where you can extend the timeout depending on whether or not the current request is an AJAX request, and destroy the session before any controllers are involved.

Here's a very basic, pretty much self-explantory example, which assumes that the timeout option value is set for the session configuration.

src/Routing/Filter/SessionTimeoutFilter.php

namespace App\Routing\Filter;

use Cake\Core\Configure;
use Cake\Event\Event;
use Cake\Routing\DispatcherFilter;

class SessionTimeoutFilter extends DispatcherFilter
{
    public function beforeDispatch(Event $event)
    {
        /* @var $request \Cake\Network\Request */
        $request = $event->data['request'];

        $session = $request->session();
        $lastAccess = $session->read('SessionTimeoutFilter.lastAccess');

        if (
            $lastAccess !== null &&
            time() - $lastAccess > Configure::read('Session.timeout') * 60
        ) {
            $request->session()->destroy();
        }

        if (!$request->is('ajax')) {
            $session->write('SessionTimeoutFilter.lastAccess', time());
        }
    }
}

src/config/bootstrap.php

DispatcherFactory::add('SessionTimeout');

Depending on your specific needs, you can of course place similar code pretty much anywhere in your application where you have access to the request object.



来源:https://stackoverflow.com/questions/32298817/how-to-prevent-cakephp-3-0-from-extending-session-timeout-with-ajax-requests

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!