-
Notifications
You must be signed in to change notification settings - Fork 319
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add reCAPTCHA support and update captcha provider handling #647
Conversation
- 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.
WalkthroughThis pull request introduces a comprehensive implementation of multi-captcha support across the application, specifically adding reCAPTCHA alongside the existing hCaptcha functionality. The changes span both the API and client-side components, introducing new environment variables, validation rules, configuration settings, and Vue components to enable dynamic captcha provider selection. The implementation allows forms to specify either 'recaptcha' or 'hcaptcha' as their preferred captcha verification method. Changes
Sequence DiagramsequenceDiagram
participant User
participant Form
participant CaptchaInput
participant CaptchaProvider
participant Backend
User->>Form: Fills out form
Form->>CaptchaInput: Render captcha
CaptchaInput->>CaptchaProvider: Load based on provider
CaptchaProvider-->>CaptchaInput: Verify response
CaptchaInput->>Backend: Submit form with captcha token
Backend->>Backend: Validate captcha
Backend-->>Form: Submission result
Possibly Related PRs
Suggested Reviewers
Poem
📜 Recent review detailsConfiguration used: CodeRabbit UI 📒 Files selected for processing (1)
🚧 Files skipped from review as they are similar to previous changes (1)
Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media? 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments. CodeRabbit Commands (Invoked using PR comments)
Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 7
🧹 Nitpick comments (6)
api/app/Rules/ValidReCaptcha.php (1)
13-13
: Consider making error messages configurableThe error message is hardcoded. Consider making it configurable through language files for better i18n support.
client/components/forms/RecaptchaV2.vue (1)
60-69
: Enhance error handling and add retry mechanismThe current error handling only logs the error. Consider adding a retry mechanism and proper error propagation.
try { window.grecaptcha.render(recaptchaContainer.value, { sitekey: props.sitekey, theme: props.theme, - callback: 'recaptchaCallback', - 'expired-callback': 'recaptchaExpiredCallback' + callback: callbacks.verify, + 'expired-callback': callbacks.expired }) } catch (error) { - console.error('Error rendering reCAPTCHA:', error) + emit('error', error) + // Optionally implement retry logic here }api/config/services.php (1)
43-46
: Add environment variable validationThe configuration looks good, but consider adding validation for these environment variables during application bootstrap.
Add the following to your
AppServiceProvider::boot()
:if (config('services.re_captcha.site_key') === null || config('services.re_captcha.secret_key') === null) { throw new \RuntimeException('reCAPTCHA configuration is missing. Please check your .env file.'); }client/components/open/forms/components/form-components/FormSecurityAccess.vue (2)
82-89
: Consider dynamic provider optionsThe captcha provider selection UI looks good, but consider making the options configurable through runtime config.
- <FlatSelectInput - v-if="form.use_captcha" - name="captcha_provider" - :form="form" - :options="captchaOptions" - class="mt-4" - label="Select a captcha provider" - /> + <FlatSelectInput + v-if="form.use_captcha" + name="captcha_provider" + :form="form" + :options="runtimeConfig.public.captchaProviders" + class="mt-4" + label="Select a captcha provider" + :required="true" + />
97-100
: Move captcha options to constants fileConsider moving the captcha options to a dedicated constants file for better maintainability.
Create a new file
constants/captcha.js
:export const CAPTCHA_PROVIDERS = [ { name: 'reCAPTCHA', value: 'recaptcha' }, { name: 'hCaptcha', value: 'hcaptcha' }, ]Then import and use it:
-const captchaOptions = [ - { name: 'reCAPTCHA', value: 'recaptcha' }, - { name: 'hCaptcha', value: 'hcaptcha' }, -] +import { CAPTCHA_PROVIDERS } from '@/constants/captcha' +const captchaOptions = CAPTCHA_PROVIDERSapi/tests/Feature/Forms/FormCaptchaTest.php (1)
22-41
: Refactor tests to reduce duplication using data setsThe two test cases for hCaptcha and reCAPTCHA are almost identical except for the
captcha_provider
value and the expected error field. Consider refactoring these tests to use a data provider or looping mechanism to reduce code duplication and improve maintainability.Here's an example of how you might refactor the tests using Pest's data sets:
// Add at the beginning of the file uses()->beforeEach(function () { $this->user = $this->actingAsUser(); $this->workspace = $this->createUserWorkspace($this->user); })->in('Feature/Forms'); // Refactored test with data sets it('creates form with :provider and raises validation issue', function ($provider, $errorField) { $form = $this->createForm($this->user, $this->workspace, [ 'use_captcha' => true, 'captcha_provider' => $provider, ]); $this->postJson(route('forms.answer', $form->slug), []) ->assertStatus(422) ->assertJson([ 'message' => 'Please complete the captcha.', 'errors' => [ $errorField => [ 'Please complete the captcha.', ], ], ]); })->with([ ['hcaptcha', 'h-captcha-response'], ['recaptcha', 'g-recaptcha-response'], ]);This approach reduces code duplication and makes it easier to maintain and extend the tests in the future.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (13)
api/.env.example
(1 hunks)api/app/Http/Requests/AnswerFormRequest.php
(2 hunks)api/app/Http/Requests/UserFormRequest.php
(1 hunks)api/app/Models/Forms/Form.php
(1 hunks)api/app/Rules/ValidReCaptcha.php
(1 hunks)api/config/services.php
(1 hunks)api/database/migrations/2024_03_21_000000_add_captcha_provider_to_forms_table.php
(1 hunks)api/tests/Feature/Forms/FormCaptchaTest.php
(2 hunks)client/.env.example
(1 hunks)client/components/forms/RecaptchaV2.vue
(1 hunks)client/components/open/forms/OpenForm.vue
(4 hunks)client/components/open/forms/components/form-components/FormSecurityAccess.vue
(1 hunks)client/runtimeConfig.js
(1 hunks)
🔇 Additional comments (7)
client/runtimeConfig.js (1)
22-22
: Verify reCAPTCHA integration in components
The configuration is correctly added. Please ensure:
- Components handle the null case gracefully
- Error states are properly managed when the key is missing
✅ Verification successful
reCAPTCHA integration is properly handled in components
The verification shows that the reCAPTCHA integration is well-implemented with proper null case handling:
- The
RecaptchaV2.vue
component has proper error handling and cleanup OpenForm.vue
correctly:- Retrieves the site key from runtime config
- Handles verification and expiration states
- Manages form submission with captcha response
- Implements proper reset functionality
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Find components using reCAPTCHA
ast-grep --pattern 'recaptchaSiteKey' client/
Length of output: 45
Script:
#!/bin/bash
# Search for reCAPTCHA related code using ripgrep for broader context
rg -i "recaptcha" client/ -A 3 -B 3
Length of output: 8621
api/app/Http/Requests/UserFormRequest.php (1)
121-121
: LGTM! The captcha provider validation rule is well-implemented.
The validation rule is correctly defined with appropriate constraints and aligns with the form's captcha functionality.
api/app/Models/Forms/Form.php (1)
85-85
: LGTM! The captcha_provider field is correctly added to the fillable array.
The field is appropriately positioned near other captcha-related fields and aligns with the form validation implementation.
api/app/Http/Requests/AnswerFormRequest.php (1)
11-11
: LGTM! The ValidReCaptcha import is correctly placed.
The import follows the established pattern and maintains alphabetical order with other rule imports.
client/.env.example (1)
9-9
: LGTM!
The addition of the environment variable NUXT_PUBLIC_RE_CAPTCHA_SITE_KEY
is appropriate and aligns with the configuration in the application.
api/database/migrations/2024_03_21_000000_add_captcha_provider_to_forms_table.php (1)
1-21
: Migration file is correctly implemented
The migration adds the captcha_provider
column with a default value of 'hcaptcha'
, ensuring backward compatibility with existing forms. The down
method properly reverses this change.
api/tests/Feature/Forms/FormCaptchaTest.php (1)
Line range hint 3-21
: LGTM!
The test case for hCaptcha correctly validates the captcha response and ensures appropriate error handling.
return Http::asForm()->post(self::RECAPTCHA_VERIFY_URL, [ | ||
'secret' => config('services.re_captcha.secret_key'), | ||
'response' => $value, | ||
])->json('success'); | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Enhance reCAPTCHA verification security and reliability
The verification request should include additional security measures and error handling:
- Include the user's IP address in the verification request (recommended by Google)
- Add timeout and error handling for the HTTP request
return Http::asForm()->post(self::RECAPTCHA_VERIFY_URL, [
'secret' => config('services.re_captcha.secret_key'),
'response' => $value,
+ 'remoteip' => request()->ip(),
- ])->json('success');
+ ])
+ ->timeout(5)
+ ->throw(function($response, $e) {
+ $this->error = 'CAPTCHA verification failed. Please try again.';
+ return false;
+ })
+ ->json('success');
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
return Http::asForm()->post(self::RECAPTCHA_VERIFY_URL, [ | |
'secret' => config('services.re_captcha.secret_key'), | |
'response' => $value, | |
])->json('success'); | |
} | |
return Http::asForm()->post(self::RECAPTCHA_VERIFY_URL, [ | |
'secret' => config('services.re_captcha.secret_key'), | |
'response' => $value, | |
'remoteip' => request()->ip(), | |
]) | |
->timeout(5) | |
->throw(function($response, $e) { | |
$this->error = 'CAPTCHA verification failed. Please try again.'; | |
return false; | |
}) | |
->json('success'); | |
} |
RE_CAPTCHA_SITE_KEY= | ||
RE_CAPTCHA_SECRET_KEY= |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
💡 Codebase verification
Documentation needed for reCAPTCHA environment variables
The new reCAPTCHA environment variables are not documented in the environment variables configuration file (docs/configuration/environment-variables.mdx
). Please add the following to the Configuration Environment Variables table:
RE_CAPTCHA_SITE_KEY
: Site key for reCAPTCHA integrationRE_CAPTCHA_SECRET_KEY
: Secret key for reCAPTCHA integration
🔗 Analysis chain
Verify documentation for new reCAPTCHA configuration
The environment variables are correctly added. Please ensure these new variables are documented in:
- Installation guide
- Configuration documentation
- Deployment checklist
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Check if documentation exists for new variables
fd -e md -e mdx | xargs rg -l "RE_CAPTCHA_(SITE|SECRET)_KEY"
Length of output: 62
Script:
#!/bin/bash
# Let's first check if there are any markdown files in docs or similar directories
fd -e md -e mdx
# Also check for README files that might contain documentation
fd README
Length of output: 907
Script:
#!/bin/bash
# Let's check the environment variables documentation and installation guides
cat docs/configuration/environment-variables.mdx
cat docs/deployment/local-deployment.mdx
Length of output: 5373
await new Promise((resolve) => { | ||
const checkGrecaptcha = () => { | ||
if (window.grecaptcha?.ready) { | ||
resolve() | ||
} else { | ||
setTimeout(checkGrecaptcha, 100) | ||
} | ||
} | ||
checkGrecaptcha() | ||
}) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Add timeout to prevent infinite polling
The grecaptcha availability check could potentially run indefinitely. Add a timeout mechanism.
await new Promise((resolve) => {
+ const MAX_RETRIES = 50; // 5 seconds
+ let retries = 0;
const checkGrecaptcha = () => {
if (window.grecaptcha?.ready) {
resolve()
+ } else if (retries >= MAX_RETRIES) {
+ console.error('reCAPTCHA failed to load')
+ resolve()
} else {
+ retries++
setTimeout(checkGrecaptcha, 100)
}
}
checkGrecaptcha()
})
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
await new Promise((resolve) => { | |
const checkGrecaptcha = () => { | |
if (window.grecaptcha?.ready) { | |
resolve() | |
} else { | |
setTimeout(checkGrecaptcha, 100) | |
} | |
} | |
checkGrecaptcha() | |
}) | |
await new Promise((resolve) => { | |
const MAX_RETRIES = 50; // 5 seconds | |
let retries = 0; | |
const checkGrecaptcha = () => { | |
if (window.grecaptcha?.ready) { | |
resolve() | |
} else if (retries >= MAX_RETRIES) { | |
console.error('reCAPTCHA failed to load') | |
resolve() | |
} else { | |
retries++ | |
setTimeout(checkGrecaptcha, 100) | |
} | |
} | |
checkGrecaptcha() | |
}) |
window.recaptchaCallback = (token) => { | ||
emit('verify', token) | ||
} | ||
|
||
window.recaptchaExpiredCallback = () => { | ||
emit('expired') | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Avoid using global window functions for callbacks
Using global window functions can lead to naming conflicts and security issues. Consider using a more encapsulated approach.
- window.recaptchaCallback = (token) => {
- emit('verify', token)
- }
-
- window.recaptchaExpiredCallback = () => {
- emit('expired')
- }
+ const callbacks = {
+ verify: (token) => emit('verify', token),
+ expired: () => emit('expired')
+ }
+
+ // Use these callbacks directly in grecaptcha.render
Committable suggestion skipped: line range outside the PR's diff.
if (!document.querySelector('script[src*="recaptcha/api.js"]')) { | ||
const script = document.createElement('script') | ||
script.src = 'https://www.google.com/recaptcha/api.js' | ||
script.async = true | ||
script.defer = true | ||
document.head.appendChild(script) | ||
|
||
await new Promise((resolve) => { | ||
script.onload = resolve | ||
}) | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Consider using a more secure script loading approach
The current implementation directly creates and appends a script tag. Consider using CSP-compliant script loading or a dedicated script loader utility.
- const script = document.createElement('script')
- script.src = 'https://www.google.com/recaptcha/api.js'
- script.async = true
- script.defer = true
- document.head.appendChild(script)
+ await useScriptLoader('https://www.google.com/recaptcha/api.js', {
+ async: true,
+ defer: true,
+ nonce: YOUR_CSP_NONCE // Add nonce for CSP compliance
+ })
Committable suggestion skipped: line range outside the PR's diff.
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()]; | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Add default case handling for captcha validation.
While the current implementation handles both reCAPTCHA and hCaptcha, it lacks handling for unexpected captcha_provider
values. This could lead to a security issue where no captcha validation is applied even when use_captcha
is true.
Consider adding a default case:
if ($this->form->use_captcha) {
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()];
+ } else {
+ // Default to hCaptcha if provider is invalid
+ $this->requestRules['h-captcha-response'] = [new ValidHCaptcha()];
}
}
Committable suggestion skipped: line range outside the PR's diff.
field-id="h-captcha-response" | ||
/> | ||
<template v-if="form.captcha_provider === 'recaptcha'"> | ||
<RecaptchaV2 |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Use Vue refs instead of direct DOM access for captcha responses
Accessing DOM elements directly with document.getElementsByName()
is not recommended in Vue.js, as it can lead to potential runtime errors and goes against Vue's reactivity principles. Using Vue refs ensures better integration with the Vue framework and improves code reliability.
Apply the following changes:
In the template (line 82~):
Add a ref
attribute to the RecaptchaV2
component:
<RecaptchaV2
+ ref="recaptcha"
:sitekey="recaptchaSiteKey"
:theme="darkMode ? 'dark' : 'light'"
@verify="onRecaptchaVerify"
@expired="onRecaptchaExpired"
/>
In the script (lines 389~ to 395~):
Update the submitForm
method to use refs:
if (this.form.captcha_provider === 'recaptcha') {
- this.dataForm['g-recaptcha-response'] = document.getElementsByName('g-recaptcha-response')[0]?.value
- window.grecaptcha?.reset()
+ this.dataForm['g-recaptcha-response'] = this.$refs.recaptcha.getResponse()
+ this.$refs.recaptcha.reset()
} else if (this.form.captcha_provider === 'hcaptcha') {
- this.dataForm['h-captcha-response'] = document.getElementsByName('h-captcha-response')[0].value
+ this.dataForm['h-captcha-response'] = this.$refs.hcaptcha.getResponse()
this.$refs.hcaptcha.reset()
}
Note: Ensure that you handle cases where the refs might not exist to prevent runtime errors. For example:
if (this.form.captcha_provider === 'recaptcha' && this.$refs.recaptcha) {
// ...
}
Also applies to: 389-395
- 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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 4
🧹 Nitpick comments (9)
client/components/forms/components/RecaptchaV2.vue (2)
57-105
: Adjust script-loading timeout for better UX on slower networks.The 10-second timeout (line 99) might be too short for users on sluggish networks, potentially causing the script to fail prematurely. Consider making the timeout configurable or extending it to reduce false negatives for users with slower connections.
107-135
: Handle script-load/render errors more explicitly.While the try/catch block properly resets the scriptLoadPromise on failure, there is no user-facing feedback about the error. It may be beneficial to emit an 'error' event or display an error message to guide the user when reCAPTCHA fails to load.
client/components/forms/components/CaptchaInput.vue (3)
72-95
: Consider more efficient re-initialization logic.Currently, when switching providers, the code:
• Clears the old provider’s values,
• Hides the captcha,
• Waits 1 second,
• Increments the component key,
• Waits another second,
• Shows the new captcha.This ensures a clean teardown for the old provider but might be too lengthy for user experience. Consider using a shorter transition or a direct teardown and re-render to reduce waiting time.
138-149
: Consider providing an 'error' event callback.In addition to opened and closed events, reCAPTCHA/hCaptcha occasionally invoke an error callback. If the user only sees open/close states, diagnosing issues in the hosting environment might be difficult. Emitting an 'error' event from onCaptchaOpen or a dedicated error handler can help track problems.
157-166
: Adjust the reset logic to handle partial or ongoing form states.The reset method only triggers if the user has completed the captcha at least once. If the user partially interacted with the captcha but didn't complete it, consider whether to reset automatically for consistency. Alternatively, rename the method to clarify it resets only after initial completion.
client/components/forms/components/HCaptchaV2.vue (2)
69-122
: Consider making the 10-second script load timeout configurable.
A fixed timeout can cause failures for users on slower networks. Allowing configuration or extension can provide a more robust user experience.
179-185
: Re-evaluate resetting the script on every “reset” call.
The current logic removes and reloads all scripts, iframe references, and styles, which is fine for a true “start from scratch” approach. However, repeatedly reloading external scripts can be relatively expensive. If partial reload or a built-in hCaptcha reset method is sufficient, consider only calling “hcaptcha.reset(widgetId)”.client/composables/forms/initForm.js (1)
39-39
: Consider validating captcha provider value.The default value 'recaptcha' is hardcoded. Consider using an enum or constant to prevent typos and ensure consistency across the codebase.
+ const CAPTCHA_PROVIDERS = { + RECAPTCHA: 'recaptcha', + HCAPTCHA: 'hcaptcha' + } ... - captcha_provider: 'recaptcha', + captcha_provider: CAPTCHA_PROVIDERS.RECAPTCHA,client/components/open/forms/OpenForm.vue (1)
79-88
: Add aria-label for accessibility.The captcha container should have proper accessibility attributes.
- <div class="mb-3 px-2 mt-4 mx-auto w-max"> + <div class="mb-3 px-2 mt-4 mx-auto w-max" aria-label="Captcha verification">
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (7)
client/components/forms/components/CaptchaInput.vue
(1 hunks)client/components/forms/components/HCaptchaV2.vue
(1 hunks)client/components/forms/components/RecaptchaV2.vue
(1 hunks)client/components/open/forms/OpenForm.vue
(4 hunks)client/components/open/forms/components/form-components/FormSecurityAccess.vue
(1 hunks)client/composables/forms/initForm.js
(2 hunks)client/package.json
(0 hunks)
💤 Files with no reviewable changes (1)
- client/package.json
🚧 Files skipped from review as they are similar to previous changes (1)
- client/components/open/forms/components/form-components/FormSecurityAccess.vue
🔇 Additional comments (5)
client/components/forms/components/CaptchaInput.vue (1)
104-113
: Confirm DOM element existence when setting element.value.
When setting DOM element values (lines 109-112), ensure that the corresponding element exists. While the conditional check helps, it might be beneficial to log or emit a warning if the element is unexpectedly missing, indicating a potential mismatch in form field naming.
client/components/forms/components/HCaptchaV2.vue (2)
124-154
: Handle or bubble up render errors for user visibility.
In the catch block, the code sets “scriptLoadPromise = null” but doesn’t surface the error to the user. This could lead to silent failures.
Would you like to log the error or display a user-friendly message? Confirm if the UX remains acceptable when captcha script fails to load.
31-67
: Ensure removal of only the hCaptcha-related elements.
Currently, any element whose src attribute partially matches “hcaptcha.com” is removed from the DOM. There's a small edge case if another script or iframe inadvertently contains “hcaptcha.com” in its src. Consider stricter matching or scoping to avoid unexpected removals.
Use the following script to scan your codebase for additional embedded elements referencing “hcaptcha.com” to ensure no conflicts with external content:
✅ Verification successful
Let's search for any references to hcaptcha.com and also look for script/iframe tags in general to better understand the context and potential conflicts.
Let's try without file type restrictions since Vue files might not be recognized by ripgrep's file type detection.
Based on the search results, I can see that the only references to hcaptcha.com in the codebase are:
- The verification URL in
ValidHCaptcha.php
- The cleanup code in
HCaptchaV2.vue
that we're reviewing - The script loading URL in
HCaptchaV2.vue
There are no other scripts or iframes containing "hcaptcha.com" in their src attributes that could be accidentally affected by the cleanup code. Let's verify one more thing to be completely certain:
The partial string matching for hcaptcha.com is safe in this context.
The codebase only uses hcaptcha.com URLs in the expected legitimate ways - for verification and script loading. There are no other scripts or iframes that could be inadvertently affected by the cleanup code's partial string matching. The cleanup is properly scoped to hCaptcha-related elements.
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
ast-grep --pattern $'<script src=$_></script>' | rg "hcaptcha.com"
Length of output: 65
Script:
#!/bin/bash
# Search for any references to hcaptcha.com in HTML/Vue files
rg -t html -t vue "hcaptcha\.com" -B 2 -A 2
# Search for any script or iframe tags with src attribute
rg -t html -t vue '(?:<script|<iframe).*?src=["'\''].*?["'\''].*?>' -B 2 -A 2
Length of output: 181
Script:
#!/bin/bash
# Search for any references to hcaptcha.com without file type restrictions
rg "hcaptcha\.com" -B 2 -A 2
# Search for any script or iframe tags with src attribute
rg '(?:<script|<iframe).*?src=["'\''].*?["'\''].*?>' -B 2 -A 2
Length of output: 68909
Script:
# Search for any DOM manipulation related to hcaptcha
rg -B 2 -A 2 'querySelector.*hcaptcha'
Length of output: 847
client/components/open/forms/OpenForm.vue (2)
130-130
: LGTM: Clean component integration.
The CaptchaInput component is properly imported and registered. This is a cleaner approach compared to the previous implementation that used direct DOM access.
Also applies to: 141-141
80-87
: Verify CaptchaInput props validation.
The component receives several props but their validation isn't visible in this file. Let's verify the implementation.
✅ Verification successful
Props validation is properly implemented in CaptchaInput component
The CaptchaInput component has proper validation for all props used in OpenForm.vue:
provider
: String (required) with validator ensuring only 'recaptcha' or 'hcaptcha'form
: Object (required)language
: String (required)darkMode
: Boolean with default false
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Search for CaptchaInput component definition and props validation
ast-grep --pattern 'export default {
props: {
provider: {
$$$
}
}
}'
Length of output: 88
Script:
#!/bin/bash
# Let's try to find the CaptchaInput component file first
fd -t f "CaptchaInput.vue"
# Then let's search for props validation with a more flexible pattern
ast-grep --pattern 'props: {
$$$
}'
Length of output: 118
Script:
#!/bin/bash
# Now that we found the file, let's examine its contents
cat client/components/forms/components/CaptchaInput.vue
Length of output: 4507
// 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 | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Potential concurrency interference when removing shared global resources.
The cleanupRecaptcha() function indiscriminately removes all reCAPTCHA scripts and iframes from the page, as well as the global window.grecaptcha object. This may cause unintended side effects if there are multiple RecaptchaV2 components or other modules using reCAPTCHA simultaneously on the same page. It is advisable to introduce a usage counter or a reference check to ensure that cleanup occurs only when no other components are depending on the global reCAPTCHA script.
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 = '' | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Avoid fully removing global reCAPTCHA data if other instances may still be active.
Similar to the earlier concurrency mention, onBeforeUnmount also calls cleanupRecaptcha(), which removes the script globally. If multiple RecaptchaV2 components exist in the same application, unmounting one could break the other(s). A reference-counting approach or scoped cleanup helps preserve a multi-recaptcha scenario.
@@ -105,6 +106,7 @@ export function setFormDefaults(formData) { | |||
bypass_success_page: false, | |||
can_be_indexed: true, | |||
use_captcha: false, | |||
captcha_provider: 'recaptcha', |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
💡 Codebase verification
Update the default captcha provider to 'hcaptcha'
The database migration sets 'hcaptcha' as the default value, but initForm.js
uses 'recaptcha'. This inconsistency should be fixed by updating the default in initForm.js
to match the database default.
client/composables/forms/initForm.js
: Change defaultcaptcha_provider
from 'recaptcha' to 'hcaptcha'
🔗 Analysis chain
Ensure consistency with initForm defaults.
The default value matches initForm
, which is good. However, let's verify that this value is used consistently across the codebase.
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Search for hardcoded captcha provider values
rg -i "captcha_provider.*['\"](?:recaptcha|hcaptcha)['\"]"
# Search for validation rules that might enforce specific values
ast-grep --pattern 'enum|const.*captcha_provider'
Length of output: 957
@@ -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() |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Add error handling for captcha reset.
The optional chaining operator is good, but consider adding error handling for failed resets.
- this.$refs.captcha?.reset()
+ try {
+ this.$refs.captcha?.reset()
+ } catch (error) {
+ console.error('Failed to reset captcha:', error)
+ useAlert().error(this.$t('forms.captcha_reset_error'))
+ }
Committable suggestion skipped: line range outside the PR's diff.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 2
🧹 Nitpick comments (8)
api/resources/lang/vi/validation.php (1)
119-120
: LGTM! Consider making the error messages more specific.The Vietnamese translations are grammatically correct and follow the file's format consistently. However, consider making the messages more specific by mentioning "CAPTCHA" instead of the generic "protection code" to align with common user expectations.
Consider this alternative translation:
- '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ệ.', + 'invalid_captcha' => 'Mã CAPTCHA không đúng. Vui lòng nhập lại và thử lại.', + 'complete_captcha' => 'Vui lòng nhập mã CAPTCHA.',api/resources/lang/ja/validation.php (1)
119-120
: LGTM! Consider provider-specific messages if needed.The Japanese translations for CAPTCHA validation messages are grammatically correct and maintain consistent style with other messages. They are generic enough to work with both hCaptcha and reCAPTCHA.
If you need to distinguish between providers in error messages (though this might not be desirable for security reasons), consider adding provider-specific messages.
Optional enhancement:
'invalid_captcha' => '無効なCAPTCHAです。ボットではないことを証明してください。', 'complete_captcha' => 'CAPTCHAを完了してください。', + 'invalid_hcaptcha' => '無効なhCaptchaです。ボットではないことを証明してください。', + 'invalid_recaptcha' => '無効なreCAPTCHAです。ボットではないことを証明してください。',api/resources/lang/te/validation.php (1)
119-120
: LGTM! Consider adding period for consistency.The new captcha validation messages are well-translated in Telugu and appropriately generic to work with both hCaptcha and reCAPTCHA providers. However, for consistency with other validation messages in the file that end with a period (.), consider adding periods at the end of these messages.
- 'invalid_captcha' => 'అవైధ క్యాప్చా. దయచేసి క్యాప్చా టైప్ మరియు మళ్లీ ప్రయత్నించండి.', - 'complete_captcha' => 'దయచేసి క్యాప్చా భరించండి.', + 'invalid_captcha' => 'అవైధ క్యాప్చా. దయచేసి క్యాప్చా టైప్ మరియు మళ్లీ ప్రయత్నించండి.', + 'complete_captcha' => 'దయచేసి క్యాప్చా భరించండి.'api/resources/lang/pt-BR/validation.php (1)
183-184
: LGTM! Consider enhancing the messages with provider-specific information.The Portuguese translations for captcha validation messages are clear and user-friendly. They work well with both hCaptcha and reCAPTCHA providers.
As an optional enhancement, you could make the messages more specific by using the provider name when known:
- 'invalid_captcha' => 'Captcha inválido. Por favor, demonstre que não é um bot.', + 'invalid_captcha' => ':provider inválido. Por favor, demonstre que não é um bot.',api/resources/lang/pt/validation.php (1)
119-120
: Maintain consistency in CAPTCHA capitalization.For consistency with other language translations, consider capitalizing "CAPTCHA":
- 'invalid_captcha' => 'Captcha inválido. Por favor, demonstre que não é um bot.', - 'complete_captcha' => 'Por favor, complete o captcha.', + 'invalid_captcha' => 'CAPTCHA inválido. Por favor, demonstre que não é um bot.', + 'complete_captcha' => 'Por favor, complete o CAPTCHA.',api/resources/lang/es/validation.php (1)
156-157
: Maintain consistency in CAPTCHA capitalization.For consistency with other language translations, consider capitalizing "CAPTCHA":
- 'invalid_captcha' => 'Captcha no válido. Por favor, demuestre que no es un bot.', - 'complete_captcha' => 'Por favor, complete el captcha.', + 'invalid_captcha' => 'CAPTCHA no válido. Por favor, demuestre que no es un bot.', + 'complete_captcha' => 'Por favor, complete el CAPTCHA.',api/resources/lang/en/validation.php (1)
153-154
: Fix CAPTCHA capitalization inconsistency across language files.While the English messages look good, there's an inconsistency in how "CAPTCHA" is capitalized between language files:
- English uses: "CAPTCHA" (all caps)
- French uses: "Captcha" (title case)
For better consistency across the application, we should standardize the capitalization.
Apply this diff to the French translation file:
- 'invalid_captcha' => 'Captcha invalide. Veuillez prouver que vous n\'êtes pas un bot.', - 'complete_captcha' => 'Veuillez compléter le captcha.', + 'invalid_captcha' => 'CAPTCHA invalide. Veuillez prouver que vous n\'êtes pas un bot.', + 'complete_captcha' => 'Veuillez compléter le CAPTCHA.',api/app/Rules/ValidHCaptcha.php (1)
49-49
: Consider adding a fallback messageWhile using
trans()
is correct, consider adding a fallback message in case the translation key is missing.Here's a suggested improvement:
- return trans($this->error); + return trans($this->error, [], 'Invalid CAPTCHA verification');
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (24)
api/app/Rules/ValidHCaptcha.php
(3 hunks)api/app/Rules/ValidReCaptcha.php
(1 hunks)api/resources/lang/ar/validation.php
(1 hunks)api/resources/lang/bn/validation.php
(1 hunks)api/resources/lang/de/validation.php
(1 hunks)api/resources/lang/en/validation.php
(1 hunks)api/resources/lang/es/validation.php
(1 hunks)api/resources/lang/fr/validation.php
(1 hunks)api/resources/lang/hi/validation.php
(1 hunks)api/resources/lang/ja/validation.php
(1 hunks)api/resources/lang/jv/validation.php
(1 hunks)api/resources/lang/ko/validation.php
(1 hunks)api/resources/lang/mr/validation.php
(1 hunks)api/resources/lang/pa/validation.php
(1 hunks)api/resources/lang/pt-BR/validation.php
(1 hunks)api/resources/lang/pt/validation.php
(1 hunks)api/resources/lang/ru/validation.php
(1 hunks)api/resources/lang/ta/validation.php
(1 hunks)api/resources/lang/te/validation.php
(1 hunks)api/resources/lang/tr/validation.php
(1 hunks)api/resources/lang/ur/validation.php
(1 hunks)api/resources/lang/vi/validation.php
(1 hunks)api/resources/lang/zh-CN/validation.php
(1 hunks)api/resources/lang/zh/validation.php
(1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
- api/app/Rules/ValidReCaptcha.php
🔇 Additional comments (22)
api/resources/lang/zh/validation.php (1)
119-120
: LGTM! The new captcha validation messages are well-implemented.
The Chinese translations for captcha validation messages are clear, consistent with the existing messages, and appropriately handle both invalid and incomplete captcha scenarios. These messages will work well with both hCaptcha and reCAPTCHA providers.
api/resources/lang/jv/validation.php (1)
119-120
: LGTM! Well-structured CAPTCHA validation messages.
The new validation messages are properly implemented with clear Javanese translations that will work seamlessly with both hCaptcha and reCAPTCHA providers. The messages maintain consistency with the existing language style while providing clear user feedback.
api/resources/lang/mr/validation.php (1)
136-137
: LGTM! Verify translations across language files.
The new captcha validation messages are properly formatted and generic enough to work with both hCaptcha and reCAPTCHA providers.
Let's verify that these translations are consistent across all language files:
✅ Verification successful
Translations are consistent across all language files ✅
The verification shows that all language files (22 in total) have properly implemented both invalid_captcha
and complete_captcha
messages. Each translation:
- Maintains consistent meaning across languages
- Uses appropriate cultural/linguistic adaptations
- Follows the same key structure
- Contains both required messages
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Description: Check if the new captcha validation messages exist in all language files
# and ensure consistency in their implementation.
# Find all validation.php files in language directories
echo "Checking captcha validation messages across language files..."
fd --type f "validation.php" "api/resources/lang" --exec grep -l "invalid_captcha\|complete_captcha" {} \; | sort
# Show the actual translations for comparison
echo "\nComparing translations:"
fd --type f "validation.php" "api/resources/lang" --exec sh -c '
echo "\nFile: {}"
grep -A 1 "invalid_captcha\|complete_captcha" {}
'
Length of output: 5194
api/resources/lang/zh-CN/validation.php (1)
99-100
: LGTM! Verify translations in other language files.
The new validation messages are well-structured and properly translated to Chinese. They align with the existing message format and provide clear user feedback for captcha-related actions.
Let's verify if these new validation messages are consistently added across all language files:
✅ Verification successful
Translations are consistently present across all language files ✓
The verification shows that both invalid_captcha
and complete_captcha
messages are properly implemented across all language files (ar, bn, de, en, es, fr, hi, ja, jv, ko, mr, pa, pt, pt-BR, ru, ta, te, tr, ur, vi, zh, zh-CN). Each translation is culturally appropriate and maintains consistent meaning.
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Description: Check if the new captcha validation messages exist in all language files
# Expected: All language files should have these new messages
# Find all validation language files
fd "validation.php" "api/resources/lang" --exec sh -c '
echo "Checking {}"
echo "- invalid_captcha:"
grep -A 1 "invalid_captcha" "{}" || echo " Not found!"
echo "- complete_captcha:"
grep -A 1 "complete_captcha" "{}" || echo " Not found!"
echo
'
Length of output: 6286
api/resources/lang/tr/validation.php (1)
136-137
: LGTM! Consider verifying translations across all language files.
The new CAPTCHA validation messages are properly translated to Turkish and maintain consistent formatting. The messages are generic enough to work with both hCaptcha and reCAPTCHA providers.
Let's verify that these validation messages are consistently added across all language files:
✅ Verification successful
CAPTCHA validation messages are consistently present across all language files ✓
The verification shows that both invalid_captcha
and complete_captcha
messages are properly implemented across all language files (ar, bn, de, en, es, fr, hi, ja, jv, ko, mr, pa, pt, pt-BR, ru, ta, te, tr, ur, vi, zh, zh-CN). Each translation:
- Maintains consistent key names
- Provides culturally appropriate translations
- Uses proper escaping where needed
- Follows the same message structure
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Description: Check for CAPTCHA validation messages across all language files
# Find all validation.php files in language directories
fd validation.php api/resources/lang | while read -r file; do
echo "Checking $file..."
# Search for CAPTCHA-related messages
rg -A 1 "('invalid_captcha'|'complete_captcha')" "$file" || echo "Missing CAPTCHA messages"
done
Length of output: 7907
api/resources/lang/ru/validation.php (1)
119-120
: LGTM! The translations are accurate and well-structured.
The new CAPTCHA validation messages are properly translated to Russian and follow the existing message style. They are generic enough to work with both hCaptcha and reCAPTCHA providers.
Let's verify if these validation messages are consistently defined across other language files:
✅ Verification successful
CAPTCHA validation messages are consistently defined across all language files
The verification shows that both invalid_captcha
and complete_captcha
messages are properly defined in all language files (ar, bn, de, en, es, fr, hi, ja, jv, ko, mr, pa, pt, pt-BR, ru, ta, te, tr, ur, vi, zh, zh-CN). Each translation:
- Maintains consistent meaning across languages
- Uses appropriate localized terminology for "CAPTCHA"
- Follows proper grammar and punctuation rules for each language
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Description: Check if CAPTCHA validation messages are consistently defined across all language files.
# Find all validation.php files in language directories
fd validation.php api/resources/lang -x sh -c '
echo "=== Checking {}"
echo "invalid_captcha message:"
rg "invalid_captcha" {} -A 1 || echo "Not found!"
echo "complete_captcha message:"
rg "complete_captcha" {} -A 1 || echo "Not found!"
echo
'
Length of output: 6639
api/resources/lang/te/validation.php (1)
119-120
: Verify captcha validation messages in other language files.
Let's ensure these captcha validation messages are consistently added across all language files in the project.
✅ Verification successful
Captcha validation messages are consistently present across all language files
The verification results show that all language files in api/resources/lang/*/validation.php
contain the captcha validation messages. The messages are present in all 22 language files including Arabic, Bengali, German, English, Spanish, French, Hindi, Japanese, Javanese, Korean, Marathi, Punjabi, Portuguese (both BR and PT variants), Russian, Tamil, Telugu, Turkish, Urdu, Vietnamese, and Chinese (both CN and traditional variants).
No language files were found missing these messages, confirming consistent implementation across all translations.
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Description: Check if captcha validation messages exist in all language files
# Expected: All language files should have these messages for consistency
# Find all validation.php files in language directories
echo "Checking language files for captcha validation messages..."
fd --type f "validation.php" "api/resources/lang" --exec grep -l "invalid_captcha\|complete_captcha" {} \; | sort
# Show language files missing these messages
echo -e "\nLanguage files missing captcha validation messages:"
fd --type f "validation.php" "api/resources/lang" --exec sh -c '
if ! grep -q "invalid_captcha\|complete_captcha" "$1"; then
echo "$1"
fi
' sh {} \;
Length of output: 1338
api/resources/lang/hi/validation.php (2)
119-120
: LGTM! Clear and well-translated captcha validation messages.
The new Hindi translations for captcha validation messages are clear, user-friendly, and properly formatted.
119-120
: Verify translations in other language files.
Let's ensure these new captcha validation messages are consistently added across all supported language files.
✅ Verification successful
Captcha validation messages are consistently present across all language files
The verification shows that both invalid_captcha
and complete_captcha
messages are properly implemented in all validation.php files across different languages:
- Arabic (ar)
- Bengali (bn)
- German (de)
- English (en)
- Spanish (es)
- French (fr)
- Hindi (hi)
- Japanese (ja)
- Javanese (jv)
- Korean (ko)
- Marathi (mr)
- Punjabi (pa)
- Portuguese (pt and pt-BR)
- Russian (ru)
- Tamil (ta)
- Telugu (te)
- Turkish (tr)
- Urdu (ur)
- Vietnamese (vi)
- Chinese (zh and zh-CN)
The messages are appropriately localized for each language and maintain consistent meaning across translations.
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Description: Check if captcha validation messages exist in all language files
# Find all language files
echo "Checking language files for captcha validation messages..."
for lang_file in $(fd -e php . api/resources/lang); do
echo "\nChecking $lang_file:"
echo "- invalid_captcha:"
rg "'invalid_captcha'" "$lang_file" || echo " Missing!"
echo "- complete_captcha:"
rg "'complete_captcha'" "$lang_file" || echo " Missing!"
done
Length of output: 17603
api/resources/lang/ko/validation.php (1)
119-120
: LGTM! Verify translations in other language files.
The new Korean validation messages for captcha functionality are well-formatted and properly translated. The messages are generic enough to work with both hCaptcha and reCAPTCHA providers.
Let's verify that these validation messages exist in other language files:
✅ Verification successful
All language files have consistent captcha validation messages
The verification shows that all 22 language files in api/resources/lang/
include both invalid_captcha
and complete_captcha
messages. Each translation is properly localized while maintaining consistent meaning across languages:
- All translations convey the same core messages about invalid captcha verification and completing the captcha
- The messages are properly formatted and follow the same structure as other validation messages
- No language files are missing these validation entries
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Description: Check if captcha validation messages exist in all language files
# Expected: All language files should have these validation messages
# Find all validation.php files in language directories
fd validation.php api/resources/lang -x grep -l "invalid_captcha\|complete_captcha" {} \; | sort
# Show the actual translations for comparison
echo "\nTranslations across languages:"
fd validation.php api/resources/lang -x sh -c 'echo "=== {} ==="; grep -A 1 "invalid_captcha\|complete_captcha" {}' \;
Length of output: 5066
api/resources/lang/ta/validation.php (1)
136-137
: LGTM! The CAPTCHA validation messages are well-structured.
The new Tamil translations for CAPTCHA validation messages are properly integrated and follow the existing pattern in the language file. The messages cover both essential validation scenarios (invalid and incomplete CAPTCHA).
Let's verify the Tamil translations are accurate:
✅ Verification successful
The Tamil CAPTCHA validation messages are accurate and consistent with other translations
The Tamil translations are well-aligned with translations in other Indian languages (Hindi, Telugu) and follow similar patterns seen in other non-Latin script languages. The messages maintain consistent meaning while being culturally appropriate:
invalid_captcha
: "தவறான கையால் வைத்த முறை. மீண்டும் முயற்சிக்கவும்." (Invalid CAPTCHA. Please try again) - matches the error notification pattern seen in Telugu and Hindicomplete_captcha
: "கையால் வைத்த முறையை நிரப்பவும்." (Please complete the CAPTCHA) - follows the same instructional tone as other languages
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Description: Search for similar CAPTCHA validation messages in other language files to cross-reference translations
# Test: Look for CAPTCHA-related messages in other language files
fd --type f --extension php . api/resources/lang | xargs rg -l "captcha"
# Test: Compare with English translations for reference
fd --type f --extension php . api/resources/lang/en | xargs rg "invalid_captcha|complete_captcha"
Length of output: 1201
Script:
#!/bin/bash
# Let's check the translations in other Indian languages (Hindi, Tamil, Telugu) for comparison
rg "invalid_captcha|complete_captcha" api/resources/lang/hi/validation.php api/resources/lang/te/validation.php
# Also check translations in languages that use non-Latin scripts
rg "invalid_captcha|complete_captcha" api/resources/lang/zh/validation.php api/resources/lang/ar/validation.php api/resources/lang/ru/validation.php
Length of output: 1295
api/resources/lang/pt-BR/validation.php (1)
183-184
: Verify consistency across language files.
Since this PR adds support for multiple captcha providers, we should ensure these validation messages are consistently added to all supported language files.
✅ Verification successful
Captcha validation messages are consistently present across all language files
The verification shows that both 'invalid_captcha' and 'complete_captcha' validation messages are properly implemented across all language validation files:
- Present in all main language validation files (ar, bn, de, en, es, fr, hi, ja, jv, ko, mr, pa, pt, pt-BR, ru, ta, te, tr, ur, vi, zh, zh-CN)
- Messages are appropriately translated for each language
- Correctly absent from auth.php, pagination.php, and passwords.php files as these messages belong in validation.php
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Description: Check if captcha validation messages exist in all language files
# Find all language files
echo "Checking language files for captcha validation messages..."
for lang_file in $(fd . api/resources/lang -e php); do
echo "\nChecking $lang_file:"
# Search for captcha-related messages
echo "- invalid_captcha:"
rg "'invalid_captcha'" "$lang_file" || echo " Not found!"
echo "- complete_captcha:"
rg "'complete_captcha'" "$lang_file" || echo " Not found!"
done
Length of output: 17707
api/resources/lang/ur/validation.php (1)
119-120
: LGTM! Verify translations in other language files.
The new captcha validation messages are well-implemented in Urdu, providing clear user feedback for both invalid and incomplete captcha scenarios. The messages are generic enough to work with both hCaptcha and reCAPTCHA providers.
Let's verify that these new validation messages are consistently implemented across other language files:
✅ Verification successful
This script will show us the actual translations (or lack thereof) in each language file, allowing us to verify if the messages are properly translated or missing in any language.
Captcha validation messages are properly implemented across all language files
The verification shows that both invalid_captcha
and complete_captcha
messages are present and properly translated in all language files (ar, bn, de, en, es, fr, hi, ja, jv, ko, mr, pa, pt, pt-BR, ru, ta, te, tr, ur, vi, zh, zh-CN). Each translation:
- Maintains consistent meaning across languages
- Uses appropriate cultural context and language-specific terms
- Follows proper grammar and punctuation for each language
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Description: Check if the new captcha validation messages exist in all language files
# and ensure consistency across translations.
# Find all validation.php files in language directories
fd validation.php api/resources/lang | while read -r file; do
echo "Checking $file for captcha validation messages..."
# Check for both validation messages
rg -q "invalid_captcha|complete_captcha" "$file" || echo "Missing captcha messages in $file"
done
Length of output: 5923
Script:
#!/bin/bash
# Let's check the actual content of validation messages in each language file
# to ensure they are properly translated and not missing
for lang_file in $(fd validation.php api/resources/lang); do
echo "=== $lang_file ==="
rg "('|\")(invalid_captcha|complete_captcha)('|\").*=>" "$lang_file" || echo "No captcha messages found"
done
Length of output: 8601
api/resources/lang/ar/validation.php (1)
119-120
: LGTM: Proper Arabic translations for captcha validation
The added translations are linguistically appropriate and cover both invalid captcha and incomplete captcha scenarios.
api/resources/lang/pa/validation.php (1)
119-120
: LGTM: Proper Punjabi translations for captcha validation
The added translations are linguistically appropriate and maintain consistency with the existing translation patterns.
api/resources/lang/de/validation.php (1)
119-120
: LGTM! German translations are accurate and well-formatted.
The translations maintain proper German formal tone and correctly convey the CAPTCHA validation messages.
api/resources/lang/es/validation.php (1)
Line range hint 119-120
: Translations are consistent across languages.
The validation messages maintain consistent meaning and structure across German, Portuguese, and Spanish translations, effectively supporting the multi-captcha provider implementation.
Also applies to: 119-120, 156-157
✅ Verification successful
Translations are consistent across all language files
The verification confirms that CAPTCHA-related validation messages are properly implemented across all language files (21 languages) with consistent meaning and structure:
- All languages include both
invalid_captcha
andcomplete_captcha
messages - The translations maintain semantic equivalence:
- Invalid CAPTCHA messages consistently convey verification failure and bot prevention
- Complete CAPTCHA messages consistently request user completion of the verification
- The messages effectively support multi-captcha provider implementation while maintaining localization quality
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Verify consistency of CAPTCHA validation messages across all language files
echo "Checking for CAPTCHA validation messages in all language files..."
rg -l "invalid_captcha|complete_captcha" "api/resources/lang/*/validation.php"
Length of output: 297
Script:
#!/bin/bash
# First, let's find the actual path of language files
fd "validation.php" resources
# Then check the content of these files for CAPTCHA-related messages
echo "=== Checking content of validation files ==="
fd "validation.php" resources -x cat {}
Length of output: 364
Script:
#!/bin/bash
# Let's first check the directory structure to locate the language files
ls -R api/resources/lang/
# Then we'll examine the content of any validation.php files we find
find api/resources/lang/ -name "validation.php" -type f -exec cat {} \;
Length of output: 67404
Script:
#!/bin/bash
# Let's specifically check for CAPTCHA-related messages in validation files
echo "=== Checking CAPTCHA messages in validation files ==="
for lang_file in api/resources/lang/*/validation.php; do
echo "=== $lang_file ==="
grep -A 1 "invalid_captcha\|complete_captcha" "$lang_file" || true
done
Length of output: 8344
api/resources/lang/fr/validation.php (1)
119-120
: LGTM! French translations are accurate and consistent.
The new CAPTCHA validation messages are properly translated to French and maintain consistency with Laravel's translation conventions. They are also provider-agnostic, which aligns well with the multi-captcha support objective.
api/resources/lang/en/validation.php (1)
153-154
: Verify usage of translation keys across the codebase.
Let's ensure these new translation keys are properly used throughout the codebase and that there are no hardcoded CAPTCHA messages.
✅ Verification successful
Translation keys are properly used and no hardcoded messages found
The verification shows that:
- The translation keys are properly used in both
ValidHCaptcha
andValidReCaptcha
validation rules - The frontend components properly handle CAPTCHA integration without hardcoded messages
- All CAPTCHA-related messages are properly internationalized across multiple language files
- The implementation consistently uses the translation keys for both validation scenarios:
validation.invalid_captcha
for invalid responsesvalidation.complete_captcha
when CAPTCHA is not completed
No issues were found with the implementation of these translation keys.
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Description: Check for proper usage of translation keys and potential hardcoded messages
# Check for usage of translation keys
echo "Checking for usage of translation keys..."
rg "('|\")(validation\.invalid_captcha|validation\.complete_captcha)('|\")"
# Check for potential hardcoded CAPTCHA messages
echo "Checking for potential hardcoded CAPTCHA messages..."
rg -i "captcha.*invalid|invalid.*captcha|complete.*captcha" --type php --type vue --type js
Length of output: 759
Script:
#!/bin/bash
# Let's try a different approach to check for hardcoded CAPTCHA messages and verify usage
# Check for any CAPTCHA-related strings in PHP files
echo "Checking for CAPTCHA-related strings in PHP files..."
rg -i "captcha" --type php -A 2 -B 2
# Check for translation usage in validation rules
echo "Checking validation rules implementation..."
fd "ValidHCaptcha.php|ValidReCaptcha.php" --type f --exec cat {}
# Check for Vue files specifically (since previous command had issues with Vue type)
echo "Checking Vue files for CAPTCHA-related content..."
fd "\.vue$" --type f --exec rg -i "captcha" {}
Length of output: 29930
api/app/Rules/ValidHCaptcha.php (3)
25-25
: LGTM: Consistent use of translation keys
The error message for empty captcha responses now uses a translation key, maintaining consistency with the internationalization approach.
Let's verify the translation key exists:
✅ Verification successful
Translation key is properly defined across all language files
The translation key 'validation.complete_captcha' is correctly defined in all language files under api/resources/lang/, including English and multiple other languages. The key is consistently used in both ValidHCaptcha.php and ValidReCaptcha.php for captcha validation errors.
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Check if the translation key exists in language files
rg -g "*.php" "complete_captcha" resources/lang/
Length of output: 104
Script:
#!/bin/bash
# Let's first find where the language files might be located
fd -t d "lang"
# Then search for the translation key in all PHP files
rg -g "*.php" "complete_captcha"
Length of output: 2265
13-13
: LGTM: Good move to use translation keys
The change from hardcoded error message to a translation key improves internationalization support.
Let's verify the translation key exists:
✅ Verification successful
Translation key is properly defined across multiple languages
The translation key 'validation.invalid_captcha' is correctly implemented and available in all language files under api/resources/lang/*/validation.php, including English and 22 other languages. The change to use this translation key supports proper internationalization.
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Check if the translation key exists in language files
rg -g "*.php" "invalid_captcha" resources/lang/
Length of output: 103
Script:
#!/bin/bash
# Let's try to find translation files in different common locations
fd -e php -e json "lang|locales|translations" --type d
# After finding directories, let's search for the translation key
rg "invalid_captcha"
Length of output: 2775
Line range hint 1-51
: Verify integration with reCAPTCHA implementation
The changes look good, but since this is part of a multi-captcha provider implementation, we should verify the integration points.
Let's check how this class is used with the new captcha provider selection:
✅ Verification successful
Integration with reCAPTCHA implementation is properly handled
The code shows a well-structured multi-captcha provider implementation:
- Form model has
captcha_provider
field with support for both 'hcaptcha' and 'recaptcha' - AnswerFormRequest properly switches between ValidHCaptcha and ValidReCaptcha rules based on the form's captcha_provider
- Both captcha validation rules follow the same interface and validation pattern
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Check for usage of ValidHCaptcha in form requests and other validation contexts
rg -A 5 "ValidHCaptcha" app/Http/Requests/
# Check for captcha provider selection logic
ast-grep --pattern 'if ($_ === "hcaptcha") {
$$$
}'
Length of output: 157
Script:
#!/bin/bash
# Let's first find all request files in the codebase
fd "Request.php$"
# Search for ValidHCaptcha usage across the codebase
rg -l "ValidHCaptcha"
# Search for captcha provider selection or configuration
rg -l "captcha|CAPTCHA" config/
rg -A 5 "captcha.*provider"
# Look for any validation rules related to captcha
ast-grep --pattern 'rules($$$) {
return [
$$$
"captcha" => $$$
$$$
];
}'
Length of output: 68707
Script:
#!/bin/bash
# Let's check the AnswerFormRequest since it uses ValidHCaptcha
cat api/app/Http/Requests/AnswerFormRequest.php
# Look for form model to see captcha provider configuration
rg -l "captcha_provider" api/app/Models/
# Check for any captcha validation rules
rg "captcha.*rule" api/app/Http/
Length of output: 11765
Script:
#!/bin/bash
# Let's check the Form model for captcha provider configuration
cat api/app/Models/Forms/Form.php
# Check the ValidReCaptcha rule implementation
cat api/app/Rules/ValidReCaptcha.php
Length of output: 9557
'invalid_captcha' => 'অবৈধ টিপস। অনুগ্রহ করে টিপস টিপুন।', | ||
'complete_captcha' => 'অনুগ্রহ করে টিপস টিপুন।', |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Translation needs improvement for clarity
The current Bengali translations for CAPTCHA-related messages use "টিপস" (tips) which is incorrect. Consider using "ক্যাপচা" (captcha) instead for better clarity. Here are the suggested translations:
- 'invalid_captcha' => 'অবৈধ টিপস। অনুগ্রহ করে টিপস টিপুন।',
- 'complete_captcha' => 'অনুগ্রহ করে টিপস টিপুন।',
+ 'invalid_captcha' => 'অবৈধ ক্যাপচা। অনুগ্রহ করে ক্যাপচা সম্পূর্ণ করুন।',
+ 'complete_captcha' => 'অনুগ্রহ করে ক্যাপচা সম্পূর্ণ করুন।',
This will make it clearer to Bengali-speaking users that they need to complete a CAPTCHA verification.
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
'invalid_captcha' => 'অবৈধ টিপস। অনুগ্রহ করে টিপস টিপুন।', | |
'complete_captcha' => 'অনুগ্রহ করে টিপস টিপুন।', | |
'invalid_captcha' => 'অবৈধ ক্যাপচা। অনুগ্রহ করে ক্যাপচা সম্পূর্ণ করুন।', | |
'complete_captcha' => 'অনুগ্রহ করে ক্যাপচা সম্পূর্ণ করুন।', |
@@ -115,5 +115,7 @@ | |||
|
|||
'attributes' => [], | |||
|
|||
'invalid_json' => 'ਗਲਤ ਇਨਪੁਟ। ਕਿਰਪਾ ਕਰਕੇ ਸਹੀ ਕਰੋ ਅਤੇ ਦੁਬਾਰਾ ਕੋਸ਼ਿਸ਼ ਕਰੋ।', | |||
'invalid_json' => 'ਗਲਤ ਇਨਪੁਟ। ਕਿਰਪਾ ਕਰਕਕੇ ਸਹੀ ਕਰੋ ਅਤੇ ਦੁਬਾਰਾ ਕੋਸ਼ਿਸ਼ ਕਰੋ।', |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Consider reverting the spelling change in invalid_json message
The change from "ਕਿਰਪਾ ਕਰਕੇ" to "ਕਿਰਪਾ ਕਰਕਕੇ" appears to be a typo. The original spelling "ਕਿਰਪਾ ਕਰਕੇ" is the correct form in Punjabi.
- 'invalid_json' => 'ਗਲਤ ਇਨਪੁਟ। ਕਿਰਪਾ ਕਰਕਕੇ ਸਹੀ ਕਰੋ ਅਤੇ ਦੁਬਾਰਾ ਕੋਸ਼ਿਸ਼ ਕਰੋ।',
+ 'invalid_json' => 'ਗਲਤ ਇਨਪੁਟ। ਕਿਰਪਾ ਕਰਕੇ ਸਹੀ ਕਰੋ ਅਤੇ ਦੁਬਾਰਾ ਕੋਸ਼ਿਸ਼ ਕਰੋ।',
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
'invalid_json' => 'ਗਲਤ ਇਨਪੁਟ। ਕਿਰਪਾ ਕਰਕਕੇ ਸਹੀ ਕਰੋ ਅਤੇ ਦੁਬਾਰਾ ਕੋਸ਼ਿਸ਼ ਕਰੋ।', | |
'invalid_json' => 'ਗਲਤ ਇਨਪੁਟ। ਕਿਰਪਾ ਕਰਕੇ ਸਹੀ ਕਰੋ ਅਤੇ ਦੁਬਾਰਾ ਕੋਸ਼ਿਸ਼ ਕਰੋ।', |
- 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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 2
🧹 Nitpick comments (3)
api/tests/Feature/RegisterTest.php (1)
80-83
: Update test method name to match implementationThe test method name still references hCaptcha while testing reCAPTCHA functionality.
-it('requires hcaptcha token in production', function () { +it('requires recaptcha token in production', function () {client/components/pages/auth/components/RegisterForm.vue (2)
60-64
: Consider adding error handling for captcha failuresThe CaptchaInput component implementation should handle and display user-friendly error messages when the captcha verification fails.
Consider adding error handling:
<CaptchaInput ref="captcha" provider="recaptcha" :form="form" + @error="handleCaptchaError" language="en" />
And add the error handler method:
methods: { handleCaptchaError(error) { useAlert().error('Captcha verification failed. Please try again.'); console.error('Captcha error:', error); } }
177-177
: Consider adding loading state for captcha initializationThe form currently doesn't indicate when the captcha is loading. This might confuse users on slower connections.
Add a loading state:
data: () => ({ form: useForm({ // ... other fields 'g-recaptcha-response': null }), disableEmail: false, + captchaLoading: true }), computed: { recaptchaSiteKey() { return this.runtimeConfig.public.recaptchaSiteKey },
And update the template:
<div v-if="recaptchaSiteKey" class="mb-3 px-2 mt-2 mx-auto w-max"> + <div v-if="captchaLoading" class="text-center text-sm text-gray-500"> + Loading captcha... + </div> <CaptchaInput ref="captcha" provider="recaptcha" :form="form" language="en" + @ready="captchaLoading = false" /> </div>Also applies to: 183-184
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (3)
api/app/Http/Controllers/Auth/RegisterController.php
(2 hunks)api/tests/Feature/RegisterTest.php
(6 hunks)client/components/pages/auth/components/RegisterForm.vue
(4 hunks)
🔇 Additional comments (1)
api/tests/Feature/RegisterTest.php (1)
4-4
: LGTM: Test cases properly updated for reCAPTCHA integration
The changes correctly reflect the transition from hCaptcha to reCAPTCHA:
- Import statement updated to use ValidReCaptcha
- Mock response URL updated to use RECAPTCHA_VERIFY_URL
- Request payload updated to use 'g-recaptcha-response'
Also applies to: 10-10, 20-20
if (config('services.recaptcha.secret_key')) { | ||
$rules['g-recaptcha-response'] = [new ValidReCaptcha()]; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
💡 Codebase verification
Configuration check is properly implemented
The reCAPTCHA implementation is correctly configured:
- The
services.php
config file properly defines the reCAPTCHA configuration using environment variables - The
.env.example
includes the required environment variablesRE_CAPTCHA_SITE_KEY
andRE_CAPTCHA_SECRET_KEY
- The
ValidReCaptcha
rule implementation correctly uses the configuration viaconfig('services.re_captcha.secret_key')
Note: There's a minor discrepancy between the config key in the controller (services.recaptcha.secret_key
) and the actual config key (services.re_captcha.secret_key
), which should be fixed.
🔗 Analysis chain
Verify reCAPTCHA configuration in production
The validation rule is only added when recaptcha.secret_key is configured. Ensure this configuration is properly set in production environments.
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Check if reCAPTCHA configuration exists in environment files
echo "Checking for reCAPTCHA configuration..."
rg -l 'RE_CAPTCHA_SECRET_KEY|RECAPTCHA_SECRET_KEY' .env* config/*
Length of output: 255
Script:
#!/bin/bash
# Let's check the config files and environment templates more thoroughly
echo "Checking for reCAPTCHA configuration in config files..."
fd -t f . config -x cat {} \; | rg -i 'recaptcha|captcha'
echo -e "\nChecking environment template files..."
fd -g ".env*" . -x cat {} \; | rg -i 'recaptcha|captcha'
echo -e "\nChecking for ValidReCaptcha class usage..."
rg -l "ValidReCaptcha" .
Length of output: 939
Script:
#!/bin/bash
# Let's examine the ValidReCaptcha rule implementation and its usage
echo "Checking ValidReCaptcha rule implementation..."
cat ./api/app/Rules/ValidReCaptcha.php
echo -e "\nChecking reCAPTCHA configuration in services.php..."
cat ./api/config/services.php
echo -e "\nChecking .env.example for reCAPTCHA configuration..."
cat ./api/.env.example
Length of output: 5664
// Reset captcha after submission | ||
if (import.meta.client && this.recaptchaSiteKey) { | ||
this.$refs.captcha.reset() |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Improve captcha reset logic
The current implementation resets the captcha after form submission, which might be confusing if the submission fails. Consider moving the reset after successful submission.
async register() {
let data
this.form.utm_data = this.$utm.value
- // Reset captcha after submission
- if (import.meta.client && this.recaptchaSiteKey) {
- this.$refs.captcha.reset()
- }
try {
// Register the user.
data = await this.form.post("/register")
+ // Reset captcha only after successful registration
+ if (import.meta.client && this.recaptchaSiteKey) {
+ this.$refs.captcha.reset()
+ }
} catch (err) {
useAlert().error(err.response?._data?.message)
return false
}
Committable suggestion skipped: line range outside the PR's diff.
- 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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 3
🧹 Nitpick comments (1)
client/components/pages/auth/components/RegisterForm.vue (1)
145-145
: Consider implementing a proper captcha provider strategyThe current implementation lacks a robust architecture for handling multiple captcha providers. Consider these improvements:
- Add a provider selection mechanism
- Implement provider-specific validation
- Add error handling for provider-specific issues
- Create a configuration object for supported providers
Would you like help implementing these architectural improvements?
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (2)
api/app/Http/Controllers/Auth/RegisterController.php
(2 hunks)client/components/pages/auth/components/RegisterForm.vue
(4 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
- api/app/Http/Controllers/Auth/RegisterController.php
🔇 Additional comments (1)
client/components/pages/auth/components/RegisterForm.vue (1)
229-231
: Captcha reset timing issue
The captcha is still being reset before form submission, which could be problematic if the submission fails.
Please refer to the previous review comment about moving the reset after successful submission.
<!-- 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" |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Provider should be configurable, not hardcoded
The hardcoded provider="recaptcha"
contradicts the PR's objective of supporting multiple captcha providers. The provider should be dynamic to allow users to choose between hCaptcha and reCAPTCHA.
Consider this modification:
<CaptchaInput
ref="captcha"
- provider="recaptcha"
+ :provider="selectedCaptchaProvider"
:form="form"
language="en"
/>
Add a computed property or data field to determine the selected provider.
Committable suggestion skipped: line range outside the PR's diff.
@@ -177,15 +174,14 @@ | |||
agree_terms: false, | |||
appsumo_license: null, | |||
utm_data: null, | |||
'h-captcha-response': null | |||
'g-recaptcha-response': null |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Form data should handle both captcha providers
The form data only includes the reCAPTCHA response field. To support both providers, we need to handle both types of responses.
Consider this approach:
- 'g-recaptcha-response': null
+ captcha_response: null,
+ captcha_provider: null
Then update the backend to map captcha_response
to the appropriate provider-specific field based on captcha_provider
.
Committable suggestion skipped: line range outside the PR's diff.
recaptchaSiteKey() { | ||
return this.runtimeConfig.public.recaptchaSiteKey |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Computed properties should support both captcha providers
The computed properties only handle reCAPTCHA configuration. To support multiple providers, we need computed properties for both reCAPTCHA and hCaptcha.
Consider this approach:
- recaptchaSiteKey() {
- return this.runtimeConfig.public.recaptchaSiteKey
+ captchaSiteKey() {
+ const provider = this.selectedCaptchaProvider
+ return provider === 'recaptcha'
+ ? this.runtimeConfig.public.recaptchaSiteKey
+ : this.runtimeConfig.public.hcaptchaSiteKey
},
Committable suggestion skipped: line range outside the PR's diff.
…rmat - 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.
These changes improve the flexibility of captcha options available to users, enhancing form security and user experience.
Summary by CodeRabbit
Release Notes
New Features
CaptchaInput
component for flexible captcha integration.Bug Fixes
Chores