risk-management.js 2.76 KB
/**
 * 控制路由请求次数
 * @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 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'
];

module.exports = () => {
    return (req, res, next) => {
        let ip = _.get(req.yoho, 'clientIp', '');
        let path = req.path || '';
        let router = {};
        let risks = _.get(req.app.locals.wap, 'json.risk', []);

        if (_.isEmpty(path) || _.isEmpty(risks) || IP_WHITE_LIST.indexOf(ip) > -1) {
            return next();
        }

        _.isArray(risks) && risks.some(item => {
            if (item.state === 'off') {
                return false;
            }

            if (!item.regRoute) {
                item.regRoute = pathToRegexp(item.route);
                item.interval = parseInt(item.interval, 10);
                item.requests = parseInt(item.requests, 10);
            }

            if (item.regRoute.test(path)) {
                router = item;
                return true;
            }

            return false;
        });

        if (_.isEmpty(router)) {
            return next();
        }

        let key = `wap:risk:${_.trim(path, '/').replace(/\//g, ':')}:${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) {
                    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({
                        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();
        });
    };
};