ldc-crm/app/Http/Middleware/ApiCheckTimeStamps.php
Jérémy Munsch 00639792c4 - Fix Handler reponse coherence with api response
- Add ApiErrorException to the client
2021-08-04 15:07:25 +02:00

42 lines
1.2 KiB
PHP

<?php
namespace App\Http\Middleware;
use App\Enums\ApiError;
use App\Exceptions\Api\V2\ApiErrorException;
use App\Lib\Helper;
use Closure;
use Illuminate\Http\Request;
/**
* Check Http Header Timestamp with request timestamp
* to prevent replay attacks
* https://restfulapi.net/security-essentials/
*/
class ApiCheckTimeStamps
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle(Request $request, Closure $next)
{
if (Helper::isRequestForApiV2($request)) {
if (!$request->hasHeader('X-API-TIMESTAMP') or !is_numeric($request->header('X-API-TIMESTAMP'))) {
throw new ApiErrorException(ApiError::wrongTimeStamp());
}
if (!$request->timestamp or !is_numeric($request->timestamp)) {
throw new ApiErrorException(ApiError::wrongTimeStamp());
}
$diff = intval($request->timestamp) - intval($request->header('X-API-TIMESTAMP'));
$maxDiff = 120;
if (abs($diff) > $maxDiff) {
throw new ApiErrorException(ApiError::wrongTimeStamp());
}
}
return $next($request);
}
}