Friday, November 15, 2013

[node.js] express.js add ip / path filter middleware

前陣子因為有一個不同目錄限制不同IP可以連線的需求,所以研究了一下寫出這個小功能來,在這邊分享一下,因為沒啥空就懶得寫英文版了,希望老外看得懂。

基本上就是做到可以指定多個目錄分別對多個IP做到限制連線的功能,如何設定多目錄可以看config.js那段
寫得不複雜,也還沒加上sub mask 或是 192.168.1.* 之類的功能,等有需要再加吧

middleware\ipFilter.js

var config = require('../config');
var enabled = true;

module.exports = function(onoff) {
    enabled = (onoff == 'on') ? true : false;
    var IParr = config.IPFilter;
    return function(req, res, next) {
        if(enabled && IParr.length>0){
            for(var index in IParr){
                var inArea = false;
                for(var pa in IParr[index].path){
                    inArea = (req.path.indexOf(IParr[index].path[pa])>-1)?true:inArea;
                }
                if(inArea) {
                    if (IParr[index].ip.indexOf(req.connection.remoteAddress) == -1) {
                        console.log('Banned IP from '+req.connection.remoteAddress);
                        res.end('Banned');
                    }
                }
            }
            next();
        }else{
            next();
        }
    };
};

where you setting Express.js

var express = require('express');
var ipfilter = require('./middleware/ipFilter.js');
var app = express();
app.use(ipfilter('on'));


config.js

exports.IPFilter =[
    {
        path:['/static/admin/','home/statistic/'],
        ip:['127.0.0.1','192.168.1.110','123.123.123.123']
    },
    {
        path:['/job/'],
        ip:['1.1.1.1','127.0.0.1','192.168.11.1']
    }
];

懶得打字,收工。

忘記寫了,我是參考這篇"How to Write Middleware for Connect / Express.js"的

No comments:

Post a Comment