passport.authenticate successRedirect condition

Joseph Chambers picture Joseph Chambers · Jan 5, 2017 · Viewed 7.2k times · Source

In my app.js I have:

router.post('/login', passport.authenticate('local', {
  successRedirect: '/admin/users',
  failureRedirect: '/login'
}), function (req, res) {
});

My user object looks like this:

{ _id: 586afad4a4ff884d28b6ca97,
  firstName: 'Joseph',
  ...
  isAdmin: false }

What I want to do is:

router.post('/login', passport.authenticate('local', {
  successRedirect: {
    if(req.body.user.isAdmin === true) {
      res.redirect('/admin/users')
    }
    res.redirect('/dashboard');
  },
  failureRedirect: '/login'
}), function (req, res) {
});

but it doesn't seem that I can. What will be the easiest example of checking if the user is an admin or doing the login post using passport.authenticate

Answer

Joseph Chambers picture Joseph Chambers · Jan 5, 2017

I was able to figure it out. The optional object in passport.authenticate confused me. So what I did was:

router.post(
  '/login',
  passport.authenticate('local', {
    failureRedirect: '/login'
  }), (req, res) => {
    if (req.user.isAdmin === true) {
      res.redirect('/admin/gifts?filter=review');
    }
    if (req.user.isAdmin === false) {
      res.redirect('/dashboard/received');
    }
  });