Session timeout for logged in user

Submitted by ivahidmontazer - 2 years ago

Session time out for logged in user (middleware way) for prevent dashboard or ... access after specify time. if we use this middleware in route groups, it will be run on every request under route group. with this code we do not need to change php.ini file or laravel session config file and default settings are appropriate. Do not forget to register middleware in app\Http\Kernel : 'timeout' => 'App\Http\Middleware\SessionTimeout', Other notices: 1- we can use middleware paramaters in laravel 5.1 for custom conditions. 2- we must redirect user back (after session timeout and log out ), to prevent user navigate to come back. 3- we must show a message to user (after session timeout and log out), that you logged out after [20] minutes that you were not active. Our Persian web app for time management is: https://timenix.com If you have a better idea please comment it. ♥

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Session\Store;

class SessionTimeout {

    protected $session;
    protected $timeout = 1200;

    public function __construct(Store $session){
        $this->session = $session;
    }
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $isLoggedIn = $request->path() != 'dashboard/logout';
        if(! session('lastActivityTime'))
            $this->session->put('lastActivityTime', time());
        elseif(time() - $this->session->get('lastActivityTime') > $this->timeout){
            $this->session->forget('lastActivityTime');
            $cookie = cookie('intend', $isLoggedIn ? url()->current() : 'dashboard');
            $email = $request->user()->email;
            auth()->logout();
            return message('You had not activity in '.$this->timeout/60 .' minutes ago.', 'warning', 'login')->withInput(compact('email'))->withCookie($cookie);
        }
        $isLoggedIn ? $this->session->put('lastActivityTime', time()) : $this->session->forget('lastActivityTime');
        return $next($request);
    }

}

Ads cover the costs of maintaining Laravel-tricks

comments powered by Disqus

Ads cover the costs of maintaining Laravel-tricks