Authored by 陈峰

ua black list

@@ -39,6 +39,8 @@ exports.createApp = async(app) => { @@ -39,6 +39,8 @@ exports.createApp = async(app) => {
39 res.status(200).end(); 39 res.status(200).end();
40 }); 40 });
41 41
  42 + app.use(require('./doraemon/middleware/backlist'));
  43 +
42 const logger = global.yoho.logger; 44 const logger = global.yoho.logger;
43 45
44 if (app.locals.devEnv) { 46 if (app.locals.devEnv) {
  1 +const _ = require('lodash');
  2 +const cache = global.yoho.cache.master;
  3 +const logger = global.yoho.logger;
  4 +
  5 +const uaMatch = (list, ua) => {
  6 + let result = false;
  7 +
  8 + _.each(list, (item) => {
  9 + let regexp;
  10 +
  11 + try {
  12 + regexp = new RegExp(item);
  13 + } catch (e) {
  14 + logger.error(e);
  15 + }
  16 +
  17 + if (regexp.test(ua)) {
  18 + result = true;
  19 + }
  20 + });
  21 +
  22 + return result;
  23 +};
  24 +
  25 +module.exports = async(req, res, next) => {
  26 + const blackKey = 'pc:limiter:ua:black';
  27 + const whiteKey = 'pc:limiter:ua:white';
  28 +
  29 + try {
  30 + const results = await Promise.all([
  31 + cache.getAsync(blackKey),
  32 + cache.getAsync(whiteKey)
  33 + ]);
  34 +
  35 + const ualist = _.concat([], ..._.map(results, args => {
  36 + let list = [];
  37 +
  38 + try {
  39 + list = JSON.parse(args) || [];
  40 + } catch (error) {
  41 + logger.error(error);
  42 + }
  43 + return list;
  44 + }));
  45 +
  46 + if (ualist.length === 0) {
  47 + return next();
  48 + }
  49 + const ua = req.get('User-Agent');
  50 +
  51 + if (uaMatch(ualist, ua)) {
  52 + return res.status(200).end();
  53 + }
  54 + return next();
  55 + } catch (error) {
  56 + logger.error(error);
  57 + return next();
  58 + }
  59 +};