Skip to content

Commit d7ce853

Browse files
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>
1 parent 7365479 commit d7ce853

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

43 files changed

+770
-97
lines changed

api/.env.example

+3
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,9 @@ STRIPE_TEST_DEFAULT_PRICING_YEARLY=
7272
H_CAPTCHA_SITE_KEY=
7373
H_CAPTCHA_SECRET_KEY=
7474

75+
RE_CAPTCHA_SITE_KEY=
76+
RE_CAPTCHA_SECRET_KEY=
77+
7578
MUX_WORKSPACE_ID=
7679
MUX_API_TOKEN=
7780

api/app/Http/Controllers/Auth/RegisterController.php

+3-3
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212
use Illuminate\Http\Request;
1313
use Illuminate\Support\Facades\Validator;
1414
use Illuminate\Validation\Rule;
15-
use App\Rules\ValidHCaptcha;
15+
use App\Rules\ValidReCaptcha;
1616

1717
class RegisterController extends Controller
1818
{
@@ -71,8 +71,8 @@ protected function validator(array $data)
7171
'utm_data' => ['nullable', 'array'],
7272
];
7373

74-
if (config('services.h_captcha.secret_key')) {
75-
$rules['h-captcha-response'] = [new ValidHCaptcha()];
74+
if (config('services.re_captcha.secret_key')) {
75+
$rules['g-recaptcha-response'] = [new ValidReCaptcha()];
7676
}
7777

7878
return Validator::make($data, $rules, [

api/app/Http/Requests/AnswerFormRequest.php

+7-2
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
use App\Rules\StorageFile;
99
use App\Rules\ValidHCaptcha;
1010
use App\Rules\ValidPhoneInputRule;
11+
use App\Rules\ValidReCaptcha;
1112
use App\Rules\ValidUrl;
1213
use App\Service\Forms\FormLogicPropertyResolver;
1314
use Illuminate\Foundation\Http\FormRequest;
@@ -116,9 +117,13 @@ public function rules()
116117
$this->requestRules[$propertyId] = $rules;
117118
}
118119

119-
// Validate hCaptcha
120+
// Validate Captcha
120121
if ($this->form->use_captcha) {
121-
$this->requestRules['h-captcha-response'] = [new ValidHCaptcha()];
122+
if ($this->form->captcha_provider === 'recaptcha') {
123+
$this->requestRules['g-recaptcha-response'] = [new ValidReCaptcha()];
124+
} elseif ($this->form->captcha_provider === 'hcaptcha') {
125+
$this->requestRules['h-captcha-response'] = [new ValidHCaptcha()];
126+
}
122127
}
123128

124129
// Validate submission_id for edit mode

api/app/Http/Requests/UserFormRequest.php

+1
Original file line numberDiff line numberDiff line change
@@ -118,6 +118,7 @@ public function rules()
118118
'can_be_indexed' => 'boolean',
119119
'password' => 'sometimes|nullable',
120120
'use_captcha' => 'boolean',
121+
'captcha_provider' => ['sometimes', Rule::in(['recaptcha', 'hcaptcha'])],
121122

122123
// Custom SEO
123124
'seo_meta' => 'nullable|array',

api/app/Models/Forms/Form.php

+1
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,7 @@ class Form extends Model implements CachableAttributes
8282
'submitted_text',
8383
'redirect_url',
8484
'use_captcha',
85+
'captcha_provider',
8586
'closes_at',
8687
'closed_text',
8788
'max_submissions_count',

api/app/Rules/ValidHCaptcha.php

+3-3
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ class ValidHCaptcha implements ImplicitRule
1010
{
1111
public const H_CAPTCHA_VERIFY_URL = 'https://hcaptcha.com/siteverify';
1212

13-
private $error = 'Invalid CAPTCHA. Please prove you\'re not a bot.';
13+
private $error = 'validation.invalid_captcha';
1414

1515
/**
1616
* Determine if the validation rule passes.
@@ -22,7 +22,7 @@ class ValidHCaptcha implements ImplicitRule
2222
public function passes($attribute, $value)
2323
{
2424
if (empty($value)) {
25-
$this->error = 'Please complete the captcha.';
25+
$this->error = 'validation.complete_captcha';
2626

2727
return false;
2828
}
@@ -46,6 +46,6 @@ public function validate(string $attribute, mixed $value, Closure $fail): void
4646
*/
4747
public function message()
4848
{
49-
return $this->error;
49+
return trans($this->error);
5050
}
5151
}

api/app/Rules/ValidReCaptcha.php

+51
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
<?php
2+
3+
namespace App\Rules;
4+
5+
use Closure;
6+
use Illuminate\Contracts\Validation\ImplicitRule;
7+
use Illuminate\Support\Facades\Http;
8+
9+
class ValidReCaptcha implements ImplicitRule
10+
{
11+
public const RECAPTCHA_VERIFY_URL = 'https://www.google.com/recaptcha/api/siteverify';
12+
13+
private $error = 'validation.invalid_captcha';
14+
15+
/**
16+
* Determine if the validation rule passes.
17+
*
18+
* @param string $attribute
19+
* @param mixed $value
20+
* @return bool
21+
*/
22+
public function passes($attribute, $value)
23+
{
24+
if (empty($value)) {
25+
$this->error = 'validation.complete_captcha';
26+
27+
return false;
28+
}
29+
30+
return Http::asForm()->post(self::RECAPTCHA_VERIFY_URL, [
31+
'secret' => config('services.re_captcha.secret_key'),
32+
'response' => $value,
33+
])->json('success');
34+
}
35+
public function validate(string $attribute, mixed $value, Closure $fail): void
36+
{
37+
if (!$this->passes($attribute, $value)) {
38+
$fail($this->message());
39+
}
40+
}
41+
42+
/**
43+
* Get the validation error message.
44+
*
45+
* @return string
46+
*/
47+
public function message()
48+
{
49+
return trans($this->error);
50+
}
51+
}

api/config/services.php

+5
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,11 @@
4040
'secret_key' => env('H_CAPTCHA_SECRET_KEY'),
4141
],
4242

43+
're_captcha' => [
44+
'site_key' => env('RE_CAPTCHA_SITE_KEY'),
45+
'secret_key' => env('RE_CAPTCHA_SECRET_KEY'),
46+
],
47+
4348
'canny' => [
4449
'api_key' => env('CANNY_API_KEY'),
4550
],
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
<?php
2+
3+
use Illuminate\Database\Migrations\Migration;
4+
use Illuminate\Database\Schema\Blueprint;
5+
use Illuminate\Support\Facades\Schema;
6+
7+
return new class () extends Migration {
8+
public function up()
9+
{
10+
Schema::table('forms', function (Blueprint $table) {
11+
$table->string('captcha_provider')->default('hcaptcha')->after('use_captcha');
12+
});
13+
}
14+
15+
public function down()
16+
{
17+
Schema::table('forms', function (Blueprint $table) {
18+
$table->dropColumn('captcha_provider');
19+
});
20+
}
21+
};

api/resources/lang/ar/validation.php

+2
Original file line numberDiff line numberDiff line change
@@ -116,4 +116,6 @@
116116
'attributes' => [],
117117

118118
'invalid_json' => 'إدخال غير صالح. يرجى التصحيح والمحاولة مرة أخرى.',
119+
'invalid_captcha' => 'التحقق من صحة الحقل غير صحيح. يرجى التحقق من صحة الحقل والمحاولة مرة أخرى.',
120+
'complete_captcha' => 'يرجى إكمال التحقق من صحة الحقل.',
119121
];

api/resources/lang/bn/validation.php

+2
Original file line numberDiff line numberDiff line change
@@ -116,4 +116,6 @@
116116
'attributes' => [],
117117

118118
'invalid_json' => 'অবৈধ ইনপুট। অনুগ্রহ করে সংশোধন করে আবার চেষ্টা করুন।',
119+
'invalid_captcha' => 'অবৈধ টিপস। অনুগ্রহ করে টিপস টিপুন।',
120+
'complete_captcha' => 'অনুগ্রহ করে টিপস টিপুন।',
119121
];

api/resources/lang/de/validation.php

+2
Original file line numberDiff line numberDiff line change
@@ -116,4 +116,6 @@
116116
'attributes' => [],
117117

118118
'invalid_json' => 'Ungültige Eingabe. Bitte korrigieren Sie und versuchen Sie es erneut.',
119+
'invalid_captcha' => 'Ungültige CAPTCHA. Bitte beweisen Sie, dass Sie kein Bot sind.',
120+
'complete_captcha' => 'Bitte füllen Sie die CAPTCHA aus.',
119121
];

api/resources/lang/en/validation.php

+2
Original file line numberDiff line numberDiff line change
@@ -150,5 +150,7 @@
150150
'attributes' => [],
151151

152152
'invalid_json' => 'Invalid input. Please correct and try again.',
153+
'invalid_captcha' => 'Invalid CAPTCHA. Please prove you\'re not a bot.',
154+
'complete_captcha' => 'Please complete the captcha.',
153155

154156
];

api/resources/lang/es/validation.php

+2
Original file line numberDiff line numberDiff line change
@@ -153,5 +153,7 @@
153153
],
154154

155155
'invalid_json' => 'Entrada no válida. Por favor, corrija e intente nuevamente.',
156+
'invalid_captcha' => 'Captcha no válido. Por favor, demuestre que no es un bot.',
157+
'complete_captcha' => 'Por favor, complete el captcha.',
156158

157159
];

api/resources/lang/fr/validation.php

+2
Original file line numberDiff line numberDiff line change
@@ -116,4 +116,6 @@
116116
'attributes' => [],
117117

118118
'invalid_json' => 'Entrée invalide. Veuillez corriger et réessayer.',
119+
'invalid_captcha' => 'Captcha invalide. Veuillez prouver que vous n\'êtes pas un bot.',
120+
'complete_captcha' => 'Veuillez compléter le captcha.',
119121
];

api/resources/lang/hi/validation.php

+2
Original file line numberDiff line numberDiff line change
@@ -116,4 +116,6 @@
116116
'attributes' => [],
117117

118118
'invalid_json' => 'अमान्य इनपुट। कृपया सुधारें और पुनः प्रयास करें।',
119+
'invalid_captcha' => 'अमान्य कैप्चा। कृपया दिखाएं कि आप एक बॉट नहीं हैं।',
120+
'complete_captcha' => 'कृपया कैप्चा भरें।',
119121
];

api/resources/lang/ja/validation.php

+2
Original file line numberDiff line numberDiff line change
@@ -116,4 +116,6 @@
116116
'attributes' => [],
117117

118118
'invalid_json' => '無効な入力です。修正して再度お試しください。',
119+
'invalid_captcha' => '無効なCAPTCHAです。ボットではないことを証明してください。',
120+
'complete_captcha' => 'CAPTCHAを完了してください。',
119121
];

api/resources/lang/jv/validation.php

+2
Original file line numberDiff line numberDiff line change
@@ -116,4 +116,6 @@
116116
'attributes' => [],
117117

118118
'invalid_json' => 'Input ora valid. Mangga dibenakake lan dicoba maneh.',
119+
'invalid_captcha' => 'CAPTCHA ora valid. Mangga dibenakake lan dicoba maneh.',
120+
'complete_captcha' => 'CAPTCHA kudu diisi.',
119121
];

api/resources/lang/ko/validation.php

+2
Original file line numberDiff line numberDiff line change
@@ -116,4 +116,6 @@
116116
'attributes' => [],
117117

118118
'invalid_json' => '잘못된 입력입니다. 수정 후 다시 시도해 주세요.',
119+
'invalid_captcha' => '잘못된 캡차입니다. 봇이 아님을 증명해 주세요.',
120+
'complete_captcha' => '캡차를 완료해 주세요.',
119121
];

api/resources/lang/mr/validation.php

+2
Original file line numberDiff line numberDiff line change
@@ -133,4 +133,6 @@
133133
'attributes' => [],
134134

135135
'invalid_json' => 'अवैध इनपुट. कृपया सुधारून पुन्हा प्रयत्न करा.',
136+
'invalid_captcha' => 'अवैध कैप्चा। कृपया कैप्चा टिपला आणि पुन्हा प्रयत्न करा।',
137+
'complete_captcha' => 'कृपया कैप्चा भरा.',
136138
];

api/resources/lang/pa/validation.php

+3-1
Original file line numberDiff line numberDiff line change
@@ -115,5 +115,7 @@
115115

116116
'attributes' => [],
117117

118-
'invalid_json' => 'ਗਲਤ ਇਨਪੁਟ। ਕਿਰਪਾ ਕਰਕੇ ਸਹੀ ਕਰੋ ਅਤੇ ਦੁਬਾਰਾ ਕੋਸ਼ਿਸ਼ ਕਰੋ।',
118+
'invalid_json' => 'ਗਲਤ ਇਨਪੁਟ। ਕਿਰਪਾ ਕਰਕਕੇ ਸਹੀ ਕਰੋ ਅਤੇ ਦੁਬਾਰਾ ਕੋਸ਼ਿਸ਼ ਕਰੋ।',
119+
'invalid_captcha' => 'ਗਲਤ ਕੈਪਚਾ। ਕਿਰਪਾ ਕਰੋ ਕੈਪਚਾ ਟੀਪ ਅਤੇ ਦੁਬਾਰਾ ਕੋਸ਼ਿਸ਼ ਕਰੋ।',
120+
'complete_captcha' => 'ਕਿਰਪਾ ਕਰੋ ਕੈਪਚਾ ਭਰੋ।',
119121
];

api/resources/lang/pt-BR/validation.php

+2
Original file line numberDiff line numberDiff line change
@@ -180,4 +180,6 @@
180180
],
181181

182182
'invalid_json' => 'Entrada inválida. Por favor, corrija e tente novamente.',
183+
'invalid_captcha' => 'Captcha inválido. Por favor, demonstre que não é um bot.',
184+
'complete_captcha' => 'Por favor, complete o captcha.',
183185
];

api/resources/lang/pt/validation.php

+2
Original file line numberDiff line numberDiff line change
@@ -116,4 +116,6 @@
116116
'attributes' => [],
117117

118118
'invalid_json' => 'Entrada inválida. Por favor, corrija e tente novamente.',
119+
'invalid_captcha' => 'Captcha inválido. Por favor, demonstre que não é um bot.',
120+
'complete_captcha' => 'Por favor, complete o captcha.',
119121
];

api/resources/lang/ru/validation.php

+2
Original file line numberDiff line numberDiff line change
@@ -116,4 +116,6 @@
116116
'attributes' => [],
117117

118118
'invalid_json' => 'Неверный ввод. Пожалуйста, исправьте и попробуйте снова.',
119+
'invalid_captcha' => 'Неверный CAPTCHA. Пожалуйста, докажите, что вы не бот.',
120+
'complete_captcha' => 'Пожалуйста, заполните CAPTCHA.',
119121
];

api/resources/lang/ta/validation.php

+2
Original file line numberDiff line numberDiff line change
@@ -133,4 +133,6 @@
133133
'attributes' => [],
134134

135135
'invalid_json' => 'தவறான உள்ளீடு. சரிசெய்து மீண்டும் முயற்சிக்கவும்.',
136+
'invalid_captcha' => 'தவறான கையால் வைத்த முறை. மீண்டும் முயற்சிக்கவும்.',
137+
'complete_captcha' => 'கையால் வைத்த முறையை நிரப்பவும்.',
136138
];

api/resources/lang/te/validation.php

+2
Original file line numberDiff line numberDiff line change
@@ -116,4 +116,6 @@
116116
'attributes' => [],
117117

118118
'invalid_json' => 'చెల్లని ఇన్‌పుట్. దయచేసి సరిచేసి మళ్లీ ప్రయత్నించండి.',
119+
'invalid_captcha' => 'అవైధ క్యాప్చా. దయచేసి క్యాప్చా టైప్ మరియు మళ్లీ ప్రయత్నించండి.',
120+
'complete_captcha' => 'దయచేసి క్యాప్చా భరించండి.',
119121
];

api/resources/lang/tr/validation.php

+2
Original file line numberDiff line numberDiff line change
@@ -133,4 +133,6 @@
133133
'attributes' => [],
134134

135135
'invalid_json' => 'Geçersiz girdi. Lütfen düzeltin ve tekrar deneyin.',
136+
'invalid_captcha' => 'Geçersiz CAPTCHA. Lütfen bot olmadığınızı gösterin.',
137+
'complete_captcha' => 'Lütfen CAPTCHA\'yı tamamlayın.',
136138
];

api/resources/lang/ur/validation.php

+2
Original file line numberDiff line numberDiff line change
@@ -116,4 +116,6 @@
116116
'attributes' => [],
117117

118118
'invalid_json' => 'غلط ان پٹ۔ براہ کرم درست کریں اور دوبارہ کوشش کریں۔',
119+
'invalid_captcha' => 'غلط کپچا۔ براہ کرم کپچا ٹائپ کریں اور دوبارہ کوشش کریں۔',
120+
'complete_captcha' => 'براہ کرم کپچا پر کام کریں۔',
119121
];

api/resources/lang/vi/validation.php

+2
Original file line numberDiff line numberDiff line change
@@ -116,4 +116,6 @@
116116
'attributes' => [],
117117

118118
'invalid_json' => 'Dữ liệu không hợp lệ. Vui lòng sửa và thử lại.',
119+
'invalid_captcha' => 'Mã bảo vệ không đúng. Vui lòng nhập lại và thử lại.',
120+
'complete_captcha' => 'Vui lòng nhập mã bảo vệ.',
119121
];

api/resources/lang/zh-CN/validation.php

+2
Original file line numberDiff line numberDiff line change
@@ -96,4 +96,6 @@
9696
'attributes' => [],
9797

9898
'invalid_json' => '输入无效。请修正后重试。',
99+
'invalid_captcha' => '验证码错误。请重新输入并重试。',
100+
'complete_captcha' => '请完成验证码。',
99101
];

api/resources/lang/zh/validation.php

+2
Original file line numberDiff line numberDiff line change
@@ -116,4 +116,6 @@
116116
'attributes' => [],
117117

118118
'invalid_json' => '输入无效。请修正后重试。',
119+
'invalid_captcha' => '验证码错误。请重新输入并重试。',
120+
'complete_captcha' => '请完成验证码。',
119121
];

api/tests/Feature/Forms/FormCaptchaTest.php

+22-1
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,11 @@
11
<?php
22

3-
it('create form with captcha and raise validation issue', function () {
3+
it('create form with hcaptcha and raise validation issue', function () {
44
$user = $this->actingAsUser();
55
$workspace = $this->createUserWorkspace($user);
66
$form = $this->createForm($user, $workspace, [
77
'use_captcha' => true,
8+
'captcha_provider' => 'hcaptcha',
89
]);
910

1011
$this->postJson(route('forms.answer', $form->slug), [])
@@ -18,3 +19,23 @@
1819
],
1920
]);
2021
});
22+
23+
it('create form with recaptcha and raise validation issue', function () {
24+
$user = $this->actingAsUser();
25+
$workspace = $this->createUserWorkspace($user);
26+
$form = $this->createForm($user, $workspace, [
27+
'use_captcha' => true,
28+
'captcha_provider' => 'recaptcha',
29+
]);
30+
31+
$this->postJson(route('forms.answer', $form->slug), [])
32+
->assertStatus(422)
33+
->assertJson([
34+
'message' => 'Please complete the captcha.',
35+
'errors' => [
36+
'g-recaptcha-response' => [
37+
'Please complete the captcha.',
38+
],
39+
],
40+
]);
41+
});

0 commit comments

Comments
 (0)