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
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']);
});