skip to Main Content

I have three different types of users in my node-js schema:
1 -> user, 2 -> merchant 3 -> provider

Now i am giving only merchant users to post the data about parking.

I have this query in node.js to update the parking data:

exports.updateParking = async (req, res) => {
  try {
    const { parkingId, parkingName, price, address, name, phoneNumber, about } =
      req.body;
    const check_exist = await Auth.findById(req.data.id);
    if (!check_exist) return res.status(404).json({ error: "User not found" });

    const updateData = await Parking.updateOne(
      { _id: parkingId },
      {
        $set: {
          parkingName,
          price,
          //...other details
        },
      }
    );
    return res.status(200).json({
      success: true,
      msg: "Parking has updated successfully",
    });
  } catch (error) {
    return error.message;
  }
};

I am using JWT to authenticate the users.
Here is the middleware: routing.patch("/parking/update/:id",middleware.authenticateToken,merchant.updateParking);

How to alter the above query such that only the original poster(merchant user) may edit the details and that anybody else cannot.

2

Answers


  1. You can check current session userid vs request body

    if(req.session.userid !== req.data.id){
      return res.status(403).json({ error: "Forbidden" });
    }
    
    Login or Signup to reply.
  2. If the request is authenticated with a JWT token, you can obtain the user (probably their email address) as

    const jwt = require("jsonwebtoken");
    var user = jwt.decode(token).sub;
    

    If you store the user in every Parking entry, you can make sure that every user can only see or change their own entries.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search