useragent.js 1.55 KB
'use strict';

const cache = global.yoho.cache.master;
const _ = require('lodash');
const logger = global.yoho.logger;
const Promise = require('bluebird');

module.exports = async({user}, next) => {
    const blackKey = `${user.app}:limiter:ua:black`;
    const whiteKey = `${user.app}:limiter:ua:white`;

    const ua = user.userAgent;

    logger.debug('userAgent==>%s', user.userAgent);

    Promise.all([
        cache.getAsync(blackKey),
        cache.getAsync(whiteKey)
    ]).then((args) => {
        let blacklist = [];
        let whitelist = [];

        try {
            blacklist = JSON.parse(args[0]);
        } catch (error) {
            logger.error(error);
        }

        try {
            whitelist = JSON.parse(args[1]);
        } catch (error) {
            logger.error(error);
        }

        blacklist = blacklist || [];
        whitelist = whitelist || [];

        if (blacklist.length === 0 && whitelist.length === 0) {
            return next();
        }

        const test = (list) => {
            let result = false;

            _.each(list, (item) => {
                let regexp;

                try {
                    regexp = new RegExp(item);
                } catch (e) {
                    logger.error(e);
                }

                if (regexp.test(ua)) {
                    result = true;
                }
            });

            return result;
        };

        if (test(blacklist) || test(whitelist)) {
            return;
        }
        return next();
    }).catch(() => {
        return next();
    });
};