2FAuth/app/Http/Middleware/LogoutInactiveUser.php

60 lines
1.6 KiB
PHP
Raw Normal View History

2020-10-08 15:38:36 +02:00
<?php
namespace App\Http\Middleware;
use Closure;
use App\User;
use Carbon\Carbon;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Auth;
class LogoutInactiveUser
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
// Not a logged in user
if (!Auth::guard('api')->check()) {
return $next($request);
}
$user = Auth::guard('api')->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
$settingService = resolve('App\Services\SettingServiceInterface');
$settings = $settingService->all();
2020-10-08 15:38:36 +02:00
2020-10-09 13:35:03 +02:00
$kickUserAfterXSecond = intval($settings['kickUserAfter']) * 60;
// 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();
2020-10-09 13:35:03 +02:00
$accessToken = $user->token();
// phpunit does not generate token during tests, so we revoke it only if it exists
// @codeCoverageIgnoreStart
if( $accessToken ) {
$accessToken->revoke();
}
// @codeCoverageIgnoreEnd
2020-10-08 15:38:36 +02:00
return response()->json(['message' => 'unauthorised'], Response::HTTP_UNAUTHORIZED);
}
return $next($request);
}
}