Skip to content

Commit

Permalink
add a more specific message if the user is authenticated
Browse files Browse the repository at this point in the history
  • Loading branch information
mateusjatenee committed Apr 3, 2024
1 parent cb40d37 commit d31af36
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -16,4 +16,16 @@ public static function forLimiter(string $limiter)
{
return new static("Named rate limiter [{$limiter}] is not defined.");
}

/**
* Create a new exception for an invalid rate limiter based on a model property.
*
* @param string $limiter
* @param class-string $model
* @return static
*/
public static function forLimiterAndUser(string $limiter, string $model)
{
return new static("Named rate limiter [{$model}::{$limiter}] is not defined.");
}
}
6 changes: 5 additions & 1 deletion src/Illuminate/Routing/Middleware/ThrottleRequests.php
Original file line number Diff line number Diff line change
Expand Up @@ -196,7 +196,11 @@ protected function resolveMaxAttempts($request, $maxAttempts)
// If by this time we still don't have a numeric value, it means there was no matching rate limiter,
// and that the attribute in the authenticated model either did not exist or was invalid.
if (! is_numeric($maxAttempts)) {
throw InvalidNamedRateLimiterException::forLimiter($maxAttempts);
if (is_null($request->user())) {
throw InvalidNamedRateLimiterException::forLimiter($maxAttempts);
}

throw InvalidNamedRateLimiterException::forLimiterAndUser($maxAttempts, get_class($request->user()));
}

return (int) $maxAttempts;
Expand Down
2 changes: 1 addition & 1 deletion tests/Integration/Http/ThrottleRequestsTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -255,7 +255,7 @@ public function testItFailsIfNamedLimiterDoesNotExist()
public function testItFailsIfNamedLimiterDoesNotExistAndAuthenticatedUserDoesNotHaveFallbackProperty()
{
$this->expectException(InvalidNamedRateLimiterException::class);
$this->expectExceptionMessage('Named rate limiter [rateLimiting] is not defined.');
$this->expectExceptionMessage('Named rate limiter [' . User::class . '::rateLimiting] is not defined.');

Route::get('/', fn () => 'ok')->middleware(['auth', ThrottleRequests::using('rateLimiting')]);

Expand Down

0 comments on commit d31af36

Please sign in to comment.