Glad To Help
Glad To Help

Reputation: 5387

Laravel Throttle Middleware: is there a callback / handler for it?

I want to use Laravel's Throttle Middleware, but I want to also log any cases where the user made too many attempts.

Is there any Callback / Handler where I can detect this and do something with it?

Let's say I have a route like this:

Route::get('foo', array('before' => 'throttle:5,10', function () {
    return 'You shall pass!';
}, ));

Upvotes: 1

Views: 1557

Answers (3)

depalage
depalage

Reputation: 21

Illuminate\Auth\Events\Lockout event is only fired in Illuminate\Foundation\Auth\ThrottlesLogins but you can still fire it by hand.

This is how I've done that:

  1. In app/Exceptions/Handler.php add these use statements:
use Illuminate\Auth\Events\Lockout;
use Symfony\Component\HttpKernel\Exception\HttpException;
  1. Add this to report method of the same file:
if ($exception instanceof HttpException) {
    if ('Too Many Attempts.' == $exception->getMessage()) {
        event(new Lockout(request()));
    }
}
  1. Execute php artisan make:listener LogThrottleLimitReached and add this code inside handle method of app/Listeners/LogThrottleLimitReached.php file:
$request = $event->request;

\Log::error(sprintf(
    'Throttling rate limit reached. URL: %s, Body: %s, IP: %s',
    $request->url(),
    json_encode($request->all()),
    $request->ip()
));
  1. Register that listener in app/Providers/EventServiceProvider.php:
use App\Listeners\LogThrottleLimitReached;
use Illuminate\Auth\Events\Lockout;

and

protected $listen = [
    Lockout::class => [
        LogThrottleLimitReached::class,
    ],
];

Upvotes: 2

phy25
phy25

Reputation: 101

You can just extend the ThrottleRequests class and redeclare its buildException, or try handling its exception (\Symfony\Component\HttpKernel\Exception\HttpException with 429 'Too Many Attempts.') inside app/Exceptions/Handler.php.

Upvotes: 1

Antonio Carlos Ribeiro
Antonio Carlos Ribeiro

Reputation: 87719

If it reaches the max count, it will fire this event:

Illuminate\Auth\Events\Lockout

So you can probably listen to it

protected $listen = [
    ...
    'Illuminate\Auth\Events\Lockout' => [
        'App\Listeners\LogLockout',
    ],
];

Upvotes: 2

Related Questions