0

In the PassportJS Google OAuth Strategy, for some strange reasons, when I serialize the user id and send it to the cookie to be sent to the browser, it does not return the id to deserialize it and that tells me because when I console.log user, it returns undefined,

passport.deserializeUser((id, done) => {
    User.findById(id).then((user, done) => {
        console.log(user);
        done(null, user);
    });
});

To go into details my cookie is below

app.use(cookieSession({
  maxAge: 24 * 60 * 60 * 1000,
  keys: 'dkfehfhgddf'
}));
31piy
  • 23,323
  • 6
  • 47
  • 67

1 Answers1

0

In case you are using Mongoose, you have made a mistake in your code which is causing the unexpected behaviour.

If you are trying to use the Promise version of the findById() funciton, you have to call .exec() afterwards, in order to dispatch the action. Also, you have shadowed the deserializeUser's done callback, so it will never be called.

Here is how it should work:

passport.deserializeUser((id, done) => {
  User.findById(id).exec()
    .then(user => {
      if (user) {// user may be null
        done(null, user);
      } else {
        done(new Error("User not found"), null);
      }  
   })
   .catch(error => {
     done(error, false);
   });
});
Tsvetan Ganev
  • 8,246
  • 4
  • 26
  • 43
  • thanks for the clarification. well it happens that when i console.log the id returned to the mongo, it returns nothing from the browser. therefore the db does not even recieve the id to query it – Obed Tetteh Dec 27 '17 at 22:26