Passport Authentication immediately after New User Registration Passport Authentication immediately after New User Registration express express

Passport Authentication immediately after New User Registration


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.


I think you're looking for the register method, which will register (and hide the password)

https://www.npmjs.com/package/passport-local-mongoose (search the register method).

app.post('/register', function(req, res) {  // New user variable created.  // Note: Password is not part of the new User variable; you don't want to simply store sensitive information in the database.  var registerUser = new User({ email: req.body.email, name: req.body.name });  // Register new user. Note the 2nd variable (password). If registration's successful (no errors), redirect.  registerUser.register(registerUser, req.body.password, function (err, newUser){      if(!err){           passport.authenticate('local', req, res, function(){                   res.redirect('/dashboard');                                });       }  });});