91 lines
2.7 KiB
JavaScript
91 lines
2.7 KiB
JavaScript
// @ts-check
|
|
|
|
/**
|
|
* @typedef {object} GoogleGetAccessTokenFunctionParams
|
|
* @property {string} clientId - Google app client ID: {@link https://datasquirel.com/docs}
|
|
* @property {boolean} [triggerPrompt] - Whether to trigger Google signing popup or not: {@link https://datasquirel.com/docs}
|
|
* @property {React.Dispatch<React.SetStateAction<boolean>>} [setLoading] - React setState Function: sets whether the google login button is ready or not
|
|
*
|
|
*/
|
|
|
|
/** @type {any} */
|
|
let interval;
|
|
|
|
/**
|
|
* Login with Google Function
|
|
* ===============================================================================
|
|
* @description This function uses google identity api to login a user with datasquirel
|
|
*
|
|
* @async
|
|
*
|
|
* @requires script "https://accounts.google.com/gsi/client" async script added to head
|
|
*
|
|
* @param {GoogleGetAccessTokenFunctionParams} params - Single object passed
|
|
|
|
* @returns {Promise<boolean>} - Return
|
|
*/
|
|
module.exports = async function getAccessToken(params) {
|
|
/** @type {any} */
|
|
|
|
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);
|
|
});
|
|
|
|
params.setLoading?.(false);
|
|
|
|
return response;
|
|
};
|
|
|
|
/**
|
|
* # Google Login Function
|
|
*
|
|
* @param {GoogleGetAccessTokenFunctionParams & { google: any }} params
|
|
* @returns
|
|
*/
|
|
function googleLogin({ google, clientId, setLoading, triggerPrompt }) {
|
|
setTimeout(() => {
|
|
setLoading?.(false);
|
|
}, 3000);
|
|
|
|
return new Promise((resolve, reject) => {
|
|
/**
|
|
* # Callback Function
|
|
* @param {import("../../../package-shared/types").GoogleAccessTokenObject} response
|
|
*/
|
|
function handleCredentialResponse(response) {
|
|
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) {
|
|
console.log(notification);
|
|
}
|
|
});
|
|
}
|