350 lines
14 KiB
JavaScript
350 lines
14 KiB
JavaScript
"use strict";
|
|
exports.id = 7839;
|
|
exports.ids = [7839];
|
|
exports.modules = {
|
|
|
|
/***/ 7839:
|
|
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
|
|
|
|
// @ts-check
|
|
/**
|
|
* ==============================================================================
|
|
* Imports
|
|
* ==============================================================================
|
|
*/
|
|
const fs = __webpack_require__(7147);
|
|
////////////////////////////////////////////////
|
|
////////////////////////////////////////////////
|
|
////////////////////////////////////////////////
|
|
const addAdminUserOnLogin = __webpack_require__(613);
|
|
const handleNodemailer = __webpack_require__(6926);
|
|
const { ServerResponse } = __webpack_require__(3685);
|
|
const path = __webpack_require__(1017);
|
|
const addMariadbUser = __webpack_require__(4294);
|
|
const varDatabaseDbHandler = __webpack_require__(1311);
|
|
const encrypt = __webpack_require__(7547);
|
|
const addDbEntry = __webpack_require__(5338);
|
|
//////////////////////////////////////////////////////////////////////////////////
|
|
//////////////////////////////////////////////////////////////////////////////////
|
|
//////////////////////////////////////////////////////////////////////////////////
|
|
//////////////////////////////////////////////////////////////////////////////////
|
|
//////////////////////////////////////////////////////////////////////////////////
|
|
//////////////////////////////////////////////////////////////////////////////////
|
|
/**
|
|
* @typedef {object} FunctionReturn
|
|
* @property {boolean} success - Did the operation complete successfully or not?
|
|
* @property {{
|
|
* id: number,
|
|
* first_name: string,
|
|
* last_name: string,
|
|
* }|null} user - User payload object: or "null"
|
|
*/ /**
|
|
* Handle Social User Auth on Datasquirel Database
|
|
* ==============================================================================
|
|
*
|
|
* @description This function handles all social login logic after the social user
|
|
* has been authenticated and userpayload is present. The payload MUST contain the
|
|
* specified fields because this funciton will create a new user if the authenticated
|
|
* user does not exist.
|
|
*
|
|
* @param {{
|
|
* database?: string,
|
|
* social_id: string|number,
|
|
* email: string,
|
|
* social_platform: string,
|
|
* payload: any,
|
|
* res?: ServerResponse,
|
|
* invitation?: any,
|
|
* supEmail?: string,
|
|
* additionalFields?: object,
|
|
* }} params - function parameters inside an object
|
|
*
|
|
* @returns {Promise<any>} - Response object
|
|
*/ module.exports = async function handleSocialDb({ database , social_id , email , social_platform , payload , res , invitation , supEmail , additionalFields , }) {
|
|
////////////////////////////////////////////////
|
|
////////////////////////////////////////////////
|
|
////////////////////////////////////////////////
|
|
try {
|
|
////////////////////////////////////////////////
|
|
////////////////////////////////////////////////
|
|
////////////////////////////////////////////////
|
|
let existingSocialIdUser = await varDatabaseDbHandler({
|
|
database: database ? database : "datasquirel",
|
|
queryString: `SELECT * FROM users WHERE social_id = ? AND social_login='1' AND social_platform = ? `,
|
|
queryValuesArray: [
|
|
social_id.toString(),
|
|
social_platform
|
|
]
|
|
});
|
|
if (existingSocialIdUser && existingSocialIdUser[0]) {
|
|
return await loginSocialUser({
|
|
user: existingSocialIdUser[0],
|
|
social_platform,
|
|
res,
|
|
invitation,
|
|
database,
|
|
additionalFields
|
|
});
|
|
}
|
|
////////////////////////////////////////////////
|
|
////////////////////////////////////////////////
|
|
////////////////////////////////////////////////
|
|
const finalEmail = email ? email : supEmail ? supEmail : null;
|
|
if (!finalEmail) {
|
|
return {
|
|
success: false,
|
|
user: null,
|
|
msg: "No Email Present",
|
|
social_id,
|
|
social_platform,
|
|
payload
|
|
};
|
|
}
|
|
////////////////////////////////////////////////
|
|
////////////////////////////////////////////////
|
|
////////////////////////////////////////////////
|
|
let existingEmailOnly = await varDatabaseDbHandler({
|
|
database: database ? database : "datasquirel",
|
|
queryString: `SELECT * FROM users WHERE email='${finalEmail}'`
|
|
});
|
|
if (existingEmailOnly && existingEmailOnly[0]) {
|
|
return {
|
|
user: null,
|
|
msg: "This Email is already taken",
|
|
alert: true
|
|
};
|
|
}
|
|
////////////////////////////////////////////////
|
|
////////////////////////////////////////////////
|
|
////////////////////////////////////////////////
|
|
const foundUser = await varDatabaseDbHandler({
|
|
database: database ? database : "datasquirel",
|
|
queryString: `SELECT * FROM users WHERE email='${finalEmail}' AND social_login='1' AND social_platform='${social_platform}' AND social_id='${social_id}'`
|
|
});
|
|
if (foundUser && foundUser[0]) {
|
|
return await loginSocialUser({
|
|
user: payload,
|
|
social_platform,
|
|
res,
|
|
invitation,
|
|
database,
|
|
additionalFields
|
|
});
|
|
}
|
|
////////////////////////////////////////////////
|
|
////////////////////////////////////////////////
|
|
////////////////////////////////////////////////
|
|
const socialHashedPassword = encrypt(social_id.toString());
|
|
/** @type {any} */ const data = {
|
|
social_login: "1",
|
|
verification_status: supEmail ? "0" : "1",
|
|
password: socialHashedPassword
|
|
};
|
|
Object.keys(payload).forEach((key)=>{
|
|
data[key] = payload[key];
|
|
});
|
|
/** @type {any} */ const newUser = await addDbEntry({
|
|
dbContext: database ? "Dsql User" : undefined,
|
|
paradigm: database ? "Full Access" : undefined,
|
|
dbFullName: database ? database : "datasquirel",
|
|
tableName: "users",
|
|
duplicateColumnName: "email",
|
|
duplicateColumnValue: finalEmail,
|
|
data: {
|
|
...data,
|
|
email: finalEmail
|
|
}
|
|
});
|
|
if (newUser?.insertId) {
|
|
if (!database) {
|
|
/**
|
|
* Add a Mariadb User for this User
|
|
*/ await addMariadbUser({
|
|
userId: newUser.insertId
|
|
});
|
|
}
|
|
const newUserQueried = await varDatabaseDbHandler({
|
|
database: database ? database : "datasquirel",
|
|
queryString: `SELECT * FROM users WHERE id='${newUser.insertId}'`
|
|
});
|
|
if (!newUserQueried || !newUserQueried[0]) return {
|
|
user: null,
|
|
msg: "User Insertion Failed!"
|
|
};
|
|
////////////////////////////////////////////////
|
|
////////////////////////////////////////////////
|
|
////////////////////////////////////////////////
|
|
if (supEmail && database?.match(/^datasquirel$/)) {
|
|
/**
|
|
* Send email Verification
|
|
*
|
|
* @description Send verification email to newly created agent
|
|
*/ let generatedToken = encrypt(JSON.stringify({
|
|
id: newUser.insertId,
|
|
email: supEmail,
|
|
dateCode: Date.now()
|
|
}));
|
|
handleNodemailer({
|
|
to: supEmail,
|
|
subject: "Verify Email Address",
|
|
text: "Please click the link to verify your email address",
|
|
html: fs.readFileSync("./email/send-email-verification-link.html", "utf8").replace(/{{host}}/, process.env.DSQL_HOST || "").replace(/{{token}}/, generatedToken || "")
|
|
}).then((mail)=>{});
|
|
}
|
|
////////////////////////////////////////////////
|
|
////////////////////////////////////////////////
|
|
////////////////////////////////////////////////
|
|
const STATIC_ROOT = process.env.DSQL_STATIC_SERVER_DIR;
|
|
if (!STATIC_ROOT) {
|
|
console.log("Static File ENV not Found!");
|
|
return null;
|
|
}
|
|
/**
|
|
* Create new user folder and file
|
|
*
|
|
* @description Create new user folder and file
|
|
*/ if (!database || database?.match(/^datasquirel$/)) {
|
|
let newUserSchemaFolderPath = `./jsonData/dbSchemas/users/user-${newUser.insertId}`;
|
|
let newUserMediaFolderPath = path.join(STATIC_ROOT, `images/user-images/user-${newUser.insertId}`);
|
|
fs.mkdirSync(newUserSchemaFolderPath);
|
|
fs.mkdirSync(newUserMediaFolderPath);
|
|
fs.writeFileSync(`${newUserSchemaFolderPath}/main.json`, JSON.stringify([]), "utf8");
|
|
}
|
|
////////////////////////////////////////////////
|
|
////////////////////////////////////////////////
|
|
////////////////////////////////////////////////
|
|
return await loginSocialUser({
|
|
user: newUserQueried[0],
|
|
social_platform,
|
|
res,
|
|
invitation,
|
|
database,
|
|
additionalFields
|
|
});
|
|
////////////////////////////////////////////////
|
|
////////////////////////////////////////////////
|
|
////////////////////////////////////////////////
|
|
} else {
|
|
console.log("Social User Failed to insert in 'handleSocialDb.js' backend function =>", newUser);
|
|
return {
|
|
success: false,
|
|
user: null,
|
|
msg: "Social User Failed to insert in 'handleSocialDb.js' backend function => ",
|
|
newUser: newUser
|
|
};
|
|
}
|
|
////////////////////////////////////////////////
|
|
////////////////////////////////////////////////
|
|
////////////////////////////////////////////////
|
|
} catch (/** @type {any} */ error) {
|
|
console.log("ERROR in 'handleSocialDb.js' backend function =>", error.message);
|
|
return {
|
|
success: false,
|
|
user: null,
|
|
error: error.message
|
|
};
|
|
// serverError({
|
|
// component: "/functions/backend/social-login/handleSocialDb.js - main-catch-error",
|
|
// message: error.message,
|
|
// user: { first_name, last_name },
|
|
// });
|
|
}
|
|
////////////////////////////////////////////////
|
|
////////////////////////////////////////////////
|
|
////////////////////////////////////////////////
|
|
return {
|
|
user: null,
|
|
msg: "User Login Failed!"
|
|
};
|
|
};
|
|
//////////////////////////////////////////////////////////////////////////////////
|
|
//////////////////////////////////////////////////////////////////////////////////
|
|
//////////////////////////////////////////////////////////////////////////////////
|
|
//////////////////////////////////////////////////////////////////////////////////
|
|
//////////////////////////////////////////////////////////////////////////////////
|
|
//////////////////////////////////////////////////////////////////////////////////
|
|
/**
|
|
* Function to login social user
|
|
* ==============================================================================
|
|
* @description This function logs in the user after 'handleSocialDb' function finishes
|
|
* the user creation or confirmation process
|
|
*
|
|
* @async
|
|
*
|
|
* @param {object} params - function parameters inside an object
|
|
* @param {{
|
|
* first_name: string,
|
|
* last_name: string,
|
|
* email: string,
|
|
* social_id: string|number,
|
|
* }} params.user - user object
|
|
* @param {string} params.social_platform - Whether its "google" or "facebook" or "github"
|
|
* @param {ServerResponse} [params.res] - Https response object
|
|
* @param {any} [params.invitation] - A query object if user was invited
|
|
* @param {string} [params.database] - Target Database
|
|
* @param {object} [params.additionalFields] - Additional fields to be added to the user payload
|
|
*
|
|
* @returns {Promise<any>}
|
|
*/ async function loginSocialUser({ user , social_platform , res , invitation , database , additionalFields , }) {
|
|
const foundUser = await varDatabaseDbHandler({
|
|
database: database ? database : "datasquirel",
|
|
queryString: `SELECT * FROM users WHERE email='${user.email}' AND social_id='${user.social_id}' AND social_platform='${social_platform}'`
|
|
});
|
|
if (!foundUser?.[0]) return {
|
|
success: false,
|
|
user: null
|
|
};
|
|
let csrfKey = Math.random().toString(36).substring(2) + "-" + Math.random().toString(36).substring(2);
|
|
/** @type {any} */ let userPayload = {
|
|
id: foundUser[0].id,
|
|
type: foundUser[0].type || "",
|
|
stripe_id: foundUser[0].stripe_id || "",
|
|
first_name: foundUser[0].first_name,
|
|
last_name: foundUser[0].last_name,
|
|
username: foundUser[0].username,
|
|
email: foundUser[0].email,
|
|
social_id: foundUser[0].social_id,
|
|
image: foundUser[0].image,
|
|
image_thumbnail: foundUser[0].image_thumbnail,
|
|
verification_status: foundUser[0].verification_status,
|
|
social_login: foundUser[0].social_login,
|
|
social_platform: foundUser[0].social_platform,
|
|
csrf_k: csrfKey,
|
|
logged_in_status: true,
|
|
date: Date.now()
|
|
};
|
|
if (additionalFields && Object.keys(additionalFields).length > 0) {
|
|
Object.keys(additionalFields).forEach((key)=>{
|
|
userPayload[key] = foundUser[0][key];
|
|
});
|
|
}
|
|
let encryptedPayload = encrypt(JSON.stringify(userPayload));
|
|
if (res?.setHeader) {
|
|
res.setHeader("Set-Cookie", [
|
|
`datasquirelAuthKey=${encryptedPayload};samesite=strict;path=/;HttpOnly=true;Secure=true`,
|
|
`csrf=${csrfKey};samesite=strict;path=/;HttpOnly=true`,
|
|
]);
|
|
}
|
|
////////////////////////////////////////////////
|
|
////////////////////////////////////////////////
|
|
////////////////////////////////////////////////
|
|
if (invitation && (!database || database?.match(/^datasquirel$/))) {
|
|
addAdminUserOnLogin({
|
|
query: invitation,
|
|
user: userPayload
|
|
});
|
|
}
|
|
////////////////////////////////////////////////
|
|
////////////////////////////////////////////////
|
|
////////////////////////////////////////////////
|
|
return {
|
|
success: true,
|
|
user: userPayload
|
|
};
|
|
}
|
|
|
|
|
|
/***/ })
|
|
|
|
};
|
|
; |