Home > other >  How to manage roles in node.js?
How to manage roles in node.js?

Time:07-02

I have three distinct categories of users in the auth model, as follows:

accountType: {
    type: String,
    required: true,
    trim: true,
    default: "user",
    enum: ["merchant", "user", "provider"],
  }

Now I want to simply let the merchant upload the parking information. Here is the query:

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

        let new_parking = new Parking({
            merchantId: req.data.id,
            parkingName,
            price,
            contactInfo: {
                name,
                phoneNumber
            },
            about,
            parkingType,
            address: {
                address,
                city,
                state,
                zipCode
            }
        });
        const save = await new_parking.save();
        return res.status(200).json({
            success: true,
            msg: "Parking has been added successfully",
            data: { parkingDetails: save },
        });
    }
    catch (error) {
        return error.message;
    }
}

how to change the above request so that only the merchant may upload the information regarding parking details. Because normal user is able to add the details regarding parking as well. I want to restrict this.

routing.post("/parking/add",middleware.authenticateToken,merchant.parkingAdd);

CodePudding user response:

Ok, I found the solution as well. In the query it should be

if (check_exist.accountType !== "merchant")
      return res
        .status(401)
        .json({
          error: "You must be a merchant user to post the parking details",
});

CodePudding user response:

Suppose loggin user has accountType in his session,

const authenticateToken=(req,res,next)=>{
  if(req.user.accountType !== "merchant"){
      return res
        .status(403)
        .json({status: false, message:"Forbidden"})
  }
  next();
}
exports.authenticateToken=authenticateToken;
  • Related