-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcaptcha.ts
45 lines (37 loc) · 1.35 KB
/
captcha.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
/*
* Copyright (c) 2014-2021 Bjoern Kimminich.
* SPDX-License-Identifier: MIT
*/
import models = require('../models/index')
function captchas () {
return (req, res) => {
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 = models.Captcha.build(captcha)
captchaInstance.save().then(() => {
res.json(captcha)
})
}
}
captchas.verifyCaptcha = () => (req, res, next) => {
models.Captcha.findOne({ where: { captchaId: req.body.captchaId } }).then(captcha => {
if (captcha && req.body.captcha === captcha.dataValues.answer) {
next()
} else {
res.status(401).send(res.__('Wrong answer to CAPTCHA. Please try again.'))
}
})
}
module.exports = captchas