Skip to content

Commit

Permalink
feat: setup ReCaptcha API endpoint
Browse files Browse the repository at this point in the history
  • Loading branch information
martapanc committed Feb 16, 2024
1 parent 1d1f673 commit a69c3ef
Show file tree
Hide file tree
Showing 3 changed files with 54 additions and 58 deletions.
35 changes: 18 additions & 17 deletions src/components/molecules/ContactForm/ContactForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,18 +6,12 @@ import ReCAPTCHA from 'react-google-recaptcha';
import { Trans, useTranslation } from 'react-i18next';
import * as Yup from 'yup';

import { verifyCaptcha } from '@/lib/verifyCaptcha';

import Button from '@/components/atoms/buttons/Button';

import { Input } from './Input';
import { Select } from './Select';
import { TextArea } from './TextArea';

export interface ContactFormProps {
subjects: Subject[];
}

export interface Subject {
key: string;
value: string;
Expand All @@ -33,17 +27,24 @@ const ContactForm = () => {
const reCaptchaSiteKey = '6LcSyzAoAAAAAC7JTJ6gtOWW3cjTK_vKRm2WjEtC';

async function handleCaptchaSubmission(token: string | null) {
// Server function to verify captcha
await verifyCaptcha(token)
.then(() => {
setIsVerified(true);
})
.catch((err) => {
// eslint-disable-next-line no-console
console.log(err);
setIsVerified(false);
setError(true);
});
const res = await fetch('/api/recaptcha', {
body: JSON.stringify({ token }),
headers: {
'Content-Type': 'application/json',
},
method: 'POST',
});

const { success, error } = await res.json();

if (success) {
setIsVerified(true);
} else {
setIsVerified(false);
setError(true);
// eslint-disable-next-line no-console
console.error(error);
}
}

useEffect(() => {}, [isVerified]);
Expand Down
41 changes: 0 additions & 41 deletions src/lib/verifyCaptcha.ts

This file was deleted.

36 changes: 36 additions & 0 deletions src/pages/api/recaptcha.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { NextApiRequest, NextApiResponse } from 'next';

export default async function handler(
req: NextApiRequest,
res: NextApiResponse,
) {
const { token } = req.body;

if (!token) {
return res.status(400).json({ error: 'Error providing ReCaptcha token' });
}

const key = process.env.RECAPTCHA_SECRET_KEY;

if (!key) {
return res
.status(500)
.json({ error: 'Error retrieving reCaptcha secret key.' });
}

const url = 'https://www.google.com/recaptcha/api/siteverify';

const response = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: `secret=${key}&response=${token}`,
});

if (!response.ok) {
return res.status(500).json({ error: 'Error verifying reCaptcha.' });
}

return res.status(200).json({ success: 'Verified' });
}

0 comments on commit a69c3ef

Please sign in to comment.