How to redirect user to registration page if the user does not exist?

46 Views Asked by At

I'm developing a project using NestJS and I want to allow users to login with Google OAuth 2.0

I'm using passport and passport-google-oauth

Everything works well but I want to redirect a user to a registration page when they first time login with their google account, which looks like the following screen:

enter image description here

Currently my validate method is to create a new user if the user does not exist:

async validate(
  accessToken: string,
  refreshToken: string,
  profile: Profile,
  done: VerifyCallback
): Promise<any> {
  const user = await User.findOne({ googleId: profile.id });

  // If user doesn't exist creates a new user. (similar to sign up)
  if (!user) {
    const newUser = await User.create({
      googleId: profile.id,
      name: profile.displayName,
      email: profile.emails?.[0].value,
      // we are using optional chaining because profile.emails may be undefined.
    });
    if (newUser) {
      done(null, newUser);
    }
  } else {
    done(null, user);
  }
}

And I'm using NextJS in my frontend. I have done some research but without luck. Can anyone tell me how to do this? Thank you.

0

There are 0 best solutions below