2021-03-14 10:45:42 +01:00
|
|
|
<?php
|
|
|
|
|
|
|
|
|
|
namespace App\Http\Middleware;
|
|
|
|
|
|
|
|
|
|
use App\Enums\ApiError;
|
2021-07-28 14:18:47 +02:00
|
|
|
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'))) {
|
2021-08-04 15:07:25 +02:00
|
|
|
throw new ApiErrorException(ApiError::wrongTimeStamp());
|
2021-03-14 10:45:42 +01:00
|
|
|
}
|
|
|
|
|
if (!$request->timestamp or !is_numeric($request->timestamp)) {
|
2021-08-04 15:07:25 +02:00
|
|
|
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) {
|
2021-08-04 15:07:25 +02:00
|
|
|
throw new ApiErrorException(ApiError::wrongTimeStamp());
|
2021-03-14 10:45:42 +01:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
return $next($request);
|
|
|
|
|
}
|
|
|
|
|
}
|