skip to Main Content

I am trying to make a feature where a user can delete an expense they created OR a manager can delete an expense they have created but I am getting a not authorized error when trying to delete my expense I just created

Expense Controller Delete

export const deleteExpense = async (req, res, next) => {
  try {
    const expense = await Expense.findById(req.params.id);
    if (!expense) return error404(req, res, next);

    // Retrieve the user making the request
    const requestingUser = await User.findById(req.userId);
    if (!requestingUser) return error404(req, res, next);

    // Check if the user is authorized to delete the expense
    if (req.userId !== expense.userID && requestingUser.role !== "manager")
      return error403(req, res, next);

    const deletedExpense = await Expense.findByIdAndDelete(req.params.id);

    if (!deletedExpense) return res.status(404).send("House not found");
    res.status(200).json({ message: "deleted" });
  } catch (error) {
    errorServer(error, req, res, next);
  }
};

jwt middleware

import jwt from "jsonwebtoken";
import createError from "http-errors";

export const verifyToken = (req, res, next) => {
  const token = req.cookies.accessToken;

  if (!token) return next(createError(401, "You are not authenticated!"));

  jwt.verify(token, process.env.JWT_KEY, async (err, payload) => {
    if (err) return next(createError(403, "Token is not valid!"));

    req.userId = payload.id;
    req.role = payload.role;

    next();
  });
};

2

Answers


  1. Your problem’s solution is in your question only

    where a user can delete an expense they created OR a manager can delete an expense they have created

    So the below line can be changed to handle your conditions.

    if (req.userId !== expense.userID || requestingUser.role !== "manager")
    

    Just check whether its working or not as its totally dependent on your functionality.

    Login or Signup to reply.
  2. You need to be clear about what do you mean by "…getting a not authorized error".

    If you mean that you’re getting the You are not authenticated! error from the createError instance, then that is most probably because your request is not adding the accessToken inside the request body.

    If that’s not the case, then probably you need to update the following condition based on your functionality:

    if (req.userId !== expense.userID && requestingUser.role !== "manager")
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search