Skip to content

Instantly share code, notes, and snippets.

@ovdojoey
Created April 6, 2016 16:12
Show Gist options
  • Select an option

  • Save ovdojoey/b5f5731fd9fa10650d4e2a3308f041ed to your computer and use it in GitHub Desktop.

Select an option

Save ovdojoey/b5f5731fd9fa10650d4e2a3308f041ed to your computer and use it in GitHub Desktop.
This class uses a memcached caching DB to find malicious users
namespace App\Http\Middleware;
use Closure;
use Illuminate\Contracts\Cache\Repository;
class ThrottleMiddleware
{
public $cache;
public function __construct(Repository $memcache)
{
$this->cache = $memcache;
}
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
$ip = $_SERVER['REMOTE_ADDR'];
$jsonOfRequest = json_encode($request->all());
// check for blacklisted IP
$status = $this->cache->get($ip);
if ( $status === "blacklisted" ) {
return response('503 Service Unavailable', '503');
}
// save unix timestamp of request
$lastUnixRequest = $this->cache->get('last:'.$ip);
$this->cache->put('last:'.$ip, time(), 5);
// grab the most recent requests in 5 minutes
$recentRequests = ($this->cache->get('recent:' . $ip)) ? intval($this->cache->get('recent:' . $ip)) : 0;
$totalRequests = ($this->cache->get('total:' . $ip)) ? intval($this->cache->get('total:' . $ip)) : 0;
// if last submit was less than 15 seconds ago
if ( $lastUnixRequest >= ( time() - 15 ) ) {
$lastRequest = $this->cache->get('lastRequest:'.$ip);
if ( $recentRequests > 5 ) {
$this->cache->put('watchlist', $ip . ";" . time(), 1200);
}
if ( $totalRequests > 50 && $recentRequests > 10 ) {
$this->cache->forever($ip, "blacklisted");
$this->cache->forever("blacklist", $ip.";".time());
}
if ($lastRequest === $jsonOfRequest) {
return redirect("forms/repeat-request");
}
}
// store recent requests increment for 5 minute;
$increasedRecentRequest = $recentRequests + 1;
$this->cache->put('recent:'.$ip, $increasedRecentRequest, 5);
// store total requests increment 20 hours
$increasedTotalRequest = $totalRequests + 1;
$this->cache->put('total:'.$ip, $increasedTotalRequest, 1200);
// store request for 1 minute
$this->cache->put('lastRequest:'.$ip, $jsonOfRequest, 1);
return $next($request);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment