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 ApiErrorException With ApiError::wrongTimeStamp if timestamp has an incorrect format or is timed out.
25     */
26    public function handle(Request $request, \Closure $next)
27    {
28        if (Helper::isRequestForApiV2($request)) {
29            if (!\is_string($request->timestamp) or !Carbon::hasFormat($request->timestamp, 'Y-m-d H:i:s')) {
30                throw new ApiErrorException(ApiError::wrongTimeStamp());
31            }
32            if (
33                Carbon::parse($request->timestamp, 'utc')
34                ->isBefore(Carbon::now('UTC')->subSeconds(config('api.timestampTimeout', 10)))
35            ) {
36                throw new ApiErrorException(ApiError::wrongTimeStamp());
37            }
38        }
39        return $next($request);
40    }
41}