Home > Mobile >  Middleware OR other middleware validation
Middleware OR other middleware validation

Time:10-21

I need to check if a user is an administrator OR if the user is the same as the one requested. I tried but in one case it doesn't work.

router.get('/:id', isSigned, isSameUser || isAdmin, getUser)

Is there a way to do what I want without creating a dedicated function?

CodePudding user response:

You could write a different middleware to avoid unnecessary middleware chaining, which you can call Auth or AuthMiddleware, the name you want is up to you. In this middleware you could do the logic for checking the user's authentication status, something similar to this:

function AuthMiddleware(request, response, next) {
  if(isSigned) {
    // User is signed in, so we can proceed doing the next check

    if(isSameUser || isAdmin || getUser) {
      // Validation checks out, go to next middleware without warnings.
      return next();
    } else {
      // User failed to show some ID and cannot access the page.
      return next(new Error("Unauthorized."));
    }

  } else {
    // The user has not signed in to your application
    return next(new Error("Unauthenticated"));
  }
}

router.get('/:id', AuthMiddleWare, (request, response) => {
  // DO LOGIC
});

Place this middleware inside a new file, and every time you need it, you can just import it rather than copy and paste the same code over and over.

! Note that this is a rough sketch code just to put you on the right track, so you most likely have to adjust this snippet to your own needs and logic.

The benefits of having a single authentication middleware, is so you can use it on every route, so you don't have to use so many chaining in your requests.

  • Related