img-captcha.js
2.82 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
95
96
97
98
99
100
101
102
103
104
105
/**
* Created by TaoHuang on 2016/6/18.
*/
/**
* 验证码的形式: xxxx|page
*/
const CaptchaServiceModel = require('../models/captcha-img-service');
const request = require('request');
const {CAPTCHA_SWITCH, CAPTCHA_TYPE} = require('../models/captcha-type');
// 对比函数
const _mustEqualAsync = (req) => {
let id = req.session.id;
let verifyCode = req.body.verifyCode;
if (!id || !verifyCode) {
return Promise.resolve({
code: 405,
message: '请将所有图片点击翻转至正向朝上'
});
}
return req.ctx(CaptchaServiceModel).check(id, verifyCode);
};
// 中间件
const requiredAPI = (req, res, next) => {
next();
};
// 验证码
const generate = (req, res, next) => {
req.ctx(CaptchaServiceModel).generateCaptcha(req.session.id).then((result) => {
res.type('png');
if (result.code === 200) {
request({
url: result.data.url,
headers: Object.assign({
'X-request-ID': req.reqID || '',
'X-YOHO-IP': req.yoho.clientIp || '',
'X-Forwarded-For': req.yoho.clientIp || '',
'User-Agent': 'yoho/nodejs'
}, result.headers || {})
}).pipe(res);
}
}).catch(next);
};
// api风控验证码
const generateRisk = (req, res, next) => {
req.ctx(CaptchaServiceModel).getRiskCheckImg(req.yoho.udid).then((result) => {
request({
url: result,
headers: {
'X-request-ID': req.reqID || '',
'X-YOHO-IP': req.yoho.clientIp || '',
'X-Forwarded-For': req.yoho.clientIp || '',
'User-Agent': 'yoho/nodejs'
}
}).on('response', response => {
// status code 204 接口关闭图形验证码,通过cookie通知验证页刷行切换验证方式
if (response.statusCode === 204) {
res.cookie('refresh_page', 1, {
path: '/',
maxAge: 60000
});
delete req.session.apiRiskValidate;
req.session.apiRiskClear = true;
return res.json({code: 204});
}
}).pipe(res);
}).catch(next);
};
// 端到端检查
const checkAPI = (req, res, next) => {
_mustEqualAsync(req).then(result => {
res.json(result);
}).catch(next);
};
const trySwitch = (req, res) => {
return req.ctx(CaptchaServiceModel).try().then((result) => {
const captcha = {
type: CAPTCHA_TYPE.image,
value: result ? CAPTCHA_SWITCH.on : CAPTCHA_SWITCH.off
};
req.session.captcha = captcha;
res.locals.captcha = captcha;
});
};
module.exports = {
requiredAPI,
generate,
generateRisk,
checkAPI,
trySwitch
};