38 lines
1.1 KiB
PHP
38 lines
1.1 KiB
PHP
<?php
|
|
|
|
namespace App\Http\Middleware;
|
|
|
|
use App\Enums\ApiError;
|
|
use App\Exceptions\Api\ApiErrorException;
|
|
use Illuminate\Http\Request;
|
|
use Illuminate\Support\Carbon;
|
|
|
|
/**
|
|
* 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
|
|
* @throws ApiErrorException With ApiError::wrongTimeStamp if timestamp has an incorrect format or is timed out.
|
|
*/
|
|
public function handle(Request $request, \Closure $next)
|
|
{
|
|
if (!\is_string($request->timestamp) or !Carbon::hasFormat($request->timestamp, 'Y-m-d H:i:s')) {
|
|
throw new ApiErrorException(ApiError::wrongTimeStamp());
|
|
}
|
|
if (
|
|
Carbon::parse($request->timestamp, 'utc')
|
|
->isBefore(Carbon::now('UTC')->subSeconds(config('api.timestampTimeout', 10)))
|
|
) {
|
|
throw new ApiErrorException(ApiError::wrongTimeStamp());
|
|
}
|
|
return $next($request);
|
|
}
|
|
}
|