2020-10-08 15:38:36 +02:00
|
|
|
<?php
|
|
|
|
|
|
|
|
namespace App\Http\Middleware;
|
|
|
|
|
2022-11-22 15:15:52 +01:00
|
|
|
use App\Facades\Settings;
|
2020-10-08 15:38:36 +02:00
|
|
|
use Carbon\Carbon;
|
2022-11-22 15:15:52 +01:00
|
|
|
use Closure;
|
2020-10-08 15:38:36 +02:00
|
|
|
use Illuminate\Http\Response;
|
|
|
|
use Illuminate\Support\Facades\Auth;
|
2021-10-15 23:46:21 +02:00
|
|
|
use Illuminate\Support\Facades\Log;
|
2020-10-08 15:38:36 +02:00
|
|
|
|
2021-11-17 23:37:16 +01:00
|
|
|
class KickOutInactiveUser
|
2020-10-08 15:38:36 +02:00
|
|
|
{
|
|
|
|
/**
|
|
|
|
* Handle an incoming request.
|
|
|
|
*
|
|
|
|
* @param \Illuminate\Http\Request $request
|
|
|
|
* @param \Closure $next
|
2022-11-22 15:15:52 +01:00
|
|
|
* @param string $guards
|
2020-10-08 15:38:36 +02:00
|
|
|
* @return mixed
|
|
|
|
*/
|
2022-09-07 17:54:27 +02:00
|
|
|
public function handle($request, Closure $next, ...$guards)
|
2020-10-08 15:38:36 +02:00
|
|
|
{
|
2022-03-24 14:58:30 +01:00
|
|
|
// We do not track activity of:
|
|
|
|
// - Guest
|
|
|
|
// - User authenticated against a bearer token
|
|
|
|
// - User authenticated via a reverse-proxy
|
|
|
|
if (Auth::guest() || $request->bearerToken() || config('auth.defaults.guard') === 'reverse-proxy-guard') {
|
2020-10-08 15:38:36 +02:00
|
|
|
return $next($request);
|
|
|
|
}
|
2022-11-22 15:15:52 +01:00
|
|
|
|
|
|
|
$user = Auth::user();
|
|
|
|
$now = Carbon::now();
|
2020-10-09 13:35:03 +02:00
|
|
|
$inactiveFor = $now->diffInSeconds(Carbon::parse($user->last_seen_at));
|
2020-10-08 15:38:36 +02:00
|
|
|
|
|
|
|
// Fetch all setting values
|
2022-07-30 17:51:02 +02:00
|
|
|
$kickUserAfterXSecond = intval(Settings::get('kickUserAfter')) * 60;
|
2020-10-09 13:35:03 +02:00
|
|
|
|
|
|
|
// If user has been inactive longer than the allowed inactivity period
|
|
|
|
if ($kickUserAfterXSecond > 0 && $inactiveFor > $kickUserAfterXSecond) {
|
2020-10-08 15:38:36 +02:00
|
|
|
$user->last_seen_at = $now->format('Y-m-d H:i:s');
|
|
|
|
$user->save();
|
2022-11-22 15:15:52 +01:00
|
|
|
|
2022-10-18 17:34:56 +02:00
|
|
|
Log::info('Inactive user detected, authentication rejected');
|
2022-05-10 00:59:07 +02:00
|
|
|
if (method_exists('Illuminate\Support\Facades\Auth', 'logout')) {
|
|
|
|
Auth::logout();
|
|
|
|
}
|
2022-11-22 15:15:52 +01:00
|
|
|
|
2022-05-14 13:45:12 +02:00
|
|
|
return response()->json(['message' => 'inactivity detected'], Response::HTTP_I_AM_A_TEAPOT);
|
2020-10-08 15:38:36 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
return $next($request);
|
|
|
|
}
|
2022-11-22 15:15:52 +01:00
|
|
|
}
|