1

I have 2 authentication systems. They was implemented in auth1 middleware, and auth2 middleware. They look like:

// service1 for auth1 and service2 for auth2
let authInfo = service1.check(username, password); 
if (authInfo) {
    req.user = authInfo;
}
next();

For some routes need only auth1 as following example.

router.post('/staff', auth1, newStaff);

For some routes need only auth2 as following example.

router.post('/user', auth2, newUser);

For some route need both of them.

router.post('/vip', auth1, auth2, newVip);

I tried to add another middleware called authCheck to above routes like the following code. It works fine.

router.post('/staff', auth1, authCheck, newStaff);
router.post('/user', auth2, authCheck, newUser);
router.post('/vip', auth1, auth2, authCheck, newVip);

In authCheck looks like the following code.

if (req.user) {
    next();
}
else {
    res.status(401).end();
}

Is it the proper way to deal with 2 authentication systems? Can I avoid the authCheck middleware?

  • That's one way to do it. There are certainly other ways to design your code. The way you have your code structured, only `authCheck()` actually enforces authentication and you have to have something that does enforcement. So, you can only get rid of `authCheck()` if you integrate that logic into other middleware or routes. – jfriend00 Jun 20 '21 at 16:07
  • Thanks @jfriend00. I wonder if it can be shorter than this solution. Any ideas would be appreciated. – Pruk Ambavamata Jun 20 '21 at 18:37
  • There are probably much cleaner ways to do it, but we would require some knowledge about your URL structure for all your routes and which specific routes require which auth. This information could allow you to structure your routes into routers that have a single auth point for the whole router so rather than assigning auth middleware to individual routes, you assign it to whole routers. The order of how the routes are declared can also contribute. It's a "whole" design problem that needs to look at the whole picture of what you're doing, not a micro-design issue. – jfriend00 Jun 20 '21 at 18:39

0 Answers0