please how can i make only admin access a specific route
this is my mongodb database
{
"_id": {
"$oid": "640e16b3186c0b1910c1dedf"
},
"isAdmin": true,
"name": "sample name",
"email": "[email protected]",
"password": "$2a$10$tbi9fblLS9NXai3Osb7H7OdLVqq34I0OTKgvB5BmVBEASabvX/ybu",
"__v": 0
}
isAdmin is set to true i want admin to be the only one to access this route
router.post(`/categories`, async (req, res) => {
if(req.body.isAdmin){
try {
let category = new Category();
category.type = req.body.type;
category.description = req.body.description;
await category.save();
res.json({
status: true,
message: "save succes"
});
} catch (error) {
res.status(500).json({ success: false, message: error.message });
}}
else{
console.log("auth")
}
});
each time i try the above code the it skips the if statement and goes to the else
2
Answers
If you are accessing
req.body.isAdmin
that means you post request body json must contain a propertyisAdmin
and be set totrue
:eg.
This isn’t secure because the client has control over whether to show admin access or not.
Following your implementation, you should return a HTTP 401 Unauthorised in the else clause.
A better way is to create a middleware for checking isAdmin and put that middle on the route which you want to access only by admin.
In your route file import the middleware from middlewares folder and apply it on the routes you want to protect.
like this:
Middleware
Route
In this way, you can reuse this middleware for multiple routes and you don’t need to repeat the code to check for
isAdmin
on every controller function.Note: if isAdmin key is not in request body or it is false then middleware will return status 401.