I'm very new to Laravel framework. I am working on an app that automatically logs out the user if there is no activity for 5 minutes. I found some code on this website: https://github.com/unicodeveloper/laravel-sessiontimeout/blob/master/src/Middleware/SessionTimeout.php, but it doesn't seem to be working for me.
Here is the middleware code:
Here is the middleware code:
<?php
namespace App\Http\Middleware;
use Closure;
use Auth;
use Illuminate\Session\Store;
class SessionTimeOutMiddleware
{
/**
* Instance of Session Store
* @var session
*/
protected $session;
/**
* Time for user to remain active, set to 300 secs( 5 minutes )
* @var timeout
*/
protected $timeout = 300;
public function __construct(Store $session){
$this->session = $session;
$this->redirectUrl = 'auth/login';
$this->sessionLabel = 'warning';
}
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
if(! $this->session->has('lastActivityTime'))
{
$this->session->put('lastActivityTime', time());
}
else if( time() - $this->session->get('lastActivityTime') > $this->getTimeOut())
{
$this->session->forget('lastActivityTime');
Auth::logout();
return redirect($this->getRedirectUrl())->with([ $this->getSessionLabel() => 'You have been inactive for '. $this->timeout/60 .' minutes ago.']);
}
$this->session->put('lastActivityTime',time());
return $next($request);
}
/**
* Get timeout from laravel default's session lifetime, if it's not set/empty, set timeout to 15 minutes
* @return int
*/
private function getTimeOut()
{
return ($this->lifetime) ?: $this->timeout;
}
/**
* Get redirect url from env file
* @return string
*/
private function getRedirectUrl()
{
return (env('SESSION_TIMEOUT_REDIRECTURL')) ?: $this->redirectUrl;
}
/**
* Get Session label from env file
* @return string
*/
private function getSessionLabel()
{
return (env('SESSION_LABEL')) ?: $this->sessionLabel;
}
这是config/session.php
文件。
'lifetime' => env('SESSION_LIFETIME', 5),
'expire_on_close' => true,
并且在Kernel.php
中
protected $middleware = [
\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
\App\Http\Middleware\TrimStrings::class,
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
\App\Http\Middleware\TrustProxies::class,
\App\Http\Middleware\SessionTimeOutMiddleware::class,
];
我是否漏掉了什么? 我已经做了很多研究,似乎找不到这个问题的答案。如果有人能帮助我解决这个问题,我将非常感激。