Google OAuth keeps failing

Issue

I am trying to implement sign-in based on Google OAuth2. Couldnt figure out the problem.

app.route('/auth/google').get(
  passport.authenticate('google', { scope: ['profile email'] }));

    app.route('/auth/google/callback').get( 
    passport.authenticate('google', { failureRedirect: '/' }),
    function(req, res) {
        req.session.user_id=req.user.id;
        res.redirect('/chat');
    });
 passport.use(new GoogleStrategy({
        clientID: 'GOOGLE-CLIENT-ID',
        clientSecret: 'GOOGLE-CLIENT-SECRET',
        callbackURL: "https://chat-roomproject.herokuapp.com/auth/google/callback"
      },
      function(accessToken, refreshToken, profile, cb) {
        myDataBase.findOneAndUpdate({ googleId: profile.id }, 
          {
            $setOnInsert: {
              googleId: profile.id,
            },
          },function (err, user) {
          return cb(err, user.value);
        });
      }
    ));

It keeps redirecting to home page even after sign-in.

These are the logs.

2021-08-09T16:34:34.862956+00:00 heroku[router]: at=info method=GET path="/auth/google/callback?code=4%2F0AX4XfWh9LlA9ydQdyKwNx9sBUeFaSrMnC2RHJ4luL9fhjZ9OHlOoMljZlCmKz2jEHMTVTQ&scope=email+profile+openid+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.profile&authuser=0&prompt=none" host=chat-roomproject.herokuapp.com request_id=a5b37882-9e8e-4004-8340-07ed8cc532c5 fwd="157.48.190.189" dyno=web.1 connect=0ms service=441ms status=302 bytes=234 protocol=https


2021-08-09T16:34:35.157420+00:00 heroku[router]: at=info method=GET path="/" host=chat-roomproject.herokuapp.com request_id=833924df-8397-4601-b718-d915d72856cc fwd="157.48.190.189" dyno=web.1 connect=0ms service=5ms status=304 bytes=151 protocol=https

Solution

{ upsert: true, new: true }
adds new user to database, and this was missing in the code.

This should work:

passport.use(new GoogleStrategy({
        clientID: 'GOOGLE-CLIENT-ID',
        clientSecret: 'GOOGLE-CLIENT-SECRET',
        callbackURL: "https://chat-roomproject.herokuapp.com/auth/google/callback"
      },
      function(accessToken, refreshToken, profile, cb) {
        myDataBase.findOneAndUpdate({ googleId: profile.id }, 
          {
            $setOnInsert: {
              googleId: profile.id,
            },
          {upsert: true, new: true},

          },function (err, user) {
          return cb(err, user.value);
        });
      }
    ));

Answered By – ans

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published