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