Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passport.js and Mongoose.js populate User on login - loses populated field on req.user

Using Mongoose.js, my authenticate method populates the field "companyRoles._company," but the populated data reverts to the company reference ID when I try to access the same populated field in my req.user object.

//Authentication 
UserSchema.static('authenticate', function(email, password, callback) {
  this.findOne({ email: email })
  .populate('companyRoles._company', ['name', '_id'])
    .run(function(err, user) {
      if (err) { return callback(err); }
      if (!user) { return callback(null, false); }
      user.verifyPassword(password, function(err, passwordCorrect) {
        if (err) { return callback(err); }
        if (!passwordCorrect) { return callback(null, false); }
        return callback(null, user);
      });
    });
});

//login post
app.post('/passportlogin', function(req, res, next) {
  passport.authenticate('local', function(err, user, info) {
    if (err) { return next(err) }
    if (!user) { return res.redirect('/passportlogin') }
    req.logIn(user, function(err) {
      if (err) { return next(err); }
      console.log('req User');
      console.log(req.user); 
      return res.redirect('/companies/' + user.companyRoles[0]._company._id);
    });
  })(req, res, next);
});

app.get('/companies/:cid', function(req, res){
    console.log('req.user in companies:cid');
    console.log(req.user);   
});

After req.logIn, logging req.user shows - companyRoles{_company: [Object]}

But when I redirect to /companies/:id route after logging in, it is showing the id and not a populated [object] - companyRoles{_company: 4fbe8b2513e90be8280001a5}

Any ideas as to why the field does not remain populated? Thanks.

like image 293
Michael McCabe Avatar asked Jun 12 '12 00:06

Michael McCabe


1 Answers

The problem was that I was not populating the field in the passport.deserializeUser function, here is the updated function:

//deserialize
passport.deserializeUser(function(id, done) {
    User.findById(id)
    .populate('companyRoles._company', ['name', '_id'])
    .run(function (err, user) {
        done(err, user);
     });
});
like image 71
Michael McCabe Avatar answered Nov 11 '22 14:11

Michael McCabe