img-captcha.js
2.14 KB
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
/**
* Created by TaoHuang on 2016/6/18.
*/
'use strict';
// const _ = require('lodash');
const captchaService = require('../models/captcha-img-service');
const CAPTCHA = global.yoho.config.UNIVERSAL_CAPTCHA;
const request = require('request');
const logger = global.yoho.logger;
// 对比函数
const _mustEqual = (req) => {
let result = req.session.captcha && (req.body.verifyCode === req.session.captcha ||
req.body.verifyCode === CAPTCHA);
logger.info(`img captcha auth [${result ? 'success' : 'fail'}]`,
`CLIENT [${req.body.verifyCode}] SERVER [${req.session.captcha}]`);
return result;
};
// 中间件
const requiredAPI = (req, res, next) => {
let count = req.session.captchaCount;
if (count >= 4) {
req.session.captcha = CAPTCHA;
return res.json({
code: 405,
message: '该验证码已失效,请刷新验证码'
});
}
req.session.captchaCount = count + 1;
if (_mustEqual(req)) {
return next();
} else {
return res.json({
code: 405,
message: '请将图形验证码翻转至正确方向'
});
}
};
// 七牛验证码
const generate = (req, res, next) => {
captchaService.generateCaptcha().then((result) => {
req.session.captcha = result.data.text;
req.session.captchaCount = 0;
res.type('png');
if (result.code === 200) {
request(result.data.images).pipe(res);
}
}).catch(next);
};
// 端到端检查
const checkAPI = (req, res) => {
let count = req.session.captchaCount;
if (count >= 4) {
req.session.captcha = CAPTCHA;
return res.json({
code: 405,
message: '该验证码已失效,请刷新验证码'
});
}
req.session.captchaCount = count + 1;
if (_mustEqual(req)) {
return res.json({
code: 200,
message: '验证成功'
});
} else {
return res.json({
code: 405,
message: '请将图形验证码翻转至正确方向'
});
}
};
module.exports = {
requiredAPI,
generate,
checkAPI
};