ldc-bien-etre-animal/app/Http/Requests/Concerns/HasEmailRateLimit.php

80 lines
1.8 KiB
PHP
Raw Permalink Normal View History

<?php
declare(strict_types=1);
namespace App\Http\Requests\Concerns;
2026-09-04 12:15:37 +02:00
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;
}
2026-09-04 12:15:37 +02:00
/**
* Lockout duration in seconds.
*/
protected function rateLimitDecaySeconds(): int
{
return 3600;
}
/**
* Translation key for the error message.
*/
abstract protected function rateLimitMessageKey(): string;
2026-09-04 12:15:37 +02:00
/**
* Increments the rate limit counter for the submitted email address.
*/
protected function applyEmailRateLimit(Validator $validator): void
{
$email = $this->input('email');
2026-09-04 12:15:37 +02:00
if (! is_string($email) || $email === '') {
return;
}
$key = $this->rateLimitKey($email);
if (RateLimiter::tooManyAttempts($key, $this->rateLimitMaxAttempts())) {
$validator->errors()->add(
'email',
2026-09-02 16:25:53 +02:00
trans($this->rateLimitMessageKey())
);
}
}
2026-08-31 16:02:50 +02:00
public function hitEmailRateLimit(): void
{
$email = $this->input('email');
2026-09-04 12:15:37 +02:00
if (! is_string($email) || $email === '') {
return;
}
2026-09-04 12:15:37 +02:00
if (! app()->environment('local')) {
2026-09-02 18:44:52 +02:00
RateLimiter::hit($this->rateLimitKey($email), $this->rateLimitDecaySeconds());
}
}
private function rateLimitKey(string $email): string
{
return "{$this->rateLimitPrefix()}:" . strtolower($email);
}
}