I have a user management system where admin has the rights to update the role of their users, how to prevent admin from updating a document with roles higher than him? Example, order of authority in descending order: 1: superadmin 2: admin 3: supervisor 4: user
Now I have a code which updates the role of a user as:
router.post('/changeRole', async (req, res) => {
const { email } = req.body;
const updatedUser = await Users.findOneAndUpdate({ email }, { $set: { role } }, { new: true });
}
);
By the above code admin could make anyone a superdmin and it would give that user every access. Is there a way something like this below to prevent that in query?
router.post('/changeRole', async (req, res) => {
const { email } = req.body;
const updatedUser = await Users.findOneAndUpdate({ email }, { $set: { role !== "superadmin" } }, { new: true });
}
);
CodePudding user response:
I think this can help you:
const updatedUser = await Users.findOneAndUpdate(
{
email: email,
role: {$ne: "superadmin"}
},
{ $set: role },
{ new: true }
);
$ne
operator means not equal
, so this only updates the document when email matches and role is different from superadmin
.