ldc-bien-etre-animal/app/Http/Requests/Concerns/HasEmailRateLimit.php
2026-08-31 12:05:37 +02:00

69 lines
1.6 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Http\Requests\Concerns;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Validation\Validator;
trait HasEmailRateLimit
{
/**
* Prefix per form.
* must be defined in each Request that uses this trait.
*/
protected function rateLimitPrefix(): string
{
return '';
}
/**
* Number of attempts.
*/
protected function rateLimitMaxAttempts(): int
{
return 3;
}
/**
* Lockout duration in seconds.
*/
protected function rateLimitDecaySeconds(): int
{
return 3600;
}
/**
* Translation key for the error message.
*/
abstract protected function rateLimitMessageKey(): string;
/**
* Apply a rate limit based on the submitted email address, adding
* a validation error on the "email" field once the limit is reached.
*/
protected function applyEmailRateLimit(Validator $validator): void
{
$email = $this->input('email');
if (!is_string($email) || $email === '') {
return;
}
$key = "{$this->rateLimitPrefix()}:" . strtolower($email);
if (RateLimiter::tooManyAttempts($key, $this->rateLimitMaxAttempts())) {
$seconds = RateLimiter::availableIn($key);
$minutes = (int) ceil($seconds / 60);
$validator->errors()->add(
'email',
trans($this->rateLimitMessageKey(), ['minutes' => $minutes])
);
return;
}
RateLimiter::hit($key, $this->rateLimitDecaySeconds());
}
}