I have a newsletter livewire component which accepts an email and do create/read operation.
I would like to add a rate limit to this component. That is, allow users to submit the newsletter form 10 times per minute.
I am able to achieve this by setting 'middleware_group' => ['web', 'throttle:10,1'], in config/livewire.php. But this will apply to every livewire calls. I do not want that.
And since this is not directly called from a route, in such case I would have simply added rate limit from the web.php itself, I'm not sure how to add to a livewire component only.
@snapey's method is unfortunately insecure. Since public properties are mutable from the frontend on demand, an attacker could simply alter the timestamp in this property and bypass the "rate limit".
Hey @danharrin, I am facing an issue while installing. I have created a discussion on github. Could you please take out some time and assist me on this. Thanks.
@danharrin Just upgraded to Laravel 8, your package is working as expected.
Also, @snapey this package will restrict the call when tested on multiple tabs, incognito mode and on different browsers within the specified rate limit.
I just stumbled over that topic and tried to get RateLimiter running in a Livewire/Volt Component. Also tried the package of @danharrin but somehow couldn't get it working (I assume I did something wrong as it states there is volt compatibility in the release notes).
I implemented it now a little differently and it seems to work quite well. (I hope I haven't overseen anything as I am quite new to the laravel world)
I just added the following lines at the beginning of the function
public function send() {
$key = auth()->id() ?: request()->ip();
// Check if the user has hit the rate limit
if (RateLimiter::tooManyAttempts($key, 1)) {
// Notify the user somehow
}
// Record a hit (increment the rate limit count)
RateLimiter::hit($key, 60); // Limit resets after 60 seconds
// Original Code of the function follows here
...
}