2

I am trying to create a policy that allows only an Admin to view a page. I have shown the policy below, but it's not returning the right user.

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

};
Talha Awan
  • 4,573
  • 4
  • 25
  • 40
linux
  • 141
  • 2
  • 12

1 Answers1

2

You need to verify and parse the passed token with jwt methods and then find the user by 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);
}

source : NodeJs - Retrieve user infor from JWT token?

Community
  • 1
  • 1
Robert I
  • 1,509
  • 2
  • 11
  • 18