【发布时间】:2015-11-21 19:06:31
【问题描述】:
我想验证用户是否具有允许他/她在我的 API 中使用端点的角色。通常我会通过将 userId 作为 JWT 的一部分发送并在 DB 上查找以查看用户的角色来这样做。它会在 API 调用中发生,看起来像这样:
var userId = getUserIdFromJwt();
app.models.User.findOne({_id: userId}, function (err, user) {
...check if user is in role...
});
现在我想尝试将该代码移动到一个中间件,如下所示:
exports.isUserInRole = function(app, allowableRoles) {
var userId = getUserIdFromJwt();
app.models.User.findOne({_id: userId}, function (error, user) {
if (error) {
return res.status(500).json(error);
}
return function (req, res, next) {
if(_.includes(allowableRoles, user.Role)) {
next();
} else {
return res.status(401).json({"error": "User not in role"});
}
}
});
};
中间件的实现方式如下:
const allowableRoles = ['admin', 'implementor'];
app.get('/getStuff/', isUserInRole(app, allowableRoles), function (req, res) {
... do stuff if user is in role ...
});
此时我遇到了app.models.User 值始终为undefined 的问题。
我不明白为什么此时 app.models.User 未定义,因为我可以在 get 调用中的匿名函数中访问它。
如果我无法发送app.models.User,我将如何从我的中间件中访问数据库?
作为参考,我正在使用 Mongoose 并将其暴露给我访问 MongoDB 数据库的 server.js 中的应用程序。
【问题讨论】:
-
为了我理解正确,
app.models.User在isUserInRole之后或期间调用的函数中是否未定义? -
即
app.models.User.findOne是未定义的吗? -
app.models.User在isUserInRole被调用为中间件的那一刻是未定义的,但它在下一个函数中可用。例如,如果我将isUserInRole作为中间件并将其作为匿名函数中的普通函数调用,那么我可以看到调用了数据库,因为app.models.User不是未定义的。
标签: node.js mongodb express mongoose middleware