1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace CSlant\Blog\Api\Http\Middlewares; |
4
|
|
|
|
5
|
|
|
use Closure; |
6
|
|
|
use CSlant\Blog\Core\Models\User; |
7
|
|
|
use Illuminate\Http\JsonResponse; |
8
|
|
|
use Illuminate\Http\Request; |
9
|
|
|
use Illuminate\Http\Response; |
10
|
|
|
use Illuminate\Support\Facades\RateLimiter; |
11
|
|
|
|
12
|
|
|
class ConfigurableRateLimiter |
13
|
|
|
{ |
14
|
|
|
/** |
15
|
|
|
* Handle an incoming request with configurable rate limiting. |
16
|
|
|
* |
17
|
|
|
* |
18
|
|
|
*/ |
19
|
|
|
public function handle(Request $request, Closure $next, string $name): Response|JsonResponse |
20
|
|
|
{ |
21
|
|
|
/** @var null|User $user */ |
22
|
|
|
$user = $request->user(); |
23
|
|
|
$identifier = $user ? $user->id : $request->ip(); |
24
|
|
|
$key = $name . ':' . $identifier; |
25
|
|
|
|
26
|
|
|
// Get max attempts from env variable |
27
|
|
|
$maxAttempts = (int) config('blog-core.blog_api_default_rate_limit', 50); |
|
|
|
|
28
|
|
|
|
29
|
|
|
if (RateLimiter::tooManyAttempts($key, $maxAttempts)) { |
30
|
|
|
return $this->buildTooManyAttemptsResponse($maxAttempts); |
31
|
|
|
} |
32
|
|
|
|
33
|
|
|
RateLimiter::hit($key); |
34
|
|
|
|
35
|
|
|
/** @var Response $response */ |
36
|
|
|
$response = $next($request); |
37
|
|
|
|
38
|
|
|
$response->headers->add([ |
39
|
|
|
'X-RateLimit-Limit' => $maxAttempts, |
40
|
|
|
'X-RateLimit-Remaining' => RateLimiter::remaining($key, $maxAttempts), |
41
|
|
|
]); |
42
|
|
|
|
43
|
|
|
return $response; |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
/** |
47
|
|
|
* Build a response for too many attempts. |
48
|
|
|
* |
49
|
|
|
* @param int $maxAttempts |
50
|
|
|
* @return JsonResponse |
51
|
|
|
*/ |
52
|
|
|
private function buildTooManyAttemptsResponse(int $maxAttempts): JsonResponse |
53
|
|
|
{ |
54
|
|
|
return response()->json([ |
55
|
|
|
'error' => true, |
56
|
|
|
'message' => 'Too many attempts. Please try again later.', |
57
|
|
|
'maxAttempts' => $maxAttempts, |
58
|
|
|
])->setStatusCode(429); |
59
|
|
|
} |
60
|
|
|
} |
61
|
|
|
|
This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.
If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.