captchaImage) { $this->refreshCaptcha(); } } public function refreshCaptcha(): void { $captchaService = app(CaptchaService::class); $code = $captchaService->generateCode(); // Store code in cache with user's session ID as key Cache::put( 'verification_code_' . session()->getId(), $code, now()->addMinutes(5) ); $this->captchaImage = $captchaService->generateImage($code); $this->dispatch('captcha-refreshed'); } public function captchaImageUrl(): string { if(!$this->captchaImage)$this->refreshCaptcha(); return $this->captchaImage; } public function form(Form $form): Form { return $form ->schema([ $this->getEmailFormComponent(), $this->getPasswordFormComponent(), $this->getVerificationCodeFormComponent(), ViewField::make('captcha') ->view('filament.pages.auth.captcha'), $this->getRememberFormComponent(), ]) ->statePath('data'); } protected function getVerificationCodeFormComponent(): Component { return TextInput::make('verification_code') ->label('Verification Code') ->required() ->length(6) ->placeholder('Enter code shown above'); } public function authenticate(): ?LoginResponse { $this->validate(); $formData = $this->form->getState(); if (! $this->verifyCode($formData['verification_code'])) { throw ValidationException::withMessages([ 'data.verification_code' => __('驗證碼錯誤'), ]); } try { return parent::authenticate(); } catch (ValidationException $e) { $this->refreshCaptcha(); // throw $e; throw ValidationException::withMessages([ 'verification_code' => __('Invalid verification code.'), ]); } } protected function verifyCode(string $code): bool { $validCode = Cache::get('verification_code_' . session()->getId()); return $code === $validCode; } }