Add reCAPTCHA support and update captcha provider handling (#647)

* Add reCAPTCHA support and update captcha provider handling

- Introduced reCAPTCHA as an additional captcha provider alongside hCaptcha.
- Updated form request validation to handle different captcha providers based on user selection.
- Added a new validation rule for reCAPTCHA.
- Modified the forms model to include a 'captcha_provider' field.
- Created a migration to add the 'captcha_provider' column to the forms table.
- Updated frontend components to support dynamic rendering of captcha based on the selected provider.
- Enhanced tests to cover scenarios for both hCaptcha and reCAPTCHA.

These changes improve the flexibility of captcha options available to users, enhancing form security and user experience.

* fix pint

* change comment text

* Refactor captcha implementation and integrate new captcha components

- Removed the old RecaptchaV2 component and replaced it with a new implementation that supports both reCAPTCHA and hCaptcha through a unified CaptchaInput component.
- Updated the OpenForm component to utilize the new CaptchaInput for dynamic captcha rendering based on user-selected provider.
- Cleaned up the package.json by removing the deprecated @hcaptcha/vue3-hcaptcha dependency.
- Enhanced form initialization to set a default captcha provider.
- Improved error handling and cleanup for both reCAPTCHA and hCaptcha scripts.

These changes streamline captcha integration, improve maintainability, and enhance user experience by providing a more flexible captcha solution.

* Refactor captcha error messages and localization support

* Refactor registration process to integrate reCAPTCHA

- Replaced hCaptcha implementation with reCAPTCHA in RegisterController and related test cases.
- Updated validation rules to utilize g-recaptcha-response instead of h-captcha-response.
- Modified RegisterForm component to support reCAPTCHA, including changes to the form data structure and component references.
- Enhanced test cases to reflect the new reCAPTCHA integration, ensuring proper validation and response handling.

These changes improve security and user experience during the registration process by adopting a more widely used captcha solution.

* Fix reCAPTCHA configuration and update RegisterForm styling

- Corrected the configuration key for reCAPTCHA in RegisterController from 'services.recaptcha.secret_key' to 'services.re_captcha.secret_key'.
- Updated the styling of the Captcha input section in RegisterForm.vue to improve layout consistency.

These changes ensure proper reCAPTCHA functionality and enhance the user interface during the registration process.

* Fix reCAPTCHA configuration in RegisterTest to use the correct key format

- Updated the configuration key for reCAPTCHA in RegisterTest from 'services.recaptcha.secret_key' to 'services.re_captcha.secret_key' to ensure proper functionality during tests.

This change aligns the test setup with the recent updates in the reCAPTCHA integration, improving the accuracy of the registration process tests.

---------

Co-authored-by: Julien Nahum <julien@nahum.net>
This commit is contained in:
Chirag Chhatrala 2024-12-18 21:05:09 +05:30 committed by GitHub
parent 7365479c83
commit d7ce8536c8
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
43 changed files with 770 additions and 97 deletions

View File

@ -72,6 +72,9 @@ STRIPE_TEST_DEFAULT_PRICING_YEARLY=
H_CAPTCHA_SITE_KEY=
H_CAPTCHA_SECRET_KEY=
RE_CAPTCHA_SITE_KEY=
RE_CAPTCHA_SECRET_KEY=
MUX_WORKSPACE_ID=
MUX_API_TOKEN=

View File

@ -12,7 +12,7 @@ use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
use App\Rules\ValidHCaptcha;
use App\Rules\ValidReCaptcha;
class RegisterController extends Controller
{
@ -71,8 +71,8 @@ class RegisterController extends Controller
'utm_data' => ['nullable', 'array'],
];
if (config('services.h_captcha.secret_key')) {
$rules['h-captcha-response'] = [new ValidHCaptcha()];
if (config('services.re_captcha.secret_key')) {
$rules['g-recaptcha-response'] = [new ValidReCaptcha()];
}
return Validator::make($data, $rules, [

View File

@ -8,6 +8,7 @@ use App\Rules\MatrixValidationRule;
use App\Rules\StorageFile;
use App\Rules\ValidHCaptcha;
use App\Rules\ValidPhoneInputRule;
use App\Rules\ValidReCaptcha;
use App\Rules\ValidUrl;
use App\Service\Forms\FormLogicPropertyResolver;
use Illuminate\Foundation\Http\FormRequest;
@ -116,9 +117,13 @@ class AnswerFormRequest extends FormRequest
$this->requestRules[$propertyId] = $rules;
}
// Validate hCaptcha
// Validate Captcha
if ($this->form->use_captcha) {
$this->requestRules['h-captcha-response'] = [new ValidHCaptcha()];
if ($this->form->captcha_provider === 'recaptcha') {
$this->requestRules['g-recaptcha-response'] = [new ValidReCaptcha()];
} elseif ($this->form->captcha_provider === 'hcaptcha') {
$this->requestRules['h-captcha-response'] = [new ValidHCaptcha()];
}
}
// Validate submission_id for edit mode

View File

@ -118,6 +118,7 @@ abstract class UserFormRequest extends \Illuminate\Foundation\Http\FormRequest
'can_be_indexed' => 'boolean',
'password' => 'sometimes|nullable',
'use_captcha' => 'boolean',
'captcha_provider' => ['sometimes', Rule::in(['recaptcha', 'hcaptcha'])],
// Custom SEO
'seo_meta' => 'nullable|array',

View File

@ -82,6 +82,7 @@ class Form extends Model implements CachableAttributes
'submitted_text',
'redirect_url',
'use_captcha',
'captcha_provider',
'closes_at',
'closed_text',
'max_submissions_count',

View File

@ -10,7 +10,7 @@ class ValidHCaptcha implements ImplicitRule
{
public const H_CAPTCHA_VERIFY_URL = 'https://hcaptcha.com/siteverify';
private $error = 'Invalid CAPTCHA. Please prove you\'re not a bot.';
private $error = 'validation.invalid_captcha';
/**
* Determine if the validation rule passes.
@ -22,7 +22,7 @@ class ValidHCaptcha implements ImplicitRule
public function passes($attribute, $value)
{
if (empty($value)) {
$this->error = 'Please complete the captcha.';
$this->error = 'validation.complete_captcha';
return false;
}
@ -46,6 +46,6 @@ class ValidHCaptcha implements ImplicitRule
*/
public function message()
{
return $this->error;
return trans($this->error);
}
}

View File

@ -0,0 +1,51 @@
<?php
namespace App\Rules;
use Closure;
use Illuminate\Contracts\Validation\ImplicitRule;
use Illuminate\Support\Facades\Http;
class ValidReCaptcha implements ImplicitRule
{
public const RECAPTCHA_VERIFY_URL = 'https://www.google.com/recaptcha/api/siteverify';
private $error = 'validation.invalid_captcha';
/**
* Determine if the validation rule passes.
*
* @param string $attribute
* @param mixed $value
* @return bool
*/
public function passes($attribute, $value)
{
if (empty($value)) {
$this->error = 'validation.complete_captcha';
return false;
}
return Http::asForm()->post(self::RECAPTCHA_VERIFY_URL, [
'secret' => config('services.re_captcha.secret_key'),
'response' => $value,
])->json('success');
}
public function validate(string $attribute, mixed $value, Closure $fail): void
{
if (!$this->passes($attribute, $value)) {
$fail($this->message());
}
}
/**
* Get the validation error message.
*
* @return string
*/
public function message()
{
return trans($this->error);
}
}

View File

@ -40,6 +40,11 @@ return [
'secret_key' => env('H_CAPTCHA_SECRET_KEY'),
],
're_captcha' => [
'site_key' => env('RE_CAPTCHA_SITE_KEY'),
'secret_key' => env('RE_CAPTCHA_SECRET_KEY'),
],
'canny' => [
'api_key' => env('CANNY_API_KEY'),
],

View File

@ -0,0 +1,21 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class () extends Migration {
public function up()
{
Schema::table('forms', function (Blueprint $table) {
$table->string('captcha_provider')->default('hcaptcha')->after('use_captcha');
});
}
public function down()
{
Schema::table('forms', function (Blueprint $table) {
$table->dropColumn('captcha_provider');
});
}
};

View File

@ -116,4 +116,6 @@ return [
'attributes' => [],
'invalid_json' => 'إدخال غير صالح. يرجى التصحيح والمحاولة مرة أخرى.',
'invalid_captcha' => 'التحقق من صحة الحقل غير صحيح. يرجى التحقق من صحة الحقل والمحاولة مرة أخرى.',
'complete_captcha' => 'يرجى إكمال التحقق من صحة الحقل.',
];

View File

@ -116,4 +116,6 @@ return [
'attributes' => [],
'invalid_json' => 'অবৈধ ইনপুট। অনুগ্রহ করে সংশোধন করে আবার চেষ্টা করুন।',
'invalid_captcha' => 'অবৈধ টিপস। অনুগ্রহ করে টিপস টিপুন।',
'complete_captcha' => 'অনুগ্রহ করে টিপস টিপুন।',
];

View File

@ -116,4 +116,6 @@ return [
'attributes' => [],
'invalid_json' => 'Ungültige Eingabe. Bitte korrigieren Sie und versuchen Sie es erneut.',
'invalid_captcha' => 'Ungültige CAPTCHA. Bitte beweisen Sie, dass Sie kein Bot sind.',
'complete_captcha' => 'Bitte füllen Sie die CAPTCHA aus.',
];

View File

@ -150,5 +150,7 @@ return [
'attributes' => [],
'invalid_json' => 'Invalid input. Please correct and try again.',
'invalid_captcha' => 'Invalid CAPTCHA. Please prove you\'re not a bot.',
'complete_captcha' => 'Please complete the captcha.',
];

View File

@ -153,5 +153,7 @@ return [
],
'invalid_json' => 'Entrada no válida. Por favor, corrija e intente nuevamente.',
'invalid_captcha' => 'Captcha no válido. Por favor, demuestre que no es un bot.',
'complete_captcha' => 'Por favor, complete el captcha.',
];

View File

@ -116,4 +116,6 @@ return [
'attributes' => [],
'invalid_json' => 'Entrée invalide. Veuillez corriger et réessayer.',
'invalid_captcha' => 'Captcha invalide. Veuillez prouver que vous n\'êtes pas un bot.',
'complete_captcha' => 'Veuillez compléter le captcha.',
];

View File

@ -116,4 +116,6 @@ return [
'attributes' => [],
'invalid_json' => 'अमान्य इनपुट। कृपया सुधारें और पुनः प्रयास करें।',
'invalid_captcha' => 'अमान्य कैप्चा। कृपया दिखाएं कि आप एक बॉट नहीं हैं।',
'complete_captcha' => 'कृपया कैप्चा भरें।',
];

View File

@ -116,4 +116,6 @@ return [
'attributes' => [],
'invalid_json' => '無効な入力です。修正して再度お試しください。',
'invalid_captcha' => '無効なCAPTCHAです。ボットではないことを証明してください。',
'complete_captcha' => 'CAPTCHAを完了してください。',
];

View File

@ -116,4 +116,6 @@ return [
'attributes' => [],
'invalid_json' => 'Input ora valid. Mangga dibenakake lan dicoba maneh.',
'invalid_captcha' => 'CAPTCHA ora valid. Mangga dibenakake lan dicoba maneh.',
'complete_captcha' => 'CAPTCHA kudu diisi.',
];

View File

@ -116,4 +116,6 @@ return [
'attributes' => [],
'invalid_json' => '잘못된 입력입니다. 수정 후 다시 시도해 주세요.',
'invalid_captcha' => '잘못된 캡차입니다. 봇이 아님을 증명해 주세요.',
'complete_captcha' => '캡차를 완료해 주세요.',
];

View File

@ -133,4 +133,6 @@ return [
'attributes' => [],
'invalid_json' => 'अवैध इनपुट. कृपया सुधारून पुन्हा प्रयत्न करा.',
'invalid_captcha' => 'अवैध कैप्चा। कृपया कैप्चा टिपला आणि पुन्हा प्रयत्न करा।',
'complete_captcha' => 'कृपया कैप्चा भरा.',
];

View File

@ -115,5 +115,7 @@ return [
'attributes' => [],
'invalid_json' => 'ਗਲਤ ਇਨਪੁਟ। ਕਿਰਪਾ ਕਰਕੇ ਸਹੀ ਕਰੋ ਅਤੇ ਦੁਬਾਰਾ ਕੋਸ਼ਿਸ਼ ਕਰੋ।',
'invalid_json' => 'ਗਲਤ ਇਨਪੁਟ। ਕਿਰਪਾ ਕਰਕਕੇ ਸਹੀ ਕਰੋ ਅਤੇ ਦੁਬਾਰਾ ਕੋਸ਼ਿਸ਼ ਕਰੋ।',
'invalid_captcha' => 'ਗਲਤ ਕੈਪਚਾ। ਕਿਰਪਾ ਕਰੋ ਕੈਪਚਾ ਟੀਪ ਅਤੇ ਦੁਬਾਰਾ ਕੋਸ਼ਿਸ਼ ਕਰੋ।',
'complete_captcha' => 'ਕਿਰਪਾ ਕਰੋ ਕੈਪਚਾ ਭਰੋ।',
];

View File

@ -180,4 +180,6 @@ return [
],
'invalid_json' => 'Entrada inválida. Por favor, corrija e tente novamente.',
'invalid_captcha' => 'Captcha inválido. Por favor, demonstre que não é um bot.',
'complete_captcha' => 'Por favor, complete o captcha.',
];

View File

@ -116,4 +116,6 @@ return [
'attributes' => [],
'invalid_json' => 'Entrada inválida. Por favor, corrija e tente novamente.',
'invalid_captcha' => 'Captcha inválido. Por favor, demonstre que não é um bot.',
'complete_captcha' => 'Por favor, complete o captcha.',
];

View File

@ -116,4 +116,6 @@ return [
'attributes' => [],
'invalid_json' => 'Неверный ввод. Пожалуйста, исправьте и попробуйте снова.',
'invalid_captcha' => 'Неверный CAPTCHA. Пожалуйста, докажите, что вы не бот.',
'complete_captcha' => 'Пожалуйста, заполните CAPTCHA.',
];

View File

@ -133,4 +133,6 @@ return [
'attributes' => [],
'invalid_json' => 'தவறான உள்ளீடு. சரிசெய்து மீண்டும் முயற்சிக்கவும்.',
'invalid_captcha' => 'தவறான கையால் வைத்த முறை. மீண்டும் முயற்சிக்கவும்.',
'complete_captcha' => 'கையால் வைத்த முறையை நிரப்பவும்.',
];

View File

@ -116,4 +116,6 @@ return [
'attributes' => [],
'invalid_json' => 'చెల్లని ఇన్‌పుట్. దయచేసి సరిచేసి మళ్లీ ప్రయత్నించండి.',
'invalid_captcha' => 'అవైధ క్యాప్చా. దయచేసి క్యాప్చా టైప్ మరియు మళ్లీ ప్రయత్నించండి.',
'complete_captcha' => 'దయచేసి క్యాప్చా భరించండి.',
];

View File

@ -133,4 +133,6 @@ return [
'attributes' => [],
'invalid_json' => 'Geçersiz girdi. Lütfen düzeltin ve tekrar deneyin.',
'invalid_captcha' => 'Geçersiz CAPTCHA. Lütfen bot olmadığınızı gösterin.',
'complete_captcha' => 'Lütfen CAPTCHA\'yı tamamlayın.',
];

View File

@ -116,4 +116,6 @@ return [
'attributes' => [],
'invalid_json' => 'غلط ان پٹ۔ براہ کرم درست کریں اور دوبارہ کوشش کریں۔',
'invalid_captcha' => 'غلط کپچا۔ براہ کرم کپچا ٹائپ کریں اور دوبارہ کوشش کریں۔',
'complete_captcha' => 'براہ کرم کپچا پر کام کریں۔',
];

View File

@ -116,4 +116,6 @@ return [
'attributes' => [],
'invalid_json' => 'Dữ liệu không hợp lệ. Vui lòng sửa và thử lại.',
'invalid_captcha' => 'Mã bảo vệ không đúng. Vui lòng nhập lại và thử lại.',
'complete_captcha' => 'Vui lòng nhập mã bảo vệ.',
];

View File

@ -96,4 +96,6 @@ return [
'attributes' => [],
'invalid_json' => '输入无效。请修正后重试。',
'invalid_captcha' => '验证码错误。请重新输入并重试。',
'complete_captcha' => '请完成验证码。',
];

View File

@ -116,4 +116,6 @@ return [
'attributes' => [],
'invalid_json' => '输入无效。请修正后重试。',
'invalid_captcha' => '验证码错误。请重新输入并重试。',
'complete_captcha' => '请完成验证码。',
];

View File

@ -1,10 +1,11 @@
<?php
it('create form with captcha and raise validation issue', function () {
it('create form with hcaptcha and raise validation issue', function () {
$user = $this->actingAsUser();
$workspace = $this->createUserWorkspace($user);
$form = $this->createForm($user, $workspace, [
'use_captcha' => true,
'captcha_provider' => 'hcaptcha',
]);
$this->postJson(route('forms.answer', $form->slug), [])
@ -18,3 +19,23 @@ it('create form with captcha and raise validation issue', function () {
],
]);
});
it('create form with recaptcha and raise validation issue', function () {
$user = $this->actingAsUser();
$workspace = $this->createUserWorkspace($user);
$form = $this->createForm($user, $workspace, [
'use_captcha' => true,
'captcha_provider' => 'recaptcha',
]);
$this->postJson(route('forms.answer', $form->slug), [])
->assertStatus(422)
->assertJson([
'message' => 'Please complete the captcha.',
'errors' => [
'g-recaptcha-response' => [
'Please complete the captcha.',
],
],
]);
});

View File

@ -1,13 +1,13 @@
<?php
use App\Models\User;
use App\Rules\ValidHCaptcha;
use App\Rules\ValidReCaptcha;
use Illuminate\Support\Facades\Http;
it('can register', function () {
Http::fake([
ValidHCaptcha::H_CAPTCHA_VERIFY_URL => Http::response(['success' => true])
ValidReCaptcha::RECAPTCHA_VERIFY_URL => Http::response(['success' => true])
]);
$this->postJson('/register', [
@ -17,7 +17,7 @@ it('can register', function () {
'password' => 'secret',
'password_confirmation' => 'secret',
'agree_terms' => true,
'h-captcha-response' => 'test-token', // Mock token for testing
'g-recaptcha-response' => 'test-token', // Mock token for testing
])
->assertSuccessful()
->assertJsonStructure(['id', 'name', 'email']);
@ -36,7 +36,7 @@ it('cannot register with existing email', function () {
'email' => 'test@test.app',
'password' => 'secret',
'password_confirmation' => 'secret',
'h-captcha-response' => 'test-token',
'g-recaptcha-response' => 'test-token',
])
->assertStatus(422)
->assertJsonValidationErrors(['email']);
@ -44,7 +44,7 @@ it('cannot register with existing email', function () {
it('cannot register with disposable email', function () {
Http::fake([
ValidHCaptcha::H_CAPTCHA_VERIFY_URL => Http::response(['success' => true])
ValidReCaptcha::RECAPTCHA_VERIFY_URL => Http::response(['success' => true])
]);
// Select random email
@ -62,7 +62,7 @@ it('cannot register with disposable email', function () {
'password' => 'secret',
'password_confirmation' => 'secret',
'agree_terms' => true,
'h-captcha-response' => 'test-token',
'g-recaptcha-response' => 'test-token',
])
->assertStatus(422)
->assertJsonValidationErrors(['email'])
@ -77,10 +77,10 @@ it('cannot register with disposable email', function () {
});
it('requires hcaptcha token in production', function () {
config(['services.h_captcha.secret_key' => 'test-key']);
config(['services.re_captcha.secret_key' => 'test-key']);
Http::fake([
ValidHCaptcha::H_CAPTCHA_VERIFY_URL => Http::response(['success' => true])
ValidReCaptcha::RECAPTCHA_VERIFY_URL => Http::response(['success' => true])
]);
$this->postJson('/register', [
@ -92,5 +92,5 @@ it('requires hcaptcha token in production', function () {
'agree_terms' => true,
])
->assertStatus(422)
->assertJsonValidationErrors(['h-captcha-response']);
->assertJsonValidationErrors(['g-recaptcha-response']);
});

View File

@ -6,4 +6,5 @@ NUXT_PUBLIC_CRISP_WEBSITE_ID=
NUXT_PUBLIC_ENV=
NUXT_PUBLIC_GOOGLE_ANALYTICS_CODE=
NUXT_PUBLIC_H_CAPTCHA_SITE_KEY=
NUXT_PUBLIC_RE_CAPTCHA_SITE_KEY=
NUXT_API_SECRET=secret

View File

@ -0,0 +1,179 @@
<template>
<div>
<div v-if="showCaptcha">
<RecaptchaV2
v-if="provider === 'recaptcha'"
:key="`recaptcha-${componentKey}`"
ref="captchaRef"
:sitekey="recaptchaSiteKey"
:theme="darkMode ? 'dark' : 'light'"
:language="language"
@verify="onCaptchaVerify"
@expired="onCaptchaExpired"
@opened="onCaptchaOpen"
@closed="onCaptchaClose"
/>
<HCaptchaV2
v-else
:key="`hcaptcha-${componentKey}`"
ref="captchaRef"
:sitekey="hCaptchaSiteKey"
:theme="darkMode ? 'dark' : 'light'"
:language="language"
@verify="onCaptchaVerify"
@expired="onCaptchaExpired"
@opened="onCaptchaOpen"
@closed="onCaptchaClose"
/>
</div>
<has-error
:form="form"
:field-id="formFieldName"
/>
</div>
</template>
<script setup>
import HCaptchaV2 from './HCaptchaV2.vue'
import RecaptchaV2 from './RecaptchaV2.vue'
const props = defineProps({
provider: {
type: String,
required: true,
validator: (value) => ['recaptcha', 'hcaptcha'].includes(value)
},
form: {
type: Object,
required: true
},
language: {
type: String,
required: true
},
darkMode: {
type: Boolean,
default: false
}
})
const config = useRuntimeConfig()
const recaptchaSiteKey = config.public.recaptchaSiteKey
const hCaptchaSiteKey = config.public.hCaptchaSiteKey
const captchaRef = ref(null)
const isIframe = ref(false)
const showCaptcha = ref(true)
const componentKey = ref(0)
const formFieldName = computed(() => props.provider === 'recaptcha' ? 'g-recaptcha-response' : 'h-captcha-response')
// Watch for provider changes to reset the form field
watch(() => props.provider, async (newProvider, oldProvider) => {
if (newProvider !== oldProvider) {
// Clear old provider's value
if (oldProvider === 'recaptcha') {
props.form['g-recaptcha-response'] = null
} else if (oldProvider === 'hcaptcha') {
props.form['h-captcha-response'] = null
}
// Force remount by toggling visibility and incrementing key
showCaptcha.value = false
// Wait longer to ensure complete cleanup
await new Promise(resolve => setTimeout(resolve, 1000))
componentKey.value++
await nextTick()
// Wait again before showing new captcha
await new Promise(resolve => setTimeout(resolve, 1000))
showCaptcha.value = true
}
})
onMounted(() => {
isIframe.value = window.self !== window.top
})
// Add a ref to track if captcha was completed
const wasCaptchaCompleted = ref(false)
// Handle captcha verification
const onCaptchaVerify = (token) => {
wasCaptchaCompleted.value = true
props.form[formFieldName.value] = token
// Also set the DOM element value for compatibility with existing code
if (import.meta.client) {
const element = document.getElementsByName(formFieldName.value)[0]
if (element) element.value = token
}
}
// Handle captcha expiration
const onCaptchaExpired = () => {
wasCaptchaCompleted.value = false
props.form[formFieldName.value] = null
// Also clear the DOM element value for compatibility with existing code
if (import.meta.client) {
const element = document.getElementsByName(formFieldName.value)[0]
if (element) element.value = ''
}
}
// Handle iframe resizing
const resizeIframe = (height) => {
if (!isIframe.value) return
try {
window.parentIFrame?.size(height)
} catch (e) {
// Silently handle error
}
}
// Handle captcha open/close for iframe resizing
const onCaptchaOpen = () => {
resizeIframe(500)
// Ensure the captcha is visible by scrolling to it
if (import.meta.client) {
nextTick(() => {
const captchaElement = captchaRef.value?.$el
if (captchaElement) {
captchaElement.scrollIntoView({ behavior: 'smooth', block: 'center' })
}
})
}
}
const onCaptchaClose = () => {
resizeIframe(0)
}
// Method to reset captcha - can be called from parent
defineExpose({
reset: () => {
// Only do a full reset if the captcha was previously completed
if (captchaRef.value) {
if (wasCaptchaCompleted.value) {
wasCaptchaCompleted.value = false
captchaRef.value.reset()
}
}
}
})
</script>
<style>
.fade-enter-active,
.fade-leave-active {
transition: opacity 0.2s ease;
}
.fade-enter-from,
.fade-leave-to {
opacity: 0;
}
</style>

View File

@ -0,0 +1,186 @@
<template>
<div class="hcaptcha-container">
<div ref="hcaptchaContainer" />
</div>
</template>
<script setup>
const props = defineProps({
sitekey: {
type: String,
required: true
},
theme: {
type: String,
default: 'light'
},
language: {
type: String,
default: 'en'
}
})
const emit = defineEmits(['verify', 'expired', 'opened', 'closed'])
const hcaptchaContainer = ref(null)
let widgetId = null
// Global script loading state
const SCRIPT_ID = 'hcaptcha-script'
let scriptLoadPromise = null
// Add this cleanup function at the script level
const cleanupHcaptcha = () => {
// Remove all hCaptcha iframes
document.querySelectorAll('iframe[src*="hcaptcha.com"]').forEach(iframe => {
iframe.remove()
})
// Remove all hCaptcha scripts
document.querySelectorAll('script[src*="hcaptcha.com"]').forEach(script => {
script.remove()
})
// Remove specific script
const script = document.getElementById(SCRIPT_ID)
if (script) {
script.remove()
}
// Remove hCaptcha styles
document.querySelectorAll('style[data-emotion]').forEach(style => {
style.remove()
})
// Clean up global variables
if (window.hcaptcha) {
delete window.hcaptcha
}
// Clean up any potential callbacks
Object.keys(window).forEach(key => {
if (key.startsWith('hcaptchaOnLoad_')) {
delete window[key]
}
})
scriptLoadPromise = null
}
const loadHcaptchaScript = () => {
if (scriptLoadPromise) return scriptLoadPromise
// Clean up before loading new script
cleanupHcaptcha()
scriptLoadPromise = new Promise((resolve, reject) => {
// If hcaptcha is already available and ready, use it
if (window.hcaptcha?.render) {
resolve(window.hcaptcha)
return
}
// Create a unique callback name
const callbackName = `hcaptchaOnLoad_${Date.now()}`
// Create the script
const script = document.createElement('script')
script.id = SCRIPT_ID
script.src = `https://js.hcaptcha.com/1/api.js?render=explicit&onload=${callbackName}&recaptchacompat=off`
script.async = true
script.defer = true
let timeoutId = null
// Set up the callback before adding the script
window[callbackName] = () => {
if (timeoutId) clearTimeout(timeoutId)
if (window.hcaptcha?.render) {
resolve(window.hcaptcha)
delete window[callbackName]
} else {
reject(new Error('hCaptcha failed to initialize'))
}
}
script.onerror = (error) => {
if (timeoutId) clearTimeout(timeoutId)
delete window[callbackName]
scriptLoadPromise = null
reject(error)
}
timeoutId = setTimeout(() => {
delete window[callbackName]
scriptLoadPromise = null
reject(new Error('hCaptcha script load timeout'))
}, 10000)
document.head.appendChild(script)
})
return scriptLoadPromise
}
const renderHcaptcha = async () => {
try {
// Clear any existing content first
if (hcaptchaContainer.value) {
hcaptchaContainer.value.innerHTML = ''
}
const hcaptcha = await loadHcaptchaScript()
// Double check container still exists after async operation
if (!hcaptchaContainer.value) return
// Render new widget
widgetId = hcaptcha.render(hcaptchaContainer.value, {
sitekey: props.sitekey,
theme: props.theme,
hl: props.language,
'callback': (token) => emit('verify', token),
'expired-callback': () => emit('expired'),
'error-callback': () => {
if (widgetId !== null) {
hcaptcha.reset(widgetId)
}
},
'open-callback': () => emit('opened'),
'close-callback': () => emit('closed')
})
} catch (error) {
scriptLoadPromise = null // Reset promise on error
}
}
onMounted(() => {
renderHcaptcha()
})
onBeforeUnmount(() => {
// Clean up widget and reset state
if (window.hcaptcha && widgetId !== null) {
try {
window.hcaptcha.remove(widgetId)
} catch (e) {
// Silently handle error
}
}
cleanupHcaptcha()
if (hcaptchaContainer.value) {
hcaptchaContainer.value.innerHTML = ''
}
widgetId = null
})
// Expose reset method that properly reloads the captcha
defineExpose({
reset: async () => {
cleanupHcaptcha()
await renderHcaptcha()
}
})
</script>

View File

@ -0,0 +1,179 @@
<template>
<div class="recaptcha-container">
<div ref="recaptchaContainer" />
</div>
</template>
<script setup>
const props = defineProps({
sitekey: {
type: String,
required: true
},
theme: {
type: String,
default: 'light'
},
language: {
type: String,
default: 'en'
}
})
const emit = defineEmits(['verify', 'expired', 'opened', 'closed'])
const recaptchaContainer = ref(null)
let widgetId = null
// Global script loading state
const SCRIPT_ID = 'recaptcha-script'
let scriptLoadPromise = null
// Add cleanup function similar to hCaptcha
const cleanupRecaptcha = () => {
// Remove all reCAPTCHA iframes
document.querySelectorAll('iframe[src*="google.com/recaptcha"]').forEach(iframe => {
iframe.remove()
})
// Remove all reCAPTCHA scripts
document.querySelectorAll('script[src*="google.com/recaptcha"]').forEach(script => {
script.remove()
})
// Remove specific script
const script = document.getElementById(SCRIPT_ID)
if (script) {
script.remove()
}
// Clean up global variables
if (window.grecaptcha) {
delete window.grecaptcha
}
scriptLoadPromise = null
}
const loadRecaptchaScript = () => {
if (scriptLoadPromise) return scriptLoadPromise
// Clean up before loading new script
cleanupRecaptcha()
scriptLoadPromise = new Promise((resolve, reject) => {
// If grecaptcha is already available and ready, use it
if (window.grecaptcha?.render) {
resolve(window.grecaptcha)
return
}
const script = document.createElement('script')
script.id = SCRIPT_ID
script.src = 'https://www.google.com/recaptcha/api.js?render=explicit'
script.async = true
script.defer = true
let timeoutId = null
script.onload = () => {
const checkGrecaptcha = () => {
if (window.grecaptcha?.render) {
if (timeoutId) clearTimeout(timeoutId)
resolve(window.grecaptcha)
} else {
setTimeout(checkGrecaptcha, 100)
}
}
checkGrecaptcha()
}
script.onerror = (error) => {
if (timeoutId) clearTimeout(timeoutId)
scriptLoadPromise = null
reject(error)
}
timeoutId = setTimeout(() => {
scriptLoadPromise = null
reject(new Error('reCAPTCHA script load timeout'))
}, 10000)
document.head.appendChild(script)
})
return scriptLoadPromise
}
const renderRecaptcha = async () => {
try {
// Clear any existing content first
if (recaptchaContainer.value) {
recaptchaContainer.value.innerHTML = ''
}
const grecaptcha = await loadRecaptchaScript()
// Double check container still exists after async operation
if (!recaptchaContainer.value) return
// Render new widget
widgetId = grecaptcha.render(recaptchaContainer.value, {
sitekey: props.sitekey,
theme: props.theme,
hl: props.language,
callback: (token) => emit('verify', token),
'expired-callback': () => emit('expired'),
'error-callback': () => {
if (widgetId !== null) {
grecaptcha.reset(widgetId)
}
}
})
} catch (error) {
scriptLoadPromise = null // Reset promise on error
}
}
onMounted(() => {
renderRecaptcha()
})
onBeforeUnmount(() => {
// Clean up widget and reset state
if (window.grecaptcha && widgetId !== null) {
try {
window.grecaptcha.reset(widgetId)
} catch (e) {
// Silently handle error
}
}
cleanupRecaptcha()
if (recaptchaContainer.value) {
recaptchaContainer.value.innerHTML = ''
}
widgetId = null
})
// Expose reset method that properly reloads the captcha
defineExpose({
reset: async () => {
if (window.grecaptcha && widgetId !== null) {
try {
// Try simple reset first
window.grecaptcha.reset(widgetId)
} catch (e) {
// If simple reset fails, do a full cleanup and reload
cleanupRecaptcha()
await renderRecaptcha()
}
} else {
// If no widget exists, do a full reload
cleanupRecaptcha()
await renderRecaptcha()
}
}
})
</script>

View File

@ -76,21 +76,16 @@
</transition>
<!-- Captcha -->
<template v-if="form.use_captcha && isLastPage">
<div class="mb-3 px-2 mt-2 mx-auto w-max">
<vue-hcaptcha
ref="hcaptcha"
:sitekey="hCaptchaSiteKey"
:theme="darkMode?'dark':'light'"
@opened="setMinHeight(500)"
@closed="setMinHeight(0)"
/>
<has-error
:form="dataForm"
field-id="h-captcha-response"
/>
</div>
</template>
<div class="mb-3 px-2 mt-4 mx-auto w-max">
<CaptchaInput
v-if="form.use_captcha && isLastPage"
ref="captcha"
:provider="form.captcha_provider"
:form="dataForm"
:language="form.language"
:dark-mode="darkMode"
/>
</div>
<!-- Submit, Next and previous buttons -->
<div class="flex flex-wrap justify-center w-full">
@ -132,7 +127,7 @@
import clonedeep from 'clone-deep'
import draggable from 'vuedraggable'
import OpenFormButton from './OpenFormButton.vue'
import VueHcaptcha from "@hcaptcha/vue3-hcaptcha"
import CaptchaInput from '~/components/forms/components/CaptchaInput.vue'
import OpenFormField from './OpenFormField.vue'
import {pendingSubmission} from "~/composables/forms/pendingSubmission.js"
import FormLogicPropertyResolver from "~/lib/forms/FormLogicPropertyResolver.js"
@ -143,7 +138,7 @@ import { storeToRefs } from 'pinia'
export default {
name: 'OpenForm',
components: {draggable, OpenFormField, OpenFormButton, VueHcaptcha, FormTimer},
components: {draggable, OpenFormField, OpenFormButton, CaptchaInput, FormTimer},
props: {
form: {
type: Object,
@ -206,14 +201,10 @@ export default {
* Used to force refresh components by changing their keys
*/
isAutoSubmit: false,
minHeight: 0
}
},
computed: {
hCaptchaSiteKey() {
return useRuntimeConfig().public.hCaptchaSiteKey
},
/**
* Create field groups (or Page) using page breaks if any
*/
@ -309,7 +300,6 @@ export default {
},
computedStyle() {
return {
...this.minHeight ? {minHeight: this.minHeight + 'px'} : {},
'--form-color': this.form.color
}
}
@ -369,8 +359,7 @@ export default {
if (!this.isAutoSubmit && this.formPageIndex !== this.fieldGroups.length - 1) return
if (this.form.use_captcha && import.meta.client) {
this.dataForm['h-captcha-response'] = document.getElementsByName('h-captcha-response')[0].value
this.$refs.hcaptcha.reset()
this.$refs.captcha?.reset()
}
if (this.form.editable_submissions && this.form.submission_id) {
@ -584,16 +573,6 @@ export default {
}
this.formPageIndex = this.fieldGroups.length - 1
},
setMinHeight(minHeight) {
if (!this.isIframe) return
this.minHeight = minHeight
try {
window.parentIFrame.size()
} catch (e) {
console.error(e)
}
}
}
}
</script>

View File

@ -72,29 +72,32 @@
<p class="text-gray-500 text-sm">
Protect your form, and your sensitive files.
</p>
<ToggleSwitchInput
name="use_captcha"
:form="form"
class="mt-4"
label="Bot Protection"
help="Protects your form from spam and abuse with a captcha"
/>
<div class="flex items-start gap-6 flex-wrap">
<ToggleSwitchInput
name="use_captcha"
:form="form"
class="mt-4"
label="Bot Protection"
help="Protects your form from spam and abuse with a captcha"
/>
<FlatSelectInput
v-if="form.use_captcha"
name="captcha_provider"
:form="form"
:options="captchaOptions"
class="mt-4 w-80"
label="Select a captcha provider"
/>
</div>
</SettingsSection>
</template>
<script>
import { useWorkingFormStore } from '../../../../../stores/working_form'
<script setup>
const workingFormStore = useWorkingFormStore()
const { content: form } = storeToRefs(workingFormStore)
export default {
components: { },
props: {},
setup () {
const workingFormStore = useWorkingFormStore()
return {
workingFormStore,
form: storeToRefs(workingFormStore).content,
crisp: useCrisp()
}
}
}
const captchaOptions = [
{ name: 'reCAPTCHA', value: 'recaptcha' },
{ name: 'hCaptcha', value: 'hcaptcha' },
]
</script>

View File

@ -52,18 +52,16 @@
label="Confirm Password"
/>
<!-- hCaptcha -->
<!-- Captcha -->
<div
v-if="hCaptchaSiteKey"
class="mb-3 px-2 mt-2 mx-auto w-max"
v-if="recaptchaSiteKey"
class="my-4 px-2 mx-auto w-max"
>
<vue-hcaptcha
ref="hcaptcha"
:sitekey="hCaptchaSiteKey"
/>
<has-error
<CaptchaInput
ref="captcha"
provider="recaptcha"
:form="form"
field-id="h-captcha-response"
language="en"
/>
</div>
@ -141,11 +139,10 @@
<script>
import {opnFetch} from "~/composables/useOpnApi.js"
import { fetchAllWorkspaces } from "~/stores/workspaces.js"
import VueHcaptcha from '@hcaptcha/vue3-hcaptcha'
export default {
name: "RegisterForm",
components: {VueHcaptcha},
components: {},
props: {
isQuick: {
type: Boolean,
@ -177,15 +174,14 @@ export default {
agree_terms: false,
appsumo_license: null,
utm_data: null,
'h-captcha-response': null
'g-recaptcha-response': null
}),
disableEmail: false,
hcaptcha: null
}),
computed: {
hCaptchaSiteKey() {
return this.runtimeConfig.public.hCaptchaSiteKey
recaptchaSiteKey() {
return this.runtimeConfig.public.recaptchaSiteKey
},
hearAboutUsOptions() {
const options = [
@ -209,10 +205,6 @@ export default {
},
mounted() {
if (this.hCaptchaSiteKey) {
this.hcaptcha = this.$refs.hcaptcha
}
// Set appsumo license
if (
this.$route.query.appsumo_license !== undefined &&
@ -234,9 +226,9 @@ export default {
async register() {
let data
this.form.utm_data = this.$utm.value
if (this.hCaptchaSiteKey) {
this.form['h-captcha-response'] = document.getElementsByName('h-captcha-response')[0].value
this.hcaptcha.reset()
// Reset captcha after submission
if (import.meta.client && this.recaptchaSiteKey) {
this.$refs.captcha.reset()
}
try {
// Register the user.

View File

@ -36,6 +36,7 @@ export const initForm = (defaultValue = {}, withDefaultProperties = false) => {
submitted_text:
"Amazing, we saved your answers. Thank you for your time and have a great day!",
use_captcha: false,
captcha_provider: 'recaptcha',
max_submissions_count: null,
max_submissions_reached_text:
"This form has now reached the maximum number of allowed submissions and is now closed.",
@ -105,6 +106,7 @@ export function setFormDefaults(formData) {
bypass_success_page: false,
can_be_indexed: true,
use_captcha: false,
captcha_provider: 'recaptcha',
properties: [],
}

View File

@ -36,7 +36,6 @@
},
"dependencies": {
"@codemirror/lang-html": "^6.4.9",
"@hcaptcha/vue3-hcaptcha": "^1.3.0",
"@iconify-json/material-symbols": "^1.2.4",
"@nuxt/ui": "^2.19.2",
"@pinia/nuxt": "^0.5.5",

View File

@ -19,6 +19,7 @@ export default {
appUrl: process.env.NUXT_PUBLIC_APP_URL || '',
env: process.env.NUXT_PUBLIC_ENV || 'local',
hCaptchaSiteKey: process.env.NUXT_PUBLIC_H_CAPTCHA_SITE_KEY || null,
recaptchaSiteKey: process.env.NUXT_PUBLIC_RE_CAPTCHA_SITE_KEY || null,
gtmCode: process.env.NUXT_PUBLIC_GTM_CODE || null,
amplitudeCode: process.env.NUXT_PUBLIC_AMPLITUDE_CODE || null,
crispWebsiteId: process.env.NUXT_PUBLIC_CRISP_WEBSITE_ID || null,