Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 697
Joseph Chambers Avatar asked Jan 05 '17 00:01

Joseph Chambers


People also ask

What does passport authenticate () do?

In this route, passport. authenticate() is middleware which will authenticate the request. By default, when authentication succeeds, the req. user property is set to the authenticated user, a login session is established, and the next function in the stack is called.

What is passport strategy?

Passport's local strategy is a Node. js module that allows you to implement a username/password authentication mechanism. You'll need to install it like any other module and configure it to use your User Mongoose model.

What is passport session?

passport. session() acts as a middleware to alter the req object and change the 'user' value that is currently the session id (from the client cookie) into the true deserialized user object.


1 Answers

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');
    }
  });
like image 169
Joseph Chambers Avatar answered Nov 18 '22 01:11

Joseph Chambers