Reputation: 819
My team is creating a large Express application at the moment, and we are wondering what the best way to "lock-down" our routes by default, and only allowing access once we add middleware.
I started off by writing a unauthorizedByDefault() middleware. It would be applied globally with app = express().use(unauthorizedByDefault()) and check if req.hasAuthMiddleware = true.
req.hasAuthMiddleware = true would be set by my auth middleware applied at the route level... app.post('/user', authMiddleware.isAdminUser(), ... Unfortunately, as you might have guessed, my route level middleware is applied after unauthorizedByDefault() runs, making every route unauthorized no matter what.
How can I make unauthorizedByDefault() run immediately after my other middleware without adding it to each and every route? Or is there another way I can accomplish this?
Upvotes: 0
Views: 150
Reputation: 36349
There's probably more than one way to skin this cat, but one option has to do with ordering and the fact that you can mount multiple things on the same mount point. So depending on how you're doing your middleware, it might look something like this:
app.post('/user', authMiddleware.isAdminUser());
app.use(unauthorizedByDefault());
app.post('/user', handleAPostToUser);
As long as your isAdminUser()
calls next, subsequent middleware will still be called.
If you have logic that applies to all the verbs on a path, you can also do:
app.use('/some-path', authMiddleware.isAdminUser());
Upvotes: 1