Currently, I am in the process of constructing an API using express and have implemented multiple middleware functions in my routes. One of the endpoints I am working on is displayed below:
Router.route('/:id/documents')
.get([isAuthenticated, isAdmin || isUserOwn], Users.getUserDocuments);
Listed below are the middleware functions I am utilizing:
export const isAdmin = (req, res, next) => {
if (req.decoded.role === 1) {
next();
} else {
res.status(401).send({
status: 'error',
message: 'Only admins are authorized to access this resource',
});
}
};
export const isUserOwn = (req, res, next) => {
if (req.decoded.userId === parseInt(req.params.id, 10)) {
next();
} else {
res.status(401).send({
status: 'error',
message: 'Only the owner can access this resource',
});
}
};
The desired functionality is to restrict access to the document to only the owner and admin users. However, the current issue I am facing is that when a user who is not an admin tries to access the document, it triggers the isAdmin middleware without progressing to the isUserOwn middleware. One solution I have considered is combining both middleware functions into one, but I also use them separately in other routes. How can I ensure that both middleware functions are executed?