OAuth but don't sign in

Hey!

I want to be able to sign in through Google OAuth to get token and refresh token only for this scope: https://www.googleapis.com/auth/gmail.readonly. In my app I’ve already logged in the user, whether it be by social auth (Google, Microsoft) or by supabase magic link. So I don’t want to change the already logged in user I just want to grab the tokens and then do stuff with them.

Haven’t been able to figure out how, any help would be appreciated!

Thanks,
Stephen

Hi @Stephen

You will have to set up a separate OAuth flow for the Connect to Gmail button, but first add the scope in Google Console. Google redirects back with a temporary code in the URL that you can pass to your edge function that will exchange for the token so you can safely store them in the database. A much simpler approach would be using the Sign In OAuth Provider action, but this would force a new login flow.

Hey @danlopes I just wanted to reply to this as I figured it out. I added this code to a Custom Javascript action on button click.

const scope = "https://www.googleapis.com/auth/gmail.readonly"; // Adjust scope as needed
const responseType = "code"; // Authorization Code Flow
const accessType = "offline"; // Get a refresh token
const prompt = "consent"; // Ensures the user is prompted every time (useful for testing)

// Construct the Google OAuth URL
const authUrl = `https://accounts.google.com/o/oauth2/v2/auth?client_id=${encodeURIComponent(
  clientId
)}&redirect_uri=${encodeURIComponent(
  redirectUri
)}&response_type=${encodeURIComponent(
  responseType
)}&scope=${encodeURIComponent(scope)}&access_type=${encodeURIComponent(
  accessType
)}&prompt=${encodeURIComponent(prompt)}`;

const popup = window.open(
  authUrl, // The constructed OAuth URL
  "_blank",
  "width=500,height=600"
);

if (!popup || popup.closed || typeof popup.closed == "undefined") {
  alert("Popup blocked! Please allow popups for this site.");
}

const handleMessage = (event) => {
  if (event.origin !== "https://editor.weweb.io") {
    console.warn("Ignored message from unknown origin:", event.origin);
    return;
  }

Works for me, I get the code from the uri and then use that code to get the token/refresh token.

You will need your own clientId and redirectUri to be set up in Google Cloud Console for your project.

1 Like