1

I'm using passportjs in order to log user and I try to redirect them after the password verify is complete with angularjs. But I keep getting "Cannot read property 'name' of undefined" when I try to get user data on another page Snippet:

app.post('/login', function(req, res, next) {
  passport.authenticate('local', function(err, usr, info) {

      res.locals.user = req.usr;
      res.json({msg:true});
      return next();
   })(req, res, next);
});

And somewhere else I try to do something like this:

user.find({name: req.user.name },function(err,q){

Which fire the error "Cannot read property 'name' of undefined"

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Xtal
  • 295
  • 5
  • 20

1 Answers1

1

You have to provide passport with serializeUser and deserializeUser functions in order for passport to store the user in the request object. For more info, check the guide:

http://passportjs.org/guide/configure/

Specifically, look at the bottom section on Sessions. Also, consult this similar question:

Do I implement serialize and deserialize NodesJS + Passport + RedisStore?

In your case, it looks like you're using name instead of id to identify users, so wherever you configure passport, you will probably want to do something like:

passport.serializeUser(function(user, done) {
  done(null, user.name);
});

passport.deserializeUser(function(name, done) {
  user.find({name: req.user.name }, function(err, user){
    done(err, user);
  });
});
Community
  • 1
  • 1
Lukas S.
  • 5,698
  • 5
  • 35
  • 50