0

我正在使用 passportJs Google Authetication。尽管数据库中存在一个用户,但当我使用该用户登录系统时,它会在数据库中再次创建该用户作为新用户。我该如何解决这个问题,你能帮忙吗?那是数据库的图像:

在此处输入图像描述

这是我的代码:

module.exports = passport.use(
  new GoogleStrategy(
    {
      clientID: config.google.clientID,
      clientSecret: config.google.clientKey,
      callbackURL: "/auth/google/callback",
    },
    async (accessToken, refreshToken, profile, done) => {
      try {
        const user = await models.User.findOne({ google: { id: profile.id } });
        if (user) {
          done(null, user);
        } else {
          const newUser = new models.User({
            google: profile,
            isSocialAuth: true,

            name: profile.name.givenName,
            lastName: profile.name.familyName,

            cart: { items: [] },
          });
          await newUser.save();

          done(null, newUser);
        }
      } catch (error) {
        done(error, null);
      }
    }
  )
);
passport.serializeUser((user, done) => {
  done(null, user._id);
});
passport.deserializeUser((id, done) => {
  models.User.findById(id, (err, user) => done(err, user));
});

我的路由器:


router.get("/auth/google", passport.authenticate("google", { scope: ["profile"] }));

router.get("/auth/google/callback", passport.authenticate("google", { failureRedirect: "/login" }), async (req, res) => {
    req.session.user = req.user;
    req.session.isAuthenticated = true;
    res.redirect("/");
  
});

module.exports = router;

我的 UserSession 中间件:

module.exports = (req, res, next) => {
  if (!req.session.user) {
    return next();
  }

  models.User.findById(req.session.user._id)
    .then((user) => {
      req.user = user;
      next();
    })
    .catch((err) => {
      console.log(err);
    });
};
4

1 回答 1

1

登录后,在 Passport 部分,findOne 查询可能有问题。它无法找到用户,因此它正在重新注册。

代替

const user = await models.User.findOne({ google: { id: profile.id } });

const user = await models.User.findOne({ "google.id": profile.id });

& 检查它是否有效。

于 2020-10-31T15:47:37.553 回答