Skip to content

feat: add Google One Tap modal #1117

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 8 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions docusaurus-common.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import path from 'node:path';
import { fileURLToPath } from 'node:url';

import type { PluginConfig, ThemeConfig } from '@docusaurus/types';
import { yes } from '@silverhand/essentials';
import { themes } from 'prism-react-renderer';
import rehypeKatex from 'rehype-katex';
import remarkMath from 'remark-math';
Expand Down Expand Up @@ -311,3 +312,23 @@ export const classicPresetConfig = {
},
},
};

// Google One Tap related configurations
export const googleOneTapScripts = [
{
src: 'https://accounts.google.com/gsi/client',
async: true,
defer: true,
},
];

export const createGoogleOneTapCustomFields = () => ({
logtoAdminConsoleUrl: process.env.LOGTO_ADMIN_CONSOLE_URL,
isDebuggingEnabled: yes(process.env.IS_DEBUGGING_ENABLED),
googleOneTapConfig: process.env.GOOGLE_ONE_TAP_CONFIG,
});

export const createCommonCustomFields = (siteSpecificFields: Record<string, unknown> = {}) => ({
...createGoogleOneTapCustomFields(),
...siteSpecificFields,
});
8 changes: 6 additions & 2 deletions docusaurus-tutorials.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,12 @@ import {
classicPresetConfig,
commonMarkdown,
commonStylesheets,
createCommonCustomFields,
createCommonThemeConfig,
currentLocale,
defaultLocale,
getCloudflareSubdomain,
googleOneTapScripts,
injectHeadTagsPlugin,
isCfPagesPreview,
localeConfigs,
Expand Down Expand Up @@ -41,17 +43,19 @@ const config: Config = {
organizationName: 'logto-io',
projectName: 'docs',

scripts: googleOneTapScripts,

i18n: {
defaultLocale,
locales: ['en', 'es', 'fr', 'ja'],
localeConfigs,
},

customFields: {
customFields: createCommonCustomFields({
mainSiteUrl,
// Remove this on purpose to avoid rendering search bar in the tutorials site
// inkeepApiKey: process.env.INKEEP_API_KEY,
},
}),

staticDirectories: ['static', 'static-localized/' + currentLocale],

Expand Down
12 changes: 10 additions & 2 deletions docusaurus.config.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,21 @@
// eslint-disable-next-line import/no-unassigned-import
import 'dotenv/config';

import type { Config } from '@docusaurus/types';
import { yes } from '@silverhand/essentials';

import {
addAliasPlugin,
cfPagesBranch,
classicPresetConfig,
commonMarkdown,
commonStylesheets,
createCommonCustomFields,
createCommonThemeConfig,
currentLocale,
defaultLocale,
getCloudflareSubdomain,
googleOneTapScripts,
injectHeadTagsPlugin,
isCfPagesPreview,
localeConfigs,
Expand All @@ -35,15 +39,19 @@ const config: Config = {
organizationName: 'logto-io',
projectName: 'docs',

scripts: googleOneTapScripts,

i18n: {
defaultLocale,
locales: ['de', 'en', 'es', 'fr', 'ja', 'ko', 'pt-BR', 'zh-CN', 'zh-TW'],
localeConfigs,
},

customFields: {
customFields: createCommonCustomFields({
inkeepApiKey: process.env.INKEEP_API_KEY,
},
logtoApiBaseUrl: process.env.LOGTO_API_BASE_URL,
isDevFeatureEnabled: yes(process.env.IS_DEV_FEATURE_ENABLED),
}),

staticDirectories: ['static', 'static-localized/' + currentLocale],

Expand Down
3 changes: 3 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -109,5 +109,8 @@
"core-js-pure",
"sharp"
]
},
"dependencies": {
"zod": "^3.25.13"
}
}
29 changes: 20 additions & 9 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

142 changes: 142 additions & 0 deletions src/theme/Layout/GoogleOneTapInitializer.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
import { appendPath, yes } from '@silverhand/essentials';
import { type ReactNode, useCallback, useEffect, useState } from 'react';

import { isGoogleOneTapTriggeredKey } from './constants';
import { useApiBaseUrl, useDebugLogger, useGoogleOneTapConfig } from './hooks';
import type { GoogleOneTapCredentialResponse } from './types';

export default function GoogleOneTapInitializer(): ReactNode {
const [isGoogleOneTapTriggered, setIsGoogleOneTapTriggered] = useState(false);
const { logtoAdminConsoleUrl, baseUrl } = useApiBaseUrl();
const { config } = useGoogleOneTapConfig();
const { debugLogger } = useDebugLogger();

useEffect(() => {
const isTriggered = yes(localStorage.getItem(isGoogleOneTapTriggeredKey));
setIsGoogleOneTapTriggered(isTriggered);
}, []);

// Function to manually build Logto sign-in URL
const buildSignInUrl = useCallback(
({ credential }: GoogleOneTapCredentialResponse) => {
try {
if (!logtoAdminConsoleUrl) {
throw new Error('Logto admin console URL is not set');
}

const signInUrl = new URL(
appendPath(new URL(logtoAdminConsoleUrl), 'external-google-one-tap')
);

signInUrl.searchParams.set('credential', credential);

return signInUrl.toString();
} catch (error) {
debugLogger.error('Failed to build sign-in URL:', error);
return null;
}
},
[logtoAdminConsoleUrl, debugLogger]
);

const handleCredentialResponse = useCallback(
async (response: GoogleOneTapCredentialResponse) => {
debugLogger.log('handleCredentialResponse received response:', response);

// // Build Logto sign-in URL with credential
// const signInUrl = buildSignInUrl(response);

// if (signInUrl) {
// localStorage.setItem(isGoogleOneTapTriggeredKey, '1');
// // Directly navigate to sign-in URL in current window
// // eslint-disable-next-line @silverhand/fp/no-mutation
// // window.location.href = signInUrl;
// debugLogger.log('Redirecting to Logto sign-in URL', signInUrl);
// }

const query = new URLSearchParams({
isExternal: 'true',
});
const fetchResponse = await fetch(
appendPath(new URL(baseUrl), `callback/muxb1fikb86yh9jose3q6?${query.toString()}`),
{
method: 'POST',
mode: 'cors',
credentials: 'omit',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
google_one_tap_credential: response.credential,
}),
redirect: 'manual',
}
);

if (fetchResponse.status === 200) {
localStorage.setItem(isGoogleOneTapTriggeredKey, '1');
// eslint-disable-next-line no-restricted-syntax
const json = (await fetchResponse.json()) as {
success: boolean;
redirectUrl: string;
};
console.log('json', JSON.stringify(json, null, 2));
const redirectUrl = new URL(json.redirectUrl);
// eslint-disable-next-line @silverhand/fp/no-mutation
redirectUrl.search = '';
const finalRedirectUrl = redirectUrl.toString();
console.log('finalRedirectUrl', finalRedirectUrl);

// Wait 2 seconds to allow viewing console logs
await new Promise((resolve) => {
setTimeout(resolve, 2000);
});

// eslint-disable-next-line @silverhand/fp/no-mutation
window.location.href = 'https://cloud.logto.dev/external-google-one-tap';
}
},
[debugLogger, baseUrl]
);

useEffect(() => {
if (
!isGoogleOneTapTriggered &&
logtoAdminConsoleUrl &&
config &&
config.oneTap?.isEnabled &&
window.google?.accounts.id
) {
debugLogger.log('Initializing Google One Tap');

try {
// Initialize Google One Tap
window.google.accounts.id.initialize({
client_id: config.clientId,

callback: handleCredentialResponse,
auto_select: config.oneTap.autoSelect,
cancel_on_tap_outside: config.oneTap.closeOnTapOutside,
itp_support: config.oneTap.itpSupport,
// Disable FedCM for prompt.
use_fedcm_for_prompt: false,
// Set context to use, to show "Use xxx" in Google One Tap prompt.
context: 'use',
});

// Show One Tap prompt
window.google.accounts.id.prompt();
} catch (error) {
console.error('Error initializing Google One Tap:', error);
}
}
}, [
config,
debugLogger,
logtoAdminConsoleUrl,
isGoogleOneTapTriggered,
handleCredentialResponse,
]);

return null;
}
4 changes: 4 additions & 0 deletions src/theme/Layout/constants.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
export const isGoogleOneTapTriggeredKey = '_logto_is_google_one_tap_triggered';

export const defaultApiBaseProdUrl = 'https://auth.logto.io';
export const defaultApiBaseDevUrl = 'https://auth.logto.dev';
Loading
Loading