微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

PassportJs Google Auth将现有用户另存为数据库中的新用户我该如何解决?

如何解决PassportJs Google Auth将现有用户另存为数据库中的新用户我该如何解决?

我正在使用passportJs Google Authetication。尽管数据库中存在一个用户,但是当我使用该用户登录系统时,它会在数据库中再次以新用户的身份创建该用户。我该如何解决此问题,您能帮忙吗? 那是数据库的图像: https://i.stack.imgur.com/tNIZJ.png

这是我的代码

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",{ 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);
    });
};

解决方法

登录后,在“护照”部分中, findOne查询可能有问题。它找不到用户,因此正在重新注册。

替换

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

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

&检查它是否有效。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?