|
|
/**
|
|
|
* 控制路由请求次数
|
|
|
* @date: 2018/03/05
|
|
|
*/
|
|
|
'use strict';
|
|
|
|
|
|
const _ = require('lodash');
|
|
|
const cache = global.yoho.cache.master;
|
|
|
const helpers = global.yoho.helpers;
|
|
|
const pathToRegexp = require('path-to-regexp');
|
|
|
const logger = global.yoho.logger;
|
|
|
const md5 = require('yoho-md5');
|
|
|
|
|
|
const statusCode = {
|
|
|
code: 4403,
|
|
|
data: {},
|
|
|
message: '亲,您的访问次数过多,请稍后再试哦...'
|
|
|
};
|
|
|
|
|
|
const _jumpUrl = (req, res, next, result) => {
|
|
|
if (result.code === 4403) {
|
|
|
if (req.xhr) {
|
|
|
res.set({
|
|
|
'Cache-Control': 'no-cache',
|
|
|
Pragma: 'no-cache',
|
|
|
Expires: (new Date(1900, 0, 1, 0, 0, 0, 0)).toUTCString()
|
|
|
});
|
|
|
return res.status(403).json(result);
|
|
|
}
|
|
|
return res.redirect(`${result.data.url}&refer=${req.originalUrl}`);
|
|
|
}
|
|
|
|
|
|
return next();
|
|
|
};
|
|
|
|
|
|
const limitKey = 'limit2';
|
|
|
|
|
|
module.exports = () => {
|
|
|
return (req, res, next) => {
|
|
|
// default open
|
|
|
if (_.get(req.app.locals.wap, 'close.risk', false)) {
|
|
|
return next();
|
|
|
}
|
|
|
|
|
|
let ip = _.get(req.yoho, 'clientIp', '');
|
|
|
let path = req.path || '';
|
|
|
let risks = _.get(req.app.locals.wap, 'json.risk', []);
|
|
|
let router = {};
|
|
|
|
|
|
logger.debug(`risk => risks: ${JSON.stringify(risks)}, path: ${path}, ip: ${ip}`); // eslint-disable-line
|
|
|
if (_.isEmpty(path) || _.isEmpty(risks)) {
|
|
|
return next();
|
|
|
}
|
|
|
|
|
|
_.isArray(risks) && risks.some(item => {
|
|
|
if (item.state === 'off') {
|
|
|
return false;
|
|
|
}
|
|
|
|
|
|
if (!item.regRoute) {
|
|
|
item.regRoute = pathToRegexp(item.route);
|
|
|
}
|
|
|
|
|
|
if (item.regRoute.test(path)) {
|
|
|
router = item;
|
|
|
return true;
|
|
|
}
|
|
|
|
|
|
return false;
|
|
|
});
|
|
|
|
|
|
logger.debug(`risk => router: ${JSON.stringify(router)}, path: ${path}`); // eslint-disable-line
|
|
|
if (_.isEmpty(router)) {
|
|
|
return next();
|
|
|
}
|
|
|
|
|
|
let keyPath = md5(`${router.regRoute}`);
|
|
|
let limitEnable = `wap:risk:${limitKey}:${keyPath}:${ip}`;
|
|
|
let checkUrl = helpers.urlFormat('/3party/check', {
|
|
|
pid: `wap:risk:${limitKey}:${keyPath}`
|
|
|
});
|
|
|
|
|
|
cache.getAsync(limitEnable)
|
|
|
.then(result => {
|
|
|
logger.debug(`risk => getCache: ${JSON.stringify(result)}, path: ${path}`); // eslint-disable-line
|
|
|
if (result) {
|
|
|
return Object.assign({}, statusCode, {
|
|
|
data: {
|
|
|
url: checkUrl
|
|
|
}
|
|
|
});
|
|
|
} else {
|
|
|
return {
|
|
|
code: 200
|
|
|
};
|
|
|
}
|
|
|
}).then(result => {
|
|
|
logger.debug(`risk => result: ${JSON.stringify(result)}, path: ${path}`); // eslint-disable-line
|
|
|
return _jumpUrl(req, res, next, result);
|
|
|
}).catch(e => {
|
|
|
console.log(`risk => path: ${path}, err: ${e.message}`);
|
|
|
return next();
|
|
|
});
|
|
|
};
|
|
|
}; |
...
|
...
|
|