Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 304
Sam Avatar asked Feb 10 '19 06:02

Sam


3 Answers

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.find(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');
like image 123
Kai Avatar answered Oct 11 '22 21:10

Kai


you can add your middleware code like below

router.get('/', isAuthenticated, function(req, res) {
   //your next function 
});
function isAuthenticated(req, res, next) {
  // do any checks you want to in here

  // CHECK THE USER STORED IN SESSION FOR A CUSTOM VARIABLE
  // you can do this however you want with whatever variables you set up
  if (req.user.authenticated)
      return next();

  // IF A USER ISN'T LOGGED IN, THEN REDIRECT THEM SOMEWHERE
  res.redirect('/');
}
like image 23
powercoder23 Avatar answered Oct 11 '22 21:10

powercoder23


As I wanted ALL routes (except for login routes off course) to pass authorization, I solved it as follows:

var ensureAuthenticated = function(req, res, next) {
    if (req.isAuthenticated()) return next();
    else res.redirect('/login')
}

// usersRouter contains all open routes like '/login':
app.use('/', usersRouter);

// From here on, all routes need authorization:
app.use(ensureAuthenticated);

app.use('/', indexRouter);
app.use('/api/foo', fooRouter);
app.use('/api/bar', barRouter);
like image 30
Sam Avatar answered Oct 11 '22 20:10

Sam