2026-08-31 12:05:37 +02:00
|
|
|
<?php
|
|
|
|
|
|
|
|
|
|
declare(strict_types=1);
|
|
|
|
|
|
|
|
|
|
namespace App\Http\Requests\Concerns;
|
|
|
|
|
|
2026-09-04 12:15:37 +02:00
|
|
|
use Illuminate\Contracts\Validation\Validator;
|
2026-08-31 12:05:37 +02:00
|
|
|
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
|
|
|
|
2026-08-31 12:05: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
|
|
|
/**
|
2026-08-31 15:35:09 +02:00
|
|
|
* Increments the rate limit counter for the submitted email address.
|
2026-08-31 12:05:37 +02:00
|
|
|
*/
|
|
|
|
|
protected function applyEmailRateLimit(Validator $validator): void
|
|
|
|
|
{
|
|
|
|
|
$email = $this->input('email');
|
|
|
|
|
|
2026-09-04 12:15:37 +02:00
|
|
|
if (! is_string($email) || $email === '') {
|
2026-08-31 12:05:37 +02:00
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
2026-08-31 15:35:09 +02:00
|
|
|
$key = $this->rateLimitKey($email);
|
2026-08-31 12:05:37 +02:00
|
|
|
|
|
|
|
|
if (RateLimiter::tooManyAttempts($key, $this->rateLimitMaxAttempts())) {
|
|
|
|
|
$validator->errors()->add(
|
|
|
|
|
'email',
|
2026-09-02 16:25:53 +02:00
|
|
|
trans($this->rateLimitMessageKey())
|
2026-08-31 12:05:37 +02:00
|
|
|
);
|
2026-08-31 15:35:09 +02:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-08-31 16:02:50 +02:00
|
|
|
public function hitEmailRateLimit(): void
|
2026-08-31 15:35:09 +02:00
|
|
|
{
|
|
|
|
|
$email = $this->input('email');
|
2026-08-31 12:05:37 +02:00
|
|
|
|
2026-09-04 12:15:37 +02:00
|
|
|
if (! is_string($email) || $email === '') {
|
2026-08-31 12:05:37 +02:00
|
|
|
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());
|
|
|
|
|
}
|
2026-08-31 15:35:09 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private function rateLimitKey(string $email): string
|
|
|
|
|
{
|
|
|
|
|
return "{$this->rateLimitPrefix()}:" . strtolower($email);
|
2026-08-31 12:05:37 +02:00
|
|
|
}
|
|
|
|
|
}
|