A free open source IT asset/license management system
Extend the built-in ThrottleRequests middleware from Laravel
snipe1822027a8f15
diff --git a/app/Http/Middleware/SetAPIResponseHeaders.php b/app/Http/Middleware/SetAPIResponseHeaders.phpindex 0ed7ebcedb..9349a34746 100644--- a/app/Http/Middleware/SetAPIResponseHeaders.php+++ b/app/Http/Middleware/SetAPIResponseHeaders.php@@ -4,9 +4,42 @@ namespace App\Http\Middleware;use Closure;use Illuminate\Http\Request;+use Illuminate\Support\Facades\Cache;+use Illuminate\Support\Facades\RateLimiter;+use Illuminate\Routing\Middleware\ThrottleRequests;+use Symfony\Component\HttpFoundation\Response;-class SetAPIResponseHeaders+class SetAPIResponseHeaders extends ThrottleRequests{++ protected function getHeaders($maxAttempts, $remainingAttempts, $retryAfter = null, ?Response $response = null)+ {+ if ($response &&+ ! is_null($response->headers->get('X-RateLimit-Remaining')) &&+ (int) $response->headers->get('X-RateLimit-Remaining') <= (int) $remainingAttempts) {+ \Log::error('Not adding headers');+ $headers = [];+ $headers['Retry-After'] = $retryAfter; // this is the only line we changed+ $headers['X-RateLimit-Reset'] = $this->availableAt($retryAfter); // this is the only line we changed+ return $headers;+ }++ $headers = [+ 'X-RateLimit-Limit' => $maxAttempts,+ 'X-RateLimit-Remaining' => $remainingAttempts,+ ];++ if (! is_null($retryAfter)) {+ \Log::error('Retry after is set');+ $headers['Retry-After'] = $retryAfter;+ $headers['X-RateLimit-Reset'] = $this->availableAt($retryAfter);+ }++ return $headers;+ }+++/*** Handle an incoming request.*@@ -14,12 +47,28 @@ class SetAPIResponseHeaders* @param \Closure $next* @return mixed*/- public function handle(Request $request, Closure $next)+ protected function handleRequest($request, Closure $next, array $limits){+ foreach ($limits as $limit) {+ if ($this->limiter->tooManyAttempts($limit->key, $limit->maxAttempts)) {+ throw $this->buildException($request, $limit->key, $limit->maxAttempts, $limit->responseCallback);+ }++ $this->limiter->hit($limit->key, $limit->decaySeconds);+ }+$response = $next($request);- // $response->headers->set('Retry-After', ($request->header('Retry-After') ?? 60));- // $response->headers->set('X-RateLimit-Reset', ($request->header('Retry-After') ?? 60) + time());- // $response->headers->set('X-Ratelimit-Used', ($request->header('X-Ratelimit-Limit') - $request->header('X-RateLimit-Remaining')));++ foreach ($limits as $limit) {+ $response = $this->addHeaders(+ $response,+ $limit->maxAttempts,+ $this->calculateRemainingAttempts($limit->key, $limit->maxAttempts),+ $this->getTimeUntilNextRetry($limit->key) // this is the only line we changed+ );+ }+return $response;}+}\ No newline at end of file