-
Notifications
You must be signed in to change notification settings - Fork 1
[659] feat(form): Add reCAPTCHA validation to form submissions #197
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
Merged
Merged
Changes from 7 commits
Commits
Show all changes
31 commits
Select commit
Hold shift + click to select a range
f474602
enhancement form validation
VitalyyP 6829362
remove commented code
VitalyyP 6102d90
remove thanks alert
VitalyyP 6611ef9
Add reCAPTCHA to form submission
IhorMasechko 2d92e5d
Merged with main branch
IhorMasechko 431b416
Fix lint errors
IhorMasechko f68f03e
Add reCAPTCHA verification to form submission
VitalyyP cecf63b
Fix spreadsheet formatting to skip recaptcha field
VitalyyP 6d73488
Downgrade node-fetch to v2.7.0 for compatibility
VitalyyP 7ff0436
Remove custom-form module and references
VitalyyP 867d8e7
Improve reCAPTCHA error handling and validation in form widget
VitalyyP a9f3349
Refactor reCAPTCHA error markup and adjust error position in form
VitalyyP 22826bb
Add reCAPTCHA validation to form handling
VitalyyP 69a164a
Improve reCAPTCHA verification and validation
VitalyyP f09adac
Use x-forwarded-for for recaptcha remoteip
VitalyyP f5dd2ba
Refactor and extend reCAPTCHA validation
VitalyyP 22cc595
Fix recaptcha validation to scope query to form element
VitalyyP 33fc6cb
Refactor reCAPTCHA validation and update node-fetch version
VitalyyP 56418a8
Update node-fetch version in website dependencies
VitalyyP 8c87275
Refactor recaptcha validation handlers to use arrow functions
VitalyyP 073a037
test commit
VitalyyP d80452e
Remove commented-out positioning styles from form error classes
VitalyyP 9e18656
Revert "test commit"
VitalyyP 4db794e
Merge branch 'main' into 659-admin-recaptcha-config
Anton-88 b80ab64
Merge branch 'main' into 659-admin-recaptcha-config
yuramax 9538251
Merge branch '659-admin-recaptcha-config' of github.com:speedandfunct…
yuramax 39f14a6
Update form widget template - SonarQube rule can be ignored for this …
yuramax 4171c1a
Extract reCAPTCHA script to separate file and exclude from SonarQube …
yuramax a345527
Fix include path for recaptcha script - use relative path
yuramax 86d6b41
Revert to inline script with SonarQube ignore comments - more reliabl…
yuramax 456194b
Extract reCAPTCHA script to separate include file
yuramax File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
36 changes: 36 additions & 0 deletions
36
website/modules/@apostrophecms/form/lib/verifyRecaptcha.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,36 @@ | ||
| const fetch = require('node-fetch'); | ||
|
|
||
| const verifyRecaptcha = async function ({ secret, token, remoteip }) { | ||
| if (!token || token.trim() === '') { | ||
| return { success: false, error: 'Missing reCAPTCHA token.' }; | ||
| } | ||
|
VitalyyP marked this conversation as resolved.
Outdated
|
||
| const params = new URLSearchParams(); | ||
| params.append('secret', secret); | ||
| params.append('response', token); | ||
| params.append('remoteip', remoteip); | ||
|
|
||
| const response = await fetch( | ||
| 'https://www.google.com/recaptcha/api/siteverify', | ||
| { | ||
| method: 'POST', | ||
| headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, | ||
| body: params, | ||
| timeout: 5000, | ||
| }, | ||
| ); | ||
|
VitalyyP marked this conversation as resolved.
Outdated
|
||
|
|
||
| if (!response.ok) { | ||
| return { success: false, error: `HTTP error! status: ${response.status}` }; | ||
| } | ||
| const data = await response.json(); | ||
| if (!data.success) { | ||
| return { | ||
| success: false, | ||
| error: 'reCAPTCHA verification failed.', | ||
| details: data, | ||
| }; | ||
| } | ||
| return { success: true, details: data }; | ||
| }; | ||
|
|
||
| module.exports = { verifyRecaptcha }; | ||
62 changes: 62 additions & 0 deletions
62
website/modules/@apostrophecms/form/lib/verifyRecaptcha.test.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,62 @@ | ||
| const { verifyRecaptcha } = require('./verifyRecaptcha'); | ||
|
|
||
| jest.mock('node-fetch'); | ||
| const fetch = require('node-fetch'); | ||
|
|
||
| describe('verifyRecaptcha', () => { | ||
| beforeEach(() => { | ||
| fetch.mockReset(); | ||
| }); | ||
|
|
||
| it('should fail if token is missing', async () => { | ||
| const result = await verifyRecaptcha({ | ||
| secret: 'test', | ||
| token: '', | ||
| remoteip: '127.0.0.1', | ||
| }); | ||
| expect(result.success).toBe(false); | ||
| expect(result.error).toBe('Missing reCAPTCHA token.'); | ||
| }); | ||
|
|
||
| it('should fail if Google returns error', async () => { | ||
| fetch.mockResolvedValueOnce({ | ||
| ok: true, | ||
| json: () => ({ success: false }), | ||
| }); | ||
| const result = await verifyRecaptcha({ | ||
| secret: 'test', | ||
| token: 'sometoken', | ||
| remoteip: '127.0.0.1', | ||
| }); | ||
| expect(result.success).toBe(false); | ||
| expect(result.error).toBe('reCAPTCHA verification failed.'); | ||
| }); | ||
|
|
||
| it('should succeed if Google returns success', async () => { | ||
| fetch.mockResolvedValueOnce({ | ||
| ok: true, | ||
| json: () => ({ success: true }), | ||
| }); | ||
| const result = await verifyRecaptcha({ | ||
| secret: 'test', | ||
| token: 'sometoken', | ||
| remoteip: '127.0.0.1', | ||
| }); | ||
| expect(result.success).toBe(true); | ||
| }); | ||
|
|
||
| it('should fail if Google returns HTTP error', async () => { | ||
| fetch.mockResolvedValueOnce({ | ||
| ok: false, | ||
| status: 500, | ||
| json: () => ({}), | ||
| }); | ||
| const result = await verifyRecaptcha({ | ||
| secret: 'test', | ||
| token: 'sometoken', | ||
| remoteip: '127.0.0.1', | ||
| }); | ||
| expect(result.success).toBe(false); | ||
| expect(result.error).toMatch(/HTTP error/u); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,61 @@ | ||
| const fetch = require('node-fetch'); | ||
|
|
||
| const handleSubmit = async (self, req) => { | ||
| const global = await req.apos.global.get(req); | ||
| const recaptchaToken = req.body['g-recaptcha-response']; | ||
|
|
||
| const enableRecaptcha = global.useRecaptcha && global.recaptchaSecret; | ||
|
|
||
| if (enableRecaptcha) { | ||
| if (!recaptchaToken) { | ||
| return req.res.status(400).json({ error: 'Missing reCAPTCHA token.' }); | ||
| } | ||
|
|
||
| try { | ||
| const params = new URLSearchParams(); | ||
| params.append('secret', global.recaptchaSecret); | ||
| params.append('response', recaptchaToken); | ||
| params.append('remoteip', req.ip); | ||
|
|
||
| const response = await fetch( | ||
| 'https://www.google.com/recaptcha/api/siteverify', | ||
| { | ||
| method: 'POST', | ||
| headers: { | ||
| 'Content-Type': 'application/x-www-form-urlencoded', | ||
| }, | ||
| body: params, | ||
| timeout: 5000, | ||
| }, | ||
| ); | ||
| if (!response.ok) { | ||
| throw new Error(`HTTP error! status: ${response.status}`); | ||
| } | ||
|
|
||
| const data = await response.json(); | ||
|
|
||
| if (!data.success) { | ||
| return req.res | ||
| .status(400) | ||
| .json({ error: 'reCAPTCHA verification failed.' }); | ||
| } | ||
| } catch (err) { | ||
| // Logging the error for debugging purposes | ||
| /* eslint-disable-next-line no-console */ | ||
| console.error('reCAPTCHA error:', err); | ||
|
|
||
| return req.res.status(500).json({ error: 'Error verifying reCAPTCHA.' }); | ||
| } | ||
| } | ||
|
|
||
| return self.super.handlers.submit(req); | ||
| }; | ||
|
|
||
| module.exports = { | ||
| extend: '@apostrophecms/form', | ||
| handlers(self) { | ||
| return { | ||
| submit: (req) => handleSubmit(self, req), | ||
| }; | ||
| }, | ||
| }; |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.