forked from juice-shop/juice-shop
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathimageCaptcha.js
48 lines (43 loc) · 1.29 KB
/
imageCaptcha.js
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
46
47
48
/*
* Copyright (c) 2014-2020 Bjoern Kimminich.
* SPDX-License-Identifier: MIT
*/
const svgCaptcha = require('svg-captcha')
const models = require('../models/index')
const Op = models.Sequelize.Op
const insecurity = require('../lib/insecurity')
function imageCaptchas () {
return (req, res) => {
const captcha = svgCaptcha.create({ size: 5, noise: 2, color: true })
const imageCaptcha = {
image: captcha.data,
answer: captcha.text,
UserId: insecurity.authenticatedUsers.from(req).data.id
}
const imageCaptchaInstance = models.ImageCaptcha.build(imageCaptcha)
imageCaptchaInstance.save().then(() => {
res.json(imageCaptcha)
})
}
}
imageCaptchas.verifyCaptcha = () => (req, res, next) => {
const user = insecurity.authenticatedUsers.from(req)
const UserId = user ? user.data ? user.data.id : undefined : undefined
models.ImageCaptcha.findAll({
limit: 1,
where: {
UserId: UserId,
createdAt: {
[Op.gt]: new Date(new Date() - 300000)
}
},
order: [['createdAt', 'DESC']]
}).then(captchas => {
if (!captchas[0] || req.body.answer === captchas[0].dataValues.answer) {
next()
} else {
res.status(401).send(res.__('Wrong answer to CAPTCHA. Please try again.'))
}
})
}
module.exports = imageCaptchas