captcha.js
1.68 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
/**
* 图形验证码
* Created by TaoHuang on 2016/6/18.
*/
'use strict';
const captchaService = require('../models/captcha-service');
const helpers = global.yoho.helpers;
/**
* 验证图形验证码中间件,返回JSON
*/
const requiredAPI = (req, res, next) => {
let captchaToken = req.body.verifyCode || '';
if (captchaToken === req.session.captcha) {
return next();
} else {
return res.json({
code: 400,
message: '您输入的验证码不正确!'
});
}
};
/**
* 验证图形验证码,失败后跳转页面
*/
const requiredPage = (req, res, next) => {
let captchaToken = req.body.verifyCode || '';
if (captchaToken === req.session.captcha) {
return next();
} else {
return res.redirect(helpers.urlFormat('/passport/back/index'));
}
};
/**
* 生成图形验证码
*/
const generate = (req, res) => {
let width = req.query.w || 150;
let height = req.query.h || 50;
let length = +(req.query.l || 4);
let captcha = captchaService.generateCaptcha(width, height, length);
req.session.captcha = captcha.text;
res.writeHead(200, {
'Content-Type': 'image/png'
});
res.end(captcha.image);
};
/**
* 验证图形码
*/
const requiredPost = (req, res) => {
let captchaToken = req.body.verifyCode || '';
if (captchaToken === req.session.captcha) {
return res.json({
code: 200,
data: {}
});
} else {
return res.json({
code: 400,
message: '您输入的验证码不正确!'
});
}
};
module.exports = {
requiredAPI,
requiredPage,
generate,
requiredPost
};