在 users 表中,我有兩個集合,一個是 admin,另一個不是。
現在我只希望管理員用戶發布資料。
這是發布請求:
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",
});
}
});
我正在使用 JWT 來確定用戶是否是管理員。我已在用戶架構中將用戶的管理員角色之一設定為“真”。
認證中間件:
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);
}
};
但是,即使是非管理員用戶也可以發布資料,然后將其保存到資料庫中。
我想限制這一點。
我不確定如何防止非管理員用戶發布資料。
uj5u.com熱心網友回復:
您需要檢查用戶是否是 Auth 中間件中的管理員。
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);
}
};
const user = await User.find({ admin: true });如果簽入路線,請洗掉線路和相關資訊。
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",
});
}
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/489447.html
上一篇:如何在discord.js和mongodbatlas上創建注冊命令?
下一篇:perl中如何匹配多個專案
