Search code examples
strongloop

Strongloop: currentContext not available in middleware?


I have my middlewares configured in Strongloop in the following way in middleware.json:

{ 
"initial:before": {
      "loopback#favicon": {}
  },
  "initial": {
    "compression": {},
    "cors": {
      "params": {
        "origin": true,
        "credentials": true,
        "maxAge": 86400
      }
    },
    "helmet#xssFilter": {},
    "helmet#frameguard": {
      "params": [
        "deny"
      ]
    },
    "helmet#hsts": {
      "params": {
        "maxAge": 0,
        "includeSubdomains": true
      }
    },
    "helmet#hidePoweredBy": {},
    "helmet#ieNoOpen": {},
    "helmet#noSniff": {},
    "helmet#noCache": {
      "enabled": false
    },
    "express-jwt": {
      "paths": [
        "${restApiRoot}"
      ],
      "params": {
        "secret": "secret"
      }
    }
  },
  "session": {},
  "auth": {
    "./middleware/token-validation": {
      "paths": [
        "${restApiRoot}"
      ]
    }
  },
  "parse": {},
  "routes": {
    "loopback#rest": {
      "paths": [
        "${restApiRoot}"
      ]
    }
  },
  "files": {},
  "final": {
    "loopback#urlNotFound": {}
  },
  "final:after": {
    "loopback#errorHandler": {}
  }
}

This file was genereated by Strongloop, except the "auth" middleware was added manually. In this middleware (token-validation.js) I want to access the currentContext like this:

return function tokenValidation(req, res, next) {
  var app = req.app;
  var ctx = app.loopback.getCurrentContext();
  console.log(ctx);
});

However, the ctx object is always null.... Any ideas?


Solution

  • Step 1: In config.json, you need to enable enableHttpContext that is

     "remoting": {
        "context": {
          "enableHttpContext": true
        }
    

    Step 2: Add below code in sever.js before app.start();

    app.use(loopback.token()); // this calls getCurrentContext
    app.use(loopback.context()); // the context is started here
    
    app.use(function (req, res, next) {
      if (!req.accessToken) return next();
    
    // your user model.js
      app.models.user.findById(req.accessToken.userId, function(err, user) {
        if (err)   return next(err);
        if (!user) return next(new Error('No user with this access token was found.'));
        res.locals.currentUser = user;
    
        var loopbackContext = loopback.getCurrentContext();
        console.log('SERVER CTX?' +loopbackContext);
        if (loopbackContext) loopbackContext.set('currentUser', user);
        next();
      });
    });
    

    Step 3: add this code in model.js or any js.

    var loopback = require('loopback');
    
    var ctx = loopback.getCurrentContext();
    var currentUser = ctx && ctx.get('currentUser');
    console.log('currentUser.username: ', currentUser);