如何防止用户在 Node.js 中查看和更新其他用户的数据?



我在猫鼬模式中存储一个商家id的停车详细信息,因为停车属于某个商家用户,它不能为空或null。

模型如下:

const parkingSchema = new mongoose.Schema({
merchantId: {
type: mongoose.Schema.Types.ObjectId,
required: true,
ref: "Merchant",
},
//other details
})

商业模式是这样的:

const merchantSchema = new mongoose.Schema({
merchantId: {
type: mongoose.Schema.Types.ObjectId,
ref: "Auth",
},
//other details
})

最后是验证模式:

const authSchema = new mongoose.Schema({
accountType: {
type: String,
required: true,
trim: true,
default: "user",
enum: ["merchant", "user", "provider"],
},
//other details
})

如果原用户希望,我只想更新停车数据;否则,我想抛出一个错误。

我使用jsonwebtoken来验证用户。

下面是更新数据的查询:

exports.updateParking = async (req, res) => {
try {
const { parkingName, price, address, name, phoneNumber, about } = req.body;
const { parkingImage } = req.files;
const check_exist = await Auth.findById(req.data.id);
if (!check_exist) return res.status(404).json({ error: "User not found" });
console.log(req.data.id);
const updateData = await Parking.findByIdAndUpdate(
{ _id: req.params.id, merchantId: req.data.id }, // I think here is the problem
{
$set: {
parkingName,
price,
address,
...
},
}
);
return res.status(200).json({
success: true,
msg: "Parking has updated successfully",
});
} catch (error) {
return error.message;
}
};

然而,问题是其他用户现在可以更新我想要阻止的另一个用户的数据

下面是中间件的查询:
routing.patch("/parking/update/:id", middleware.authenticateToken, merchant.updateParking);

如果您想要阻止从其他用户更新数据,您必须在updateParking函数中检查请求的用户。例如:

if(req.user !== req.body.user) {
return res.status(400).json({ error: "you can't update another User" });
}

点播。user是已登录的用户,req.body.user是要更新的用户。

最新更新