node.jsexpresspassport.jspassport-google-oauth

PassportJs Google Auth saves existing user as a new user in the database. How can I fix that?


I'm using passportJs Google Authetication. Although a user exist in database, When I login the system with this user, It creates this user again in the database as a new user. How can I fix this problem, can you help ? Thats image of the database:

enter image description here

Here is my codes:

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

My Router:


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;

My UserSession Middleware:

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

Solution

  • After signing in, in the Passport part, the findOne query might have some issue. It is not able to find the user & hence it is registering again.

    Replace

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

    to

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

    & check if it works.