Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions lib/verifyCaptcha.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
export async function verifyCaptcha(token: string): Promise<void> {
const secret = process.env.CAPTCHA_SECRET
if (!secret) {
throw new Error('Missing CAPTCHA secret configuration')
}
const response = await fetch(
'https://www.google.com/recaptcha/api/siteverify',
{
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: `secret=${secret}&response=${token}`
}
)
const data: { success: boolean } = await response.json()
if (!data.success) {
throw new Error('Captcha verification failed')
}
}
14 changes: 11 additions & 3 deletions routes/securityQuestion.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,17 @@ import { type Request, type Response, type NextFunction } from 'express'
import { SecurityAnswerModel } from '../models/securityAnswer'
import { UserModel } from '../models/user'
import { SecurityQuestionModel } from '../models/securityQuestion'
import { verifyCaptcha } from '../lib/verifyCaptcha'

module.exports = function securityQuestion () {
return ({ query }: Request, res: Response, next: NextFunction) => {
const email = query.email
SecurityAnswerModel.findOne({
return (req: Request, res: Response, next: NextFunction) => {
const email = req.query.email
const responseToken = req.query.captchaToken?.toString()
if (!responseToken) {
return res.status(400).json({ error: 'Missing CAPTCHA token' })
}
verifyCaptcha(responseToken).then(() => {
SecurityAnswerModel.findOne({
include: [{
model: UserModel,
where: { email: email?.toString() }
Expand All @@ -28,6 +34,8 @@ module.exports = function securityQuestion () {
}
}).catch((error: unknown) => {
next(error)
}).catch((error: Error) => {
res.status(403).json({ error: 'Invalid CAPTCHA token' })
})
}
}