Executing all middleware within an express route

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?

Answer №1

function checkUserRole(req,res,next){
  if(req.decoded.userId === parseInt(req.params.id, 10) || req.decoded.role === 1){
   next();
  }else{
   //error
  }
}

In JavaScript, functions are typically truthy, so

func1 || func2

Is equivalent to just calling func1.


An alternative solution could involve using an additional function like the one above, or a more intricate approach:

app.use(function(req,res,next){
 checkRole(req,{ 
  status(code){
    checkUserOwnership(req,res,next);
    return this;
   },
   send(){}
  },next);

Perhaps a more elegant solution would be to use wrapper functions:

function all(...funcs){
 return function(req,res,next){
   var allPass=true;
   funcs.reduce(function(func,middle){
     return function(){
       middle(req,res,func);
     }
   },_=>allPass=false);
  if(allPass) next() else res.error(404);
 };
}

function any(...funcs){
 return function(req,res,next){
   var anyPass=false;
   if(funcs.some(function(middle){
          middle(req,res,_=>anyPass=true);
          return anyPass;
     }
   })) next() else res.error(404);
 };
}

Usage example:

app.use(any(checkUserRole,checkUserOwnership),...);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having trouble with the filtering feature in Material UI Datagrid

I'm currently using Material UI Data Grid to display a table on my website. The grid has an additional filter for each column, but when I click on the filter, it hides behind my Bootstrap Modal. Is there a way to bring it to the front? https://i.stac ...

The webpage fails to refresh even after being redirected from the backend

I am facing an issue with a post request on my web app for the sign-up page. The code snippet for my sign-up page is as follows: const CustomAPIError = require('../../errors/customError') //import jsonwebtoken for using jwt to issue token from th ...

Using node.js to parse an XML file from a URL and iterate through it to retrieve all the URLs contained within

I am currently utilizing the node module xml2js. The format of my xml file looks like this: <?xml version="1.0" encoding="UTF-8" ?> <?xml-stylesheet type="text/xsl"?> <?xml-stylesheet type="text/css" media="screen" href="some url" ?> ...

JavaScript's speciality - altering the Jquery fade in and fade out effect on Firefox browsers

Utilizing Jquery, I implemented a feature on a table where moving the mouse over a row changes its color. The Javascript code was specifically designed for IE7 and works flawlessly there. However, when tested in Firefox, the text fades along with the backg ...

Updating ES6 syntax for superset in array: a step-by-step guide

I am currently working with ES6 React code that generates an array of MiniIcons on a webpage. const MiniIcons = ({miniicons}) => ( <div id="application"> {miniicons.map(miniicon => ( <MiniIcon key={miniicon.id} id={miniicon.id} ...

The API functions seamlessly with TypeScript, however, during the transpilation process, it fails to locate the model

I am in the process of developing a straightforward API that is capable of Creating, Reading, and Deleting student information within a postgres database. Interestingly, I have encountered an issue when using ts-node-dev without transpiling the files to J ...

Unleashing the power of jQuery ajax without requiring a server

I've been incorporating jQuery ajax calls on my HTML pages. $.ajax({ url: 'search/' + page + '.html', dataType: 'text', success: function(data) { $(".searchData").html(data); $(".searchData"). ...

IFrame displaying blank page instead of report

The following code snippet displays a report within an IFrame: HTML <div id="dialogReport"> <div> <iframe id="reportFrame" style="width: 800px; height: 600px; border: 2px solid black; margin: 10px auto;"> </iframe> </di ...

Dynamically import React Material UI Icons when needed

The concept here revolves around importing react material UI icons only when necessary, especially in situations where we may not know the icon name during compile time. (Ensuring that we have valid icon names) My method involved using a require statement ...

Issue with displaying nested React Elements from Component

I am currently facing an issue with my Collection component, which is utilizing a sub-component called RenderCollectionPieces to display UI elements. Strangely, I am able to see the data for image.name in the console but for some reason, the UI elements ar ...

Page encountering NextJS cors error, while API route remains unaffected

In my Next.js application, I have encountered an issue where executing a call to fetch a page from an external website works perfectly fine when done from the backend through an API route. However, when attempting the same action from the frontend, I encou ...

Obtain the values from controls within the <td> element

I'm experiencing some difficulty creating an array of table cell values because the cells contain controls, not just plain text. $("#tbl_CGT tr").each(function() { var arrayOfThisRow = []; var tableData = $(this).find('td'); if (tab ...

Exploring the Integration of jQuery AJAX in a Contact Form

I would like to incorporate AJAX functionality into a contact form. Here is the current code I have... $("#contact_form").validate({ meta: "validate", submitHandler: function (form) { $('#contact_form').hide(); ...

Create automated scripts with Selenium using the programming language JavaScript

Is it possible to create selenium webdriver scripts using only javascript? If so, what are the benefits of choosing javascript over languages like java or C#? In what situations would javascript be the preferred option? Appreciate your insights. ...

Guide to receiving dynamic argument variables in jQuery using $.get

I am currently working on developing an Ajax function call. In this function, the argument q will be dynamically defined, and the $.get method will return either true or false based on the data received from the Ajax call. <a href="any.php" class ...

Is it possible to use HTML alone in Bootstrap 5 to link a button to display a toast notification?

I'm working on a Bootstrap page that includes a button and a toast element sourced from the Bootstrap documentation. The documentation states that I need to initialize the toast in JavaScript during page load. My goal is to have the toast appear when ...

If there are multiple Monaco diff editors present on a single page, only the first instance will display the diff

I'm currently working with a Vue component that renders a diff editor using Monaco. However, when I have more than one instance of this component on the same page, only the first one displays the diff highlights. Here is the template: <template> ...

Tips for transferring properties from one React component to another React component

I need to figure out how to activate a button in a modal when text is entered into an input field. The form is part of a different class and is utilized within a parent class. How can I pass an onChange method to my form component? Check out the code for ...

Unable to get HTML text input validation with RegEx to function, despite incorporating the required attribute

I am attempting to create dynamically generated text inputs that only allow for digits and an optional decimal point. I have added the required attribute but the inputs are not responding to the RegEx pattern. var howMuch = $("<input>").attr("type", ...

The HTML canvas may sometimes produce inaccuracies in the bytes returned by the getImageData function, a phenomenon known as "

I've come across an issue where the getImageData function of an HTML canvas is returning incorrect byte values. To illustrate, I created a 1x1 pixel image using the following Python code: from PIL import Image import numpy as np a = np.array([[[12, ...