Skip to content

Instantly share code, notes, and snippets.

@developerdino
Created February 16, 2016 04:12
Show Gist options
  • Save developerdino/e82e3d1d7b1ed666c34d to your computer and use it in GitHub Desktop.
Save developerdino/e82e3d1d7b1ed666c34d to your computer and use it in GitHub Desktop.
Lumen Middleware for rate limiting - based on Laravel's implementation.
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Response;
use Illuminate\Cache\RateLimiter;
class ThrottleRequests
{
/**
* The rate limiter instance.
*
* @var \Illuminate\Cache\RateLimiter
*/
protected $limiter;
/**
* Create a new request throttler.
*
* @param \Illuminate\Cache\RateLimiter $limiter
*
* @return void
*/
public function __construct(RateLimiter $limiter)
{
$this->limiter = $limiter;
}
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @param int $maxAttempts
* @param int $decayMinutes
*
* @return mixed
*/
public function handle($request, Closure $next, $maxAttempts = 60, $decayMinutes = 1)
{
$key = $this->resolveRequestSignature($request);
if ($this->limiter->tooManyAttempts($key, $maxAttempts, $decayMinutes)) {
return $this->buildResponse($key, $maxAttempts);
}
$this->limiter->hit($key, $decayMinutes);
$response = $next($request);
return $this->addHeaders(
$response,
$maxAttempts,
$this->calculateRemainingAttempts($key, $maxAttempts)
);
}
/**
* Resolve request signature.
*
* @param \Illuminate\Http\Request $request
*
* @return string
*/
protected function resolveRequestSignature($request)
{
return sha1(
$request->method() .
'|' . $request->getHost() .
'|' . $request->ip()
);
}
/**
* Create a 'too many attempts' response.
*
* @param string $key
* @param int $maxAttempts
*
* @return \Illuminate\Http\Response
*/
protected function buildResponse($key, $maxAttempts)
{
$response = new Response('Too Many Attempts.', 429);
return $this->addHeaders(
$response,
$maxAttempts,
$this->calculateRemainingAttempts($key, $maxAttempts),
$this->limiter->availableIn($key)
);
}
/**
* Add the limit header information to the given response.
*
* @param \Illuminate\Http\Response $response
* @param int $maxAttempts
* @param int $remainingAttempts
* @param int|null $retryAfter
*
* @return \Illuminate\Http\Response
*/
protected function addHeaders(Response $response, $maxAttempts, $remainingAttempts, $retryAfter = null)
{
$headers = [
'X-RateLimit-Limit' => $maxAttempts,
'X-RateLimit-Remaining' => $remainingAttempts,
];
if (!is_null($retryAfter)) {
$headers['Retry-After'] = $retryAfter;
}
$response->headers->add($headers);
return $response;
}
/**
* Calculate the number of remaining attempts.
*
* @param string $key
* @param int $maxAttempts
*
* @return int
*/
protected function calculateRemainingAttempts($key, $maxAttempts)
{
return $maxAttempts - $this->limiter->attempts($key) + 1;
}
}
@mikemclin
Copy link

mikemclin commented Sep 10, 2016

I would recommend replacing \Illuminate\Http\Response with \Symfony\Component\HttpFoundation\Response in your addHeaders() method. I ran into a conflict, because I return Illuminate\Http\JsonResponse from my controllers (which is probably pretty common in Lumen apps). However, Illuminate\Http\JsonResponse does not extend \Illuminate\Http\Response, so an invalid type exception is thrown.

However, all responses in Lumen are based on the lower-level \Symfony\Component\HttpFoundation\Response class.

FYI, I am using Lumen 5.3.

@mikemclin
Copy link

mikemclin commented Sep 10, 2016

Also, the calculateReaminingAttempts() has a bug. If you are in an error state due to hitting the limit, this will set the X-RateLimit-Remaining header to a value of max attempts + 1. So, if your limit is 3 attempts, it will return a value of 4, once you've hit your limit.

The rate limiter has it's own retry calculation method (maybe it didn't when you made this Gist). So, now you can replace the 2 $this->calculateRemainingAttempts($key, $maxAttempts) calls with $this->limiter->retriesLeft($key, $maxAttempts) to let the Laravel RateLimiter handle this for you.

@ketavchotaliya
Copy link

Getting error Type error: Argument 1 passed to App\Http\Middleware\ThrottleRequests::addHeaders() must be an instance of Illuminate\Http\Response, instance of Illuminate\Http\JsonResponse given

Solution for error
use use Symfony\Component\HttpFoundation\Response; instead of use Illuminate\Http\Response;

@khanzadimahdi
Copy link

khanzadimahdi commented Jun 9, 2019

throttle uses session , in API we don't have any sessions! so you cant use this.
you must use IP and database in order to design a throttle.

@Pr3d4dor
Copy link

There is a bug in line number 58.

The hit method of the Laravel RateLimiter receive the time in seconds and the middleware considers time in minutes, then you must multiply the decayMinutes by 60 to set the key in cache in the correct form.

$this->limiter->($key, $decayMinutes * 60);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment