skip to Main Content

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


  1. If you are accessing req.body.isAdmin that means you post request body json must contain a property isAdmin and be set to true:

    eg.

    const postRequestBody = {
       isAdmin: true
    }
    
    

    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.

    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 {
        res.status(401).json({ success: false, message: "Sorry, you need admin access for this route" }
        console.log("auth")
      }
    });
    
    Login or Signup to reply.
  2. 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

    module.exports = (req, res, next) => {
      if (!req.body.isAdmin) {
        return res.status(401).json({ success: false, message: "Sorry, you need admin access for this route" })
      }
      next()
    }
    

    Route

    const isAdmin = require("./middlewares/isAdmin")
    
    router.post(`/categories`, isAdmin, async (req, res) => {
        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 });
        }
    });
    

    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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search