platform icon indicating copy to clipboard operation
platform copied to clipboard

Session expired

Open kaizirlewagen opened this issue 3 years ago • 0 comments

I move the sessions to the database, with to following ENV settings:

SESSION_DRIVER=database
SESSION_LIFETIME=5
SESSION_CONNECTION=mysql

The sessions are stored in my database. Everything is ok, but after 5 Minutes i expect the session has expired. So nothing happens.

I add the following middleware the monitor the session and to logout the user with a message.

<?php

namespace App\Http\Middleware;

use Closure;
use Auth;
use Session;
use Illuminate\Http\Request;
use Illuminate\Session\Store;
use Illuminate\Support\Facades\Log;

class SessionExpired
{
    protected $session;
    protected $timeout = 60; // in seconds, default 1200

    public function __construct(Store $session)
    {
        $this->session = $session;
        //$this->timeout = config('session.lifetime') * 60; / in seconds
    }	
    
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)  $next
     * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
     */
    public function handle(Request $request, Closure $next)
    {
        $isLoggedIn = $request->path() != 'login';
 
        if (! session('lastActivityTime')) {
            $this->session->put('lastActivityTime', time());
            
            //
            Log::debug('set lastActivityTime');
        }
        elseif ((time() - $this->session->get('lastActivityTime')) > $this->timeout) {       	
            //
            Log::debug('expired');
            
            $this->session->forget('lastActivityTime');
            
            $cookie = cookie('intend', $isLoggedIn ? url()->current() : 'login');
            
            auth()->logout();
                        
            //return redirect('login')->with('error','Your session has expired.');
        }
        
        //$isLoggedIn ? $this->session->put('lastActivityTime', time()) : $this->session->forget('lastActivityTime');
        
        return $next($request);
    }
}

I add the new class to the kernel with \App\Http\Middleware\SessionExpired::class,.

If the user performs some actions after the session has expired, he well be redirected to the login screen.

I try to auto redirect the user when the session has expired, but return redirect('login') does not work. And i want to show a message to the user at login screen that the session has expired.

Has some one any ideas for me?

Server (please complete the following information):

  • Platfrom Version: 12.4.4
  • Laravel Version: 9.13.0
  • PHP Version: 8.0.16
  • Database: 10.5.15

kaizirlewagen avatar May 20 '22 08:05 kaizirlewagen