Search code examples
expresspassport.jspassport-local

passport.authenticate successRedirect condition


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


Solution

  • 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');
        }
      });