1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace CSlant\Blog\Api\Http\Middlewares; |
4
|
|
|
|
5
|
|
|
use Closure; |
6
|
|
|
use Illuminate\Http\Request; |
7
|
|
|
use Illuminate\Http\JsonResponse; |
8
|
|
|
use Illuminate\Http\Response; |
9
|
|
|
use Illuminate\Support\Facades\RateLimiter; |
10
|
|
|
|
11
|
|
|
class ConfigurableRateLimiter |
12
|
|
|
{ |
13
|
|
|
/** |
14
|
|
|
* Handle an incoming request with configurable rate limiting. |
15
|
|
|
*/ |
16
|
|
|
public function handle(Request $request, Closure $next, string $name): Response|JsonResponse |
17
|
|
|
{ |
18
|
|
|
$key = $this->resolveKey($request, $name); |
19
|
|
|
$maxAttempts = $this->resolveMaxAttempts($name); |
20
|
|
|
|
21
|
|
|
if (RateLimiter::tooManyAttempts($key, $maxAttempts)) { |
22
|
|
|
return $this->tooManyAttemptsResponse($maxAttempts); |
23
|
|
|
} |
24
|
|
|
|
25
|
|
|
RateLimiter::hit($key); |
26
|
|
|
|
27
|
|
|
/** @var Response $response */ |
28
|
|
|
$response = $next($request); |
29
|
|
|
|
30
|
|
|
return $this->addRateLimitHeaders($response, $key, $maxAttempts); |
31
|
|
|
} |
32
|
|
|
|
33
|
|
|
private function resolveKey(Request $request, string $prefix): string |
34
|
|
|
{ |
35
|
|
|
$identifier = $request->user()->id ?? $request->ip(); |
36
|
|
|
return "{$prefix}:{$identifier}"; |
37
|
|
|
} |
38
|
|
|
|
39
|
|
|
private function resolveMaxAttempts(string $name): int |
40
|
|
|
{ |
41
|
|
|
return (int) config("blog-core.rate_limits.{$name}", config('blog-core.blog_api_default_rate_limit', 50)); |
|
|
|
|
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
private function tooManyAttemptsResponse(int $maxAttempts): JsonResponse |
45
|
|
|
{ |
46
|
|
|
return response()->json([ |
47
|
|
|
'error' => true, |
48
|
|
|
'message' => 'Too many attempts. Please try again later.', |
49
|
|
|
'maxAttempts' => $maxAttempts, |
50
|
|
|
], 429); |
51
|
|
|
} |
52
|
|
|
|
53
|
|
|
private function addRateLimitHeaders(Response $response, string $key, int $maxAttempts): Response |
54
|
|
|
{ |
55
|
|
|
$response->headers->add([ |
56
|
|
|
'X-RateLimit-Limit' => $maxAttempts, |
57
|
|
|
'X-RateLimit-Remaining' => RateLimiter::remaining($key, $maxAttempts), |
58
|
|
|
]); |
59
|
|
|
|
60
|
|
|
return $response; |
61
|
|
|
} |
62
|
|
|
} |
63
|
|
|
|
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.