useragent2.js 1.12 KB
'use strict';

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


module.exports = (limiter, policy) => {
    const blackKey = 'pc:limiter:ua:black';

    const ua = limiter.req.header('User-Agent');

    cache.getAsync(blackKey).then((args) => {
        let blacklist = [];

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

        if (blacklist.length === 0) {
            return Promise.resolve(true);
        }

        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)) {
            return Promise.resolve(policy);
        } else {
            return Promise.resolve(true);
        }
    });

};