Step 19: Update users route

Add this middleware to users.js:

const checkPermission = (req, res, next) => {
  try {
    if (req.method === "POST") {
      return next();
    }

    const bearerHeader = req.headers["authorization"];
    const bearer = bearerHeader.split(" ");
    const token = bearer[1];
    const { id, role } = decodeToken(token);
    if (role === UserRole.Instructor) {
      return next();
    }

    if (req.method === "GET" && id === req.params.id) {
      return next();
    } else if (req.method === "PUT" && id === req.params.id) {
      return next();
    } else if (req.method === "DELETE" && id === req.params.id) {
      return next();
    }

    next(new ApiError(403, "Forbidden"));
  } catch (err) {
    next(new ApiError(401, "Unauthorized"));
  }
};

Have all users route to use this middleware

router.get(`${endpoint}`, checkPermission, async (req, res, next) => {

});

router.get(`${endpoint}/:id`, checkPermission, async (req, res, next) => {

});

router.post(`${endpoint}`, checkPermission, async (req, res, next) => {

});

router.put(`${endpoint}/:id`, checkPermission, async (req, res, next) => {

});

router.delete(`${endpoint}/:id`, checkPermission, async (req, res, next) => {

});

Refer to the commit history to see the changes made at this step.