How to make Passport Google OAuth2.0 work with react-google-login?

Viewed 1069

My app was using Passport Google OAuth2.0, but I found out that I needed to get a response on the front-end to set the state of a custom hook that grants access to the private routes and that didn't seem possible with Passport, thus I came across this react-google-login npm package, which allows me to define an onSuccess callback.

Now, is it possible to make this React package work with Passport Google OAuth strategy without conflicts? I want Passport to keep handling user creation on the database and generating JWT token. I just have no idea how to make them communicate with each other in such way that I can get to the onSuccess callback.

My Google Strategy and authentication routes are exactly like this:

passport.js

passport.use(
    new GoogleStrategy(
      {
        clientID: process.env.GOOGLE_CLIENT_ID,
        clientSecret: process.env.GOOGLE_CLIENT_SECRET,
        callbackURL: `${serverUrl}${process.env.GOOGLE_CALLBACK_URL}`,
      },
      function (accessToken, refreshToken, profile, cb) {
        User.findOrCreate(
          { googleId: profile.id },
          { first_name: profile.displayName, email: profile._json.email },
          function (err, user) {
            return cb(err, user);
          }
        );
      }
    )
  );

auth.js

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

const clientUrl =
  process.env.NODE_ENV === "production"
    ? process.env.CLIENT_URL_PROD
    : process.env.CLIENT_URL_DEV;

router.get(
  "/google/movie-log",
  passport.authenticate("google", {
    failureRedirect: clientUrl + "/login",
    session: false,
  }),
  (req, res) => {
    const token = req.user.generateJWT();

    res.cookie("access_token", token, { httpOnly: true, sameSite: true });

    res.redirect(clientUrl + "/diary");
  }
);

module.exports = router;

The React component:

Login.js

function handleSuccess(response) {
    authContext.setIsAuthenticated(true);
    navigate(state?.path || "/diary");
    console.log("Successfully authenticated");
}

function handleFailure(response) {
    console.log("Authentication failed");
}

<GoogleLogin
  clientId="my client ID"
  uxMode="redirect"
  scope="profile email"
  redirectUri="http://localhost:5000/auth/google/movie-log"
  onSuccess={handleSuccess}
  onFailure={handleFailure}
  cookiePolicy={"single_host_origin"}
/>
0 Answers
Related