datasquirel/client/auth/google/getAccessToken.ts

84 lines
2.4 KiB
TypeScript
Raw Normal View History

2025-01-10 19:10:28 +00:00
interface GoogleGetAccessTokenFunctionParams {
clientId: string;
triggerPrompt?: boolean;
setLoading?: React.Dispatch<React.SetStateAction<boolean>>;
}
2024-12-08 08:58:57 +00:00
2025-01-10 19:10:28 +00:00
let interval: any;
2023-09-21 14:00:04 +00:00
/**
* Login with Google Function
* ===============================================================================
* @description This function uses google identity api to login a user with datasquirel
*/
2025-01-10 19:10:28 +00:00
export default async function getAccessToken(
params: GoogleGetAccessTokenFunctionParams
): Promise<string> {
2024-12-08 08:58:57 +00:00
params.setLoading?.(true);
2023-09-21 14:00:04 +00:00
2025-01-10 19:10:28 +00:00
const response = (await new Promise((resolve, reject) => {
2024-12-08 08:58:57 +00:00
interval = setInterval(() => {
// @ts-ignore
let google = window.google;
2023-09-21 14:00:04 +00:00
if (google) {
2024-12-08 08:58:57 +00:00
window.clearInterval(interval);
resolve(googleLogin({ ...params, google }));
}
}, 500);
2025-01-10 19:10:28 +00:00
})) as any;
2023-09-21 14:00:04 +00:00
2024-12-08 08:58:57 +00:00
params.setLoading?.(false);
2023-09-21 14:00:04 +00:00
2024-12-08 08:58:57 +00:00
return response;
2025-01-10 19:10:28 +00:00
}
2023-09-21 14:00:04 +00:00
2024-12-08 08:58:57 +00:00
/**
* # Google Login Function
*/
2025-01-10 19:10:28 +00:00
export function googleLogin({
google,
clientId,
setLoading,
triggerPrompt,
}: GoogleGetAccessTokenFunctionParams & { google: any }) {
2024-12-08 08:58:57 +00:00
setTimeout(() => {
setLoading?.(false);
}, 3000);
2023-09-21 14:00:04 +00:00
2024-12-08 08:58:57 +00:00
return new Promise((resolve, reject) => {
/**
* # Callback Function
* @param {import("../../../package-shared/types").GoogleAccessTokenObject} response
*/
2025-01-10 19:10:28 +00:00
function handleCredentialResponse(
response: import("../../../package-shared/types").GoogleAccessTokenObject
) {
2024-12-08 08:58:57 +00:00
resolve(response.access_token);
}
2023-09-21 14:00:04 +00:00
2024-12-08 08:58:57 +00:00
const googleAuth = google.accounts.oauth2.initTokenClient({
client_id: clientId,
scope: "email profile",
callback: handleCredentialResponse,
});
2023-09-21 14:00:04 +00:00
2024-12-08 08:58:57 +00:00
googleAuth.requestAccessToken();
2023-09-21 14:00:04 +00:00
2024-12-08 08:58:57 +00:00
if (triggerPrompt) {
google.accounts.id.prompt(triggerGooglePromptCallback);
}
2023-09-21 14:00:04 +00:00
2024-12-08 08:58:57 +00:00
/**
* Google prompt notification callback
* ========================================================
* @param {import("../../../package-shared/types").GoogleIdentityPromptNotification} notification
*/
2025-01-10 19:10:28 +00:00
function triggerGooglePromptCallback(
notification: import("../../../package-shared/types").GoogleIdentityPromptNotification
) {
2024-12-08 08:58:57 +00:00
console.log(notification);
}
});
}