Skip to content

Instantly share code, notes, and snippets.

@inkz
Created July 11, 2022 04:01
Show Gist options
  • Save inkz/2d69911f7f4cf552fcea4ad27fc7097e to your computer and use it in GitHub Desktop.
Save inkz/2d69911f7f4cf552fcea4ad27fc7097e to your computer and use it in GitHub Desktop.
/*
* Copyright (c) 2014-2022 Bjoern Kimminich & the OWASP Juice Shop contributors.
* SPDX-License-Identifier: MIT
*/
import {
Model,
InferAttributes,
InferCreationAttributes,
DataTypes,
Sequelize
} from 'sequelize'
class Captcha extends Model<InferAttributes<Captcha>, InferCreationAttributes<Captcha>> {
declare captchaId: number
declare captcha: string
declare answer: string
}
const CaptchaModelInit = (sequelize: Sequelize) => {
Captcha.init(
{
captchaId: {
type: DataTypes.INTEGER
},
captcha: DataTypes.STRING,
answer: DataTypes.STRING
},
{
tableName: 'Captchas',
sequelize
}
)
}
export { Captcha as CaptchaModel, CaptchaModelInit }
/*
* Copyright (c) 2014-2022 Bjoern Kimminich & the OWASP Juice Shop contributors.
* SPDX-License-Identifier: MIT
*/
import { Request, Response, NextFunction } from 'express'
import { Captcha } from '../data/types'
import { CaptchaModel } from '../models/captcha'
function captchas () {
return async (req: Request, res: Response) => {
const captchaId = req.app.locals.captchaId++
const operators = ['*', '+', '-']
const firstTerm = Math.floor((Math.random() * 10) + 1)
const secondTerm = Math.floor((Math.random() * 10) + 1)
const thirdTerm = Math.floor((Math.random() * 10) + 1)
const firstOperator = operators[Math.floor((Math.random() * 3))]
const secondOperator = operators[Math.floor((Math.random() * 3))]
const expression = firstTerm.toString() + firstOperator + secondTerm.toString() + secondOperator + thirdTerm.toString()
const answer = eval(expression).toString() // eslint-disable-line no-eval
const captcha = {
captchaId: captchaId,
captcha: expression,
answer: answer
}
const captchaInstance = CaptchaModel.build(captcha)
await captchaInstance.save()
res.json(captcha)
}
}
captchas.verifyCaptcha = () => (req: Request, res: Response, next: NextFunction) => {
CaptchaModel.findOne({ where: { captchaId: req.body.captchaId } }).then((captcha: Captcha | null) => {
if (captcha && req.body.captcha === captcha.answer) {
next()
} else {
res.status(401).send(res.__('Wrong answer to CAPTCHA. Please try again.'))
}
}).catch((error: Error) => {
next(error)
})
}
module.exports = captchas
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment