Skip to content

Commit

Permalink
Добавлен ThrottleRequests middleware адаптированный модуль. Т.к. моду…
Browse files Browse the repository at this point in the history
…ль отдает ответы через JsonResponse, то ThrottleRequests начинает ругаться на не верный класс Response
  • Loading branch information
butschster committed Feb 16, 2016
1 parent 7aeaa91 commit d3b679b
Show file tree
Hide file tree
Showing 2 changed files with 85 additions and 1 deletion.
2 changes: 1 addition & 1 deletion src/Http/Response.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@

use Request;
use Symfony\Component\Yaml\Yaml;
use Illuminate\Http\JsonResponse;
use KodiCMS\API\Exceptions\Exception;
use Symfony\Component\HttpFoundation\JsonResponse;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Database\Eloquent\MassAssignmentException;

Expand Down
84 changes: 84 additions & 0 deletions src/Middleware/ThrottleRequests.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
<?php

namespace KodiCMS\API\Middleware;

use Closure;
use Illuminate\Http\JsonResponse;
use KodiCMS\API\Http\Response;

class ThrottleRequests extends \Illuminate\Routing\Middleware\ThrottleRequests
{
/**
* 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->addJsonHeaders(
$response, $maxAttempts,
$this->calculateRemainingAttempts($key, $maxAttempts)
);
}

/**
* Create a 'too many attempts' response.
*
* @param string $key
* @param int $maxAttempts
* @return \Illuminate\Http\Response
*/
protected function buildResponse($key, $maxAttempts)
{
$response = (new Response())->createResponse([
'type' => Response::TYPE_ERROR,
'code' => 429,
'message' => 'Too Many Attempts'
]);

return $this->addJsonHeaders(
$response, $maxAttempts,
$this->calculateRemainingAttempts($key, $maxAttempts),
$this->limiter->availableIn($key)
);
}

/**
* Add the limit header information to the given response.
*
* @param \Illuminate\Http\JsonResponse $response
* @param int $maxAttempts
* @param int $remainingAttempts
* @param int|null $retryAfter
* @return \Illuminate\Http\Response
*/
protected function addJsonHeaders(JsonResponse $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;
}
}

0 comments on commit d3b679b

Please sign in to comment.