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