Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Express ip filter for specific routes?

Is it possible to apply different ip filters to different routes?

For example, I want only people from 123.123.123.123 can access my server's /test route, and only people from 124.124.124.124 can access my server's / route.

I know that express-ipfilter can restrict site access by IP Address. But it cannot apply the filter to specific routes.

I also know that adding app.use(ipfilter(ips, {})); in the middle of the routes can apply filter only to the routes below:

var express = require('express'),
    ipfilter = require('express-ipfilter').IpFilter;

var ips = ['::ffff:127.0.0.1'];
var app = express();

app.get('/test', function(req, res) {
    res.send('test');
});

app.use(ipfilter(ips, {})); // the ipfilter only applies to the routes below

app.get('/', function(req, res) {
    res.send('Hello World');
});

app.listen(3000);

But I want different filters for different routes.

Is it possible to do this?

like image 212
Brian Avatar asked Jan 12 '17 03:01

Brian


2 Answers

Yeah, it's possible. You could do something like:

app.get('/test', function(req, res){
    var trustedIps = ['123.123.123.123'];
    var requestIP = req.connection.remoteAddress;
    if(trustedIps.indexOf(requestIP) >= 0) {
        // do stuff
    } else {
        // handle unallowed ip
    }
})

You may need to make sure that requestIP is correctly formatted though.

like image 152
Jeremy Jackson Avatar answered Oct 21 '22 18:10

Jeremy Jackson


Warning: package express-ipfilter is now deprecated.

You can chain middlewares (and ipFilter is a middleware). There are 2 ways to do this:

var express = require('express'),
    ipfilter = require('express-ipfilter').IpFilter;

var ips = ['::ffff:127.0.0.1'];
var testers = ['1.2.3.4'];
var app = express();

app.get('/test', ipfilter(testers, {mode: 'allow'}), function(req, res) {
    res.send('test');
});


// the ipfilter only applies to the routes below  
app.get('/', ipfilter(ips, {mode: 'allow'}), function(req, res) {
    res.send('Hello World');
});

app.listen(3000);

Or qualify the use of the middleware:

var express = require('express'),
    ipfilter = require('express-ipfilter').IpFilter;

var ips = ['::ffff:127.0.0.1'];
var testers = ['1.2.3.4'];
var app = express();

app.use('/test', ipfilter(testers, {})); // the ipfilter only applies to the routes below    

app.get('/test', function(req, res) {
    res.send('test');
});

app.use('/', ipfilter(ips, {})); // the ipfilter only applies to the routes below

app.get('/', function(req, res) {
    res.send('Hello World');
});

app.listen(3000);
like image 45
bsyk Avatar answered Oct 21 '22 18:10

bsyk