Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
CRAP
100.00% covered (success)
100.00%
1 / 1
ApiCheckTimeStamps
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
5
100.00% covered (success)
100.00%
1 / 1
 handle
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
5
1<?php
2
3namespace App\Http\Middleware;
4
5use App\Enums\ApiError;
6use App\Exceptions\Api\V2\ApiErrorException;
7use App\Lib\Helper;
8use Illuminate\Http\Request;
9use 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 */
16class 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}