feat(auth): complete registration anti-spam and quota hardening

This commit is contained in:
2026-02-21 12:13:01 +01:00
parent 4fb95c872b
commit b239af9619
33 changed files with 1288 additions and 142 deletions

View File

@@ -2,24 +2,26 @@
namespace App\Http\Controllers\Auth;
use App\Jobs\SendVerificationEmailJob;
use App\Http\Controllers\Controller;
use App\Mail\RegistrationVerificationMail;
use App\Models\EmailSendEvent;
use App\Models\User;
use App\Services\Security\RecaptchaVerifier;
use Carbon\CarbonImmutable;
use App\Services\Auth\DisposableEmailService;
use App\Services\Auth\RegistrationVerificationTokenService;
use App\Services\Security\TurnstileVerifier;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\Str;
use Illuminate\View\View;
class RegisteredUserController extends Controller
{
public function __construct(
private readonly RecaptchaVerifier $recaptchaVerifier
private readonly TurnstileVerifier $turnstileVerifier,
private readonly DisposableEmailService $disposableEmailService,
private readonly RegistrationVerificationTokenService $verificationTokenService,
)
{
}
@@ -31,6 +33,8 @@ class RegisteredUserController extends Controller
{
return view('auth.register', [
'prefillEmail' => (string) $request->query('email', ''),
'requiresTurnstile' => $this->shouldRequireTurnstile($request->ip()),
'turnstileSiteKey' => (string) config('services.turnstile.site_key', ''),
]);
}
@@ -53,54 +57,77 @@ class RegisteredUserController extends Controller
public function store(Request $request): RedirectResponse
{
$validated = $request->validate([
'email' => ['required', 'string', 'lowercase', 'email', 'max:255', 'unique:'.User::class],
'email' => ['required', 'string', 'lowercase', 'email', 'max:255'],
'website' => ['nullable', 'max:0'],
'cf-turnstile-response' => ['nullable', 'string'],
]);
if ($this->recaptchaVerifier->isEnabled()) {
$request->validate([
'g-recaptcha-response' => ['required', 'string'],
]);
$email = strtolower(trim((string) $validated['email']));
$ip = $request->ip();
$verified = $this->recaptchaVerifier->verify(
(string) $request->input('g-recaptcha-response', ''),
$request->ip()
$this->trackRegisterAttempt($ip);
if ($this->shouldRequireTurnstile($ip)) {
$verified = $this->turnstileVerifier->verify(
(string) $request->input('cf-turnstile-response', ''),
$ip
);
if (! $verified) {
return back()
->withInput($request->except('website'))
->withErrors(['captcha' => 'reCAPTCHA verification failed. Please try again.']);
->withErrors(['captcha' => 'Captcha verification failed. Please try again.']);
}
}
$user = User::create([
'username' => null,
'name' => Str::before((string) $validated['email'], '@'),
'email' => $validated['email'],
'password' => Hash::make(Str::random(64)),
'is_active' => false,
'onboarding_step' => 'email',
'username_changed_at' => now(),
]);
if ($this->disposableEmailService->isDisposableEmail($email)) {
$this->logEmailEvent($email, $ip, null, 'blocked', 'disposable');
$token = Str::random(64);
DB::table('user_verification_tokens')->insert([
'user_id' => $user->id,
'token' => $token,
'expires_at' => now()->addDay(),
'created_at' => now(),
'updated_at' => now(),
]);
return back()
->withInput($request->except('website'))
->withErrors(['email' => 'Please use a real email provider.']);
}
Mail::to($user->email)->queue(new RegistrationVerificationMail($token));
$user = User::query()->where('email', $email)->first();
$cooldown = $this->resendCooldownSeconds();
$this->setResendCooldown((string) $validated['email'], $cooldown);
if ($user && $user->email_verified_at !== null) {
$this->logEmailEvent($email, $ip, (int) $user->id, 'blocked', 'already-verified');
return redirect(route('register.notice', absolute: false))
->with('status', 'Verification email sent. Please check your inbox.')
->with('registration_email', (string) $validated['email']);
return $this->redirectToRegisterNotice($email);
}
if (! $user) {
$user = User::query()->create([
'username' => null,
'name' => Str::before($email, '@'),
'email' => $email,
'password' => Hash::make(Str::random(64)),
'is_active' => false,
'onboarding_step' => 'email',
'username_changed_at' => now(),
]);
}
if ($this->isWithinEmailCooldown($user)) {
$this->logEmailEvent($email, $ip, (int) $user->id, 'blocked', 'cooldown');
return $this->redirectToRegisterNotice($email);
}
$token = $this->verificationTokenService->createForUser((int) $user->id);
$event = $this->logEmailEvent($email, $ip, (int) $user->id, 'queued', null);
SendVerificationEmailJob::dispatch(
emailEventId: (int) $event->id,
email: $email,
token: $token,
userId: (int) $user->id,
ip: $ip
);
$this->markVerificationEmailSent($user);
return $this->redirectToRegisterNotice($email);
}
public function resendVerification(Request $request): RedirectResponse
@@ -109,13 +136,8 @@ class RegisteredUserController extends Controller
'email' => ['required', 'string', 'lowercase', 'email', 'max:255'],
]);
$email = (string) $validated['email'];
$remaining = $this->resendRemainingSeconds($email);
if ($remaining > 0) {
return back()
->with('registration_email', $email)
->withErrors(['email' => "Please wait {$remaining} seconds before resending."]);
}
$email = strtolower(trim((string) $validated['email']));
$ip = $request->ip();
$user = User::query()
->where('email', $email)
@@ -124,55 +146,162 @@ class RegisteredUserController extends Controller
->first();
if (! $user) {
return back()
->with('registration_email', $email)
->withErrors(['email' => 'No pending verification found for this email.']);
$this->logEmailEvent($email, $ip, null, 'blocked', 'missing');
return $this->redirectToRegisterNotice($email);
}
DB::table('user_verification_tokens')->where('user_id', $user->id)->delete();
if ($this->isWithinEmailCooldown($user)) {
$this->logEmailEvent($email, $ip, (int) $user->id, 'blocked', 'cooldown');
$token = Str::random(64);
DB::table('user_verification_tokens')->insert([
'user_id' => $user->id,
'token' => $token,
'expires_at' => now()->addDay(),
'created_at' => now(),
'updated_at' => now(),
]);
return $this->redirectToRegisterNotice($email);
}
Mail::to($user->email)->queue(new RegistrationVerificationMail($token));
$token = $this->verificationTokenService->createForUser((int) $user->id);
$event = $this->logEmailEvent($email, $ip, (int) $user->id, 'queued', null);
$cooldown = $this->resendCooldownSeconds();
$this->setResendCooldown($email, $cooldown);
SendVerificationEmailJob::dispatch(
emailEventId: (int) $event->id,
email: $email,
token: $token,
userId: (int) $user->id,
ip: $ip
);
$this->markVerificationEmailSent($user);
return $this->redirectToRegisterNotice($email);
}
private function redirectToRegisterNotice(string $email): RedirectResponse
{
return redirect(route('register.notice', absolute: false))
->with('registration_email', $email)
->with('status', 'Verification email resent. Please check your inbox.');
->with('status', $this->genericSuccessMessage())
->with('registration_email', $email);
}
private function genericSuccessMessage(): string
{
return (string) config('registration.generic_success_message', 'If that email is valid, we sent a verification link.');
}
private function logEmailEvent(string $email, ?string $ip, ?int $userId, string $status, ?string $reason): EmailSendEvent
{
return EmailSendEvent::query()->create([
'type' => 'verify_email',
'email' => $email,
'ip' => $ip,
'user_id' => $userId,
'status' => $status,
'reason' => $reason,
'created_at' => now(),
]);
}
private function shouldRequireTurnstile(?string $ip): bool
{
if (! $this->turnstileVerifier->isEnabled()) {
return false;
}
if ($ip === null || $ip === '') {
return false;
}
$threshold = max(1, (int) config('registration.turnstile_suspicious_attempts', 2));
$attempts = (int) cache()->get($this->registerAttemptCacheKey($ip), 0);
if ($attempts >= $threshold) {
return true;
}
$minuteLimit = max(1, (int) config('registration.ip_per_minute_limit', 3));
$dailyLimit = max(1, (int) config('registration.ip_per_day_limit', 20));
if (RateLimiter::tooManyAttempts($this->registerIpRateKey($ip), $minuteLimit)) {
return true;
}
return RateLimiter::tooManyAttempts($this->registerIpDailyRateKey($ip), $dailyLimit);
}
private function trackRegisterAttempt(?string $ip): void
{
if ($ip === null || $ip === '') {
return;
}
$key = $this->registerAttemptCacheKey($ip);
$windowMinutes = max(1, (int) config('registration.turnstile_attempt_window_minutes', 30));
$seconds = $windowMinutes * 60;
$attempts = (int) cache()->get($key, 0);
cache()->put($key, $attempts + 1, $seconds);
}
private function registerAttemptCacheKey(string $ip): string
{
return 'register:attempts:' . sha1($ip);
}
private function registerIpRateKey(string $ip): string
{
return 'register:ip:' . $ip;
}
private function registerIpDailyRateKey(string $ip): string
{
return 'register:ip:daily:' . $ip;
}
private function isWithinEmailCooldown(User $user): bool
{
if ($user->last_verification_sent_at === null) {
return false;
}
$cooldownMinutes = max(1, (int) config('registration.email_cooldown_minutes', 30));
return $user->last_verification_sent_at->gt(now()->subMinutes($cooldownMinutes));
}
private function markVerificationEmailSent(User $user): void
{
$now = now();
$windowStartedAt = $user->verification_send_window_started_at;
if (! $windowStartedAt || $windowStartedAt->lt($now->copy()->subDay())) {
$user->verification_send_window_started_at = $now;
$user->verification_send_count_24h = 1;
} else {
$user->verification_send_count_24h = ((int) $user->verification_send_count_24h) + 1;
}
$user->last_verification_sent_at = $now;
$user->save();
}
private function resendCooldownSeconds(): int
{
return max(5, (int) config('antispam.register.resend_cooldown_seconds', 60));
}
private function resendCooldownCacheKey(string $email): string
{
return 'register:resend:cooldown:' . sha1(strtolower(trim($email)));
}
private function setResendCooldown(string $email, int $seconds): void
{
$until = CarbonImmutable::now()->addSeconds($seconds)->timestamp;
Cache::put($this->resendCooldownCacheKey($email), $until, $seconds + 5);
return max(60, ((int) config('registration.email_cooldown_minutes', 30)) * 60);
}
private function resendRemainingSeconds(string $email): int
{
$until = (int) Cache::get($this->resendCooldownCacheKey($email), 0);
if ($until <= 0) {
$user = User::query()
->where('email', strtolower(trim($email)))
->whereNull('email_verified_at')
->first();
if (! $user || $user->last_verification_sent_at === null) {
return 0;
}
return max(0, $until - time());
$remaining = $user->last_verification_sent_at
->copy()
->addSeconds($this->resendCooldownSeconds())
->diffInSeconds(now(), false);
return $remaining >= 0 ? 0 : abs((int) $remaining);
}
}