ldc-bien-etre-animal/app/Http/Requests/Concerns/HasEmailRateLimit.php
2026-09-04 17:29:30 +02:00

79 lines
1.8 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Http\Requests\Concerns;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Support\Facades\RateLimiter;
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;
/**
* Increments the rate limit counter for the submitted email address.
*/
protected function applyEmailRateLimit(Validator $validator): void
{
$email = $this->input('email');
if (! is_string($email) || $email === '') {
return;
}
$key = $this->rateLimitKey($email);
if (RateLimiter::tooManyAttempts($key, $this->rateLimitMaxAttempts())) {
$validator->errors()->add(
'email',
trans($this->rateLimitMessageKey())
);
}
}
public function hitEmailRateLimit(): void
{
$email = $this->input('email');
if (! is_string($email) || $email === '') {
return;
}
if (! app()->environment('local')) {
RateLimiter::hit($this->rateLimitKey($email), $this->rateLimitDecaySeconds());
}
}
private function rateLimitKey(string $email): string
{
return "{$this->rateLimitPrefix()}:" . strtolower($email);
}
}