Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
0.00% |
0 / 16 |
|
0.00% |
0 / 3 |
CRAP | |
0.00% |
0 / 1 |
| ThrottleRequests | |
0.00% |
0 / 16 |
|
0.00% |
0 / 3 |
30 | |
0.00% |
0 / 1 |
| __construct | |
0.00% |
0 / 1 |
|
0.00% |
0 / 1 |
2 | |||
| handle | |
0.00% |
0 / 9 |
|
0.00% |
0 / 1 |
12 | |||
| addHeaders | |
0.00% |
0 / 6 |
|
0.00% |
0 / 1 |
2 | |||
| 1 | <?php |
| 2 | |
| 3 | namespace App\Http\Middleware; |
| 4 | use Closure; |
| 5 | use Illuminate\Cache\RateLimiter; |
| 6 | use Illuminate\Http\Response; |
| 7 | use Symfony\Component\HttpFoundation\Response as SymfonyResponse; |
| 8 | use Symfony\Component\HttpKernel\Exception\HttpException; |
| 9 | |
| 10 | class ThrottleRequests |
| 11 | { |
| 12 | protected $limiter; |
| 13 | |
| 14 | public function __construct(RateLimiter $limiter) |
| 15 | { |
| 16 | $this->limiter = $limiter; |
| 17 | } |
| 18 | |
| 19 | public function handle($request, Closure $next, $key = null, $maxAttempts = 8, $decayMinutes = 1) |
| 20 | { |
| 21 | $key = $key ?: $request->ip(); |
| 22 | |
| 23 | if ($this->limiter->tooManyAttempts($key, $maxAttempts)) { |
| 24 | $retryAfter = $this->limiter->availableIn($key); |
| 25 | |
| 26 | $exception = new HttpException(SymfonyResponse::HTTP_TOO_MANY_REQUESTS, 'Too Many Requests'); |
| 27 | $exception->setHeaders(['Retry-After' => $retryAfter]); |
| 28 | |
| 29 | throw $exception; |
| 30 | } |
| 31 | |
| 32 | $this->limiter->hit($key, $decayMinutes * 60); |
| 33 | |
| 34 | $response = $next($request); |
| 35 | |
| 36 | return $this->addHeaders($response, $key, $maxAttempts, $decayMinutes); |
| 37 | } |
| 38 | |
| 39 | protected function addHeaders($response, $key, $maxAttempts, $decayMinutes) |
| 40 | { |
| 41 | $response->headers->add([ |
| 42 | 'X-RateLimit-Limit' => $maxAttempts, |
| 43 | 'X-RateLimit-Remaining' => $maxAttempts - $this->limiter->attempts($key) + 1, |
| 44 | 'X-RateLimit-Reset' => $this->limiter->availableIn($key), |
| 45 | ]); |
| 46 | |
| 47 | return $response; |
| 48 | } |
| 49 | } |