captcha.js
1.54 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
'use strict';
var _ = require('lodash');
var Captchapng = require('captchapng');
var Utils = {
generateCaptcha: function (width, height, length) {
var min = Math.pow(10, (length - 1 || 1));
var max = Math.pow(10, (length - 1 || 1)) * 9;
var token = '' + _.random(min, max);
var png = new Captchapng(width, height, token);//
png.color(0, 0, 0, 0); // First color: background (red, green, blue, alpha)
png.color(80, 80, 80, 255); // Second color: paint (red, green, blue, alpha)
return {
image: new Buffer(png.getBase64(), 'base64'),
text: token
};
}
};
module.exports = {
namespace: "captcha",
apis: {
create: function (req, callback) {
var width = req.query.w || 150;
var height = req.query.h || 50;
var length = +(req.query.l || 4);
var captcha = Utils.generateCaptcha(width, height, length);
req.session.captcha = captcha.text;
return callback(null, captcha.image);
},
checkCaptchaImg: function (req, callback) {
var captchaToken = req.body.verifyCode || '';
if (captchaToken === req.session.captcha) {
return callback(null, {
code: 200,
message: '验证成功'
});
} else {
return callback(null, {
code: 400,
message: '您输入的验证码不正确!'
});
}
}
}
};