strongloop / loopback

LoopBack makes it easy to build modern applications that require complex integrations.
http://loopback.io
Other
13.23k stars 1.2k forks source link

loopback.getCurrentContext() return null #2645

Closed JoeShi closed 8 years ago

JoeShi commented 8 years ago

I am just following the Using Current Context guide to get the current user. However, it always return null.

The following is my code, same as in the docs, the only modification is the print message.

app.use(function setCurrentUser(req, res, next) {
  if (!req.accessToken) {
    return next();
  }
  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.'));
    }
    var loopbackContext = loopback.getCurrentContext();

    console.log(loopbackContext);
    console.log('after loopbackContext');

    if (loopbackContext) {
      loopbackContext.set('currentUser', user);
    }
    next();
  });
});

my package.json

{
  "name": "caiyi",
  "version": "0.0.1",
  "main": "server/server.js",
  "scripts": {
    "start": "node .",
    "pretest": "jshint ."
  },
  "dependencies": {
    "compression": "^1.0.3",
    "cors": "^2.5.2",
    "express-flash": "0.0.2",
    "loopback": "^2.22.0",
    "loopback-boot": "^2.6.5",
    "loopback-component-explorer": "^2.1.0",
    "loopback-component-passport": "^2.1.0",
    "loopback-connector-mongodb": "^1.15.2",
    "loopback-datasource-juggler": "^2.39.0",
    "loopback-passport": "^1.0.2",
    "loopback-remote-routing": "^1.3.0",
    "moment": "^2.14.1",
    "qcloud_cos": "^1.0.4",
    "request": "^2.74.0",
    "serve-favicon": "^2.0.1",
    "wechat": "^2.0.3",
    "wechat-api": "^1.28.0",
    "wechat-oauth": "^1.1.1",
    "wechat-pay": "^0.2.4"
  },
  "devDependencies": {
    "grunt": "^0.4.5",
    "jshint": "^2.5.6",
    "grunt-assemble": "^0.4.0",
    "grunt-bump": "0.0.15",
    "grunt-contrib-clean": "^0.6.0",
    "grunt-contrib-concat": "^0.5.0",
    "grunt-contrib-copy": "^0.5.0",
    "grunt-contrib-cssmin": "^0.14.0",
    "grunt-contrib-htmlmin": "^0.3.0",
    "grunt-contrib-sass": "^0.9.2",
    "grunt-contrib-uglify": "^0.5.1",
    "grunt-contrib-watch": "^0.6.1",
    "grunt-sass": "^1.0.0",
    "grunt-usemin": "^3.1.1"
  },
  "repository": {
    "type": "",
    "url": ""
  },
  "description": "caiyi"
}
alexkolson commented 8 years ago

@JoeShi See #2251. In short, getCurrentContext() is not reliable and should be avoided.

0candy commented 8 years ago

@alexkolson Thank you for responding. @JoeShi Closing this as a dup.