Reputation: 609
I have Router dynamically generated. Routes files are in folders structure that corresponds to router path. e.g. route v1/users/getUsers
so getUsers.js is in /api/v1/users/
folder.
My middle wares are in /middlewares/
folder, and I am generating my express app in /createExpressApp.js
so currently I have my authorisation middlware in .use(auth)
just before .use('/api', router)
This way it works just fine, before each route , auth is executed. However, I want to protect only certain routes. I guess I could just import my middleware in each file with a route I want to protect, but some of the routes are deep in folders and my import would be something ugly like ../../../middlware/auth.js
Is there any clever way to avoid that kind of import ?
Here is my router dynamic creation, I do admit I found that solution somewhere on the internet and I do understand idea but don't know where to put some extras for router such as router.all or router.use
import { sync } from 'glob'
import { Router } from 'express'
const auth = require('../middlewares/auth.js').isAuthenticated
export default () => sync('**/*.js', { cwd: `${__dirname}/` })
.map(filename => require(`./${filename}`).default)
.filter(router => Object.getPrototypeOf(router) == Router)
.reduce(
(rootRouter, router) =>rootRouter.use(router),
Router({ mergeParams: true })
)
so answering my own problem + answer from below using router.all ( or others from documentation). I would put it here:
export default () => sync('**/*.js', { cwd: `${__dirname}/` })
.map(filename => require(`./${filename}`).default)
.filter(router => Object.getPrototypeOf(router) == Router)
.reduce(
(rootRouter, router) =>rootRouter
.all('*getUsers',auth)
.use(router)
,
Router({ mergeParams: true })
)
Upvotes: 2
Views: 240
Reputation: 1731
Anything clever or configuration based is going to leave you at the same problem: Somewhere you need to describe which routes have auth over them.
It seems the easiest way to do this would be requiring the auth on the routes needed.
You should review the express middleware documentation, as you can break up app into different routers and router.use
.
A typical pattern would be to use the router.all
to define the endpoints that need auth. You can use regex/route pattern matching, as shown in the linked documentation and in the screenshot below:
Upvotes: 2