2017-03-31 75 views
1

我試圖創建一個只允許管理員查看頁面的策略。我已經在下面顯示了該政策,但並未返回正確的用戶。我想通過分配給用戶的json Web令牌獲取用戶信息

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"); 
    }); 

}; 

回答

1

您需要verify and parse the passed token與智威湯遜方法,然後通過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); 
} 

來源:NodeJs - Retrieve user infor from JWT token?

+1

謝謝羅伯特 – linux