Code coverage report for thinkjs/lib/Lib/Behavior/DenyIpBehavior.js

Statements: 100% (14 / 14)      Branches: 100% (8 / 8)      Functions: 100% (4 / 4)      Lines: 100% (14 / 14)      Ignored: none     

All files » thinkjs/lib/Lib/Behavior/ » DenyIpBehavior.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32        1   1         7 2   5 5 5 17 15         5 3 3 3   2      
/**
 * 阻止ip来源访问
 * @return {[type]} [description]
 */
module.exports = Behavior(function(){
  'use strict';
  return {
    options: {
      deny_ip: [] //阻止的ip列表
    },
    run: function(){
      if (this.options.deny_ip.length === 0) {
        return true;
      }
      var clientIps = this.http.ip().split('.');
      var flag = this.options.deny_ip.some(function(item){
        return item.split('.').every(function(num, i){
          if (num === '*' || num === clientIps[i]) {
            return true;
          }
        });
      });
      //如果在阻止的ip在列表里,则返回一个pendding promise,让后面的代码不执行
      if (flag) {
        this.http.res.statusCode = 403;
        this.http.res.end(); 
        return getDefer().promise;
      }
      return true;
    }
  };
});