<?php namespace App\Services\Security; use App\Enums\Security\Protection\Captcha\CaptchaScope; use App\Enums\Security\Protection\Captcha\CaptchaType; use App\Enums\Security\Protection\Captcha\GoogleRecaptchaV3ActionName; use App\Rules\Captcha\GoogleRecaptchaV3ActionRule; use App\Settings\Security\Captcha\CaptchaSettings; use Illuminate\Contracts\Validation\ValidationRule; class CaptchaService { private CaptchaSettings $captchaSettings; public function __construct() { $this->captchaSettings = app(CaptchaSettings::class); } // <editor-fold desc="Methods"> /** * @see app/Rules/Captcha/CaptchaRule.php */ public function getCaptchaRule(CaptchaScope $captchaScope): ValidationRule { return match ($this->captchaSettings->type) { CaptchaType::RecaptchaV3 => $this->getGoogleRecaptchaV3Rule($captchaScope) // E.g. Another one for hCaptcha }; } /** * @see resources/views/security/captcha.blade.php */ public function getFrontendConfig(): array { return match ($this->captchaSettings->type) { CaptchaType::RecaptchaV3 => [ 'siteKey' => config('services.google.recaptcha.v3.site_key'), ] // E.g. Another one for hCaptcha }; } // </editor-fold> // <editor-fold desc="Getters/Setters"> public function getEnabled(): bool { return $this->captchaSettings->enabled; } public function setEnabled(bool $value): static { $this->captchaSettings->enabled = $value; $this->captchaSettings->save(); return $this; } public function getType(): CaptchaType { return $this->captchaSettings->type; } public function setType(CaptchaType $value): static { $this->captchaSettings->type = $value; $this->captchaSettings->save(); return $this; } // </editor-fold> // <editor-fold desc="Methods (Protected)"> /** * Get Google Recaptcha V3 action(s) for the required Captcha scope. */ protected function getGoogleRecaptchaV3Rule(CaptchaScope $captchaScope): ValidationRule { $actions = match ($captchaScope) { CaptchaScope::NewTransactions => [ GoogleRecaptchaV3ActionName::CreateTransaction->value, ], CaptchaScope::TransactionChanges => [ GoogleRecaptchaV3ActionName::DeleteTransaction->value, ], }; return new GoogleRecaptchaV3ActionRule($actions); } // </editor-fold> }