hex20dec
hex20dec

Reputation: 127

How do I wrap a middleware in a function?

I'm trying to restrict sriracha-admin to a certain IP.

So I'm doing:

var admin = require('sriracha-admin');
app.use("/sriracha-admin", admin({
    user:"user", 
    pass:"pass123"
  }) 
);

Can I do something like:

app.use("/sriracha-admin", function(){
  if(req.ip === 111.222.333.444){
    return admin({
      user:"user", 
      pass:"pass123"
    });
  }
});

Or perhaps I'm going about it totally wrong?

Upvotes: 1

Views: 3301

Answers (2)

hex20dec
hex20dec

Reputation: 127

I decided to not be lazy and read the docs and I found the answer in a matter of seconds.

Here it is if anyone is looking for an answer on how to restrict a middleware by ip or by anything else.

var ip = '1234';
app.use("/admin", function(req, res, next){
    if(ip === '123'){
      next();
    }else{
      res.sendStatus(404)
    }
  },
  admin({
      username: "user",
      password: "pass"
  })
);

My very little understanding of Express was holding me back from writing the very simple above code and perhaps explaining my question well enough. But in case someone is looking for anything similar, I hope this helps.

Upvotes: 1

Todd Price
Todd Price

Reputation: 2760

I don't know sriracha, but a quick look shows that the admin() function returns an Express app: https://github.com/hdngr/sriracha/blob/master/index.js#L104

Since middleware in Express looks like this:

app.use(function (req, res, next) {
  console.log('Request Type:', req.method);
  next();
});

(See an example here: http://expressjs.com/en/guide/using-middleware.html)

...my guess is that your example might be re-written:

app.use("/sriracha-admin", admin(myoptions).use(function(req, res, next){
  if(req.ip === 111.222.333.444){
    //throw an exception here, or redirect, or whatever
  });
});

Not sure I nailed the closing braces there but you get the idea hopefully.

Upvotes: 1

Related Questions