/** * Source: http://fideloper.com/laravel-http-middleware. */ public function handle($request, Closure $next) { $limit = $this->config->get('api.ratelimit.requests'); $time = $this->config->get('api.ratelimit.time'); // Rate limit by IP address $key = sprintf('api:%s', $request->get('key')); // Add if doesn't exist $this->cache->add($key, 0, $time); // Add to count $count = $this->cache->increment($key); if ($count > $limit) { throw new TooManyRequestsHttpException($time * 60, 'Rate limit exceed.'); } return $next($request); }
/** * Increment the hit counter for the cache key. * * @param string $key * * @return bool */ public function addHit($key) { if (!$this->cache->has($this->getKey($key))) { return $this->cache->add($this->getKey($key), 1, 1); } return $this->cache->increment($this->getKey($key), 1); }
/** * Increment the counter for a given key for a given decay time. * * @param string $key * @param int $decayMinutes * @return int */ public function hit($key, $decayMinutes = 1) { $this->cache->add($key, 1, $decayMinutes); return (int) $this->cache->increment($key); }
/** * Increment the number of failed attempts. * * @author Andrea Marco Sartori * @return void */ public function incrementAttempts() { $this->cache->add($this->key, 0, $this->getExpiry()); $this->cache->increment($this->key); }