ldc-crm/app/Http/Middleware/ApiCheckTimeStamps.php

43 lines
1.2 KiB
PHP
Raw Permalink Normal View History

2021-03-14 10:45:42 +01:00
<?php
namespace App\Http\Middleware;
use App\Enums\ApiError;
use App\Exceptions\Api\V2\ApiErrorException;
2021-03-14 10:45:42 +01:00
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());
2021-03-14 10:45:42 +01:00
}
if (!$request->timestamp or !is_numeric($request->timestamp)) {
throw new ApiErrorException(ApiError::wrongTimeStamp());
2021-03-14 10:45:42 +01:00
}
$diff = intval($request->timestamp) - intval($request->header('X-API-TIMESTAMP'));
$maxDiff = 120;
if (abs($diff) > $maxDiff) {
throw new ApiErrorException(ApiError::wrongTimeStamp());
2021-03-14 10:45:42 +01:00
}
}
return $next($request);
}
}