Home » Nodejs » Passport Authentication immediately after New User Registration

Passport Authentication immediately after New User Registration

Posted by: admin November 29, 2017 Leave a comment

Questions:

I’m trying to authenticate and login a user immediately after submitting a POST on the /register form. Ideally, I would like users to be able to register and then be redirected immediately to the dashboard without having to enter their credentials again.

My server is using Passport 0.1.17 with the local strategy configured to use email address and password for login. The current code is:

app.post('/register', function(req, res) {

  // attach POST to new User variable
  var registerUser = new User({ email: req.body.email, password: req.body.password, name: req.body.name });

  // save registerUser Mongo
  registerUser.save(function(err) {
    if(err) {
      console.log(err);
    } else {
      console.log('registerUser: ' + registerUser.email + " saved.");
    }
  });

  // here is where I am trying to authenticate and then redirect
  passport.authenticate('local', { failureRedirect: '/login', failureFlash: true }),
  res.redirect('/dashboard');
  });

How would I refactor this code to save the new user, then authenticate and finally redirect to the dashboard?

Thanks in advance!

Answers:

Here’s the solution I came up with after reading about req.login:

app.post('/register', function(req, res) {
  // attach POST to user schema
  var user = new User({ email: req.body.email, password: req.body.password, name: req.body.name });
  // save in Mongo
  user.save(function(err) {
    if(err) {
      console.log(err);
    } else {
      console.log('user: ' + user.email + " saved.");
      req.login(user, function(err) {
        if (err) {
          console.log(err);
        }
        return res.redirect('/dashboard');
      });
    }
  });
});

I would like to clean it up a bit and think that the err section could be more robust, but this is a functioning solution. Note that is someone else implements this, they should be aware that it is tailored to using the passport-local strategy with email instead of username.