Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[5.5] Request throttling #19807

Merged
merged 1 commit into from
Jul 2, 2017
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 32 additions & 2 deletions src/Illuminate/Routing/Middleware/ThrottleRequests.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
namespace Illuminate\Routing\Middleware;

use Closure;
use RuntimeException;
use Illuminate\Support\Str;
use Illuminate\Support\Carbon;
use Illuminate\Cache\RateLimiter;
use Symfony\Component\HttpFoundation\Response;
Expand Down Expand Up @@ -32,14 +34,16 @@ public function __construct(RateLimiter $limiter)
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @param int $maxAttempts
* @param int|string $maxAttempts
* @param float|int $decayMinutes
* @return mixed
*/
public function handle($request, Closure $next, $maxAttempts = 60, $decayMinutes = 1)
{
$key = $this->resolveRequestSignature($request);

$maxAttempts = $this->resolveMaxAttempts($request, $maxAttempts);

if ($this->limiter->tooManyAttempts($key, $maxAttempts, $decayMinutes)) {
return $this->buildResponse($key, $maxAttempts);
}
Expand All @@ -54,15 +58,41 @@ public function handle($request, Closure $next, $maxAttempts = 60, $decayMinutes
);
}

/**
* Resolve the number of attempts if the user is authenticated or not.
*
* @param \Illuminate\Http\Request $request
* @param int|string $maxAttempts
* @return int
*/
protected function resolveMaxAttempts($request, $maxAttempts)
{
if (Str::contains($maxAttempts, '|')) {
$parts = explode('|', $maxAttempts, 2);
$maxAttempts = $parts[$request->user() ? 1 : 0];
}

return (int) $maxAttempts;
}

/**
* Resolve request signature.
*
* @param \Illuminate\Http\Request $request
* @return string
* @throws \RuntimeException
*/
protected function resolveRequestSignature($request)
{
return $request->fingerprint();
if ($user = $request->user()) {
return sha1($user->getAuthIdentifier());
}

if ($route = $request->route()) {
return sha1($route->getDomain().'|'.$request->ip());
}

throw new RuntimeException('Unable to generate the request signature. Route unavailable.');
}

/**
Expand Down