useragent.js 1.37 KB
'use strict';

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


module.exports = (limiter, policy) => {
    const req = limiter.req,
        res = limiter.res,
        next = limiter.next;
    const blackKey = 'pc:limiter:ua:black',
        whiteKey = 'pc:limiter:ua:white';

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

    return Promise.all([
        cache.getAsync(blackKey),
        cache.getAsync(whiteKey)
    ]).then((args) => {
        const blacklist = args[0] || [], whitelist = args[1] || [];

        if (blacklist.length === 0 && whitelist.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 if (test(whitelist)) {
            return Promise.resolve({
                exclusion: true
            });
        } else {
            return Promise.resolve(true);
        }
    });

};