Skip to content

Commit a22c531

Browse files
fosrontaylorotwell
andauthored
[10.x] Add shouldHashKeys to ThrottleRequests middleware (#47368)
* Add shouldHashKeys to be able to set throttle store key names * set shouldHashKeys default to true * Styleci adjustments * formatting * formatting * remove type * formatting --------- Co-authored-by: Taylor Otwell <[email protected]>
1 parent 5768ee2 commit a22c531

File tree

1 file changed

+32
-3
lines changed

1 file changed

+32
-3
lines changed

src/Illuminate/Routing/Middleware/ThrottleRequests.php

Lines changed: 32 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,13 @@ class ThrottleRequests
2323
*/
2424
protected $limiter;
2525

26+
/**
27+
* Indicates if the rate limiter keys should be hashed.
28+
*
29+
* @var bool
30+
*/
31+
protected static $shouldHashKeys = true;
32+
2633
/**
2734
* Create a new request throttler.
2835
*
@@ -120,7 +127,7 @@ protected function handleRequestUsingNamedLimiter($request, Closure $next, $limi
120127
$next,
121128
collect(Arr::wrap($limiterResponse))->map(function ($limit) use ($limiterName) {
122129
return (object) [
123-
'key' => md5($limiterName.$limit->key),
130+
'key' => self::$shouldHashKeys ? md5($limiterName.$limit->key) : $limiterName.':'.$limit->key,
124131
'maxAttempts' => $limit->maxAttempts,
125132
'decayMinutes' => $limit->decayMinutes,
126133
'responseCallback' => $limit->responseCallback,
@@ -193,9 +200,9 @@ protected function resolveMaxAttempts($request, $maxAttempts)
193200
protected function resolveRequestSignature($request)
194201
{
195202
if ($user = $request->user()) {
196-
return sha1($user->getAuthIdentifier());
203+
return $this->formatIdentifier($user->getAuthIdentifier());
197204
} elseif ($route = $request->route()) {
198-
return sha1($route->getDomain().'|'.$request->ip());
205+
return $this->formatIdentifier($route->getDomain().'|'.$request->ip());
199206
}
200207

201208
throw new RuntimeException('Unable to generate the request signature. Route unavailable.');
@@ -299,4 +306,26 @@ protected function calculateRemainingAttempts($key, $maxAttempts, $retryAfter =
299306
{
300307
return is_null($retryAfter) ? $this->limiter->retriesLeft($key, $maxAttempts) : 0;
301308
}
309+
310+
/**
311+
* Format the given identifier based on the configured hashing settings.
312+
*
313+
* @param string $value
314+
* @return string
315+
*/
316+
private function formatIdentifier($value)
317+
{
318+
return self::$shouldHashKeys ? sha1($value) : $value;
319+
}
320+
321+
/**
322+
* Specify whether rate limiter keys should be hashed.
323+
*
324+
* @param bool $shouldHashKeys
325+
* @return void
326+
*/
327+
public static function shouldHashKeys(bool $shouldHashKeys = true)
328+
{
329+
self::$shouldHashKeys = $shouldHashKeys;
330+
}
302331
}

0 commit comments

Comments
 (0)