89 lines
2.3 KiB
JavaScript
89 lines
2.3 KiB
JavaScript
// @ts-check
|
|
|
|
const { OAuth2Client } = require("google-auth-library");
|
|
const handleSocialDb = require("../../social-login/handleSocialDb");
|
|
|
|
/** @type {import("../../../../types").APIGoogleLoginFunction} */
|
|
module.exports = async function apiGoogleLogin({
|
|
clientId,
|
|
token,
|
|
database,
|
|
userId,
|
|
additionalFields,
|
|
res,
|
|
}) {
|
|
const client = new OAuth2Client(clientId);
|
|
|
|
const ticket = await client.verifyIdToken({
|
|
idToken: token,
|
|
audience: clientId,
|
|
});
|
|
|
|
if (!ticket?.getPayload()?.email_verified) {
|
|
return {
|
|
success: false,
|
|
user: null,
|
|
};
|
|
}
|
|
|
|
const payload = ticket.getPayload();
|
|
|
|
if (!payload) throw new Error("No Payload");
|
|
|
|
////////////////////////////////////////
|
|
////////////////////////////////////////
|
|
////////////////////////////////////////
|
|
|
|
if (!database || typeof database != "string" || database?.match(/ /)) {
|
|
return {
|
|
success: false,
|
|
user: undefined,
|
|
msg: "Please provide a database slug(database name in lowercase with no spaces)",
|
|
};
|
|
}
|
|
|
|
/**
|
|
* Create new user folder and file
|
|
*
|
|
* @description Create new user folder and file
|
|
*/
|
|
const targetDbName = `datasquirel_user_${userId}_${database}`;
|
|
|
|
const { given_name, family_name, email, sub, picture, email_verified } =
|
|
payload;
|
|
|
|
/** @type {Object<string, any>} */
|
|
const payloadObject = {
|
|
email: email,
|
|
first_name: given_name,
|
|
last_name: family_name,
|
|
social_id: sub,
|
|
social_platform: "google",
|
|
image: picture,
|
|
image_thumbnail: picture,
|
|
username: `google-user-${sub}`,
|
|
};
|
|
|
|
if (additionalFields && Object.keys(additionalFields).length > 0) {
|
|
Object.keys(additionalFields).forEach((key) => {
|
|
payloadObject[key] = additionalFields[key];
|
|
});
|
|
}
|
|
|
|
const loggedInGoogleUser = await handleSocialDb({
|
|
res,
|
|
database: targetDbName,
|
|
email: email || "",
|
|
payload: payloadObject,
|
|
social_platform: "google",
|
|
social_id: sub,
|
|
additionalFields,
|
|
});
|
|
|
|
////////////////////////////////////////
|
|
////////////////////////////////////////
|
|
////////////////////////////////////////
|
|
|
|
return { success: true, ...loggedInGoogleUser, dsqlUserId: userId };
|
|
};
|