2024-01-09 09:43:07 +00:00
|
|
|
<?php
|
|
|
|
|
|
|
|
namespace App\Http\Middleware;
|
|
|
|
|
|
|
|
use Closure;
|
|
|
|
use Illuminate\Http\Request;
|
|
|
|
use Tymon\JWTAuth\Exceptions\JWTException;
|
|
|
|
|
|
|
|
class AuthenticateJWT
|
|
|
|
{
|
2024-02-23 10:54:12 +00:00
|
|
|
public const API_SERVER_SECRET_HEADER_NAME = 'x-api-secret';
|
2024-01-09 09:43:07 +00:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Verifies the JWT token and validates the IP and User Agent
|
|
|
|
* Invalidates token otherwise
|
|
|
|
*/
|
|
|
|
public function handle(Request $request, Closure $next)
|
|
|
|
{
|
|
|
|
// Parse JWT Payload
|
|
|
|
try {
|
|
|
|
$payload = \JWTAuth::parseToken()->getPayload();
|
|
|
|
} catch (JWTException $e) {
|
|
|
|
return $next($request);
|
|
|
|
}
|
|
|
|
|
|
|
|
// Validate IP and User Agent
|
|
|
|
if ($payload) {
|
2024-01-11 13:07:27 +00:00
|
|
|
if ($frontApiSecret = $request->header(self::API_SERVER_SECRET_HEADER_NAME)) {
|
|
|
|
// If it's a trusted SSR request, skip the rest
|
|
|
|
if ($frontApiSecret === config('app.front_api_secret')) {
|
|
|
|
return $next($request);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-01-09 09:43:07 +00:00
|
|
|
$error = null;
|
2024-02-23 10:54:12 +00:00
|
|
|
if (! \Hash::check($request->ip(), $payload->get('ip'))) {
|
2024-01-09 09:43:07 +00:00
|
|
|
$error = 'Origin IP is invalid';
|
|
|
|
}
|
|
|
|
|
2024-02-23 10:54:12 +00:00
|
|
|
if (! \Hash::check($request->userAgent(), $payload->get('ua'))) {
|
2024-01-09 09:43:07 +00:00
|
|
|
$error = 'Origin User Agent is invalid';
|
|
|
|
}
|
|
|
|
|
|
|
|
if ($error) {
|
|
|
|
auth()->invalidate();
|
2024-02-23 10:54:12 +00:00
|
|
|
|
2024-01-09 09:43:07 +00:00
|
|
|
return response()->json([
|
2024-02-23 10:54:12 +00:00
|
|
|
'message' => $error,
|
2024-01-09 09:43:07 +00:00
|
|
|
], 403);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return $next($request);
|
|
|
|
}
|
|
|
|
}
|