Search code examples
iphookoperationloopback

Loopback get IP address from operation hook


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 ??
});

Solution

  • 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'));
    });