Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
100.00% |
7 / 7 |
|
100.00% |
1 / 1 |
CRAP | |
100.00% |
1 / 1 |
| ApiCheckTimeStamps | |
100.00% |
7 / 7 |
|
100.00% |
1 / 1 |
5 | |
100.00% |
1 / 1 |
| handle | |
100.00% |
7 / 7 |
|
100.00% |
1 / 1 |
5 | |||
| 1 | <?php |
| 2 | |
| 3 | namespace App\Http\Middleware; |
| 4 | |
| 5 | use App\Enums\ApiError; |
| 6 | use App\Exceptions\Api\V2\ApiErrorException; |
| 7 | use App\Lib\Helper; |
| 8 | use Illuminate\Http\Request; |
| 9 | use Illuminate\Support\Carbon; |
| 10 | |
| 11 | /** |
| 12 | * Check Http Header Timestamp with request timestamp |
| 13 | * to prevent replay attacks |
| 14 | * https://restfulapi.net/security-essentials/ |
| 15 | */ |
| 16 | class ApiCheckTimeStamps |
| 17 | { |
| 18 | /** |
| 19 | * Handle an incoming request. |
| 20 | * |
| 21 | * @param \Illuminate\Http\Request $request |
| 22 | * @param \Closure $next |
| 23 | * @return mixed |
| 24 | * @throws \App\Exceptions\Api\V2\ApiErrorException With ApiError::wrongTimeStamp if |
| 25 | * timestamp has an incorrect format or is timed out. |
| 26 | */ |
| 27 | public function handle(Request $request, \Closure $next) |
| 28 | { |
| 29 | if (Helper::isRequestForApiV2($request)) { |
| 30 | if (!\is_string($request->timestamp) or !Carbon::hasFormat($request->timestamp, 'Y-m-d H:i:s')) { |
| 31 | throw new ApiErrorException(ApiError::wrongTimeStamp()); |
| 32 | } |
| 33 | if ( |
| 34 | Carbon::parse($request->timestamp, 'utc') |
| 35 | ->isBefore(Carbon::now('UTC')->subSeconds(config('api.timestampTimeout', 10))) |
| 36 | ) { |
| 37 | throw new ApiErrorException(ApiError::wrongTimeStamp()); |
| 38 | } |
| 39 | } |
| 40 | return $next($request); |
| 41 | } |
| 42 | } |