Blame view

doraemon/middleware/risk-management.js 3.99 KB
1 2 3 4 5 6 7 8 9
/**
 * 控制路由请求次数
 * @date: 2018/03/05
 */
'use strict';

const _ = require('lodash');
const cache = global.yoho.cache.master;
const helpers = global.yoho.helpers;
郝肖肖 authored
10
const pathToRegexp = require('path-to-regexp');
郝肖肖 authored
11
const logger = global.yoho.logger;
yyq authored
12
const md5 = require('yoho-md5');
13
郝肖肖 authored
14 15
const statusCode = {
    code: 4403,
郝肖肖 authored
16
    data: {},
郝肖肖 authored
17 18 19 20
    message: '亲,您的访问次数过多,请稍后再试哦...'
};

const INVALIDTIME = 3600 * 24; // 24h
郝肖肖 authored
21 22 23 24 25 26 27 28 29
const IP_WHITE_LIST = [
    '106.38.38.146',
    '106.38.38.147',
    '106.39.86.227',
    '218.94.75.58',
    '218.94.75.50',
    '218.94.77.166'
];
郝肖肖 authored
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
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();
};
46 47
module.exports = () => {
    return (req, res, next) => {
郝肖肖 authored
48 49
        // default open
        if (_.get(req.app.locals.wap, 'close.risk', false)) {
郝肖肖 authored
50 51 52
            return next();
        }
郝肖肖 authored
53
        let ip = _.get(req.yoho, 'clientIp', '');
郝肖肖 authored
54 55
        let path = req.path || '';
        let risks = _.get(req.app.locals.wap, 'json.risk', []);
郝肖肖 authored
56
        let router = {};
郝肖肖 authored
57
郝肖肖 authored
58
        logger.debug(`risk => risks: ${JSON.stringify(risks)}, path: ${path}, ip: ${ip}`); // eslint-disable-line
郝肖肖 authored
59
        if (_.isEmpty(path) || _.isEmpty(risks) || IP_WHITE_LIST.indexOf(ip) > -1) {
郝肖肖 authored
60 61 62
            return next();
        }
郝肖肖 authored
63
        _.isArray(risks) && risks.some(item => {
郝肖肖 authored
64 65 66 67
            if (item.state === 'off') {
                return false;
            }
郝肖肖 authored
68 69 70 71 72
            if (!item.regRoute) {
                item.regRoute = pathToRegexp(item.route);
                item.interval = parseInt(item.interval, 10);
                item.requests = parseInt(item.requests, 10);
            }
郝肖肖 authored
73
郝肖肖 authored
74
            if (item.regRoute.test(path)) {
郝肖肖 authored
75
                router = item;
郝肖肖 authored
76
                return true;
郝肖肖 authored
77
            }
郝肖肖 authored
78
郝肖肖 authored
79
            return false;
郝肖肖 authored
80 81
        });
郝肖肖 authored
82
        logger.debug(`risk => router: ${JSON.stringify(router)}, path: ${path}`); // eslint-disable-line
郝肖肖 authored
83
        if (_.isEmpty(router)) {
郝肖肖 authored
84 85 86
            return next();
        }
yyq authored
87
        let keyPath = md5(`${router.regRoute}`);
郝肖肖 authored
88 89
        let limitKey = `wap:risk:limit:${keyPath}:${ip}`;
        let configKey = `wap:risk:${keyPath}:${ip}`;
90
        let checkUrl = helpers.urlFormat('/3party/check', {
郝肖肖 authored
91
            pid: `wap:risk:limit:${keyPath}`
92 93
        });
郝肖肖 authored
94 95 96 97
        return Promise.all([
            cache.getAsync(limitKey),
            cache.getAsync(configKey),
        ]).then(inters => {
郝肖肖 authored
98
            logger.debug(`risk => getCache: ${JSON.stringify(inters)}, path: ${path}`); // eslint-disable-line
郝肖肖 authored
99 100
            if (inters[0]) {
                return Object.assign({}, statusCode, {data: {url: checkUrl}});
101 102
            }
郝肖肖 authored
103 104 105
            if (typeof inters[1] === 'undefined') {
                cache.setAsync(configKey, 1, router.interval || 300);
                return Object.assign({}, statusCode, {code: 200, message: ''});
106 107
            }
郝肖肖 authored
108 109 110 111 112
            inters[1] = parseInt(`0${inters[1]}`, 10);
            if (inters[1] <= router.requests) {
                router = [];
                cache.incrAsync(configKey, 1);
                return Object.assign({}, statusCode, {code: 200, message: ''});
113 114
            }
郝肖肖 authored
115 116 117 118 119 120 121
            return Promise.all([
                cache.setAsync(limitKey, 1, INVALIDTIME),
                cache.delAsync(configKey)
            ]).then(() => {
                return Object.assign({}, statusCode, {data: {url: checkUrl}});
            });
        }).then(result => {
郝肖肖 authored
122
            logger.debug(`risk => result: ${JSON.stringify(result)}, path: ${path}`); // eslint-disable-line
郝肖肖 authored
123 124
            return _jumpUrl(req, res, next, result);
        }).catch(e => {
125 126 127 128 129
            console.log(`risk => path: ${path}, err: ${e.message}`);
            return next();
        });
    };
};