Search code examples
node.jspassport.jspassport-local

Passport.js: how to protect ALL routes?


I followed the documentation for passport.js with passport-local: http://www.passportjs.org/docs/authorize/

When I send my users to /login they are authenticated, but nowhere in that document can I find how to authorise my users.

I've tried this, but that gives me a bad request:

router.get('/somepage', passport.authenticate('local'), function(req, res, next) {

});

I'm looking for way to protect all my pages at once. I'm working with Express 4.16 and use different route files to split up my routes.

Sam


Solution

  • you can use middleware with a small trick to switch between strategies

    example:

    const allowUrl = ['public', 'nonprivate','home'];
    
    
    const authenticationMiddleware = (whiteList =[]) => (req, res, next) => {
        if(whiteList.includes(req.baseUrl)) {
          next();
        }
    
        if (req.isAuthenticated()) {
          return next()
        }
        res.redirect('/');
    }
    
    
    app = express();
    app.use(passort.initialize());
    app.use(authenticationMiddleware(allowUrl));
    app.use(apiRouter);
    
    
    app.listen(3000, ()=> console.log('hello internet');