backlist.js 1.08 KB
const _ = require('lodash');
const cache = global.yoho.cache.master;
const logger = global.yoho.logger;

const uaMatch = (list, ua) => {
  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;
};

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

  try {
    const results = await Promise.all([
      cache.getAsync(blackKey),
      cache.getAsync(whiteKey)
    ]);

    const ualist = _.concat([], ..._.map(results, args => {
      let list = [];

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

    if (ualist.length === 0) {
      return next();
    }
    const ua = req.get('User-Agent');

    if (uaMatch(ualist, ua)) {
      return res.status(200).end();
    }
    return next();
  } catch (error) {
    logger.error(error);
    return next();
  }
};