在环回中使用自定义中间件的用户授权

时间:2018-05-04 09:22:13

标签: javascript node.js mongodb loopbackjs

我在VerifyUserAccess中制作了middleware loopback,如下所示:

module.exports = function(options) {
 return function storeCurrentUser(req, res, next) {
 if (!req.accessToken) {
  return next();
 }

app.models.UserModel.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.'));
  }
  const LoopBackContext = require('loopback-context');
  const loopbackContext = LoopBackContext.getCurrentContext();
  if (loopbackContext) {
    loopbackContext.set('currentUser', user);
  }
  next();
});
};
};

我还在middleware.json添加了它,如下所示:

 ...
  "initial": {
     "./middleware/verify_user_access": {},
  ...
   }
  ...

但问题是我总是loopbackContext null

第二个问题是如何访问currentUser会导致API。我在下面做了:

  Gameversionandtype.GetGameversionandtypeByGameTypeID = (ctx, callback) => 
 {
    const LoopBackContext = require('loopback-context');
    const context = LoopBackContext.getCurrentContext();
    const currentUserResult = context && context.get('currentUserResult');
    console.log('currentUser.username: ', currentUserResult.id);
    ...
    ...
 }

请告诉我如何设置currentUser结果以及如何在API中获取结果。我也提到了文档loopback-context npm模块,但我找不到任何解决方案。提前感谢你。

0 个答案:

没有答案