2

Well, that XD, how do I get the IP Address of the querier (if that's even the word xD) from within an operation hook? or a remote hook? (I can save it with loopback.getCurrentContext() to use on the operation hook).

Say:

Model.observe('loaded', function(ctx,next) {
   ctx.ip ??
});
Alons Oh
  • 195
  • 1
  • 14

5 Answers5

7

So I found this: https://github.com/strongloop/loopback/issues/1495 & this: How to determine a user's IP address in node Great help from both, I just took what I needed to get the address and save it on the loopback current context like this on a startup script:

var loopback = require('loopback'); 

module.exports = function (app) {     

  app.remotes().before('*.*', function(ctx,next) {
    loopback.getCurrentContext().set('remoteAddress',ctx.req.connection.remoteAddress);
    next();
  });

  app.remotes().before('*.prototype.*', function(ctx,instance,next) {
    loopback.getCurrentContext().set('remoteAddress',ctx.req.connection.remoteAddress);
    next();
  });
};

Then I just get it on an operation hook like this:

Model.observe('loaded', function(ctx,next) {
   console.log("Remote Address: ", loopback.getCurrentContext().get('remoteAddress'));
});
Community
  • 1
  • 1
Alons Oh
  • 195
  • 1
  • 14
1

Update for Loopback 3: you can get IP address using this property:

ctx.req.connection.remoteAddress
Irvin Sandoval
  • 742
  • 7
  • 18
1

You should also add this code in server.js to grant the real ip, otherwise you´re getting the load balancer IP:

app.set('trust proxy', ['loopback', 'linklocal', 'uniquelocal']);

https://expressjs.com/en/guide/behind-proxies.html

0

Not really the question asked, but when you need the ip address from the caller in a remote method, and your nodejs is already behind an Apache proxy (or a well configured nginx one), you can simply

    const ip = req.header('X-Forwarded-For')

to get the ip address.

boukae
  • 1
0

You can get the IP address of the requested user by using the below command.

var ipAddress = context.req.connection.remoteAddress
Praveen Yen
  • 1
  • 1
  • 2