Updates
This commit is contained in:
@@ -0,0 +1,93 @@
|
||||
// @ts-check
|
||||
|
||||
const _ = require("lodash");
|
||||
const serverError = require("../../backend/serverError");
|
||||
const runQuery = require("../../backend/db/runQuery");
|
||||
|
||||
/**
|
||||
* # Get Function FOr API
|
||||
*
|
||||
* @param {object} params
|
||||
* @param {string} params.query
|
||||
* @param {(string|number)[]} [params.queryValues]
|
||||
* @param {string} params.dbFullName
|
||||
* @param {string} [params.tableName]
|
||||
* @param {import("../../../types").DSQL_DatabaseSchemaType} [params.dbSchema]
|
||||
*
|
||||
* @returns {Promise<import("../../../types").GetReturn>}
|
||||
*/
|
||||
module.exports = async function apiGet({
|
||||
query,
|
||||
dbFullName,
|
||||
queryValues,
|
||||
tableName,
|
||||
dbSchema,
|
||||
}) {
|
||||
if (
|
||||
typeof query == "string" &&
|
||||
(query.match(/^alter|^delete|information_schema|databases|^create/i) ||
|
||||
!query.match(/^select/i))
|
||||
) {
|
||||
return { success: false, msg: "Wrong Input" };
|
||||
}
|
||||
|
||||
/**
|
||||
* Create new user folder and file
|
||||
*
|
||||
* @description Create new user folder and file
|
||||
*/
|
||||
let results;
|
||||
|
||||
try {
|
||||
let { result, error } = await runQuery({
|
||||
dbFullName: dbFullName,
|
||||
query: query,
|
||||
queryValuesArray: queryValues,
|
||||
readOnly: true,
|
||||
dbSchema,
|
||||
tableName,
|
||||
});
|
||||
|
||||
/** @type {import("../../../types").DSQL_TableSchemaType | undefined} */
|
||||
let tableSchema;
|
||||
|
||||
if (dbSchema) {
|
||||
const targetTable = dbSchema.tables.find(
|
||||
(table) => table.tableName === tableName
|
||||
);
|
||||
|
||||
if (targetTable) {
|
||||
const clonedTargetTable = _.cloneDeep(targetTable);
|
||||
delete clonedTargetTable.childTable;
|
||||
delete clonedTargetTable.childTableDbFullName;
|
||||
delete clonedTargetTable.childTableName;
|
||||
delete clonedTargetTable.childrenTables;
|
||||
delete clonedTargetTable.updateData;
|
||||
delete clonedTargetTable.tableNameOld;
|
||||
delete clonedTargetTable.indexes;
|
||||
tableSchema = clonedTargetTable;
|
||||
}
|
||||
}
|
||||
|
||||
if (error) throw error;
|
||||
if (result.error) throw new Error(result.error);
|
||||
|
||||
results = result;
|
||||
|
||||
/** @type {import("../../../types").GetReturn} */
|
||||
const resObject = {
|
||||
success: true,
|
||||
payload: results,
|
||||
schema: tableName && tableSchema ? tableSchema : undefined,
|
||||
};
|
||||
|
||||
return resObject;
|
||||
} catch (/** @type {any} */ error) {
|
||||
serverError({
|
||||
component: "/api/query/get/lines-85-94",
|
||||
message: error.message,
|
||||
});
|
||||
|
||||
return { success: false, payload: null, error: error.message };
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,100 @@
|
||||
// @ts-check
|
||||
|
||||
const _ = require("lodash");
|
||||
const serverError = require("../../backend/serverError");
|
||||
const runQuery = require("../../backend/db/runQuery");
|
||||
|
||||
/**
|
||||
* # Post Function For API
|
||||
*
|
||||
* @param {object} params
|
||||
* @param {any} params.query
|
||||
* @param {(string|number)[]} [params.queryValues]
|
||||
* @param {string} params.dbFullName
|
||||
* @param {string} [params.tableName]
|
||||
* @param {import("../../../types").DSQL_DatabaseSchemaType} [params.dbSchema]
|
||||
*
|
||||
* @returns {Promise<import("../../../types").PostReturn>}
|
||||
*/
|
||||
module.exports = async function apiPost({
|
||||
query,
|
||||
dbFullName,
|
||||
queryValues,
|
||||
tableName,
|
||||
dbSchema,
|
||||
}) {
|
||||
if (typeof query === "string" && query?.match(/^create |^alter |^drop /i)) {
|
||||
return { success: false, msg: "Wrong Input" };
|
||||
}
|
||||
|
||||
if (
|
||||
typeof query === "object" &&
|
||||
query?.action?.match(/^create |^alter |^drop /i)
|
||||
) {
|
||||
return { success: false, msg: "Wrong Input" };
|
||||
}
|
||||
|
||||
/** @type {any} */
|
||||
let results;
|
||||
|
||||
/**
|
||||
* Create new user folder and file
|
||||
*
|
||||
* @description Create new user folder and file
|
||||
*/
|
||||
try {
|
||||
let { result, error } = await runQuery({
|
||||
dbFullName: dbFullName,
|
||||
query: query,
|
||||
dbSchema: dbSchema,
|
||||
queryValuesArray: queryValues,
|
||||
tableName,
|
||||
});
|
||||
|
||||
results = result;
|
||||
|
||||
if (error) throw error;
|
||||
|
||||
/** @type {import("../../../types").DSQL_TableSchemaType | undefined} */
|
||||
let tableSchema;
|
||||
|
||||
if (dbSchema) {
|
||||
const targetTable = dbSchema.tables.find(
|
||||
(table) => table.tableName === tableName
|
||||
);
|
||||
|
||||
if (targetTable) {
|
||||
const clonedTargetTable = _.cloneDeep(targetTable);
|
||||
|
||||
delete clonedTargetTable.childTable;
|
||||
delete clonedTargetTable.childTableDbFullName;
|
||||
delete clonedTargetTable.childTableName;
|
||||
delete clonedTargetTable.childrenTables;
|
||||
delete clonedTargetTable.updateData;
|
||||
delete clonedTargetTable.tableNameOld;
|
||||
delete clonedTargetTable.indexes;
|
||||
tableSchema = clonedTargetTable;
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
payload: results,
|
||||
error: error,
|
||||
schema: tableName && tableSchema ? tableSchema : undefined,
|
||||
};
|
||||
|
||||
////////////////////////////////////////
|
||||
} catch (/** @type {any} */ error) {
|
||||
serverError({
|
||||
component: "/api/query/post/lines-132-142",
|
||||
message: error.message,
|
||||
});
|
||||
|
||||
return {
|
||||
success: false,
|
||||
payload: results,
|
||||
error: error.message,
|
||||
};
|
||||
}
|
||||
};
|
||||
+126
@@ -0,0 +1,126 @@
|
||||
// @ts-check
|
||||
|
||||
/**
|
||||
* ==============================================================================
|
||||
* Imports
|
||||
* ==============================================================================
|
||||
*/
|
||||
|
||||
const DB_HANDLER = require("../../../utils/backend/global-db/DB_HANDLER");
|
||||
const handleNodemailer = require("../../backend/handleNodemailer");
|
||||
const { hashPassword } = require("../../backend/passwordHash");
|
||||
const serverError = require("../../backend/serverError");
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
/**
|
||||
* ==============================================================================
|
||||
* Main Function
|
||||
* ==============================================================================
|
||||
* @param {object} params - parameters object
|
||||
* @param {any} params.body
|
||||
* @param {import("../../../types").UserType} params.usertype
|
||||
*/
|
||||
module.exports = async function facebookLogin({ usertype, body }) {
|
||||
try {
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
|
||||
const foundUser = await DB_HANDLER(
|
||||
`SELECT * FROM users WHERE email='${body.facebookUserEmail}' AND social_login='1'`
|
||||
);
|
||||
|
||||
if (foundUser && foundUser[0]) {
|
||||
return foundUser[0];
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
|
||||
let socialHashedPassword = hashPassword(body.facebookUserId);
|
||||
|
||||
let newUser = await DB_HANDLER(`INSERT INTO ${usertype} (
|
||||
first_name,
|
||||
last_name,
|
||||
social_platform,
|
||||
social_name,
|
||||
email,
|
||||
image,
|
||||
image_thumbnail,
|
||||
password,
|
||||
verification_status,
|
||||
social_login,
|
||||
social_id,
|
||||
terms_agreement,
|
||||
date_created,
|
||||
date_code
|
||||
) VALUES (
|
||||
'${body.facebookUserFirstName}',
|
||||
'${body.facebookUserLastName}',
|
||||
'facebook',
|
||||
'facebook_${
|
||||
body.facebookUserEmail
|
||||
? body.facebookUserEmail.replace(/@.*/, "")
|
||||
: body.facebookUserFirstName.toLowerCase()
|
||||
}',
|
||||
'${body.facebookUserEmail}',
|
||||
'${body.facebookUserImage}',
|
||||
'${body.facebookUserImage}',
|
||||
'${socialHashedPassword}',
|
||||
'1',
|
||||
'1',
|
||||
'${body.facebookUserId}',
|
||||
'1',
|
||||
'${Date()}',
|
||||
'${Date.now()}'
|
||||
)`);
|
||||
|
||||
const newFoundUser = await DB_HANDLER(
|
||||
`SELECT * FROM ${usertype} WHERE id='${newUser.insertId}'`
|
||||
);
|
||||
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
|
||||
/**
|
||||
* Send email notifications to admin
|
||||
*
|
||||
* @description Send verification email to newly created agent
|
||||
*/
|
||||
// handleNodemailer({
|
||||
// to: "",
|
||||
// subject: "New Registered Buyer",
|
||||
// text: "We have a new registered Buyer from facebook",
|
||||
// html: `
|
||||
// <h2>${newFoundUser[0].first_name} ${newFoundUser[0].last_name} just registered from facebook.</h2>
|
||||
// <p>We have a new buyer registration</p>
|
||||
// <div>Name: <b>${newFoundUser[0].first_name} ${newFoundUser[0].last_name}</b></div>
|
||||
// <div>Email: <b>${newFoundUser[0].email}</b></div>
|
||||
// <div>Site: <b>${process.env.DSQL_HOST}</b></div>
|
||||
// `,
|
||||
// }).catch((error) => {
|
||||
// console.log(
|
||||
// "error in mail notification for new Facebook user =>",
|
||||
// error.message
|
||||
// );
|
||||
// });
|
||||
} catch (/** @type {any} */ error) {
|
||||
serverError({
|
||||
component: "functions/backend/facebookLogin",
|
||||
message: error.message,
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
isFacebookAuthValid: false,
|
||||
newFoundUser: null,
|
||||
};
|
||||
};
|
||||
+160
@@ -0,0 +1,160 @@
|
||||
// @ts-check
|
||||
|
||||
const DB_HANDLER = require("../../../utils/backend/global-db/DB_HANDLER");
|
||||
const httpsRequest = require("../../backend/httpsRequest");
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
/**
|
||||
*
|
||||
* @typedef {object} GithubUserPayload
|
||||
* @property {string} login - Full name merged eg. "JohnDoe"
|
||||
* @property {number} id - github user id
|
||||
* @property {string} node_id - Some other id
|
||||
* @property {string} avatar_url - profile picture
|
||||
* @property {string} gravatar_id - some other id
|
||||
* @property {string} url - Github user URL
|
||||
* @property {string} html_url - User html URL - whatever that means
|
||||
* @property {string} followers_url - Followers URL
|
||||
* @property {string} following_url - Following URL
|
||||
* @property {string} gists_url - Gists URL
|
||||
* @property {string} starred_url - Starred URL
|
||||
* @property {string} subscriptions_url - Subscriptions URL
|
||||
* @property {string} organizations_url - Organizations URL
|
||||
* @property {string} repos_url - Repositories URL
|
||||
* @property {string} received_events_url - Received Events URL
|
||||
* @property {string} type - Common value => "User"
|
||||
* @property {boolean} site_admin - Is site admin or not? Boolean
|
||||
* @property {string} name - More like "username"
|
||||
* @property {string} company - User company
|
||||
* @property {string} blog - User blog URL
|
||||
* @property {string} location - User Location
|
||||
* @property {string} email - User Email
|
||||
* @property {string} hireable - Is user hireable
|
||||
* @property {string} bio - User bio
|
||||
* @property {string} twitter_username - User twitter username
|
||||
* @property {number} public_repos - Number of public repositories
|
||||
* @property {number} public_gists - Number of public gists
|
||||
* @property {number} followers - Number of followers
|
||||
* @property {number} following - Number of following
|
||||
* @property {string} created_at - Date created
|
||||
* @property {string} updated_at - Date updated
|
||||
*/
|
||||
|
||||
/**
|
||||
* Login/signup a github user
|
||||
* ==============================================================================
|
||||
* @async
|
||||
*
|
||||
* @param {Object} params - foundUser if any
|
||||
* @param {string} params.code - github auth token
|
||||
* @param {string} params.clientId - github client Id
|
||||
* @param {string} params.clientSecret - github client Secret
|
||||
*
|
||||
* @returns {Promise<GithubUserPayload|null|undefined>}
|
||||
*/
|
||||
module.exports = async function githubLogin({ code, clientId, clientSecret }) {
|
||||
/** @type {GithubUserPayload | undefined} */
|
||||
let gitHubUser;
|
||||
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
|
||||
try {
|
||||
/**
|
||||
* Create new user folder and file
|
||||
*
|
||||
* @description Create new user folder and file
|
||||
*/
|
||||
// const response = await fetch(`https://github.com/login/oauth/access_token?client_id=${process.env.DSQL_GITHUB_ID}`);
|
||||
const response = await httpsRequest({
|
||||
method: "POST",
|
||||
hostname: "github.com",
|
||||
path: `/login/oauth/access_token?client_id=${clientId}&client_secret=${clientSecret}&code=${code}`,
|
||||
headers: {
|
||||
Accept: "application/json",
|
||||
"User-Agent": "*",
|
||||
},
|
||||
scheme: "https",
|
||||
});
|
||||
|
||||
// `https://github.com/login/oauth/access_token?client_id=${process.env.DSQL_GITHUB_ID}&client_secret=${process.env.DSQL_GITHUB_SECRET}&code=${code}`,
|
||||
// body: JSON.stringify({
|
||||
// client_id: process.env.DSQL_GITHUB_ID,
|
||||
// client_secret: process.env.DSQL_GITHUB_SECRET,
|
||||
// code: code,
|
||||
// }),
|
||||
|
||||
const accessTokenObject = JSON.parse(response);
|
||||
|
||||
if (!accessTokenObject?.access_token) {
|
||||
return gitHubUser;
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
|
||||
const userDataResponse = await httpsRequest({
|
||||
method: "GET",
|
||||
hostname: "api.github.com",
|
||||
path: "/user",
|
||||
headers: {
|
||||
Authorization: `Bearer ${accessTokenObject.access_token}`,
|
||||
"User-Agent": "*",
|
||||
},
|
||||
scheme: "https",
|
||||
});
|
||||
|
||||
gitHubUser = JSON.parse(userDataResponse);
|
||||
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
|
||||
if (!gitHubUser?.email && gitHubUser) {
|
||||
const existingGithubUser = await DB_HANDLER(
|
||||
`SELECT email FROM users WHERE social_login='1' AND social_platform='github' AND social_id='${gitHubUser.id}'`
|
||||
);
|
||||
|
||||
if (existingGithubUser && existingGithubUser[0]) {
|
||||
gitHubUser.email = existingGithubUser[0].email;
|
||||
}
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
} catch (/** @type {any} */ error) {
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
|
||||
console.log(
|
||||
"ERROR in githubLogin.js backend function =>",
|
||||
error.message
|
||||
);
|
||||
|
||||
// serverError({
|
||||
// component: "/api/social-login/github-auth/catch-error",
|
||||
// message: error.message,
|
||||
// user: user,
|
||||
// });
|
||||
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
|
||||
return gitHubUser;
|
||||
};
|
||||
+178
@@ -0,0 +1,178 @@
|
||||
// @ts-check
|
||||
|
||||
/**
|
||||
* ==============================================================================
|
||||
* Imports
|
||||
* ==============================================================================
|
||||
*/
|
||||
const fs = require("fs");
|
||||
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
|
||||
const { OAuth2Client } = require("google-auth-library");
|
||||
|
||||
const { hashPassword } = require("../../backend/passwordHash");
|
||||
const serverError = require("../../backend/serverError");
|
||||
const { ServerResponse } = require("http");
|
||||
const DB_HANDLER = require("../../../utils/backend/global-db/DB_HANDLER");
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
/**
|
||||
* ==============================================================================
|
||||
* Main Function
|
||||
* ==============================================================================
|
||||
* @param {Object} params
|
||||
* @param {string} params.usertype
|
||||
* @param {any} params.foundUser
|
||||
* @param {boolean} params.isSocialValidated
|
||||
* @param {boolean} params.isUserValid
|
||||
* @param {any} params.reqBody
|
||||
* @param {any} params.serverRes
|
||||
* @param {any} params.loginFailureReason
|
||||
*/
|
||||
module.exports = async function googleLogin({
|
||||
usertype,
|
||||
foundUser,
|
||||
isSocialValidated,
|
||||
isUserValid,
|
||||
reqBody,
|
||||
serverRes,
|
||||
loginFailureReason,
|
||||
}) {
|
||||
const client = new OAuth2Client(
|
||||
process.env.NEXT_PUBLIC_DSQL_GOOGLE_CLIENT_ID
|
||||
);
|
||||
let isGoogleAuthValid = false;
|
||||
let newFoundUser = null;
|
||||
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
|
||||
try {
|
||||
const ticket = await client.verifyIdToken({
|
||||
idToken: reqBody.token,
|
||||
audience: process.env.NEXT_PUBLIC_DSQL_GOOGLE_CLIENT_ID, // Specify the CLIENT_ID of the app that accesses the backend
|
||||
// Or, if multiple clients access the backend:
|
||||
//[CLIENT_ID_1, CLIENT_ID_2, CLIENT_ID_3]
|
||||
});
|
||||
|
||||
const payload = ticket.getPayload();
|
||||
const userid = payload?.["sub"];
|
||||
|
||||
if (!payload)
|
||||
throw new Error("Google login failed. Credentials invalid");
|
||||
|
||||
isUserValid = Boolean(payload.email_verified);
|
||||
|
||||
if (!isUserValid || !payload || !payload.email_verified) return;
|
||||
|
||||
serverRes.isUserValid = payload.email_verified;
|
||||
isSocialValidated = payload.email_verified;
|
||||
isGoogleAuthValid = payload.email_verified;
|
||||
////// If request specified a G Suite domain:
|
||||
////// const domain = payload['hd'];
|
||||
|
||||
let socialHashedPassword = hashPassword(payload.at_hash || "");
|
||||
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
|
||||
let existinEmail = await DB_HANDLER(
|
||||
`SELECT * FROM ${usertype} WHERE email='${payload.email}' AND social_login!='1' AND social_platform!='google'`
|
||||
);
|
||||
|
||||
if (existinEmail && existinEmail[0]) {
|
||||
loginFailureReason = "Email Exists Already";
|
||||
isGoogleAuthValid = false;
|
||||
return {
|
||||
isGoogleAuthValid: isGoogleAuthValid,
|
||||
newFoundUser: newFoundUser,
|
||||
loginFailureReason: loginFailureReason,
|
||||
};
|
||||
}
|
||||
|
||||
////////////////////////////////////////
|
||||
|
||||
foundUser = await DB_HANDLER(
|
||||
`SELECT * FROM ${usertype} WHERE email='${payload.email}' AND social_login='1' AND social_platform='google'`
|
||||
);
|
||||
|
||||
if (foundUser && foundUser[0]) {
|
||||
newFoundUser = foundUser;
|
||||
return {
|
||||
isGoogleAuthValid: isGoogleAuthValid,
|
||||
newFoundUser: newFoundUser,
|
||||
};
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
|
||||
let newUser = await DB_HANDLER(`INSERT INTO ${usertype} (
|
||||
first_name,
|
||||
last_name,
|
||||
social_platform,
|
||||
social_name,
|
||||
social_id,
|
||||
email,
|
||||
image,
|
||||
image_thumbnail,
|
||||
password,
|
||||
verification_status,
|
||||
social_login,
|
||||
terms_agreement,
|
||||
date_created,
|
||||
date_code
|
||||
) VALUES (
|
||||
'${payload.given_name}',
|
||||
'${payload.family_name}',
|
||||
'google',
|
||||
'google_${payload.email?.replace(/@.*/, "")}',
|
||||
'${payload.sub}',
|
||||
'${payload.email}',
|
||||
'${payload.picture}',
|
||||
'${payload.picture}',
|
||||
'${socialHashedPassword}',
|
||||
'1',
|
||||
'1',
|
||||
'1',
|
||||
'${Date()}',
|
||||
'${Date.now()}'
|
||||
)`);
|
||||
|
||||
newFoundUser = await DB_HANDLER(
|
||||
`SELECT * FROM ${usertype} WHERE id='${newUser.insertId}'`
|
||||
);
|
||||
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
} catch (/** @type {any} */ error) {
|
||||
serverError({
|
||||
component: "googleLogin",
|
||||
message: error.message,
|
||||
});
|
||||
|
||||
loginFailureReason = error;
|
||||
|
||||
isUserValid = false;
|
||||
isSocialValidated = false;
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
|
||||
return { isGoogleAuthValid: isGoogleAuthValid, newFoundUser: newFoundUser };
|
||||
};
|
||||
+412
@@ -0,0 +1,412 @@
|
||||
// @ts-check
|
||||
|
||||
/**
|
||||
* ==============================================================================
|
||||
* Imports
|
||||
* ==============================================================================
|
||||
*/
|
||||
const fs = require("fs");
|
||||
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
|
||||
const addAdminUserOnLogin = require("../../backend/addAdminUserOnLogin");
|
||||
const handleNodemailer = require("../../backend/handleNodemailer");
|
||||
const { ServerResponse } = require("http");
|
||||
const path = require("path");
|
||||
const addMariadbUser = require("../../backend/addMariadbUser");
|
||||
const varDatabaseDbHandler = require("../../backend/varDatabaseDbHandler");
|
||||
const encrypt = require("../../dsql/encrypt");
|
||||
const addDbEntry = require("../../backend/db/addDbEntry");
|
||||
const getAuthCookieNames = require("../../backend/cookies/get-auth-cookie-names");
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
/**
|
||||
* @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"
|
||||
*/
|
||||
|
||||
/**
|
||||
* @type {import("../../../types").HandleSocialDbFunction}
|
||||
*/
|
||||
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 {
|
||||
success: false,
|
||||
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({
|
||||
data: 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 {
|
||||
success: false,
|
||||
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({
|
||||
data: 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 = `${process.env.DSQL_USER_DB_SCHEMA_PATH}/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,
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
/**
|
||||
* 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({ data: JSON.stringify(userPayload) });
|
||||
|
||||
const { keyCookieName, csrfCookieName } = getAuthCookieNames();
|
||||
|
||||
if (res?.setHeader) {
|
||||
res.setHeader("Set-Cookie", [
|
||||
`${keyCookieName}=${encryptedPayload};samesite=strict;path=/;HttpOnly=true;Secure=true`,
|
||||
`${csrfCookieName}=${csrfKey};samesite=strict;path=/;HttpOnly=true`,
|
||||
]);
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
|
||||
if (invitation && (!database || database?.match(/^datasquirel$/))) {
|
||||
addAdminUserOnLogin({
|
||||
query: invitation,
|
||||
user: userPayload,
|
||||
});
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
|
||||
return {
|
||||
success: true,
|
||||
user: userPayload,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
// @ts-check
|
||||
|
||||
const addUsersTableToDb = require("../../backend/addUsersTableToDb");
|
||||
const addDbEntry = require("../../backend/db/addDbEntry");
|
||||
const varDatabaseDbHandler = require("../../backend/varDatabaseDbHandler");
|
||||
const hashPassword = require("../../dsql/hashPassword");
|
||||
|
||||
/** @type {import("../../../types").APICreateUserFunction} */
|
||||
module.exports = async function apiCreateUser({
|
||||
encryptionKey,
|
||||
payload,
|
||||
database,
|
||||
userId,
|
||||
}) {
|
||||
const dbFullName = database;
|
||||
|
||||
const hashedPassword = hashPassword({
|
||||
encryptionKey: encryptionKey,
|
||||
password: String(payload.password),
|
||||
});
|
||||
|
||||
payload.password = hashedPassword;
|
||||
|
||||
let fields = await varDatabaseDbHandler({
|
||||
queryString: `SHOW COLUMNS FROM users`,
|
||||
database: dbFullName,
|
||||
});
|
||||
|
||||
if (!fields) {
|
||||
const newTable = await addUsersTableToDb({
|
||||
userId: Number(userId),
|
||||
database: database,
|
||||
});
|
||||
|
||||
fields = await varDatabaseDbHandler({
|
||||
queryString: `SHOW COLUMNS FROM users`,
|
||||
database: dbFullName,
|
||||
});
|
||||
}
|
||||
|
||||
if (!fields) {
|
||||
return {
|
||||
success: false,
|
||||
msg: "Could not create users table",
|
||||
};
|
||||
}
|
||||
|
||||
const fieldsTitles = fields.map(
|
||||
(/** @type {any} */ fieldObject) => fieldObject.Field
|
||||
);
|
||||
|
||||
let invalidField = null;
|
||||
|
||||
for (let i = 0; i < Object.keys(payload).length; i++) {
|
||||
const key = Object.keys(payload)[i];
|
||||
if (!fieldsTitles.includes(key)) {
|
||||
invalidField = key;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (invalidField) {
|
||||
return {
|
||||
success: false,
|
||||
msg: `${invalidField} is not a valid field!`,
|
||||
};
|
||||
}
|
||||
|
||||
const existingUser = await varDatabaseDbHandler({
|
||||
queryString: `SELECT * FROM users WHERE email = ?${
|
||||
payload.username ? " OR username = ?" : ""
|
||||
}`,
|
||||
queryValuesArray: payload.username
|
||||
? [payload.email, payload.username]
|
||||
: [payload.email],
|
||||
database: dbFullName,
|
||||
});
|
||||
|
||||
if (existingUser?.[0]) {
|
||||
return {
|
||||
success: false,
|
||||
msg: "User Already Exists",
|
||||
payload: null,
|
||||
};
|
||||
}
|
||||
|
||||
const addUser = await addDbEntry({
|
||||
dbContext: "Dsql User",
|
||||
paradigm: "Full Access",
|
||||
dbFullName: dbFullName,
|
||||
tableName: "users",
|
||||
data: {
|
||||
...payload,
|
||||
image: "/images/user-preset.png",
|
||||
image_thumbnail: "/images/user-preset-thumbnail.png",
|
||||
},
|
||||
});
|
||||
|
||||
if (addUser?.insertId) {
|
||||
const newlyAddedUser = await varDatabaseDbHandler({
|
||||
queryString: `SELECT id,first_name,last_name,email,username,phone,image,image_thumbnail,city,state,country,zip_code,address,verification_status,more_user_data FROM users WHERE id='${addUser.insertId}'`,
|
||||
database: dbFullName,
|
||||
});
|
||||
|
||||
return {
|
||||
success: true,
|
||||
payload: newlyAddedUser[0],
|
||||
};
|
||||
} else {
|
||||
return {
|
||||
success: false,
|
||||
msg: "Could not create user",
|
||||
sqlResult: addUser,
|
||||
payload: null,
|
||||
};
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,26 @@
|
||||
// @ts-check
|
||||
|
||||
const varDatabaseDbHandler = require("../../backend/varDatabaseDbHandler");
|
||||
|
||||
/** @type {import("../../../types").APIGetUserFunction} */
|
||||
module.exports = async function apiGetUser({ fields, dbFullName, userId }) {
|
||||
const query = `SELECT ${fields.join(",")} FROM users WHERE id=?`;
|
||||
|
||||
let foundUser = await varDatabaseDbHandler({
|
||||
queryString: query,
|
||||
queryValuesArray: [userId],
|
||||
database: dbFullName.replace(/[^a-z0-9_]/g, ""),
|
||||
});
|
||||
|
||||
if (!foundUser || !foundUser[0]) {
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
payload: foundUser[0],
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,159 @@
|
||||
// @ts-check
|
||||
|
||||
const varDatabaseDbHandler = require("../../backend/varDatabaseDbHandler");
|
||||
const hashPassword = require("../../dsql/hashPassword");
|
||||
|
||||
/** @type {import("../../../types").APILoginFunction} */
|
||||
module.exports = async function apiLoginUser({
|
||||
encryptionKey,
|
||||
email,
|
||||
username,
|
||||
password,
|
||||
database,
|
||||
additionalFields,
|
||||
email_login,
|
||||
email_login_code,
|
||||
email_login_field,
|
||||
token,
|
||||
skipPassword,
|
||||
social,
|
||||
}) {
|
||||
const dbFullName = database;
|
||||
|
||||
/**
|
||||
* Check input validity
|
||||
*
|
||||
* @description Check input validity
|
||||
*/
|
||||
if (
|
||||
email?.match(/ /) ||
|
||||
(username && username?.match(/ /)) ||
|
||||
(password && password?.match(/ /))
|
||||
) {
|
||||
return {
|
||||
success: false,
|
||||
msg: "Invalid Email/Password format",
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Password hash
|
||||
*
|
||||
* @description Password hash
|
||||
*/
|
||||
let hashedPassword = password
|
||||
? hashPassword({
|
||||
encryptionKey: encryptionKey,
|
||||
password: password,
|
||||
})
|
||||
: null;
|
||||
|
||||
let isSocialValidated = false;
|
||||
let loginFailureReason = null;
|
||||
|
||||
let foundUser = await varDatabaseDbHandler({
|
||||
queryString: `SELECT * FROM users WHERE email = ? OR username = ?`,
|
||||
queryValuesArray: [email, username],
|
||||
database: dbFullName.replace(/[^a-z0-9_]/g, ""),
|
||||
});
|
||||
|
||||
if ((!foundUser || !foundUser[0]) && !social)
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: "No user found",
|
||||
};
|
||||
|
||||
let isPasswordCorrect = false;
|
||||
|
||||
if (foundUser?.[0] && !email_login && skipPassword) {
|
||||
isPasswordCorrect = true;
|
||||
} else if (foundUser?.[0] && !email_login) {
|
||||
isPasswordCorrect = hashedPassword === foundUser[0].password;
|
||||
} else if (
|
||||
foundUser &&
|
||||
foundUser[0] &&
|
||||
email_login &&
|
||||
email_login_code &&
|
||||
email_login_field
|
||||
) {
|
||||
/** @type {string} */
|
||||
const tempCode = foundUser[0][email_login_field];
|
||||
|
||||
if (!tempCode) throw new Error("No code Found!");
|
||||
|
||||
const tempCodeArray = tempCode.split("-");
|
||||
const [code, codeDate] = tempCodeArray;
|
||||
const millisecond15mins = 1000 * 60 * 15;
|
||||
|
||||
if (Date.now() - Number(codeDate) > millisecond15mins) {
|
||||
throw new Error("Code Expired");
|
||||
}
|
||||
isPasswordCorrect = code === email_login_code;
|
||||
}
|
||||
|
||||
let socialUserValid = false;
|
||||
|
||||
if (!isPasswordCorrect && !socialUserValid) {
|
||||
return {
|
||||
success: false,
|
||||
msg: "Wrong password, no social login validity",
|
||||
payload: null,
|
||||
};
|
||||
}
|
||||
|
||||
if (isPasswordCorrect && email_login) {
|
||||
const resetTempCode = await varDatabaseDbHandler({
|
||||
queryString: `UPDATE users SET ${email_login_field} = ? WHERE email = ? OR username = ?`,
|
||||
queryValuesArray: ["", email, username],
|
||||
database: dbFullName.replace(/[^a-z0-9_]/g, ""),
|
||||
});
|
||||
}
|
||||
|
||||
let csrfKey =
|
||||
Math.random().toString(36).substring(2) +
|
||||
"-" +
|
||||
Math.random().toString(36).substring(2);
|
||||
|
||||
/** @type {import("../../../types").DATASQUIREL_LoggedInUser} */
|
||||
let userPayload = {
|
||||
id: foundUser[0].id,
|
||||
first_name: foundUser[0].first_name,
|
||||
last_name: foundUser[0].last_name,
|
||||
username: foundUser[0].username,
|
||||
email: foundUser[0].email,
|
||||
phone: foundUser[0].phone,
|
||||
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,
|
||||
more_data: foundUser[0].more_user_data,
|
||||
logged_in_status: true,
|
||||
date: Date.now(),
|
||||
};
|
||||
|
||||
const resposeObject = {
|
||||
success: true,
|
||||
msg: "Login Successful",
|
||||
payload:
|
||||
/** @type {import("../../../types").DATASQUIREL_LoggedInUser} */ (
|
||||
userPayload
|
||||
),
|
||||
userId: foundUser[0].id,
|
||||
};
|
||||
|
||||
if (
|
||||
additionalFields &&
|
||||
Array.isArray(additionalFields) &&
|
||||
additionalFields.length > 0
|
||||
) {
|
||||
additionalFields.forEach((key) => {
|
||||
userPayload[key] = foundUser[0][key];
|
||||
});
|
||||
}
|
||||
|
||||
return resposeObject;
|
||||
};
|
||||
@@ -0,0 +1,92 @@
|
||||
// @ts-check
|
||||
|
||||
const varDatabaseDbHandler = require("../../backend/varDatabaseDbHandler");
|
||||
const nodemailer = require("nodemailer");
|
||||
|
||||
/**
|
||||
* # Re-authenticate API user
|
||||
* @param {object} param
|
||||
* @param {Object<string, any>} param.existingUser
|
||||
* @param {string} param.database
|
||||
* @param {string | number} [param.userId]
|
||||
* @param {string[]} [param.additionalFields]
|
||||
*
|
||||
* @returns {Promise<import("../../../types").ApiReauthUserReturn>}
|
||||
*/
|
||||
module.exports = async function apiReauthUser({
|
||||
existingUser,
|
||||
database,
|
||||
userId,
|
||||
additionalFields,
|
||||
}) {
|
||||
let foundUser =
|
||||
existingUser?.id && existingUser.id.toString().match(/./)
|
||||
? await varDatabaseDbHandler({
|
||||
queryString: `SELECT * FROM users WHERE id=?`,
|
||||
queryValuesArray: [existingUser.id.toString()],
|
||||
database,
|
||||
})
|
||||
: null;
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
if (!foundUser || !foundUser[0])
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: "No user found",
|
||||
};
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
let csrfKey =
|
||||
Math.random().toString(36).substring(2) +
|
||||
"-" +
|
||||
Math.random().toString(36).substring(2);
|
||||
|
||||
/** @type {Object<string, string | number | boolean>} */
|
||||
let userPayload = {
|
||||
id: foundUser[0].id,
|
||||
first_name: foundUser[0].first_name,
|
||||
last_name: foundUser[0].last_name,
|
||||
username: foundUser[0].username,
|
||||
email: foundUser[0].email,
|
||||
phone: foundUser[0].phone,
|
||||
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,
|
||||
more_data: foundUser[0].more_user_data,
|
||||
logged_in_status: true,
|
||||
date: Date.now(),
|
||||
};
|
||||
|
||||
if (
|
||||
additionalFields &&
|
||||
Array.isArray(additionalFields) &&
|
||||
additionalFields.length > 0
|
||||
) {
|
||||
additionalFields.forEach((key) => {
|
||||
userPayload[key] = foundUser[0][key];
|
||||
});
|
||||
}
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
/** ********************* Send Response */
|
||||
return {
|
||||
success: true,
|
||||
msg: "Login Successful",
|
||||
payload: userPayload,
|
||||
userId,
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,116 @@
|
||||
// @ts-check
|
||||
|
||||
const varDatabaseDbHandler = require("../../backend/varDatabaseDbHandler");
|
||||
const nodemailer = require("nodemailer");
|
||||
|
||||
/**
|
||||
* # Send Email Login Code
|
||||
*
|
||||
* @param {object} param
|
||||
* @param {string} param.email
|
||||
* @param {string} param.database
|
||||
* @param {string} [param.email_login_field]
|
||||
* @param {string} [param.mail_domain]
|
||||
* @param {number} [param.mail_port]
|
||||
* @param {string} [param.sender]
|
||||
* @param {string} [param.mail_username]
|
||||
* @param {string} [param.mail_password]
|
||||
* @param {string} param.html
|
||||
*
|
||||
* @returns {Promise<{success: boolean, msg?: string}>}
|
||||
*/
|
||||
module.exports = async function apiSendEmailCode({
|
||||
email,
|
||||
database,
|
||||
email_login_field,
|
||||
mail_domain,
|
||||
mail_port,
|
||||
sender,
|
||||
mail_username,
|
||||
mail_password,
|
||||
html,
|
||||
}) {
|
||||
if (email?.match(/ /)) {
|
||||
return {
|
||||
success: false,
|
||||
msg: "Invalid Email/Password format",
|
||||
};
|
||||
}
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
let foundUser = await varDatabaseDbHandler({
|
||||
queryString: `SELECT * FROM users WHERE email = ?`,
|
||||
queryValuesArray: [email],
|
||||
database,
|
||||
});
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
if (!foundUser || !foundUser[0]) {
|
||||
return {
|
||||
success: false,
|
||||
msg: "No user found",
|
||||
};
|
||||
}
|
||||
|
||||
function generateCode() {
|
||||
const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
|
||||
let code = "";
|
||||
for (let i = 0; i < 8; i++) {
|
||||
code += chars[Math.floor(Math.random() * chars.length)];
|
||||
}
|
||||
return code;
|
||||
}
|
||||
|
||||
if (foundUser && foundUser[0] && email_login_field) {
|
||||
const tempCode = generateCode();
|
||||
|
||||
let transporter = nodemailer.createTransport({
|
||||
host: mail_domain || process.env.DSQL_MAIL_HOST,
|
||||
port: mail_port || 465,
|
||||
secure: true,
|
||||
auth: {
|
||||
user: mail_username || process.env.DSQL_MAIL_EMAIL,
|
||||
pass: mail_password || process.env.DSQL_MAIL_PASSWORD,
|
||||
},
|
||||
});
|
||||
|
||||
let mailObject = {};
|
||||
|
||||
mailObject["from"] = `"Datasquirel SSO" <${
|
||||
sender || "support@datasquirel.com"
|
||||
}>`;
|
||||
mailObject["sender"] = sender || "support@datasquirel.com";
|
||||
mailObject["to"] = email;
|
||||
mailObject["subject"] = "One Time Login Code";
|
||||
mailObject["html"] = html.replace(/{{code}}/, tempCode);
|
||||
|
||||
const info = await transporter.sendMail(mailObject);
|
||||
|
||||
if (!info?.accepted) throw new Error("Mail not Sent!");
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
let setTempCode = await varDatabaseDbHandler({
|
||||
queryString: `UPDATE users SET ${email_login_field} = ? WHERE email = ?`,
|
||||
queryValuesArray: [tempCode + `-${Date.now()}`, email],
|
||||
database: database,
|
||||
});
|
||||
}
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
return {
|
||||
success: true,
|
||||
msg: "Success",
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,43 @@
|
||||
// @ts-check
|
||||
|
||||
const updateDbEntry = require("../../backend/db/updateDbEntry");
|
||||
|
||||
/**
|
||||
* # Update API User Function
|
||||
*
|
||||
* @param {object} params
|
||||
* @param {{ id: string | number } & Object<string, (string | number | null | undefined)>} params.payload
|
||||
* @param {string} params.dbFullName
|
||||
*
|
||||
* @returns {Promise<{ success: boolean, payload: any }>}
|
||||
*/
|
||||
module.exports = async function apiUpdateUser({ payload, dbFullName }) {
|
||||
const data = (() => {
|
||||
const reqBodyKeys = Object.keys(payload);
|
||||
|
||||
/** @type {any} */
|
||||
const finalData = {};
|
||||
|
||||
reqBodyKeys.forEach((key) => {
|
||||
if (key?.match(/^date_|^id$/)) return;
|
||||
finalData[key] = payload[key];
|
||||
});
|
||||
|
||||
return finalData;
|
||||
})();
|
||||
|
||||
const updateUser = await updateDbEntry({
|
||||
dbContext: "Dsql User",
|
||||
paradigm: "Full Access",
|
||||
dbFullName,
|
||||
tableName: "users",
|
||||
identifierColumnName: "id",
|
||||
identifierValue: payload.id,
|
||||
data: data,
|
||||
});
|
||||
|
||||
return {
|
||||
success: true,
|
||||
payload: updateUser,
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,110 @@
|
||||
// @ts-check
|
||||
|
||||
const handleSocialDb = require("../../social-login/handleSocialDb");
|
||||
const githubLogin = require("../../social-login/githubLogin");
|
||||
const camelJoinedtoCamelSpace = require("../../../../utils/camelJoinedtoCamelSpace");
|
||||
|
||||
/**
|
||||
* # Login with Github
|
||||
* @param {object} param
|
||||
* @param {string} [param.code]
|
||||
* @param {string} [param.clientId]
|
||||
* @param {string} [param.clientSecret]
|
||||
* @param {string} [param.database]
|
||||
* @param {Object<string, any>} [param.additionalFields]
|
||||
* @param {any} [param.res]
|
||||
* @param {string} [param.email]
|
||||
* @param {string | number} [param.userId]
|
||||
*
|
||||
* @returns {Promise<import("../../../../types").APIGoogleLoginFunctionReturn>}
|
||||
*/
|
||||
module.exports = async function apiGithubLogin({
|
||||
code,
|
||||
clientId,
|
||||
clientSecret,
|
||||
database,
|
||||
additionalFields,
|
||||
res,
|
||||
email,
|
||||
userId,
|
||||
}) {
|
||||
if (!code || !clientId || !clientSecret || !database) {
|
||||
return {
|
||||
success: false,
|
||||
msg: "Missing query params",
|
||||
};
|
||||
}
|
||||
|
||||
if (
|
||||
typeof code !== "string" ||
|
||||
typeof clientId !== "string" ||
|
||||
typeof clientSecret !== "string" ||
|
||||
typeof database !== "string"
|
||||
) {
|
||||
return {
|
||||
success: false,
|
||||
msg: "Wrong Parameters",
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Create new user folder and file
|
||||
*
|
||||
* @description Create new user folder and file
|
||||
*/
|
||||
const gitHubUser = await githubLogin({
|
||||
code: code,
|
||||
clientId: clientId,
|
||||
clientSecret: clientSecret,
|
||||
});
|
||||
|
||||
if (!gitHubUser) {
|
||||
return {
|
||||
success: false,
|
||||
msg: "No github user returned",
|
||||
};
|
||||
}
|
||||
|
||||
const socialId = gitHubUser.name || gitHubUser.id || gitHubUser.login;
|
||||
const targetName = gitHubUser.name || gitHubUser.login;
|
||||
const nameArray = targetName?.match(/ /)
|
||||
? targetName?.split(" ")
|
||||
: targetName?.match(/\-/)
|
||||
? targetName?.split("-")
|
||||
: [targetName];
|
||||
|
||||
const payload = {
|
||||
email: gitHubUser.email,
|
||||
first_name: camelJoinedtoCamelSpace(nameArray[0]),
|
||||
last_name: camelJoinedtoCamelSpace(nameArray[1]),
|
||||
social_id: socialId,
|
||||
social_platform: "github",
|
||||
image: gitHubUser.avatar_url,
|
||||
image_thumbnail: gitHubUser.avatar_url,
|
||||
username: "github-user-" + socialId,
|
||||
};
|
||||
|
||||
if (additionalFields && Object.keys(additionalFields).length > 0) {
|
||||
Object.keys(additionalFields).forEach((key) => {
|
||||
// @ts-ignore
|
||||
payload[key] = additionalFields[key];
|
||||
});
|
||||
}
|
||||
|
||||
const loggedInGithubUser = await handleSocialDb({
|
||||
database,
|
||||
email: gitHubUser.email,
|
||||
payload: payload,
|
||||
social_platform: "github",
|
||||
res: res,
|
||||
social_id: socialId,
|
||||
supEmail: email,
|
||||
additionalFields,
|
||||
});
|
||||
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
|
||||
return { success: true, ...loggedInGithubUser, dsqlUserId: userId };
|
||||
};
|
||||
@@ -0,0 +1,88 @@
|
||||
// @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 };
|
||||
};
|
||||
+191
@@ -0,0 +1,191 @@
|
||||
// @ts-check
|
||||
|
||||
const serverError = require("./serverError");
|
||||
const DB_HANDLER = require("../../utils/backend/global-db/DB_HANDLER");
|
||||
const addDbEntry = require("./db/addDbEntry");
|
||||
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
|
||||
/**
|
||||
* Add Admin User on Login
|
||||
* ==============================================================================
|
||||
*
|
||||
* @description this function handles admin users that have been invited by another
|
||||
* admin user. This fires when the invited user has been logged in or a new account
|
||||
* has been created for the invited user
|
||||
*
|
||||
* @param {object} params - parameters object
|
||||
*
|
||||
* @param {object} params.query - query object
|
||||
* @param {number} params.query.invite - Invitation user id
|
||||
* @param {string} params.query.database_access - String containing authorized databases
|
||||
* @param {string} params.query.priviledge - String containing databases priviledges
|
||||
* @param {string} params.query.email - Inviting user email address
|
||||
*
|
||||
* @param {import("../../types").UserType} params.user - invited user object
|
||||
*
|
||||
* @returns {Promise<any>} new user auth object payload
|
||||
*/
|
||||
module.exports = async function addAdminUserOnLogin({ query, user }) {
|
||||
try {
|
||||
/**
|
||||
* Fetch user
|
||||
*
|
||||
* @description Fetch user from db
|
||||
*/ // @ts-ignore
|
||||
const { invite, database_access, priviledge, email } = query;
|
||||
|
||||
const lastInviteTimeArray = await DB_HANDLER(
|
||||
`SELECT date_created_code FROM invitations WHERE inviting_user_id=? AND invited_user_email=?`,
|
||||
[invite, email]
|
||||
);
|
||||
|
||||
// if (lastInviteTimeArray && lastInviteTimeArray[0]?.date_created_code) {
|
||||
// const timeSinceLastInvite = Date.now() - parseInt(lastInviteTimeArray[0].date_created_code);
|
||||
// if (timeSinceLastInvite > 21600000) {
|
||||
// throw new Error("Invitation expired");
|
||||
// }
|
||||
// } else if (!lastInviteTimeArray || !lastInviteTimeArray[0]) {
|
||||
// throw new Error("No Invitation Found");
|
||||
// }
|
||||
|
||||
if (!lastInviteTimeArray || !lastInviteTimeArray[0]) {
|
||||
throw new Error("No Invitation Found");
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
|
||||
// @ts-ignore
|
||||
const invitingUserDb = await DB_HANDLER(
|
||||
`SELECT first_name,last_name,email FROM users WHERE id=?`,
|
||||
[invite]
|
||||
);
|
||||
|
||||
if (invitingUserDb?.[0]) {
|
||||
const existingUserUser = await DB_HANDLER(
|
||||
`SELECT email FROM user_users WHERE user_id=? AND invited_user_id=? AND user_type='admin' AND email=?`,
|
||||
[invite, user.id, email]
|
||||
);
|
||||
|
||||
if (existingUserUser?.[0]) {
|
||||
console.log("User already added");
|
||||
} else {
|
||||
// const newUserUser = await DB_HANDLER(
|
||||
// `INSERT IGNORE INTO user_users
|
||||
// (user_id, invited_user_id, database_access, first_name, last_name, phone, email, username, user_type, user_priviledge)
|
||||
// VALUES
|
||||
// (?,?,?,?,?,?,?,?,?,?)
|
||||
// )`,
|
||||
// [
|
||||
// invite,
|
||||
// user.id,
|
||||
// database_access,
|
||||
// user.first_name,
|
||||
// user.last_name,
|
||||
// user.phone,
|
||||
// user.email,
|
||||
// user.username,
|
||||
// "admin",
|
||||
// priviledge,
|
||||
// ]
|
||||
// );
|
||||
addDbEntry({
|
||||
dbFullName: "datasquirel",
|
||||
tableName: "user_users",
|
||||
data: {
|
||||
user_id: invite,
|
||||
invited_user_id: user.id,
|
||||
database_access: database_access,
|
||||
first_name: user.first_name,
|
||||
last_name: user.last_name,
|
||||
phone: user.phone,
|
||||
email: user.email,
|
||||
username: user.username,
|
||||
user_type: "admin",
|
||||
user_priviledge: priviledge,
|
||||
image: user.image,
|
||||
image_thumbnail: user.image_thumbnail,
|
||||
},
|
||||
});
|
||||
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
|
||||
// @ts-ignore
|
||||
const dbTableData = await DB_HANDLER(
|
||||
`SELECT db_tables_data FROM invitations WHERE inviting_user_id=? AND invited_user_email=?`,
|
||||
[invite, email]
|
||||
);
|
||||
|
||||
// @ts-ignore
|
||||
const clearEntries = await DB_HANDLER(
|
||||
`DELETE FROM delegated_user_tables WHERE root_user_id=? AND delegated_user_id=?`,
|
||||
[invite, user.id]
|
||||
);
|
||||
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
|
||||
if (dbTableData && dbTableData[0]) {
|
||||
const dbTableEntries =
|
||||
dbTableData[0].db_tables_data.split("|");
|
||||
|
||||
for (let i = 0; i < dbTableEntries.length; i++) {
|
||||
const dbTableEntry = dbTableEntries[i];
|
||||
const dbTableEntryArray = dbTableEntry.split("-");
|
||||
const [db_slug, table_slug] = dbTableEntryArray;
|
||||
|
||||
const newEntry = await addDbEntry({
|
||||
dbFullName: "datasquirel",
|
||||
tableName: "delegated_user_tables",
|
||||
data: {
|
||||
delegated_user_id: user.id,
|
||||
root_user_id: invite,
|
||||
database: db_slug,
|
||||
table: table_slug,
|
||||
priviledge: priviledge,
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
}
|
||||
|
||||
// @ts-ignore
|
||||
const inviteAccepted = await DB_HANDLER(
|
||||
`UPDATE invitations SET invitation_status='Accepted' WHERE inviting_user_id=? AND invited_user_email=?`,
|
||||
[invite, email]
|
||||
);
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
} catch (/** @type {any} */ error) {
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
|
||||
serverError({
|
||||
component: "addAdminUserOnLogin",
|
||||
message: error.message,
|
||||
user: user,
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
@@ -3,8 +3,8 @@
|
||||
const generator = require("generate-password");
|
||||
const DB_HANDLER = require("../../utils/backend/global-db/DB_HANDLER");
|
||||
const NO_DB_HANDLER = require("../../utils/backend/global-db/NO_DB_HANDLER");
|
||||
const encrypt = require("./encrypt");
|
||||
const addDbEntry = require("./db/addDbEntry");
|
||||
const encrypt = require("../dsql/encrypt");
|
||||
|
||||
/**
|
||||
* # Add Mariadb User
|
||||
@@ -28,7 +28,7 @@ module.exports = async function addMariadbUser({ userId }) {
|
||||
uppercase: true,
|
||||
exclude: "*#.'`\"",
|
||||
});
|
||||
const encryptedPassword = encrypt(password);
|
||||
const encryptedPassword = encrypt({ data: password });
|
||||
|
||||
await NO_DB_HANDLER(
|
||||
`CREATE USER IF NOT EXISTS '${username}'@'127.0.0.1' IDENTIFIED BY '${password}' REQUIRE SSL`
|
||||
|
||||
+95
@@ -0,0 +1,95 @@
|
||||
// @ts-check
|
||||
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
const { execSync } = require("child_process");
|
||||
const serverError = require("./serverError");
|
||||
const DB_HANDLER = require("../../utils/backend/global-db/DB_HANDLER");
|
||||
const { default: grabUserSchemaData } = require("./grabUserSchemaData");
|
||||
const { default: setUserSchemaData } = require("./setUserSchemaData");
|
||||
const addDbEntry = require("./db/addDbEntry");
|
||||
const createDbFromSchema = require("../../shell/createDbFromSchema");
|
||||
|
||||
/**
|
||||
* # Add User Table to Database
|
||||
*
|
||||
* @param {object} params
|
||||
* @param {number} params.userId - user id
|
||||
* @param {string} params.database
|
||||
*
|
||||
* @returns {Promise<any>} new user auth object payload
|
||||
*/
|
||||
module.exports = async function addUsersTableToDb({ userId, database }) {
|
||||
/**
|
||||
* Initialize
|
||||
*
|
||||
* @description Initialize
|
||||
*/
|
||||
const dbFullName = `datasquirel_user_${userId}_${database}`;
|
||||
/** @type {import("../../types").DSQL_TableSchemaType} */
|
||||
const userPreset = require("../../data/presets/users.json");
|
||||
|
||||
try {
|
||||
/**
|
||||
* Fetch user
|
||||
*
|
||||
* @description Fetch user from db
|
||||
*/
|
||||
const userSchemaData = grabUserSchemaData({ userId });
|
||||
if (!userSchemaData) throw new Error("User schema data not found!");
|
||||
|
||||
let targetDatabase = userSchemaData.filter(
|
||||
(db) => db.dbSlug === database
|
||||
)[0];
|
||||
|
||||
let existingTableIndex;
|
||||
// @ts-ignore
|
||||
let existingTable = targetDatabase.tables.filter((table, index) => {
|
||||
if (table.tableName === "users") {
|
||||
existingTableIndex = index;
|
||||
return true;
|
||||
}
|
||||
});
|
||||
|
||||
if (existingTable && existingTable[0] && existingTableIndex) {
|
||||
targetDatabase.tables[existingTableIndex] = userPreset;
|
||||
} else {
|
||||
targetDatabase.tables.push(userPreset);
|
||||
}
|
||||
|
||||
setUserSchemaData({ schemaData: userSchemaData, userId });
|
||||
|
||||
const targetDb = await DB_HANDLER(
|
||||
`SELECT id FROM user_databases WHERE user_id=? AND db_slug=?`,
|
||||
[userId, database]
|
||||
);
|
||||
|
||||
if (targetDb && targetDb[0]) {
|
||||
const newTableEntry = await addDbEntry({
|
||||
dbFullName: "datasquirel",
|
||||
tableName: "user_database_tables",
|
||||
data: {
|
||||
user_id: userId,
|
||||
db_id: targetDb[0].id,
|
||||
db_slug: database,
|
||||
table_name: "Users",
|
||||
table_slug: "users",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const dbShellUpdate = await createDbFromSchema({
|
||||
userId,
|
||||
targetDatabase: dbFullName,
|
||||
});
|
||||
|
||||
return `Done!`;
|
||||
} catch (/** @type {any} */ error) {
|
||||
serverError({
|
||||
component: "addUsersTableToDb",
|
||||
message: error.message,
|
||||
user: { id: userId },
|
||||
});
|
||||
return error.message;
|
||||
}
|
||||
};
|
||||
@@ -1,7 +1,7 @@
|
||||
// @ts-check
|
||||
|
||||
const fs = require("fs");
|
||||
const decrypt = require("./decrypt");
|
||||
const decrypt = require("../dsql/decrypt");
|
||||
|
||||
/** @type {import("../../types").CheckApiCredentialsFn} */
|
||||
const grabApiCred = ({ key, database, table, user_id }) => {
|
||||
@@ -16,7 +16,7 @@ const grabApiCred = ({ key, database, table, user_id }) => {
|
||||
"process.env.DSQL_API_KEYS_PATH variable not found"
|
||||
);
|
||||
|
||||
const ApiJSON = decrypt(key);
|
||||
const ApiJSON = decrypt({ encryptedString: key });
|
||||
/** @type {import("../../types").ApiKeyObject} */
|
||||
const ApiObject = JSON.parse(ApiJSON || "");
|
||||
const isApiKeyValid = fs.existsSync(
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
module.exports = function getAuthCookieNames() {
|
||||
const cookiesPrefix = process.env.DSQL_COOKIES_PREFIX || "dsql_";
|
||||
const cookiesKeyName = process.env.DSQL_COOKIES_KEY_NAME || "key";
|
||||
const cookiesCSRFName = process.env.DSQL_COOKIES_CSRF_NAME || "csrf";
|
||||
|
||||
const keyCookieName = cookiesPrefix + cookiesKeyName;
|
||||
const csrfCookieName = cookiesPrefix + cookiesCSRFName;
|
||||
|
||||
return {
|
||||
keyCookieName,
|
||||
csrfCookieName,
|
||||
};
|
||||
};
|
||||
@@ -1,9 +1,5 @@
|
||||
// @ts-check
|
||||
|
||||
/**
|
||||
* Imports: Handle imports
|
||||
*/
|
||||
const encrypt = require("../encrypt");
|
||||
const sanitizeHtml = require("sanitize-html");
|
||||
const sanitizeHtmlOptions = require("../html/sanitizeHtmlOptions");
|
||||
const updateDb = require("./updateDbEntry");
|
||||
@@ -11,6 +7,7 @@ const updateDbEntry = require("./updateDbEntry");
|
||||
const _ = require("lodash");
|
||||
const DB_HANDLER = require("../../../utils/backend/global-db/DB_HANDLER");
|
||||
const DSQL_USER_DB_HANDLER = require("../../../utils/backend/global-db/DSQL_USER_DB_HANDLER");
|
||||
const encrypt = require("../../dsql/encrypt");
|
||||
|
||||
/**
|
||||
* Add a db Entry Function
|
||||
@@ -146,7 +143,11 @@ async function addDbEntry({
|
||||
continue;
|
||||
|
||||
if (targetFieldSchema?.encrypted) {
|
||||
value = encrypt(value, encryptionKey, encryptionSalt);
|
||||
value = encrypt({
|
||||
data: value,
|
||||
encryptionKey,
|
||||
encryptionSalt,
|
||||
});
|
||||
console.log("DSQL: Encrypted value =>", value);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,30 +0,0 @@
|
||||
export = runQuery;
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/**
|
||||
* Run DSQL users queries
|
||||
* ==============================================================================
|
||||
* @param {object} params - An object containing the function parameters.
|
||||
* @param {string} params.dbFullName - Database full name. Eg. "datasquire_user_2_test"
|
||||
* @param {string | any} params.query - Query string or object
|
||||
* @param {boolean} [params.readOnly] - Is this operation read only?
|
||||
* @param {boolean} [params.local] - Is this operation read only?
|
||||
* @param {import("../../../types").DSQL_DatabaseSchemaType} [params.dbSchema] - Database schema
|
||||
* @param {string[]} [params.queryValuesArray] - An optional array of query values if "?" is used in the query string
|
||||
* @param {string} [params.tableName] - Table Name
|
||||
*
|
||||
* @return {Promise<any>}
|
||||
*/
|
||||
declare function runQuery({ dbFullName, query, readOnly, dbSchema, queryValuesArray, tableName, local, }: {
|
||||
dbFullName: string;
|
||||
query: string | any;
|
||||
readOnly?: boolean;
|
||||
local?: boolean;
|
||||
dbSchema?: import("../../../types").DSQL_DatabaseSchemaType;
|
||||
queryValuesArray?: string[];
|
||||
tableName?: string;
|
||||
}): Promise<any>;
|
||||
@@ -38,7 +38,7 @@ const trimSql = require("../../../utils/trim-sql");
|
||||
* @param {boolean} [params.readOnly] - Is this operation read only?
|
||||
* @param {boolean} [params.local] - Is this operation read only?
|
||||
* @param {import("../../../types").DSQL_DatabaseSchemaType} [params.dbSchema] - Database schema
|
||||
* @param {string[]} [params.queryValuesArray] - An optional array of query values if "?" is used in the query string
|
||||
* @param {(string | number)[]} [params.queryValuesArray] - An optional array of query values if "?" is used in the query string
|
||||
* @param {string} [params.tableName] - Table Name
|
||||
*
|
||||
* @return {Promise<any>}
|
||||
@@ -120,14 +120,14 @@ async function runQuery({
|
||||
} else if (readOnly) {
|
||||
result = await varReadOnlyDatabaseDbHandler({
|
||||
queryString: formattedQuery,
|
||||
queryValuesArray,
|
||||
queryValuesArray: queryValuesArray?.map((vl) => String(vl)),
|
||||
database: dbFullName,
|
||||
tableSchema,
|
||||
});
|
||||
} else {
|
||||
result = await fullAccessDbHandler({
|
||||
queryString: formattedQuery,
|
||||
queryValuesArray,
|
||||
queryValuesArray: queryValuesArray?.map((vl) => String(vl)),
|
||||
database: dbFullName,
|
||||
tableSchema,
|
||||
});
|
||||
|
||||
@@ -3,11 +3,11 @@
|
||||
/**
|
||||
* Imports: Handle imports
|
||||
*/
|
||||
const encrypt = require("../encrypt");
|
||||
const sanitizeHtml = require("sanitize-html");
|
||||
const sanitizeHtmlOptions = require("../html/sanitizeHtmlOptions");
|
||||
const DB_HANDLER = require("../../../utils/backend/global-db/DB_HANDLER");
|
||||
const DSQL_USER_DB_HANDLER = require("../../../utils/backend/global-db/DSQL_USER_DB_HANDLER");
|
||||
const encrypt = require("../../dsql/encrypt");
|
||||
|
||||
/**
|
||||
* Update DB Function
|
||||
@@ -94,7 +94,11 @@ async function updateDbEntry({
|
||||
}
|
||||
|
||||
if (targetFieldSchema?.encrypted) {
|
||||
value = encrypt(value, encryptionKey, encryptionSalt);
|
||||
value = encrypt({
|
||||
data: value,
|
||||
encryptionKey,
|
||||
encryptionSalt,
|
||||
});
|
||||
}
|
||||
|
||||
if (typeof value === "object") {
|
||||
|
||||
@@ -1,6 +0,0 @@
|
||||
export = decrypt;
|
||||
/**
|
||||
* @param {string} encryptedString
|
||||
* @returns {string | null}
|
||||
*/
|
||||
declare function decrypt(encryptedString: string): string | null;
|
||||
@@ -1,29 +0,0 @@
|
||||
// @ts-check
|
||||
|
||||
const { scryptSync, createDecipheriv } = require("crypto");
|
||||
const { Buffer } = require("buffer");
|
||||
|
||||
/**
|
||||
* @param {string} encryptedString
|
||||
* @returns {string | null}
|
||||
*/
|
||||
const decrypt = (encryptedString) => {
|
||||
const algorithm = "aes-192-cbc";
|
||||
const password = process.env.DSQL_ENCRYPTION_PASSWORD || "";
|
||||
const salt = process.env.DSQL_ENCRYPTION_SALT || "";
|
||||
|
||||
let key = scryptSync(password, salt, 24);
|
||||
let iv = Buffer.alloc(16, 0);
|
||||
// @ts-ignore
|
||||
const decipher = createDecipheriv(algorithm, key, iv);
|
||||
|
||||
try {
|
||||
let decrypted = decipher.update(encryptedString, "hex", "utf8");
|
||||
decrypted += decipher.final("utf8");
|
||||
return decrypted;
|
||||
} catch (error) {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = decrypt;
|
||||
@@ -1,9 +0,0 @@
|
||||
export = encrypt;
|
||||
/**
|
||||
* @async
|
||||
* @param {string} data
|
||||
* @param {string} [encryptionKey]
|
||||
* @param {string} [encryptionSalt]
|
||||
* @returns {string | null}
|
||||
*/
|
||||
declare function encrypt(data: string, encryptionKey?: string, encryptionSalt?: string): string | null;
|
||||
@@ -1,43 +0,0 @@
|
||||
// @ts-check
|
||||
|
||||
const { scryptSync, createCipheriv } = require("crypto");
|
||||
const { Buffer } = require("buffer");
|
||||
const serverError = require("./serverError");
|
||||
|
||||
/**
|
||||
* @async
|
||||
* @param {string} data
|
||||
* @param {string} [encryptionKey]
|
||||
* @param {string} [encryptionSalt]
|
||||
* @returns {string | null}
|
||||
*/
|
||||
const encrypt = (data, encryptionKey, encryptionSalt) => {
|
||||
const algorithm = "aes-192-cbc";
|
||||
const password = encryptionKey
|
||||
? encryptionKey
|
||||
: process.env.DSQL_ENCRYPTION_PASSWORD || "";
|
||||
|
||||
/** ********************* Generate key */
|
||||
const salt = encryptionSalt
|
||||
? encryptionSalt
|
||||
: process.env.DSQL_ENCRYPTION_SALT || "";
|
||||
let key = scryptSync(password, salt, 24);
|
||||
let iv = Buffer.alloc(16, 0);
|
||||
// @ts-ignore
|
||||
const cipher = createCipheriv(algorithm, key, iv);
|
||||
|
||||
/** ********************* Encrypt data */
|
||||
try {
|
||||
let encrypted = cipher.update(data, "utf8", "hex");
|
||||
encrypted += cipher.final("hex");
|
||||
return encrypted;
|
||||
} catch (/** @type {any} */ error) {
|
||||
serverError({
|
||||
component: "encrypt",
|
||||
message: error.message,
|
||||
});
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = encrypt;
|
||||
+46
@@ -0,0 +1,46 @@
|
||||
// @ts-check
|
||||
|
||||
const serverError = require("./serverError");
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
|
||||
/**
|
||||
* ==============================================================================
|
||||
* @param {Object} params
|
||||
* @param {string | number} params.userId
|
||||
* @returns {import("../../types").DSQL_DatabaseSchemaType[] | null}
|
||||
*/
|
||||
export default function grabUserSchemaData({ userId }) {
|
||||
try {
|
||||
const userSchemaFilePath = path.resolve(
|
||||
process.cwd(),
|
||||
`${process.env.DSQL_USER_DB_SCHEMA_PATH}/user-${userId}/main.json`
|
||||
);
|
||||
const userSchemaData = JSON.parse(
|
||||
fs.readFileSync(userSchemaFilePath, "utf-8")
|
||||
);
|
||||
|
||||
return userSchemaData;
|
||||
} catch (/** @type {any} */ error) {
|
||||
serverError({
|
||||
component: "grabUserSchemaData",
|
||||
message: error.message,
|
||||
});
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
+129
@@ -0,0 +1,129 @@
|
||||
// @ts-check
|
||||
|
||||
/**
|
||||
* Imports
|
||||
* ==============================================================================
|
||||
*/
|
||||
|
||||
const fs = require("fs");
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
const nodemailer = require("nodemailer");
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
let transporter = nodemailer.createTransport({
|
||||
host: process.env.DSQL_MAIL_HOST,
|
||||
port: 465,
|
||||
secure: true,
|
||||
auth: {
|
||||
user: process.env.DSQL_MAIL_EMAIL,
|
||||
pass: process.env.DSQL_MAIL_PASSWORD,
|
||||
},
|
||||
});
|
||||
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
|
||||
/**
|
||||
* # Handle mails
|
||||
* @param {object} mailObject - Mail Object with params
|
||||
* @param {string} [mailObject.to] - who is recieving this email? Comma separated for multiple recipients
|
||||
* @param {string} [mailObject.subject] - Mail Subject
|
||||
* @param {string} [mailObject.text] - Mail text
|
||||
* @param {string} [mailObject.html] - Mail HTML
|
||||
* @param {string | null} [mailObject.alias] - Sender alias: "support" or null
|
||||
*
|
||||
* @returns {Promise<any>} mail object
|
||||
*/
|
||||
module.exports = async function handleNodemailer({
|
||||
to,
|
||||
subject,
|
||||
text,
|
||||
html,
|
||||
alias,
|
||||
}) {
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
if (
|
||||
!process.env.DSQL_MAIL_HOST ||
|
||||
!process.env.DSQL_MAIL_EMAIL ||
|
||||
!process.env.DSQL_MAIL_PASSWORD
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const sender = (() => {
|
||||
if (alias?.match(/support/i)) return process.env.DSQL_MAIL_EMAIL;
|
||||
return process.env.DSQL_MAIL_EMAIL;
|
||||
})();
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
let sentMessage;
|
||||
|
||||
if (!fs.existsSync("./email/index.html")) {
|
||||
return;
|
||||
}
|
||||
|
||||
let mailRoot = fs.readFileSync("./email/index.html", "utf8");
|
||||
let finalHtml = mailRoot
|
||||
.replace(/{{email_body}}/, html ? html : "")
|
||||
.replace(/{{issue_date}}/, Date().substring(0, 24));
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
try {
|
||||
let mailObject = {};
|
||||
|
||||
mailObject["from"] = `"Datasquirel" <${sender}>`;
|
||||
mailObject["sender"] = sender;
|
||||
if (alias) mailObject["replyTo "] = sender;
|
||||
// mailObject["priority"] = "high";
|
||||
mailObject["to"] = to;
|
||||
mailObject["subject"] = subject;
|
||||
mailObject["text"] = text;
|
||||
mailObject["html"] = finalHtml;
|
||||
|
||||
// send mail with defined transport object
|
||||
let info = await transporter.sendMail(mailObject);
|
||||
|
||||
sentMessage = info;
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
} catch (/** @type {any} */ error) {
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
console.log("ERROR in handleNodemailer Function =>", error.message);
|
||||
// serverError({
|
||||
// component: "handleNodemailer",
|
||||
// message: error.message,
|
||||
// user: { email: to },
|
||||
// });
|
||||
}
|
||||
|
||||
return sentMessage;
|
||||
};
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
@@ -0,0 +1,141 @@
|
||||
// @ts-check
|
||||
|
||||
/**
|
||||
* Imports
|
||||
* ==============================================================================
|
||||
*/
|
||||
const https = require("https");
|
||||
const http = require("http");
|
||||
const { URL } = require("url");
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
/**
|
||||
* Main Function
|
||||
* ==============================================================================
|
||||
* @param {{
|
||||
* scheme?: string,
|
||||
* url?: string,
|
||||
* method?: string,
|
||||
* hostname?: string,
|
||||
* path?: string,
|
||||
* port?: number | string,
|
||||
* headers?: object,
|
||||
* body?: object,
|
||||
* }} params - params
|
||||
*/
|
||||
module.exports = function httpsRequest({
|
||||
url,
|
||||
method,
|
||||
hostname,
|
||||
path,
|
||||
headers,
|
||||
body,
|
||||
port,
|
||||
scheme,
|
||||
}) {
|
||||
const reqPayloadString = body ? JSON.stringify(body) : null;
|
||||
|
||||
const PARSED_URL = url ? new URL(url) : null;
|
||||
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
|
||||
/** @type {any} */
|
||||
let requestOptions = {
|
||||
method: method || "GET",
|
||||
hostname: PARSED_URL ? PARSED_URL.hostname : hostname,
|
||||
port: scheme?.match(/https/i)
|
||||
? 443
|
||||
: PARSED_URL
|
||||
? PARSED_URL.protocol?.match(/https/i)
|
||||
? 443
|
||||
: PARSED_URL.port
|
||||
: port
|
||||
? Number(port)
|
||||
: 80,
|
||||
headers: {},
|
||||
};
|
||||
|
||||
if (path) requestOptions.path = path;
|
||||
// if (href) requestOptions.href = href;
|
||||
|
||||
if (headers) requestOptions.headers = headers;
|
||||
if (body) {
|
||||
requestOptions.headers["Content-Type"] = "application/json";
|
||||
requestOptions.headers["Content-Length"] = reqPayloadString
|
||||
? Buffer.from(reqPayloadString).length
|
||||
: undefined;
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
|
||||
return new Promise((res, rej) => {
|
||||
const httpsRequest = (
|
||||
scheme?.match(/https/i)
|
||||
? https
|
||||
: PARSED_URL?.protocol?.match(/https/i)
|
||||
? https
|
||||
: http
|
||||
).request(
|
||||
/* ====== Request Options object ====== */
|
||||
requestOptions,
|
||||
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
|
||||
/* ====== Callback function ====== */
|
||||
(response) => {
|
||||
var str = "";
|
||||
|
||||
// ## another chunk of data has been received, so append it to `str`
|
||||
response.on("data", function (chunk) {
|
||||
str += chunk;
|
||||
});
|
||||
|
||||
// ## the whole response has been received, so we just print it out here
|
||||
response.on("end", function () {
|
||||
res(str);
|
||||
});
|
||||
|
||||
response.on("error", (error) => {
|
||||
console.log("HTTP response error =>", error.message);
|
||||
rej(`HTTP response error =>, ${error.message}`);
|
||||
});
|
||||
|
||||
response.on("close", () => {
|
||||
console.log("HTTP(S) Response Closed Successfully");
|
||||
});
|
||||
}
|
||||
);
|
||||
|
||||
if (body) httpsRequest.write(reqPayloadString);
|
||||
|
||||
httpsRequest.on("error", (error) => {
|
||||
console.log("HTTPS request ERROR =>", error.message);
|
||||
rej(`HTTP request error =>, ${error.message}`);
|
||||
});
|
||||
|
||||
httpsRequest.end();
|
||||
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
});
|
||||
};
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
@@ -1,6 +1,6 @@
|
||||
// @ts-check
|
||||
|
||||
const decrypt = require("./decrypt");
|
||||
const decrypt = require("../dsql/decrypt");
|
||||
const defaultFieldsRegexp = require("./defaultFieldsRegexp");
|
||||
|
||||
/**
|
||||
@@ -55,7 +55,9 @@ module.exports = async function parseDbResults({
|
||||
|
||||
if (resultFieldSchema?.encrypted) {
|
||||
if (value?.match(/./)) {
|
||||
result[resultFieldName] = decrypt(value);
|
||||
result[resultFieldName] = decrypt({
|
||||
encryptedString: value,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,12 +0,0 @@
|
||||
declare function _exports({ user, message, component, noMail, }: {
|
||||
user?: {
|
||||
id?: number | string;
|
||||
first_name?: string;
|
||||
last_name?: string;
|
||||
email?: string;
|
||||
} & any;
|
||||
message: string;
|
||||
component?: string;
|
||||
noMail?: boolean;
|
||||
}): Promise<void>;
|
||||
export = _exports;
|
||||
Regular → Executable
+61
-13
@@ -6,7 +6,7 @@
|
||||
* ==============================================================================
|
||||
*/
|
||||
const fs = require("fs");
|
||||
// const handleNodemailer = require("./handleNodemailer");
|
||||
const { IncomingMessage } = require("http");
|
||||
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
@@ -24,6 +24,7 @@ const fs = require("fs");
|
||||
* message: string,
|
||||
* component?: string,
|
||||
* noMail?: boolean,
|
||||
* req?: import("next").NextApiRequest & IncomingMessage,
|
||||
* }} params - user id
|
||||
*
|
||||
* @returns {Promise<void>}
|
||||
@@ -33,21 +34,68 @@ module.exports = async function serverError({
|
||||
message,
|
||||
component,
|
||||
noMail,
|
||||
req,
|
||||
}) {
|
||||
const log = `🚀 SERVER ERROR ===========================\nUser Id: ${
|
||||
user?.id
|
||||
}\nUser Name: ${user?.first_name} ${user?.last_name}\nUser Email: ${
|
||||
user?.email
|
||||
}\nError Message: ${message}\nComponent: ${component}\nDate: ${Date()}\n========================================`;
|
||||
const date = new Date();
|
||||
|
||||
if (!fs.existsSync(`./.tmp/error.log`)) {
|
||||
fs.writeFileSync(`./.tmp/error.log`, "", "utf-8");
|
||||
const reqIp = (() => {
|
||||
if (!req) return null;
|
||||
try {
|
||||
const forwarded = req.headers["x-forwarded-for"];
|
||||
const realIp = req.headers["x-real-ip"];
|
||||
const cloudflareIp = req.headers["cf-connecting-ip"];
|
||||
|
||||
// Convert forwarded IPs to string and get the first IP if multiple exist
|
||||
const forwardedIp = Array.isArray(forwarded)
|
||||
? forwarded[0]
|
||||
: forwarded?.split(",")[0];
|
||||
|
||||
const clientIp =
|
||||
cloudflareIp ||
|
||||
forwardedIp ||
|
||||
realIp ||
|
||||
req.socket.remoteAddress;
|
||||
if (!clientIp) return null;
|
||||
|
||||
return String(clientIp);
|
||||
} catch (error) {
|
||||
return null;
|
||||
}
|
||||
})();
|
||||
|
||||
try {
|
||||
let log = `🚀 SERVER ERROR ===========================\nError Message: ${message}\nComponent: ${component}`;
|
||||
|
||||
if (user?.id && user?.first_name && user?.last_name && user?.email) {
|
||||
log += `\nUser Id: ${user?.id}\nUser Name: ${user?.first_name} ${user?.last_name}\nUser Email: ${user?.email}`;
|
||||
}
|
||||
|
||||
if (req?.url) {
|
||||
log += `\nURL: ${req.url}`;
|
||||
}
|
||||
|
||||
if (req?.body) {
|
||||
log += `\nRequest Body: ${JSON.stringify(req.body, null, 4)}`;
|
||||
}
|
||||
|
||||
if (reqIp) {
|
||||
log += `\nIP: ${reqIp}`;
|
||||
}
|
||||
|
||||
log += `\nDate: ${date.toDateString()}`;
|
||||
log += "\n========================================";
|
||||
|
||||
if (!fs.existsSync(`./.tmp/error.log`)) {
|
||||
fs.writeFileSync(`./.tmp/error.log`, "", "utf-8");
|
||||
}
|
||||
|
||||
const initialText = fs.readFileSync(`./.tmp/error.log`, "utf-8");
|
||||
|
||||
fs.writeFileSync(`./.tmp/error.log`, log);
|
||||
fs.appendFileSync(`./.tmp/error.log`, `\n\n\n\n\n${initialText}`);
|
||||
} catch (/** @type {any} */ error) {
|
||||
console.log("Server Error Reporting Error:", error.message);
|
||||
}
|
||||
|
||||
const initialText = fs.readFileSync(`./.tmp/error.log`, "utf-8");
|
||||
|
||||
fs.writeFileSync(`./.tmp/error.log`, log);
|
||||
fs.appendFileSync(`./.tmp/error.log`, `\n\n\n\n\n${initialText}`);
|
||||
};
|
||||
|
||||
////////////////////////////////////////
|
||||
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
// @ts-check
|
||||
|
||||
const serverError = require("./serverError");
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
|
||||
/**
|
||||
* ==============================================================================
|
||||
* @param {Object} params
|
||||
* @param {string | number} params.userId
|
||||
* @param {import("../../types").DSQL_DatabaseSchemaType[]} params.schemaData
|
||||
* @returns {boolean}
|
||||
*/
|
||||
export default function setUserSchemaData({ userId, schemaData }) {
|
||||
try {
|
||||
const userSchemaFilePath = path.resolve(
|
||||
process.cwd(),
|
||||
`${process.env.DSQL_USER_DB_SCHEMA_PATH}/user-${userId}/main.json`
|
||||
);
|
||||
fs.writeFileSync(
|
||||
userSchemaFilePath,
|
||||
JSON.stringify(schemaData),
|
||||
"utf8"
|
||||
);
|
||||
|
||||
return true;
|
||||
} catch (/** @type {any} */ error) {
|
||||
serverError({
|
||||
component: "/functions/backend/setUserSchemaData",
|
||||
message: error.message,
|
||||
});
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
@@ -1,8 +1,9 @@
|
||||
// @ts-check
|
||||
|
||||
const { IncomingMessage } = require("http");
|
||||
const decrypt = require("./decrypt");
|
||||
const parseCookies = require("../../utils/backend/parseCookies");
|
||||
const decrypt = require("../dsql/decrypt");
|
||||
const getAuthCookieNames = require("./cookies/get-auth-cookie-names");
|
||||
|
||||
/**
|
||||
* @async
|
||||
@@ -11,14 +12,18 @@ const parseCookies = require("../../utils/backend/parseCookies");
|
||||
* @returns {Promise<({ email: string, password: string, authKey: string, logged_in_status: boolean, date: number } | null)>}
|
||||
*/
|
||||
module.exports = async function (req) {
|
||||
const { keyCookieName, csrfCookieName } = getAuthCookieNames();
|
||||
const suKeyName = `${keyCookieName}_su`;
|
||||
|
||||
const cookies = parseCookies({ request: req });
|
||||
/** ********************* Check for existence of required cookie */
|
||||
if (!cookies?.datasquirelSuAdminUserAuthKey) {
|
||||
if (!cookies?.[suKeyName]) {
|
||||
return null;
|
||||
}
|
||||
|
||||
/** ********************* Grab the payload */
|
||||
let userPayload = decrypt(cookies.datasquirelSuAdminUserAuthKey);
|
||||
let userPayload = decrypt({
|
||||
encryptedString: cookies[suKeyName],
|
||||
});
|
||||
|
||||
/** ********************* Return if no payload */
|
||||
if (!userPayload) return null;
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
// @ts-check
|
||||
|
||||
const { scryptSync, createDecipheriv } = require("crypto");
|
||||
const { Buffer } = require("buffer");
|
||||
|
||||
/**
|
||||
* @param {object} param0
|
||||
* @param {string} param0.encryptedString
|
||||
* @param {string} [param0.encryptionKey]
|
||||
* @param {string} [param0.encryptionSalt]
|
||||
* @returns
|
||||
*/
|
||||
const decrypt = ({ encryptedString, encryptionKey, encryptionSalt }) => {
|
||||
if (!encryptedString?.match(/./)) {
|
||||
console.log("Encrypted string is invalid");
|
||||
return encryptedString;
|
||||
}
|
||||
|
||||
const finalEncryptionKey =
|
||||
encryptionKey || process.env.DSQL_ENCRYPTION_PASSWORD;
|
||||
const finalEncryptionSalt =
|
||||
encryptionSalt || process.env.DSQL_ENCRYPTION_SALT;
|
||||
const finalKeyLen = process.env.DSQL_ENCRYPTION_KEY_LENGTH
|
||||
? Number(process.env.DSQL_ENCRYPTION_KEY_LENGTH)
|
||||
: 24;
|
||||
|
||||
if (!finalEncryptionKey?.match(/.{8,}/)) {
|
||||
console.log("Decrption key is invalid");
|
||||
return encryptedString;
|
||||
}
|
||||
|
||||
if (!finalEncryptionSalt?.match(/.{8,}/)) {
|
||||
console.log("Decrption salt is invalid");
|
||||
return encryptedString;
|
||||
}
|
||||
|
||||
const algorithm = "aes-192-cbc";
|
||||
|
||||
let key = scryptSync(finalEncryptionKey, finalEncryptionSalt, finalKeyLen);
|
||||
let iv = Buffer.alloc(16, 0);
|
||||
// @ts-ignore
|
||||
const decipher = createDecipheriv(algorithm, key, iv);
|
||||
|
||||
try {
|
||||
let decrypted = decipher.update(encryptedString, "hex", "utf8");
|
||||
decrypted += decipher.final("utf8");
|
||||
return decrypted;
|
||||
} catch (/** @type {*} */ error) {
|
||||
console.log("Error in decrypting =>", error.message);
|
||||
return encryptedString;
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = decrypt;
|
||||
@@ -0,0 +1,55 @@
|
||||
// @ts-check
|
||||
|
||||
const { scryptSync, createCipheriv } = require("crypto");
|
||||
const { Buffer } = require("buffer");
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {object} param0
|
||||
* @param {string} param0.data
|
||||
* @param {string} [param0.encryptionKey]
|
||||
* @param {string} [param0.encryptionSalt]
|
||||
* @returns {string | null}
|
||||
*/
|
||||
const encrypt = ({ data, encryptionKey, encryptionSalt }) => {
|
||||
if (!data?.match(/./)) {
|
||||
console.log("Encryption string is invalid");
|
||||
return data;
|
||||
}
|
||||
|
||||
const finalEncryptionKey =
|
||||
encryptionKey || process.env.DSQL_ENCRYPTION_PASSWORD;
|
||||
const finalEncryptionSalt =
|
||||
encryptionSalt || process.env.DSQL_ENCRYPTION_SALT;
|
||||
const finalKeyLen = process.env.DSQL_ENCRYPTION_KEY_LENGTH
|
||||
? Number(process.env.DSQL_ENCRYPTION_KEY_LENGTH)
|
||||
: 24;
|
||||
|
||||
if (!finalEncryptionKey?.match(/.{8,}/)) {
|
||||
console.log("Encryption key is invalid");
|
||||
return data;
|
||||
}
|
||||
if (!finalEncryptionSalt?.match(/.{8,}/)) {
|
||||
console.log("Encryption salt is invalid");
|
||||
return data;
|
||||
}
|
||||
|
||||
const algorithm = "aes-192-cbc";
|
||||
const password = finalEncryptionKey;
|
||||
|
||||
let key = scryptSync(password, finalEncryptionSalt, finalKeyLen);
|
||||
let iv = Buffer.alloc(16, 0);
|
||||
// @ts-ignore
|
||||
const cipher = createCipheriv(algorithm, key, iv);
|
||||
|
||||
try {
|
||||
let encrypted = cipher.update(data, "utf8", "hex");
|
||||
encrypted += cipher.final("hex");
|
||||
return encrypted;
|
||||
} catch (/** @type {*} */ error) {
|
||||
console.log("Error in encrypting =>", error.message);
|
||||
return data;
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = encrypt;
|
||||
@@ -0,0 +1,5 @@
|
||||
declare function _exports({ password, encryptionKey }: {
|
||||
password: string;
|
||||
encryptionKey: string;
|
||||
}): string;
|
||||
export = _exports;
|
||||
@@ -0,0 +1,27 @@
|
||||
/** # MODULE TRACE
|
||||
======================================================================
|
||||
* Detected 4 files that call this module. The files are listed below:
|
||||
======================================================================
|
||||
* `require` Statement Found in [add-user.js] => file:///d:\GitHub\dsql\engine\user\add-user.js
|
||||
* `require` Statement Found in [login-user.js] => file:///d:\GitHub\dsql\engine\user\login-user.js
|
||||
* `require` Statement Found in [googleLogin.js] => file:///d:\GitHub\dsql\engine\user\social\utils\googleLogin.js
|
||||
* `require` Statement Found in [update-user.js] => file:///d:\GitHub\dsql\engine\user\update-user.js
|
||||
==== MODULE TRACE END ==== */
|
||||
|
||||
// @ts-check
|
||||
|
||||
const { createHmac } = require("crypto");
|
||||
|
||||
/**
|
||||
* # Hash password Function
|
||||
* @param {object} param0
|
||||
* @param {string} param0.password - Password to hash
|
||||
* @param {string} param0.encryptionKey - Encryption key
|
||||
* @returns {string}
|
||||
*/
|
||||
module.exports = function hashPassword({ password, encryptionKey }) {
|
||||
const hmac = createHmac("sha512", encryptionKey);
|
||||
hmac.update(password);
|
||||
let hashed = hmac.digest("base64");
|
||||
return hashed;
|
||||
};
|
||||
@@ -0,0 +1,24 @@
|
||||
export = sqlDeleteGenerator;
|
||||
/**
|
||||
* @typedef {object} SQLDeleteGenReturn
|
||||
* @property {string} query
|
||||
* @property {string[]} values
|
||||
*/
|
||||
/**
|
||||
* @param {object} param0
|
||||
* @param {any} param0.data
|
||||
* @param {string} param0.tableName
|
||||
*
|
||||
* @return {SQLDeleteGenReturn | undefined}
|
||||
*/
|
||||
declare function sqlDeleteGenerator({ tableName, data }: {
|
||||
data: any;
|
||||
tableName: string;
|
||||
}): SQLDeleteGenReturn | undefined;
|
||||
declare namespace sqlDeleteGenerator {
|
||||
export { SQLDeleteGenReturn };
|
||||
}
|
||||
type SQLDeleteGenReturn = {
|
||||
query: string;
|
||||
values: string[];
|
||||
};
|
||||
@@ -0,0 +1,41 @@
|
||||
// @ts-check
|
||||
|
||||
/**
|
||||
* @typedef {object} SQLDeleteGenReturn
|
||||
* @property {string} query
|
||||
* @property {string[]} values
|
||||
*/
|
||||
|
||||
/**
|
||||
* @param {object} param0
|
||||
* @param {any} param0.data
|
||||
* @param {string} param0.tableName
|
||||
*
|
||||
* @return {SQLDeleteGenReturn | undefined}
|
||||
*/
|
||||
function sqlDeleteGenerator({ tableName, data }) {
|
||||
try {
|
||||
let queryStr = `DELETE FROM ${tableName}`;
|
||||
|
||||
/** @type {string[]} */
|
||||
let deleteBatch = [];
|
||||
/** @type {string[]} */
|
||||
let queryArr = [];
|
||||
|
||||
Object.keys(data).forEach((ky) => {
|
||||
deleteBatch.push(`${ky}=?`);
|
||||
queryArr.push(data[ky]);
|
||||
});
|
||||
queryStr += ` WHERE ${deleteBatch.join(" AND ")}`;
|
||||
|
||||
return {
|
||||
query: queryStr,
|
||||
values: queryArr,
|
||||
};
|
||||
} catch (/** @type {any} */ error) {
|
||||
console.log(`SQL delete gen ERROR: ${error.message}`);
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = sqlDeleteGenerator;
|
||||
@@ -0,0 +1,10 @@
|
||||
export = sqlGenerator;
|
||||
declare function sqlGenerator(Param0: {
|
||||
genObject?: import("../../../types").ServerQueryParam;
|
||||
tableName: string;
|
||||
}):
|
||||
| {
|
||||
string: string;
|
||||
values: string[];
|
||||
}
|
||||
| undefined;
|
||||
@@ -0,0 +1,194 @@
|
||||
// @ts-check
|
||||
|
||||
/**
|
||||
* # SQL Query Generator
|
||||
* @description Generates an SQL Query for node module `mysql` or `serverless-mysql`
|
||||
* @type {import("../../../types").SqlGeneratorFn}
|
||||
*/
|
||||
function sqlGenerator({ tableName, genObject }) {
|
||||
if (!genObject) return undefined;
|
||||
|
||||
const finalQuery = genObject.query ? genObject.query : undefined;
|
||||
|
||||
const queryKeys = finalQuery ? Object.keys(finalQuery) : undefined;
|
||||
|
||||
/** @type {string[]} */
|
||||
const sqlSearhValues = [];
|
||||
const sqlSearhString = queryKeys?.map((field) => {
|
||||
const queryObj = finalQuery?.[field];
|
||||
if (!queryObj) return;
|
||||
|
||||
const finalFieldName = (() => {
|
||||
if (queryObj?.tableName) {
|
||||
return `${queryObj.tableName}.${field}`;
|
||||
}
|
||||
if (genObject.join) {
|
||||
return `${tableName}.${field}`;
|
||||
}
|
||||
return field;
|
||||
})();
|
||||
|
||||
let str = `${finalFieldName}=?`;
|
||||
|
||||
if (
|
||||
typeof queryObj.value == "string" ||
|
||||
typeof queryObj.value == "number"
|
||||
) {
|
||||
const valueParsed = String(queryObj.value);
|
||||
if (queryObj.equality == "LIKE") {
|
||||
str = `LOWER(${finalFieldName}) LIKE LOWER('%${valueParsed}%')`;
|
||||
} else {
|
||||
sqlSearhValues.push(valueParsed);
|
||||
}
|
||||
} else if (Array.isArray(queryObj.value)) {
|
||||
/** @type {string[]} */
|
||||
const strArray = [];
|
||||
queryObj.value.forEach((val) => {
|
||||
const valueParsed = val;
|
||||
if (queryObj.equality == "LIKE") {
|
||||
strArray.push(
|
||||
`LOWER(${finalFieldName}) LIKE LOWER('%${valueParsed}%')`
|
||||
);
|
||||
} else {
|
||||
strArray.push(`${finalFieldName} = ?`);
|
||||
sqlSearhValues.push(valueParsed);
|
||||
}
|
||||
});
|
||||
|
||||
str = "(" + strArray.join(` ${queryObj.operator || "AND"} `) + ")";
|
||||
}
|
||||
|
||||
return str;
|
||||
});
|
||||
|
||||
function generateJoinStr(
|
||||
/** @type {import("../../../types").ServerQueryParamsJoinMatchObject} */ mtch,
|
||||
/** @type {import("../../../types").ServerQueryParamsJoin} */ join
|
||||
) {
|
||||
return `${
|
||||
typeof mtch.source == "object" ? mtch.source.tableName : tableName
|
||||
}.${
|
||||
typeof mtch.source == "object" ? mtch.source.fieldName : mtch.source
|
||||
}=${(() => {
|
||||
if (mtch.targetLiteral) {
|
||||
return `'${mtch.targetLiteral}'`;
|
||||
}
|
||||
|
||||
return `${
|
||||
typeof mtch.target == "object"
|
||||
? mtch.target.tableName
|
||||
: join.tableName
|
||||
}.${
|
||||
typeof mtch.target == "object"
|
||||
? mtch.target.fieldName
|
||||
: mtch.target
|
||||
}`;
|
||||
})()}`;
|
||||
}
|
||||
|
||||
let queryString = (() => {
|
||||
let str = "SELECT";
|
||||
if (genObject.selectFields?.[0]) {
|
||||
if (genObject.join) {
|
||||
str += ` ${genObject.selectFields
|
||||
?.map((fld) => `${tableName}.${fld}`)
|
||||
.join(",")}`;
|
||||
} else {
|
||||
str += ` ${genObject.selectFields?.join(",")}`;
|
||||
}
|
||||
} else {
|
||||
if (genObject.join) {
|
||||
str += ` ${tableName}.*`;
|
||||
} else {
|
||||
str += " *";
|
||||
}
|
||||
}
|
||||
|
||||
if (genObject.join) {
|
||||
/** @type {string[]} */
|
||||
const existingJoinTableNames = [tableName];
|
||||
|
||||
str +=
|
||||
"," +
|
||||
genObject.join
|
||||
.map((joinObj) => {
|
||||
if (existingJoinTableNames.includes(joinObj.tableName))
|
||||
return null;
|
||||
existingJoinTableNames.push(joinObj.tableName);
|
||||
|
||||
if (joinObj.selectFields) {
|
||||
return joinObj.selectFields
|
||||
.map((slFld) => {
|
||||
if (typeof slFld == "string") {
|
||||
return `${joinObj.tableName}.${slFld}`;
|
||||
} else if (typeof slFld == "object") {
|
||||
let aliasSlctFld = `${joinObj.tableName}.${slFld.field}`;
|
||||
if (slFld.alias)
|
||||
aliasSlctFld += ` as ${slFld.alias}`;
|
||||
return aliasSlctFld;
|
||||
}
|
||||
})
|
||||
.join(",");
|
||||
} else {
|
||||
return `${joinObj.tableName}.*`;
|
||||
}
|
||||
})
|
||||
.filter((_) => Boolean(_))
|
||||
.join(",");
|
||||
}
|
||||
|
||||
str += ` FROM ${tableName}`;
|
||||
|
||||
if (genObject.join) {
|
||||
str +=
|
||||
" " +
|
||||
genObject.join
|
||||
.map((join) => {
|
||||
return (
|
||||
join.joinType +
|
||||
" " +
|
||||
join.tableName +
|
||||
" ON " +
|
||||
(() => {
|
||||
if (Array.isArray(join.match)) {
|
||||
return (
|
||||
"(" +
|
||||
join.match
|
||||
.map((mtch) =>
|
||||
generateJoinStr(mtch, join)
|
||||
)
|
||||
.join(" AND ") +
|
||||
")"
|
||||
);
|
||||
} else if (typeof join.match == "object") {
|
||||
return generateJoinStr(join.match, join);
|
||||
}
|
||||
})()
|
||||
);
|
||||
})
|
||||
.join(" ");
|
||||
}
|
||||
|
||||
return str;
|
||||
})();
|
||||
|
||||
if (sqlSearhString) {
|
||||
const stringOperator = genObject?.searchOperator || "AND";
|
||||
queryString += ` WHERE ${sqlSearhString.join(` ${stringOperator} `)} `;
|
||||
}
|
||||
|
||||
if (genObject.order)
|
||||
queryString += ` ORDER BY ${
|
||||
genObject.join
|
||||
? `${tableName}.${genObject.order.field}`
|
||||
: genObject.order.field
|
||||
} ${genObject.order.strategy}`;
|
||||
if (genObject.limit) queryString += ` LIMIT ${genObject.limit}`;
|
||||
|
||||
return {
|
||||
string: queryString,
|
||||
values: sqlSearhValues,
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = sqlGenerator;
|
||||
@@ -0,0 +1,24 @@
|
||||
export = sqlInsertGenerator;
|
||||
/**
|
||||
* @typedef {object} SQLINsertGenReturn
|
||||
* @property {string} query
|
||||
* @property {string[]} values
|
||||
*/
|
||||
/**
|
||||
* @param {object} param0
|
||||
* @param {any[]} param0.data
|
||||
* @param {string} param0.tableName
|
||||
*
|
||||
* @return {SQLINsertGenReturn | undefined}
|
||||
*/
|
||||
declare function sqlInsertGenerator({ tableName, data }: {
|
||||
data: any[];
|
||||
tableName: string;
|
||||
}): SQLINsertGenReturn | undefined;
|
||||
declare namespace sqlInsertGenerator {
|
||||
export { SQLINsertGenReturn };
|
||||
}
|
||||
type SQLINsertGenReturn = {
|
||||
query: string;
|
||||
values: string[];
|
||||
};
|
||||
@@ -0,0 +1,67 @@
|
||||
// @ts-check
|
||||
|
||||
/**
|
||||
* @typedef {object} SQLInsertGenReturn
|
||||
* @property {string} query
|
||||
* @property {string[]} values
|
||||
*/
|
||||
|
||||
/**
|
||||
* @param {object} param0
|
||||
* @param {any[]} param0.data
|
||||
* @param {string} param0.tableName
|
||||
*
|
||||
* @return {SQLInsertGenReturn | undefined}
|
||||
*/
|
||||
function sqlInsertGenerator({ tableName, data }) {
|
||||
try {
|
||||
if (Array.isArray(data) && data?.[0]) {
|
||||
/** @type {string[]} */
|
||||
let insertKeys = [];
|
||||
|
||||
data.forEach((dt) => {
|
||||
const kys = Object.keys(dt);
|
||||
kys.forEach((ky) => {
|
||||
if (!insertKeys.includes(ky)) {
|
||||
insertKeys.push(ky);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
/** @type {string[]} */
|
||||
let queryBatches = [];
|
||||
/** @type {string[]} */
|
||||
let queryValues = [];
|
||||
|
||||
data.forEach((item) => {
|
||||
queryBatches.push(
|
||||
`(${insertKeys
|
||||
.map((ky) => {
|
||||
queryValues.push(
|
||||
item[ky]?.toString()?.match(/./)
|
||||
? item[ky]
|
||||
: null
|
||||
);
|
||||
return "?";
|
||||
})
|
||||
.join(",")})`
|
||||
);
|
||||
});
|
||||
let query = `INSERT INTO ${tableName} (${insertKeys.join(
|
||||
","
|
||||
)}) VALUES ${queryBatches.join(",")}`;
|
||||
|
||||
return {
|
||||
query: query,
|
||||
values: queryValues,
|
||||
};
|
||||
} else {
|
||||
return undefined;
|
||||
}
|
||||
} catch (/** @type {any} */ error) {
|
||||
console.log(`SQL insert gen ERROR: ${error.message}`);
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = sqlInsertGenerator;
|
||||
Reference in New Issue
Block a user