Home > database >  How can I restrict the ability to post and save data to the database to only the admin in node.js?
How can I restrict the ability to post and save data to the database to only the admin in node.js?

Time:06-09

In the users table, I have two collections, one of which is admin and the other which is not.

Now I only want admin user to post data.

Here is the post request:

router.post("/bus/add", auth, async (req, res) => {
  const bus = new Bus(req.body);
  const user = await User.find({ admin: true });
  try {
    if (user) {
      await bus.save();
      res.status(201).send(bus);
    } else {
      return res.status(401).send("You are not allowed to perform this action");
    }
  } catch (e) {
    res.status(500).json({
      message: "Please enter the valid data",
    });
  }
});

I'm using JWT to determine whether or not the user is an admin. I've set one of the users' admin roles to 'true' in the user schema.

Authentication middleware:

const authentication = async (req, res, next) => {
  try {
    const token = req.header("Authorization").replace("Bearer ", "");
    const decoded = jwt.verify(token, process.env.JWT_SECRET_KEY);
    const user = await User.findOne({ _id: decoded._id, "tokens.token": token });

    if (!user) {
      throw new error();
    }

    req.token = token
    req.user = user
    next();
  } catch (e) {
    res.status(401).send(e);
  }
};

However, even non-admin users can post data, which is then saved to the database.

I want to restrict this.

I'm not sure how I can prevent non-admin users from posting data.

CodePudding user response:

You need to check if the user is admin in the Auth middleware.

const authentication = async (req, res, next) => {
    try {
        const token = req.header('Authorization').replace('Bearer ', '');
        const decoded = jwt.verify(token, process.env.JWT_SECRET_KEY);
        const user = await User.findOne({
            _id: decoded._id,
            'tokens.token': token,
            admin: true
        });

        if (!user) {
            throw new error();
        }

        req.token = token;
        req.user = user;
        next();
    } catch (e) {
        res.status(401).send(e);
    }
};

And remove the line const user = await User.find({ admin: true }); and related if check in the route.

router.post("/bus/add", auth, async (req, res) => {
  const bus = new Bus(req.body);

  try {
      await bus.save();
      res.status(201).send(bus);
  } catch (e) {
    res.status(500).json({
      message: "Please enter the valid data",
    });
  }
});

  • Related