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'
}));
4

1 回答 1

0

如果您使用的是 Mongoose,那么您的代码中出现了错误,导致了意外行为。

如果您尝试使用功能的 Promise 版本,则findById()必须在之后调用.exec(),以便调度操作。此外,您已经隐藏了deserializeUserdone回调,因此它永远不会被调用。

这是它应该如何工作的:

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);
   });
});
于 2017-12-27T12:12:33.223 回答