我正在尝试创建一个仅允许管理员查看页面的策略。我已经显示了下面的策略,但它没有返回正确的用户。
module.exports = function (req, res, next) {
User.findOne({ id: token.id }, function (err, user) {
console.log(user);
if (err) throw (err);
if (user.permission === "admin") {
return next();
}
return res.send("You Must be an ADMIN to perform this task");
});
};
最佳答案
您需要verify and parse the passed token
使用 jwt 方法,然后通过 id extracted from the token
查找用户:
exports.me = function(req,res){
if (req.headers && req.headers.authorization) {
var authorization = headers.authorization,
decoded;
try {
decoded = jwt.verify(authorization, secret.secretToken);
} catch (e) {
return res.status(401).send('unauthorized');
}
var userId = decoded.id;
// Fetch the user by id
User.findOne({_id: userId}).then(function(user){
// Do something with the user
return res.send(200);
});
}
return res.send(500);
}
关于node.js - 我想通过分配给用户的 json Web token 获取用户信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43149701/