0

I would like to protect some endpoints in my express app, I want to create something simple to manage if my app became a big app...now I'm doing something like this:

setProtected(router) {
    const self = this;
    router.use(this.auth);
    ...
}


setPublic(router) {
    const self = this;
    ...
}


getRouter() {
    const router = express.Router();
    this.setPublic(router);
    this.setProtected(router);
    return router;
}

with:

  auth(req, res, next) {
    if(req.isAuthenticated()) {
      console.log('req.isAuthenticated()', req.isAuthenticated());
      return next();
    }
    return res.send(401);
  }

the problem in this case is that is difficult maintain and it doesn't work well as if I have /:id in my publicRoute and for example /my-items in my protected route when I'm not logged and I try to reach /my-items I get the code of /:id.

Another idea was to create a json with the list of all my urls with same information like protected/not protected and eventual roles and then change auth with something like:

import urls from './urls';
auth(req, res, next) {
    if (urls[req.url] == 'public') {
        return next()
    } 
    else if (urls[req.url] == 'protected' && req.isAuthenticated()) {
        return next();
    }
    return res.send(401);
}

whats the best way for you?

francesco.venica
  • 1,703
  • 2
  • 19
  • 54

2 Answers2

0

You can chain middlewares: eg.

const authenticate = (req, res, next) {
.. some auth logic
next();
}

app.use('/', main...
app.use('/profile', authenticate, otherMiddleware, 
app.use('/admin', authenticate, isAdmin, otherMiddleware... 
Artur P.
  • 886
  • 4
  • 12
0

in your main file (server.js) import the routes and use the middleware there :)

server.js

const express = require('express')
const cors = require('cors')
const app = express()

// import admin routes
const adminRoute = require('./app/routes/admin.route.js')

// Add middleware for parsing URL encoded bodies (which are usually sent by browser)
app.use(cors())
// Add middleware for parsing JSON and urlencoded data and populating `req.body`
app.use(express.urlencoded({ extended: false }))
app.use(express.json())


// homepage route
app.get("/", (req, res) => {
  res.json({ message: "Hello World" })
})

// restricted by middleware "isAdmin"
app.use('/api/v1', isAdmin, adminRoute)

app.listen(8008).on('listening', () => {
  console.log('Server is running on 8008')
})

admin.route.js

const express = require('express')
const admin = require('../controllers/admin.controller.js')

const router = express.Router()

// get all admin users
router.get('/users', (req, res, next)  => {
  admin.getAdminUsers(req, res, next)
})

module.exports = router
Mr.P
  • 1,182
  • 3
  • 20
  • 44