gee-captcha.js
3.47 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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
'use strict';
/**
* 极验证
* Created by Tao.Huang on 2017/3/17.
*/
const Geetest = require('../models/captcha-gee-service');
const config = global.yoho.config;
const logger = global.yoho.logger;
const CAPTCHA = config.UNIVERSAL_CAPTCHA;
// 对比函数
const _mustEqual = (req) => {
return req.body.verifyCode === CAPTCHA;
};
var pcGeetest = new Geetest({
geetest_id: config.gee_captcha.id,
geetest_key: config.gee_captcha.key
});
const generate = (req, res) => {
pcGeetest.register(function(err, data) {
if (err) {
return;
}
if (!data.success) {
req.session.captchaType = 'img';
res.json({
code: 501,
data: data
});
} else {
// 正常模式
req.session.captchaType = 'geetest';
res.send({
code: 200,
data: data
});
}
});
};
/**
* 中间件检查
*/
const requiredAPI = (req, res, next) => {
let verifyCode = req.body.verifyCode || '';
let captcha = verifyCode.split(',');
if (!verifyCode) {
return res.send({
code: 405,
message: '未输入图形验证码,请输入图形验证码',
data: {
needCaptcha: true
}
});
}
if (_mustEqual(req)) {
return next();
} else {
pcGeetest.validate({
challenge: captcha[0],
validate: captcha[1],
seccode: captcha[2]
}, function(err, success) {
logger.info(`geetest captcha auth [${err ? 'fail' : 'success'}]`,
`CLIENT [${req.body.verifyCode}] SERVER [${err}]`);
if (err) {
res.send({
message: '网络失败,请刷新图形验证码',
code: 405,
data: {
needCaptcha: true
}
});
} else if (!success) {
res.send({
message: '图形验证失败, 请刷新图形验证码',
code: 405,
data: {
needCaptcha: true
}
});
} else {
return next();
}
});
}
};
// 端到端检查
const checkAPI = (req, res) => {
let verifyCode = req.body.verifyCode || '';
let captcha = verifyCode.split(',');
if (!verifyCode) {
return res.send({
code: 405,
message: '参数失效'
});
}
if (_mustEqual(req)) {
return res.json({
message: '验证成功',
code: 200
});
}
pcGeetest.validate({
challenge: captcha[0],
validate: captcha[1],
seccode: captcha[2]
}, function(err, success) {
logger.info(`geetest captcha auth [${err ? 'fail' : 'success'}]`,
`CLIENT [${req.body.verifyCode}] SERVER [${err}]`);
if (err) {
return res.send({
message: '网络失败',
code: 405
});
} else if (!success) {
return res.send({
message: '图形验证失败',
code: 405
});
} else {
return res.send({
message: '验证成功',
code: 200
});
}
});
};
module.exports = {
generate,
requiredAPI,
checkAPI
};