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

In JavaScript, the function is unable to access elements within an iteration of ng-repeat

I am using ng-repeat to display datepickers that are powered by flatpickr. To make this work, a script needs to be added on the page for each input element like so: <script> $('[name="DOB"]').flatpickr({ enableTime: false, dateForm ...

formula for an arbitrary velocity vector

In the game I'm developing, I want the ball to move in a random direction on the HTML canvas when it starts, but always with the same velocity. The current code I have is: vx = Math.floor(Math.random() * 20) vy = Math.floor(Math.random() * 20) Howev ...

Extracting JavaScript OnClick button using Selenium

I'm having trouble extracting the email address from the following URL: https://www.iolproperty.co.za/view-property.jsp?PID=2000026825 that is only visible after clicking on the "Show email address" button. However, every time I attempt to click and r ...

using node.js to extract a cookie from a 302 redirect

Need help simulating a login using node.js. The request is a post method and returns a 302 status code. However, when trying to simulate the request in node, I encounter the following error: Error handling unrejected promise: StatusCodeError: 302 Upon i ...

Encountering a problem with AngularJS ui router templates

I have defined the following routes in my project: $stateProvider .state('access', { abstract: true, url: '/access', templateUrl: 'login.html' }) .state('access.signin', { ...

Enable Parse5's case sensitivity

Recently, I've attempted to parse Angular Templates into AST using the powerful parse5 library. It seemed like the perfect solution, until I encountered an issue - while parsing HTML, it appears that the library transforms everything to lowercase. Fo ...

how can you activate a modal without relying on bootstrap?

Could anyone suggest a more efficient way to create a pop-up modal triggered by a button click without relying on bootstrap? I've attempted different methods but haven't achieved the desired result. Here's a sample plunker for reference. Any ...

Tips for muting console.log output from a third-party iframe

As I work on developing a web application using NEXT.js, I am encountering an issue with a third party iframe that is generating numerous console logs. I am seeking a way to silence these outputs for the iframe. The code in question simply includes an < ...

Expanding the capabilities of search and replace in Javascript is imperative for enhancing its

I have developed a search and replace function. How can I enhance it by adding a comment or alert to describe the pattern and incorporating a functional input box? Any suggestions are welcome! <html> <head> <title> Search & Replace ...

Convert a Twitter Direct Message Link by changing the `<button>` tag to an `<a>` tag

When you log into Twitter and have Direct Message enabled, a "Send Message" button will appear. Can someone please provide the URL for sending a DM to a specific user? I tried looking at the code but I could use some assistance. Any thoughts? Thank you in ...

Discovering browser back button press event utilizing Angular

Can we identify when a user has navigated to a page using the browser's history back button? I am looking for a solution in angular.js without relying on angular routing. Additionally, it should also detect if a user returns to a form after submitting ...

Automatically initiate a click event when the page is loaded

I'm having trouble getting a click event to trigger on my controller when the page loads. I really just want the checkboxes to be clicked automatically. <!DOCTYPE html> <html > <head> <link rel="stylesheet" type="text/css" ...

Having issues with Facebook's login API for JavaScript?

Apologies for the improper formatting. I am encountering errors in my JavaScript compiler while working with the Facebook Login API... Error: Invalid App Id - Must be a number or numeric string representing the application id." all.js:53 "FB.getL ...

Adjusting the size of the iframe to match the dimensions of the window

Is there a way to make the iframe automatically fill up the entire space? For example, only opens the iframe up to half of the window in Mozilla Firefox and IE6. How can I ensure that it takes the maximum size of the screen? Are there any CSS or JavaScr ...

If I use npm install to update my packages, could that cause any conflicts with the code on the remote server?

As I navigate through the numerous issues, I stumbled upon the command npm ci that is supposed to not change the package-lock.json file. However, when I attempt to run npm ci, it fails: ERR! cipm can only install packages when your package.json and package ...

Having trouble with implementing both filter and infinite scroll simultaneously in an Ionic list?

I've encountered an issue with my ionic hybrid app related to angularjs filters. The code snippet below showcases the problem: <input type="search" placeholder="Search personalities" ng-model="name" ng-change='alert("changed!")&apo ...

JavaScript (geolocation) error: Unhandled TypeError - Invocation not allowed

Encountering the Javascript error "Uncaught TypeError: Illegal invocation" while executing the code var nativeGeoloation = window.navigator.geolocation.getCurrentPosition; nativeGeoloation(function (){ alert("ok")}); Despite attempting to call the code w ...

Govern Your Gateway with Expressive Logs

I'm facing some issues with the logs in my Express Gateway: Although I followed the documentation and enabled Express Gateway logs, I cannot locate any log files under my gateway root directory. Whenever I start the gateway using the command LOG_L ...

What is the best way to create individual Menu items in a React/MUI navigation bar?

I am currently developing a navigation bar for an application, and I seem to be facing an issue with differentiating between multiple Menu/MenuItem elements. No matter what approach I take, both Menus and their respective MenuItems end up directing to the ...

How to Stop AJAX Requests Mid-Flight with JQuery's .ajax?

Similar Question: Stopping Ajax Requests in JavaScript with jQuery Below is the straightforward piece of code that I am currently using: $("#friend_search").keyup(function() { if($(this).val().length > 0) { obtainFriendlist($(this).va ...