John Oliver
John Oliver

Reputation: 91

Role based access control in node.js

I want to implement the user and admin roles and permissions in node.js. I have watched the video of web-dev-simplified (Link)

I quite liked that approach but in the example he is using JSON file to store the users data. In my case I am storing user data in MongoDB database. In the user schema I have a field called role which is as following.

role: {
      type: String,
      enum: ["admin", "user"],
      default: "user",
    }

How can I go on from here. This is the JWT auhentication function.

module.exports = middlewares = {
  authenticateToken: async (req, res, next) => {
    try {
      if (!req.headers["x-access-token"]) {
        return res.status(401).json({
          error: "Key x-access-token not found",
        });
      }
      if (req.headers["x-access-token"] === "") {
        return res.status(401).json({
          error: "Token not found",
        });
      }
      const token = req.headers["x-access-token"];
      const data = jwt.verify(token, keys.JWToken);
      if (!data) return res.status(401).json({ error: "Invalid token" });
      req.data = data;
      next();
    } catch (err) {
      return res.status(400).json({ error: err.message });
    }
  },
};

Or is there any better alternative to that?

This is the most difficult question I find in node.js. Can anyone help me here.

Upvotes: 1

Views: 711

Answers (0)

Related Questions