Skip to content

Commit

Permalink
Add reCAPTCHA support and update captcha provider handling (#647)
Browse files Browse the repository at this point in the history
* 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 <[email protected]>
  • Loading branch information
chiragchhatrala and JhumanJ authored Dec 18, 2024
1 parent 7365479 commit d7ce853
Show file tree
Hide file tree
Showing 43 changed files with 770 additions and 97 deletions.
3 changes: 3 additions & 0 deletions api/.env.example
Original file line number Diff line number Diff line change
Expand Up @@ -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=

Expand Down
6 changes: 3 additions & 3 deletions api/app/Http/Controllers/Auth/RegisterController.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
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
{
Expand Down Expand Up @@ -71,8 +71,8 @@ protected function validator(array $data)
'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, [
Expand Down
9 changes: 7 additions & 2 deletions api/app/Http/Requests/AnswerFormRequest.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
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;
Expand Down Expand Up @@ -116,9 +117,13 @@ public function rules()
$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
Expand Down
1 change: 1 addition & 0 deletions api/app/Http/Requests/UserFormRequest.php
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,7 @@ public function rules()
'can_be_indexed' => 'boolean',
'password' => 'sometimes|nullable',
'use_captcha' => 'boolean',
'captcha_provider' => ['sometimes', Rule::in(['recaptcha', 'hcaptcha'])],

// Custom SEO
'seo_meta' => 'nullable|array',
Expand Down
1 change: 1 addition & 0 deletions api/app/Models/Forms/Form.php
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand Down
6 changes: 3 additions & 3 deletions api/app/Rules/ValidHCaptcha.php
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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;
}
Expand All @@ -46,6 +46,6 @@ public function validate(string $attribute, mixed $value, Closure $fail): void
*/
public function message()
{
return $this->error;
return trans($this->error);
}
}
51 changes: 51 additions & 0 deletions api/app/Rules/ValidReCaptcha.php
Original file line number Diff line number Diff line change
@@ -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);
}
}
5 changes: 5 additions & 0 deletions api/config/services.php
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,11 @@
'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'),
],
Expand Down
Original file line number Diff line number Diff line change
@@ -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');
});
}
};
2 changes: 2 additions & 0 deletions api/resources/lang/ar/validation.php
Original file line number Diff line number Diff line change
Expand Up @@ -116,4 +116,6 @@
'attributes' => [],

'invalid_json' => 'إدخال غير صالح. يرجى التصحيح والمحاولة مرة أخرى.',
'invalid_captcha' => 'التحقق من صحة الحقل غير صحيح. يرجى التحقق من صحة الحقل والمحاولة مرة أخرى.',
'complete_captcha' => 'يرجى إكمال التحقق من صحة الحقل.',
];
2 changes: 2 additions & 0 deletions api/resources/lang/bn/validation.php
Original file line number Diff line number Diff line change
Expand Up @@ -116,4 +116,6 @@
'attributes' => [],

'invalid_json' => 'অবৈধ ইনপুট। অনুগ্রহ করে সংশোধন করে আবার চেষ্টা করুন।',
'invalid_captcha' => 'অবৈধ টিপস। অনুগ্রহ করে টিপস টিপুন।',
'complete_captcha' => 'অনুগ্রহ করে টিপস টিপুন।',
];
2 changes: 2 additions & 0 deletions api/resources/lang/de/validation.php
Original file line number Diff line number Diff line change
Expand Up @@ -116,4 +116,6 @@
'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.',
];
2 changes: 2 additions & 0 deletions api/resources/lang/en/validation.php
Original file line number Diff line number Diff line change
Expand Up @@ -150,5 +150,7 @@
'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.',

];
2 changes: 2 additions & 0 deletions api/resources/lang/es/validation.php
Original file line number Diff line number Diff line change
Expand Up @@ -153,5 +153,7 @@
],

'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.',

];
2 changes: 2 additions & 0 deletions api/resources/lang/fr/validation.php
Original file line number Diff line number Diff line change
Expand Up @@ -116,4 +116,6 @@
'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.',
];
2 changes: 2 additions & 0 deletions api/resources/lang/hi/validation.php
Original file line number Diff line number Diff line change
Expand Up @@ -116,4 +116,6 @@
'attributes' => [],

'invalid_json' => 'अमान्य इनपुट। कृपया सुधारें और पुनः प्रयास करें।',
'invalid_captcha' => 'अमान्य कैप्चा। कृपया दिखाएं कि आप एक बॉट नहीं हैं।',
'complete_captcha' => 'कृपया कैप्चा भरें।',
];
2 changes: 2 additions & 0 deletions api/resources/lang/ja/validation.php
Original file line number Diff line number Diff line change
Expand Up @@ -116,4 +116,6 @@
'attributes' => [],

'invalid_json' => '無効な入力です。修正して再度お試しください。',
'invalid_captcha' => '無効なCAPTCHAです。ボットではないことを証明してください。',
'complete_captcha' => 'CAPTCHAを完了してください。',
];
2 changes: 2 additions & 0 deletions api/resources/lang/jv/validation.php
Original file line number Diff line number Diff line change
Expand Up @@ -116,4 +116,6 @@
'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.',
];
2 changes: 2 additions & 0 deletions api/resources/lang/ko/validation.php
Original file line number Diff line number Diff line change
Expand Up @@ -116,4 +116,6 @@
'attributes' => [],

'invalid_json' => '잘못된 입력입니다. 수정 후 다시 시도해 주세요.',
'invalid_captcha' => '잘못된 캡차입니다. 봇이 아님을 증명해 주세요.',
'complete_captcha' => '캡차를 완료해 주세요.',
];
2 changes: 2 additions & 0 deletions api/resources/lang/mr/validation.php
Original file line number Diff line number Diff line change
Expand Up @@ -133,4 +133,6 @@
'attributes' => [],

'invalid_json' => 'अवैध इनपुट. कृपया सुधारून पुन्हा प्रयत्न करा.',
'invalid_captcha' => 'अवैध कैप्चा। कृपया कैप्चा टिपला आणि पुन्हा प्रयत्न करा।',
'complete_captcha' => 'कृपया कैप्चा भरा.',
];
4 changes: 3 additions & 1 deletion api/resources/lang/pa/validation.php
Original file line number Diff line number Diff line change
Expand Up @@ -115,5 +115,7 @@

'attributes' => [],

'invalid_json' => 'ਗਲਤ ਇਨਪੁਟ। ਕਿਰਪਾ ਕਰਕੇ ਸਹੀ ਕਰੋ ਅਤੇ ਦੁਬਾਰਾ ਕੋਸ਼ਿਸ਼ ਕਰੋ।',
'invalid_json' => 'ਗਲਤ ਇਨਪੁਟ। ਕਿਰਪਾ ਕਰਕਕੇ ਸਹੀ ਕਰੋ ਅਤੇ ਦੁਬਾਰਾ ਕੋਸ਼ਿਸ਼ ਕਰੋ।',
'invalid_captcha' => 'ਗਲਤ ਕੈਪਚਾ। ਕਿਰਪਾ ਕਰੋ ਕੈਪਚਾ ਟੀਪ ਅਤੇ ਦੁਬਾਰਾ ਕੋਸ਼ਿਸ਼ ਕਰੋ।',
'complete_captcha' => 'ਕਿਰਪਾ ਕਰੋ ਕੈਪਚਾ ਭਰੋ।',
];
2 changes: 2 additions & 0 deletions api/resources/lang/pt-BR/validation.php
Original file line number Diff line number Diff line change
Expand Up @@ -180,4 +180,6 @@
],

'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.',
];
2 changes: 2 additions & 0 deletions api/resources/lang/pt/validation.php
Original file line number Diff line number Diff line change
Expand Up @@ -116,4 +116,6 @@
'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.',
];
2 changes: 2 additions & 0 deletions api/resources/lang/ru/validation.php
Original file line number Diff line number Diff line change
Expand Up @@ -116,4 +116,6 @@
'attributes' => [],

'invalid_json' => 'Неверный ввод. Пожалуйста, исправьте и попробуйте снова.',
'invalid_captcha' => 'Неверный CAPTCHA. Пожалуйста, докажите, что вы не бот.',
'complete_captcha' => 'Пожалуйста, заполните CAPTCHA.',
];
2 changes: 2 additions & 0 deletions api/resources/lang/ta/validation.php
Original file line number Diff line number Diff line change
Expand Up @@ -133,4 +133,6 @@
'attributes' => [],

'invalid_json' => 'தவறான உள்ளீடு. சரிசெய்து மீண்டும் முயற்சிக்கவும்.',
'invalid_captcha' => 'தவறான கையால் வைத்த முறை. மீண்டும் முயற்சிக்கவும்.',
'complete_captcha' => 'கையால் வைத்த முறையை நிரப்பவும்.',
];
2 changes: 2 additions & 0 deletions api/resources/lang/te/validation.php
Original file line number Diff line number Diff line change
Expand Up @@ -116,4 +116,6 @@
'attributes' => [],

'invalid_json' => 'చెల్లని ఇన్‌పుట్. దయచేసి సరిచేసి మళ్లీ ప్రయత్నించండి.',
'invalid_captcha' => 'అవైధ క్యాప్చా. దయచేసి క్యాప్చా టైప్ మరియు మళ్లీ ప్రయత్నించండి.',
'complete_captcha' => 'దయచేసి క్యాప్చా భరించండి.',
];
2 changes: 2 additions & 0 deletions api/resources/lang/tr/validation.php
Original file line number Diff line number Diff line change
Expand Up @@ -133,4 +133,6 @@
'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.',
];
2 changes: 2 additions & 0 deletions api/resources/lang/ur/validation.php
Original file line number Diff line number Diff line change
Expand Up @@ -116,4 +116,6 @@
'attributes' => [],

'invalid_json' => 'غلط ان پٹ۔ براہ کرم درست کریں اور دوبارہ کوشش کریں۔',
'invalid_captcha' => 'غلط کپچا۔ براہ کرم کپچا ٹائپ کریں اور دوبارہ کوشش کریں۔',
'complete_captcha' => 'براہ کرم کپچا پر کام کریں۔',
];
2 changes: 2 additions & 0 deletions api/resources/lang/vi/validation.php
Original file line number Diff line number Diff line change
Expand Up @@ -116,4 +116,6 @@
'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ệ.',
];
2 changes: 2 additions & 0 deletions api/resources/lang/zh-CN/validation.php
Original file line number Diff line number Diff line change
Expand Up @@ -96,4 +96,6 @@
'attributes' => [],

'invalid_json' => '输入无效。请修正后重试。',
'invalid_captcha' => '验证码错误。请重新输入并重试。',
'complete_captcha' => '请完成验证码。',
];
2 changes: 2 additions & 0 deletions api/resources/lang/zh/validation.php
Original file line number Diff line number Diff line change
Expand Up @@ -116,4 +116,6 @@
'attributes' => [],

'invalid_json' => '输入无效。请修正后重试。',
'invalid_captcha' => '验证码错误。请重新输入并重试。',
'complete_captcha' => '请完成验证码。',
];
23 changes: 22 additions & 1 deletion api/tests/Feature/Forms/FormCaptchaTest.php
Original file line number Diff line number Diff line change
@@ -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), [])
Expand All @@ -18,3 +19,23 @@
],
]);
});

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

0 comments on commit d7ce853

Please sign in to comment.