Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strongloop: currentContext not available in middleware?

Tags:

strongloop

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?

like image 595
pfust75 Avatar asked Apr 10 '26 16:04

pfust75


1 Answers

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);
like image 195
Riaz Avatar answered Apr 19 '26 07:04

Riaz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!