Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passport.js async vs sync deserialization

I'm implementing a payment feature on my app, and my provider requres AccountId (identification of the user in my system) and Email. I've noticed some strange behaviour I cannot explain with Passport.js. First of all, deserialization looks like in docs:

passport.deserializeUser(function(id, done) {
  User.findById(id, function(err, user) {
    done(err, user);
  });
});

Now, I get that this is an async operation, however when I form the data for the request, I do:

var data = {
    AccountId: toString(req.user._id),
    Email: req.user.auth.local.email
    // ...
}

For some reason Email gets set correctly, but AccountId always returns [object Undefined]. Well, I thought that maybe it's due to Passport's async nature of deserialization (since it requires time to User.findById()), but why does Email gets set correctly then?

I've found a way of setting AccountId to req.session.passport.user, but it seems like a hack to me.

like image 996
Anton Egorov Avatar asked Sep 06 '25 03:09

Anton Egorov


1 Answers

Your problem is here:

AccountId: toString(req.user._id),

toString is a method of an object. In the browser, simply calling toString assumes that you mean window.toString() and it returns [object Window]. In Node, since the global window does not exist, you get [object Undefined].

I think the way you meant to call that function would be like so:

 AccountId: req.user._id.toString(),
like image 54
Chris Foster Avatar answered Sep 07 '25 22:09

Chris Foster