risk-management.js
2.05 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
/**
* 控制路由请求次数
* @date: 2018/03/05
*/
'use strict';
const _ = require('lodash');
const md5 = require('yoho-md5');
const cache = global.yoho.cache.master;
const helpers = global.yoho.helpers;
const pathToRegexp = require('path-to-regexp');
module.exports = () => {
return (req, res, next) => {
let path = req.path || '';
let router = {};
let risks = _.get(req.app.locals.wap, 'json.risk', []);
_.isArray(risks) && risks.some(item => {
item.regRoute = item.regRoute || pathToRegexp(item.route);
if (item.regRoute.test(path)) {
router = item;
return true;
}
return false;
});
if (_.isEmpty(router) || _.isEmpty(path)) {
return next();
}
let ip = _.get(req.yoho, 'clientIp', '');
let key = md5(`${_.trim(path, '/')}${ip}`);
let checkUrl = helpers.urlFormat('/3party/check', {
pid: key
});
return cache.getAsync(key).then(inter => {
if (typeof inter === 'undefined') {
return cache.setAsync(key, 1, router.interval || 300);
}
inter = parseInt(`0${inter}`, 10);
if (inter <= router.requests) {
return cache.incrAsync(key, 1);
}
return inter;
}).then(inter => {
if (inter === true) { // cache set OR incr
return next();
}
if (inter > router.requests) {
if (req.xhr) {
return res.status(403).json({
code: 4403,
date: {url: checkUrl},
message: '亲,您的访问次数过多,请稍后再试哦...'
});
}
return res.redirect(`${checkUrl}&refer=${req.originalUrl}`);
}
return next();
}).catch((e) => {
console.log(`risk => path: ${path}, err: ${e.message}`);
return next();
});
};
};