This commit is contained in:
Benjamin Toby
2024-12-06 11:31:24 +01:00
parent 6df20790f4
commit 8ca2779741
153 changed files with 6621 additions and 3899 deletions
+79
View File
@@ -0,0 +1,79 @@
[
{
"title": "VARCHAR",
"name": "VARCHAR",
"value": "0-255",
"argument": true,
"description": "Varchar is simply letters and numbers within the range 0 - 255",
"maxValue": 255
},
{
"title": "TINYINT",
"name": "TINYINT",
"value": "0-100",
"description": "TINYINT means Integers: 0 to 100",
"maxValue": 127
},
{
"title": "SMALLINT",
"name": "SMALLINT",
"value": "0-255",
"description": "SMALLINT means Integers: 0 to 240933",
"maxValue": 32767
},
{
"title": "MEDIUMINT",
"name": "MEDIUMINT",
"value": "0-255",
"description": "MEDIUMINT means Integers: 0 to 1245568545560",
"maxValue": 8388607
},
{
"title": "INT",
"name": "INT",
"value": "0-255",
"description": "INT means Integers: 0 to 12560",
"maxValue": 2147483647
},
{
"title": "BIGINT",
"name": "BIGINT",
"value": "0-255",
"description": "BIGINT means Integers: 0 to 1245569056767568545560",
"maxValue": 2e63
},
{
"title": "TINYTEXT",
"name": "TINYTEXT",
"value": "0-255",
"description": "Text with 255 max characters",
"maxValue": 127
},
{
"title": "TEXT",
"name": "TEXT",
"value": "0-100",
"description": "MEDIUMTEXT is just text with max length 16,777,215",
"maxValue": 127
},
{
"title": "MEDIUMTEXT",
"name": "MEDIUMTEXT",
"value": "0-255",
"description": "MEDIUMTEXT is just text with max length 16,777,215",
"maxValue": 127
},
{
"title": "LONGTEXT",
"name": "LONGTEXT",
"value": "0-255",
"description": "LONGTEXT is just text with max length 4,294,967,295",
"maxValue": 127
},
{
"title": "UUID",
"name": "UUID",
"valueLiteral": "UUID()",
"description": "A Unique ID"
}
]
+45
View File
@@ -0,0 +1,45 @@
[
{
"fieldName": "id",
"dataType": "BIGINT",
"notNullValue": true,
"primaryKey": true,
"autoIncrement": true
},
{
"fieldName": "uuid",
"dataType": "UUID",
"defaultValueLiteral": "UUID()"
},
{
"fieldName": "date_created",
"dataType": "VARCHAR(250)",
"nullValue": true
},
{
"fieldName": "date_created_code",
"dataType": "BIGINT",
"nullValue": true
},
{
"fieldName": "date_created_timestamp",
"dataType": "TIMESTAMP",
"defaultValueLiteral": "CURRENT_TIMESTAMP"
},
{
"fieldName": "date_updated",
"dataType": "VARCHAR(250)",
"nullValue": true
},
{
"fieldName": "date_updated_code",
"dataType": "BIGINT",
"nullValue": true
},
{
"fieldName": "date_updated_timestamp",
"dataType": "TIMESTAMP",
"defaultValueLiteral": "CURRENT_TIMESTAMP",
"onUpdateLiteral": "CURRENT_TIMESTAMP"
}
]
+21
View File
@@ -0,0 +1,21 @@
{
"fieldName": "string",
"dataType": "BIGINT",
"nullValue": true,
"primaryKey": true,
"autoIncrement": true,
"defaultValue": "CURRENT_TIMESTAMP",
"defaultValueLiteral": "CURRENT_TIMESTAMP",
"notNullValue": true,
"foreignKey": {
"foreignKeyName": "Name",
"destinationTableName": "Table Name",
"destinationTableColumnName": "Column Name",
"cascadeDelete": true,
"cascadeUpdate": true
},
"onUpdate": "CURRENT_TIMESTAMP",
"onUpdateLiteral": "CURRENT_TIMESTAMP",
"onDelete": "CURRENT_TIMESTAMP",
"onDeleteLiteral": "CURRENT_TIMESTAMP"
}
+100
View File
@@ -0,0 +1,100 @@
{
"tableName": "users",
"tableFullName": "Users",
"fields": [
{
"fieldName": "first_name",
"dataType": "VARCHAR(100)",
"notNullValue": true
},
{
"fieldName": "last_name",
"dataType": "VARCHAR(100)",
"notNullValue": true
},
{
"fieldName": "email",
"dataType": "VARCHAR(200)",
"notNullValue": true
},
{
"fieldName": "phone",
"dataType": "VARCHAR(50)"
},
{
"fieldName": "user_type",
"dataType": "VARCHAR(20)",
"defaultValue": "default"
},
{
"fieldName": "username",
"dataType": "VARCHAR(100)",
"nullValue": true
},
{
"fieldName": "password",
"dataType": "VARCHAR(250)",
"notNullValue": true
},
{
"fieldName": "image",
"dataType": "VARCHAR(250)",
"defaultValue": "/images/user-preset.png"
},
{
"fieldName": "image_thumbnail",
"dataType": "VARCHAR(250)",
"defaultValue": "/images/user-preset-thumbnail.png"
},
{
"fieldName": "address",
"dataType": "VARCHAR(255)"
},
{
"fieldName": "city",
"dataType": "VARCHAR(50)"
},
{
"fieldName": "state",
"dataType": "VARCHAR(50)"
},
{
"fieldName": "country",
"dataType": "VARCHAR(50)"
},
{
"fieldName": "zip_code",
"dataType": "VARCHAR(50)"
},
{
"fieldName": "social_login",
"dataType": "TINYINT",
"defaultValue": "0"
},
{
"fieldName": "social_platform",
"dataType": "VARCHAR(50)",
"nullValue": true
},
{
"fieldName": "social_id",
"dataType": "VARCHAR(250)",
"nullValue": true
},
{
"fieldName": "more_user_data",
"dataType": "BIGINT",
"defaultValue": "0"
},
{
"fieldName": "verification_status",
"dataType": "TINYINT",
"defaultValue": "0"
},
{
"fieldName": "temp_login_code",
"dataType": "VARCHAR(50)",
"nullValue": true
}
]
}
+93
View File
@@ -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 };
}
};
+100
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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;
}
};
+2 -2
View File
@@ -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);
}
-30
View File
@@ -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") {
-6
View File
@@ -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;
-9
View File
@@ -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
View File
@@ -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
View File
@@ -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,
});
}
}
}
-12
View File
@@ -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;
+61 -13
View File
@@ -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
View File
@@ -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;
+54
View File
@@ -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;
+55
View File
@@ -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;
+5
View File
@@ -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;
+10
View File
@@ -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;
+3
View File
@@ -0,0 +1,3 @@
<p>Please use this code to login</p>
<h2>{{code}}</h2>
<p>Please note that this code expires after 15 minutes</p>
+57
View File
@@ -0,0 +1,57 @@
// @ts-check
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
require("dotenv").config({ path: "./../.env" });
const mysql = require("serverless-mysql");
const grabDbSSL = require("../utils/backend/grabDbSSL");
const connection = mysql({
config: {
host: process.env.DSQL_DB_HOST,
user: process.env.DSQL_DB_USERNAME,
password: process.env.DSQL_DB_PASSWORD,
database: process.env.DSQL_DB_NAME,
charset: "utf8mb4",
ssl: grabDbSSL(),
},
});
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
/**
* # Main DB Handler Function
* @async
*
* @param {object} params
* @param {string} params.query
* @param {string[] | object} [params.values]
* @param {string} [params.database]
*
* @returns {Promise<object|null>}
*/
(async () => {
/**
* Switch Database
*
* @description If a database is provided, switch to it
*/
try {
const result = await connection.query(
"SELECT id,first_name,last_name FROM users LIMIT 3"
);
console.log("Connection Query Success =>", result);
} catch (/** @type {any} */ error) {
console.log("Connection query ERROR =>", error.message);
} finally {
connection.end();
process.exit();
}
})();
+302
View File
@@ -0,0 +1,302 @@
// @ts-check
const path = require("path");
const fs = require("fs");
require("dotenv").config({ path: "./../.env" });
const noDatabaseDbHandler = require("./utils/noDatabaseDbHandler");
const varDatabaseDbHandler = require("./utils/varDatabaseDbHandler");
const createTable = require("./utils/createTable");
const updateTable = require("./utils/updateTable");
const dbHandler = require("./utils/dbHandler");
const EJSON = require("../utils/ejson");
const execFlag = process.argv.find((arg) => arg === "--exec");
/**
* Create database from Schema Function
* ==============================================================================
* @param {object} params - Single object params
* @param {number|string|null} [params.userId] - User ID or null
* @param {string} [params.targetDatabase] - User Database full name
* @param {import("../types").DSQL_DatabaseSchemaType[]} [params.dbSchemaData]
*/
async function createDbFromSchema({ userId, targetDatabase, dbSchemaData }) {
const schemaPath = userId
? path.join(
String(process.env.DSQL_USER_DB_SCHEMA_PATH),
`/user-${userId}/main.json`
)
: path.resolve(__dirname, "../../jsonData/dbSchemas/main.json");
/** @type {import("../types").DSQL_DatabaseSchemaType[] | undefined} */
const dbSchema =
dbSchemaData ||
/** @type {import("../types").DSQL_DatabaseSchemaType[] | undefined} */ (
EJSON.parse(fs.readFileSync(schemaPath, "utf8"))
);
if (!dbSchema) {
console.log("Schema Not Found!");
return;
}
// await createDatabasesFromSchema(dbSchema);
for (let i = 0; i < dbSchema.length; i++) {
/** @type {import("../types").DSQL_DatabaseSchemaType} */
const database = dbSchema[i];
const { dbFullName, tables, dbName, dbSlug, childrenDatabases } =
database;
if (targetDatabase && dbFullName != targetDatabase) {
continue;
}
/** @type {any} */
const dbCheck = await noDatabaseDbHandler(
`SELECT SCHEMA_NAME AS dbFullName FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = '${dbFullName}'`
);
if (dbCheck && dbCheck[0]?.dbFullName) {
// Database Exists
} else {
const newDatabase = await noDatabaseDbHandler(
`CREATE DATABASE IF NOT EXISTS \`${dbFullName}\` CHARACTER SET utf8mb4 COLLATE utf8mb4_bin`
);
}
/**
* Select all tables
* @type {any}
* @description Select All tables in target database
*/
const allTables = await noDatabaseDbHandler(
`SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA='${dbFullName}'`
);
// let tableDropped;
for (let tb = 0; tb < allTables.length; tb++) {
const { TABLE_NAME } = allTables[tb];
/**
* @description Check if TABLE_NAME is part of the tables contained
* in the user schema JSON. If it's not, the table is either deleted
* or the table name has been recently changed
*/
if (
!tables.filter((_table) => _table.tableName === TABLE_NAME)[0]
) {
const oldTableFilteredArray = tables.filter(
(_table) =>
_table.tableNameOld &&
_table.tableNameOld === TABLE_NAME
);
/**
* @description Check if this table has been recently renamed. Rename
* table id true. Drop table if false
*/
if (oldTableFilteredArray && oldTableFilteredArray[0]) {
console.log("Renaming Table");
await varDatabaseDbHandler({
queryString: `RENAME TABLE \`${oldTableFilteredArray[0].tableNameOld}\` TO \`${oldTableFilteredArray[0].tableName}\``,
database: dbFullName,
});
} else {
console.log(`Dropping Table from ${dbFullName}`);
await varDatabaseDbHandler({
queryString: `DROP TABLE \`${TABLE_NAME}\``,
database: dbFullName,
});
const deleteTableEntry = await dbHandler({
query: `DELETE FROM user_database_tables WHERE user_id = ? AND db_slug = ? AND table_slug = ?`,
values: [userId, dbSlug, TABLE_NAME],
database: "datasquirel",
});
}
}
}
const recordedDbEntryArray = userId
? await varDatabaseDbHandler({
database: "datasquirel",
queryString: `SELECT * FROM user_databases WHERE db_full_name = ?`,
queryValuesArray: [dbFullName],
})
: undefined;
const recordedDbEntry = recordedDbEntryArray?.[0];
/**
* @description Iterate through each table and perform table actions
*/
for (let t = 0; t < tables.length; t++) {
const table = tables[t];
const { tableName, fields, indexes } = table;
/**
* @description Check if table exists
* @type {any}
*/
const tableCheck = await varDatabaseDbHandler({
queryString: `
SELECT EXISTS (
SELECT
TABLE_NAME
FROM
information_schema.TABLES
WHERE
TABLE_SCHEMA = ? AND
TABLE_NAME = ?
) AS tableExists`,
queryValuesArray: [dbFullName, table.tableName],
database: dbFullName,
});
////////////////////////////////////////
if (tableCheck && tableCheck[0]?.tableExists > 0) {
/**
* @description Update table if table exists
*/
const updateExistingTable = await updateTable({
dbFullName: dbFullName,
tableName: tableName,
tableNameFull: table.tableFullName,
tableInfoArray: fields,
userId,
dbSchema,
tableIndexes: indexes,
tableIndex: t,
childDb: database.childDatabase || undefined,
recordedDbEntry,
tableSchema: table,
});
if (table.childrenTables && table.childrenTables[0]) {
for (let ch = 0; ch < table.childrenTables.length; ch++) {
const childTable = table.childrenTables[ch];
const updateExistingChildTable = await updateTable({
dbFullName: childTable.dbNameFull,
tableName: childTable.tableName,
tableNameFull: childTable.tableNameFull,
tableInfoArray: fields,
userId,
dbSchema,
tableIndexes: indexes,
clone: true,
childDb: database.childDatabase || undefined,
recordedDbEntry,
tableSchema: table,
});
}
}
////////////////////////////////////////
} else {
////////////////////////////////////////
/**
* @description Create new Table if table doesnt exist
*/
const createNewTable = await createTable({
tableName: tableName,
tableInfoArray: fields,
dbFullName: dbFullName,
dbSchema,
tableSchema: table,
recordedDbEntry,
});
if (indexes && indexes[0]) {
/**
* Handle DATASQUIREL Table Indexes
* ===================================================
* @description Iterate through each datasquirel schema
* table index(if available), and perform operations
*/
if (indexes && indexes[0]) {
for (let g = 0; g < indexes.length; g++) {
const {
indexType,
indexName,
indexTableFields,
alias,
} = indexes[g];
if (!alias?.match(/./)) continue;
/**
* @description Check for existing Index in MYSQL db
*/
try {
/**
* @type {import("../types").DSQL_MYSQL_SHOW_INDEXES_Type[]}
* @description All indexes from MYSQL db
*/ // @ts-ignore
const allExistingIndexes =
await varDatabaseDbHandler({
queryString: `SHOW INDEXES FROM \`${tableName}\``,
database: dbFullName,
});
const existingKeyInDb =
allExistingIndexes.filter(
(indexObject) =>
indexObject.Key_name === alias
);
if (!existingKeyInDb[0])
throw new Error(
"This Index Does not Exist"
);
} catch (error) {
/**
* @description Create new index if determined that it
* doesn't exist in MYSQL db
*/
await varDatabaseDbHandler({
queryString: `CREATE${
indexType?.match(/fullText/i)
? " FULLTEXT"
: ""
} INDEX \`${alias}\` ON ${tableName}(${indexTableFields
?.map((nm) => nm.value)
.map((nm) => `\`${nm}\``)
.join(",")}) COMMENT 'schema_index'`,
database: dbFullName,
});
}
}
}
}
}
}
/**
* @description Check all children databases
*/
if (childrenDatabases?.[0]) {
for (let ch = 0; ch < childrenDatabases.length; ch++) {
const childDb = childrenDatabases[ch];
const { dbFullName } = childDb;
await createDbFromSchema({
userId,
targetDatabase: dbFullName,
});
}
}
}
}
module.exports = createDbFromSchema;
if (execFlag) {
createDbFromSchema({});
}
+7
View File
@@ -0,0 +1,7 @@
// @ts-check
const fs = require("fs");
async function deploy() {}
deploy();
+58
View File
@@ -0,0 +1,58 @@
// @ts-check
require("dotenv").config({ path: "./../.env" });
////////////////////////////////////////
const varDatabaseDbHandler = require("../functions/backend/varDatabaseDbHandler");
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/**
* Grab Schema
*
* @description Grab Schema
*/
varDatabaseDbHandler({
queryString: `SELECT user_database_tables.*,user_databases.db_full_name FROM user_database_tables JOIN user_databases ON user_database_tables.db_id=user_databases.id`,
database: "datasquirel",
}).then(async (tables) => {
for (let i = 0; i < tables.length; i++) {
const table = tables[i];
const {
id,
user_id,
db_id,
db_full_name,
table_name,
table_slug,
table_description,
} = table;
const tableInfo = await varDatabaseDbHandler({
queryString: `SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA='${db_full_name}' AND TABLE_NAME='${table_slug}'`,
database: db_full_name,
});
const updateDbCharset = await varDatabaseDbHandler({
queryString: `ALTER DATABASE ${db_full_name} CHARACTER SET = utf8mb4 COLLATE = utf8mb4_bin;`,
database: db_full_name,
});
const updateEncoding = await varDatabaseDbHandler({
queryString: `ALTER TABLE \`${table_slug}\` CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_bin`,
database: db_full_name,
});
}
process.exit();
});
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
@@ -0,0 +1,10 @@
// @ts-check
const fs = require("fs");
const path = require("path");
const jsonFile = path.resolve(__dirname, "../../jsonData/userPriviledges.json");
const base64File = Buffer.from(fs.readFileSync(jsonFile, "utf8")).toString(
"base64"
);
console.log(base64File);
+79
View File
@@ -0,0 +1,79 @@
// @ts-check
require("dotenv").config({ path: "./../.env" });
const serverError = require("../functions/backend/serverError");
const noDatabaseDbHandler = require("./utils/noDatabaseDbHandler");
////////////////////////////////////////
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/**
* # Create Database From Schema
* @param {object} param0
* @param {string | null} param0.userId
*/
async function createDbFromSchema({ userId }) {
/**
* Grab Schema
*
* @description Grab Schema
*/
try {
const defaultMariadbUserHost = process.env.DSQL_DB_HOST || "127.0.0.1";
const allDatabases = await noDatabaseDbHandler(`SHOW DATABASES`);
const datasquirelUserDatabases = allDatabases.filter(
(/** @type {any} */ database) =>
database.Database.match(/datasquirel_user_/)
);
for (let i = 0; i < datasquirelUserDatabases.length; i++) {
const datasquirelUserDatabase = datasquirelUserDatabases[i];
const { Database } = datasquirelUserDatabase;
const grantDbPriviledges = await noDatabaseDbHandler(
`GRANT ALL PRIVILEGES ON ${Database}.* TO '${process.env.DSQL_DB_FULL_ACCESS_USERNAME}'@'%' WITH GRANT OPTION`
);
const grantRead = await noDatabaseDbHandler(
`GRANT SELECT ON ${Database}.* TO '${process.env.DSQL_DB_READ_ONLY_USERNAME}'@'%'`
);
}
const flushPriviledged = await noDatabaseDbHandler(`FLUSH PRIVILEGES`);
} catch (/** @type {any} */ error) {
serverError({
component: "shell/grantDbPriviledges/main-catch-error",
message: error.message,
user: { id: userId },
});
}
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
process.exit();
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
}
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
const userArg = process.argv[process.argv.indexOf("--user")];
const externalUser = process.argv[process.argv.indexOf("--user") + 1];
createDbFromSchema({ userId: userArg ? externalUser : null });
+79
View File
@@ -0,0 +1,79 @@
const fs = require("fs");
const { exec } = require("child_process");
require("dotenv").config({ path: "./../.env" });
const sourceFile =
process.argv.indexOf("--src") >= 0
? process.argv[process.argv.indexOf("--src") + 1]
: null;
const destinationFile =
process.argv.indexOf("--dst") >= 0
? process.argv[process.argv.indexOf("--dst") + 1]
: null;
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
console.log("Running Less compiler ...");
const sourceFiles = sourceFile.split(",");
const dstFiles = destinationFile.split(",");
for (let i = 0; i < sourceFiles.length; i++) {
const srcFolder = sourceFiles[i];
const dstFile = dstFiles[i];
fs.watch(srcFolder, { recursive: true }, (evtType, prev) => {
if (prev?.match(/\(/) || prev?.match(/\.js$/i)) {
return;
}
let finalSrcPath = `${srcFolder}/main.less`;
let finalDstPath = dstFile;
if (prev?.match(/\[/)) {
const paths = prev.split("/");
const targetPathFull = paths[paths.length - 1];
const targetPath = targetPathFull
.replace(/\[|\]/g, "")
.replace(/\.less/, "");
const destinationFileParentFolder = dstFile.replace(
/\/[^\/]+\.css$/,
""
);
const targetDstFilePath = `${destinationFileParentFolder}/${targetPath}.css`;
finalSrcPath = `${srcFolder}/${targetPathFull}`;
finalDstPath = targetDstFilePath;
}
exec(
`lessc ${finalSrcPath} ${
finalDstPath?.match(/\.css$/)
? finalDstPath
: finalDstPath.replace(/\/$/, "") + "/_main.css"
}`,
(error, stdout, stderr) => {
/** @type {Error} */
if (error) {
console.log("ERROR =>", error.message);
if (!evtType?.match(/change/i) && prev.match(/\[/)) {
fs.unlinkSync(finalDstPath);
}
return;
}
console.log("Less Compilation \x1b[32msuccessful\x1b[0m!");
}
);
});
}
@@ -0,0 +1,7 @@
# Handle Datasquirel MariaDB Users and Grants
## Files
### refreshUsersAndGrants.js
This script checks MariaDB users and updates their privileges using the `mariadb_users` table in `datasquirel` database.
+105
View File
@@ -0,0 +1,105 @@
// @ts-check
const noDatabaseDbHandler = require("../utils/noDatabaseDbHandler");
/**
* @typedef {object} GrantType
* @property {string} database - Database Name
* @property {string} table - Table Name
* @property {string[]} privileges - Privileges
*/
/**
* Handle Grants for Users
* ================================================
* @param {object} params - Single object params
* @param {string} params.username - Username
* @param {string} params.host - Host
* @param {GrantType[]} params.grants - Grants
* @param {string} params.userId
*
* @returns {Promise<boolean>} success
*/
async function handleGrants({ username, host, grants, userId }) {
let success = false;
console.log(`Handling Grants for User =>`, username, host);
if (!username) {
console.log(`No username provided.`);
return success;
}
if (!host) {
console.log(
`No Host provided. \x1b[35m\`--host\`\x1b[0m flag is required`
);
return success;
}
if (!grants) {
console.log(`No grants Array provided.`);
return success;
}
try {
const existingUser = await noDatabaseDbHandler(
`SELECT * FROM mysql.user WHERE User = '${username}' AND Host = '${host}'`
);
const isUserExisting = Boolean(existingUser?.[0]?.User);
if (isUserExisting) {
const userGrants = await noDatabaseDbHandler(
`SHOW GRANTS FOR '${username}'@'${host}'`
);
for (let i = 0; i < userGrants.length; i++) {
const grantObject = userGrants[i];
const grant = grantObject?.[Object.keys(grantObject)[0]];
if (grant?.match(/GRANT .* PRIVILEGES ON .* TO/)) {
const revokeGrantText = grant
.replace(/GRANT/, "REVOKE")
.replace(/ TO /, " FROM ");
const revokePrivilege = await noDatabaseDbHandler(
revokeGrantText
);
}
}
/**
* @type {GrantType[]}
*/
const grantsArray = grants;
for (let i = 0; i < grantsArray.length; i++) {
const grantObject = grantsArray[i];
const { database, table, privileges } = grantObject;
const tableText = table == "*" ? "*" : `\`${table}\``;
const databaseText =
database == "*"
? `\`${process.env.DSQL_USER_DB_PREFIX}${userId}_%\``
: `\`${database}\``;
const privilegesText = privileges.includes("ALL")
? "ALL PRIVILEGES"
: privileges.join(", ");
const grantText = `GRANT ${privilegesText} ON ${databaseText}.${tableText} TO '${username}'@'${host}'`;
const grantPriviledge = await noDatabaseDbHandler(grantText);
}
}
success = true;
} catch (/** @type {any} */ error) {
console.log(`Error in adding SQL user =>`, error.message);
}
return success;
}
module.exports = handleGrants;
+269
View File
@@ -0,0 +1,269 @@
// @ts-check
const path = require("path");
require("dotenv").config({ path: path.resolve(__dirname, "../../../.env") });
const generator = require("generate-password");
const noDatabaseDbHandler = require("../utils/noDatabaseDbHandler");
const dbHandler = require("../utils/dbHandler");
const handleGrants = require("./handleGrants");
const encrypt = require("../../functions/dsql/encrypt");
const decrypt = require("../../functions/dsql/decrypt");
const defaultMariadbUserHost = process.env.DSQL_DB_HOST || "127.0.0.1";
/**
* Refresh Mariadb User Grants
* ===================================================
* @param {object} params
* @param {number | string} [params.userId]
* @param {string} [params.mariadbUserHost]
* @param {string} [params.mariadbUser]
* @param {string | number} [params.sqlUserID]
*/
async function refreshUsersAndGrants({
userId,
mariadbUserHost,
mariadbUser,
sqlUserID,
}) {
/**
* @description Users
* @type {*[] | null}
*/ // @ts-ignore
const users = await dbHandler({
query: `SELECT * FROM users`,
});
if (!users?.[0]) {
process.exit();
}
for (let i = 0; i < users.length; i++) {
const user = users[i];
if (!user) continue;
if (userId && user.id != userId) continue;
try {
const { mariadb_user, mariadb_host, mariadb_pass, id } = user;
const existingUser = await noDatabaseDbHandler(
`SELECT * FROM mysql.user WHERE User = '${mariadb_user}' AND Host = '${mariadb_host}'`
);
const existingMariaDBUserArray =
userId && sqlUserID
? await dbHandler({
query: `SELECT * FROM mariadb_users WHERE id = ? AND user_id = ?`,
values: [sqlUserID, userId],
})
: null;
/**
* @type {import("../../types").MYSQL_mariadb_users_table_def | undefined}
*/
const activeMariadbUserObject = Array.isArray(
existingMariaDBUserArray
)
? existingMariaDBUserArray?.[0]
: undefined;
const isPrimary = activeMariadbUserObject
? String(activeMariadbUserObject.primary)?.match(/1/)
? true
: false
: false;
const isUserExisting = Boolean(existingUser?.[0]?.User);
const isThisPrimaryHost = Boolean(
mariadbUserHost == defaultMariadbUserHost
);
const dslUsername = `dsql_user_${id}`;
const dsqlPassword = activeMariadbUserObject?.password
? activeMariadbUserObject.password
: isUserExisting
? mariadb_pass
: generator.generate({
length: 16,
numbers: true,
symbols: true,
uppercase: true,
exclude: "*#.'`\"",
});
const encryptedPassword = activeMariadbUserObject?.password
? activeMariadbUserObject.password
: isUserExisting
? mariadb_pass
: encrypt({
data: dsqlPassword,
encryptionKey: process.env.DSQL_ENCRYPTION_PASSWORD,
encryptionSalt: process.env.DSQL_ENCRYPTION_SALT,
});
if (
!isUserExisting &&
!sqlUserID &&
!isPrimary &&
!mariadbUserHost &&
!mariadbUser
) {
const createNewUser = await noDatabaseDbHandler(
`CREATE USER IF NOT EXISTS '${dslUsername}'@'${defaultMariadbUserHost}' IDENTIFIED BY '${dsqlPassword}' REQUIRE SSL`
);
console.log("createNewUser", createNewUser);
console.log(
`User ${user.id}: ${user.first_name} ${user.last_name} SQL credentials successfully updated.`
);
const updateUser = await dbHandler({
query: `UPDATE users SET mariadb_user = ?, mariadb_host = ?, mariadb_pass = ? WHERE id = ?`,
values: [
dslUsername,
defaultMariadbUserHost,
encryptedPassword,
user.id,
],
});
}
if (isPrimary) {
const finalHost = mariadbUserHost
? mariadbUserHost
: mariadb_host;
const updateUser = await dbHandler({
query: `UPDATE users SET mariadb_user = ?, mariadb_host = ?, mariadb_pass = ? WHERE id = ?`,
values: [
dslUsername,
finalHost,
encryptedPassword,
user.id,
],
});
}
//////////////////////////////////////////////
//////////////////////////////////////////////
//////////////////////////////////////////////
/**
* @description Handle mariadb_users table
*/
const existingMariadbPrimaryUser = await dbHandler({
query: `SELECT * FROM mariadb_users WHERE user_id = ? AND \`primary\` = 1`,
values: [id],
});
const isPrimaryUserExisting = Boolean(
Array.isArray(existingMariadbPrimaryUser) &&
existingMariadbPrimaryUser?.[0]?.user_id
);
/** @type {import("./handleGrants").GrantType[]} */
const primaryUserGrants = [
{
database: "*",
table: "*",
privileges: ["ALL"],
},
];
if (!isPrimaryUserExisting) {
const insertPrimaryMariadbUser = await dbHandler({
query: `INSERT INTO mariadb_users (user_id, username, password, \`primary\`, grants) VALUES (?, ?, ?, ?, ?)`,
values: [
id,
dslUsername,
encryptedPassword,
"1",
JSON.stringify(primaryUserGrants),
],
});
}
//////////////////////////////////////////////
const existingExtraMariadbUsers = await dbHandler({
query: `SELECT * FROM mariadb_users WHERE user_id = ? AND \`primary\` != '1'`,
values: [id],
});
if (Array.isArray(existingExtraMariadbUsers)) {
for (let i = 0; i < existingExtraMariadbUsers.length; i++) {
const mariadbUser = existingExtraMariadbUsers[i];
const {
user_id,
username,
host,
password,
primary,
grants,
} = mariadbUser;
if (mariadbUser && username != mariadbUser) continue;
if (mariadbUserHost && host != mariadbUserHost) continue;
const decrptedPassword = decrypt({
encryptedString: password,
encryptionKey: process.env.DSQL_ENCRYPTION_PASSWORD,
encryptionSalt: process.env.DSQL_ENCRYPTION_SALT,
});
const existingExtraMariadbUser = await noDatabaseDbHandler(
`SELECT * FROM mysql.user WHERE User = '${username}' AND Host = '${host}'`
);
const isExtraMariadbUserExisting = Boolean(
existingExtraMariadbUser?.[0]?.User
);
if (!isExtraMariadbUserExisting) {
await noDatabaseDbHandler(
`CREATE USER IF NOT EXISTS '${username}'@'${host}' IDENTIFIED BY '${decrptedPassword}' REQUIRE SSL`
);
}
const isGrantHandled = await handleGrants({
username,
host,
grants:
grants && typeof grants == "string"
? JSON.parse(grants)
: [],
userId: String(userId),
});
if (!isGrantHandled) {
console.log(
`Error in handling grants for user ${username}@${host}`
);
}
}
}
//////////////////////////////////////////////
//////////////////////////////////////////////
//////////////////////////////////////////////
} catch (/** @type {any} */ error) {
console.log(`Error in adding SQL user =>`, error.message);
}
}
process.exit();
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
}
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
module.exports = refreshUsersAndGrants;
+105
View File
@@ -0,0 +1,105 @@
// @ts-check
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
require("dotenv").config({ path: "../../.env" });
const generator = require("generate-password");
const noDatabaseDbHandler = require("../utils/noDatabaseDbHandler");
const dbHandler = require("../utils/dbHandler");
const encrypt = require("../../functions/dsql/encrypt");
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/**
* Create database from Schema Function
* ==============================================================================
* @param {object} params - Single object params
* @param {number|string|null} params.userId - User ID or null
*/
async function resetSQLCredentialsPasswords() {
/**
* @description Users
* @type {*[] | null}
*/ // @ts-ignore
const users = await dbHandler({
query: `SELECT * FROM users`,
});
if (!users) {
process.exit();
}
for (let i = 0; i < users.length; i++) {
const user = users[i];
if (!user) continue;
try {
/**
* @type {any[]}
*/ // @ts-ignore
const maridbUsers = await dbHandler({
query: `SELECT * FROM mysql.user WHERE User = 'dsql_user_${user.id}'`,
});
for (let j = 0; j < maridbUsers.length; j++) {
const { User, Host } = maridbUsers[j];
const password = generator.generate({
length: 16,
numbers: true,
symbols: true,
uppercase: true,
exclude: "*#.'`\"",
});
const encryptedPassword = encrypt({
data: password,
encryptionKey: process.env.DSQL_ENCRYPTION_PASSWORD,
encryptionSalt: process.env.DSQL_ENCRYPTION_SALT,
});
await noDatabaseDbHandler(
`SET PASSWORD FOR '${User}'@'${Host}' = PASSWORD('${password}')`
);
if (user.mariadb_user == User && user.mariadb_host == Host) {
const updateUser = await dbHandler({
query: `UPDATE users SET mariadb_pass = ? WHERE id = ?`,
values: [encryptedPassword, user.id],
});
}
console.log(
`User ${user.id}: ${user.first_name} ${user.last_name} Password Updated successfully added.`
);
}
} catch (/** @type {any} */ error) {
console.log(
`Error Updating User ${user.id} Password =>`,
error.message
);
}
}
process.exit();
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
}
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
resetSQLCredentialsPasswords();
+185
View File
@@ -0,0 +1,185 @@
// @ts-check
const path = require("path");
require("dotenv").config({ path: "../../../.env" });
const fs = require("fs");
const { execSync } = require("child_process");
const EJSON = require("../../../utils/ejson");
const DB_HANDLER = require("../../../utils/backend/global-db/DB_HANDLER");
const addDbEntry = require("../../../functions/backend/db/addDbEntry");
const addMariadbUser = require("../../../functions/backend/addMariadbUser");
const updateDbEntry = require("../../../functions/backend/db/updateDbEntry");
const hashPassword = require("../../../functions/dsql/hashPassword");
const tmpDir = process.argv[process.argv.length - 1];
/**
* # Create New User
*/
async function createUser() {
/**
* Validate Form
*
* @description Check if request body is valid
*/
try {
const isTmpDir = Boolean(tmpDir?.match(/\.json$/));
const targetPath = isTmpDir
? path.resolve(process.cwd(), tmpDir)
: path.resolve(__dirname, "./new-user.json");
const userObj = EJSON.parse(fs.readFileSync(targetPath, "utf-8"));
if (typeof userObj !== "object" || Array.isArray(userObj))
throw new Error("User Object Invalid!");
const ROOT_DIR = path.resolve(__dirname, "../../../");
/**
* Validate Form
*
* @description Check if request body is valid
*/
const first_name = userObj.first_name;
const last_name = userObj.last_name;
const email = userObj.email;
const password = userObj.password;
const username = userObj.username;
if (!email?.match(/.*@.*\..*/)) return false;
if (
!first_name?.match(/^[a-zA-Z]+$/) ||
!last_name?.match(/^[a-zA-Z]+$/)
)
return false;
if (password?.match(/ /)) return false;
if (username?.match(/ /)) return false;
let hashedPassword = hashPassword({
encryptionKey: process.env.DSQL_ENCRYPTION_PASSWORD || "",
password: password,
});
let existingUser = await DB_HANDLER(
`SELECT * FROM users WHERE email='${email}'`
);
if (existingUser?.[0]) {
console.log("User Exists");
return false;
}
const newUser = await addDbEntry({
dbFullName: "datasquirel",
tableName: "users",
data: { ...userObj, password: hashedPassword },
});
if (!newUser?.insertId) return false;
/**
* Add a Mariadb User for this User
*/
await addMariadbUser({ userId: newUser.insertId });
const STATIC_ROOT = process.env.DSQL_STATIC_SERVER_DIR;
if (!STATIC_ROOT) {
console.log("Static File ENV not Found!");
throw new Error("No Static Path");
}
/**
* Create new user folder and file
*
* @description Create new user folder and file
*/
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, { recursive: true });
fs.mkdirSync(newUserMediaFolderPath, { recursive: true });
fs.writeFileSync(
`${newUserSchemaFolderPath}/main.json`,
JSON.stringify([]),
"utf8"
);
const imageBasePath = path.join(
STATIC_ROOT,
`images/user-images/user-${newUser.insertId}`
);
if (!fs.existsSync(imageBasePath)) {
fs.mkdirSync(imageBasePath, { recursive: true });
}
let imagePath = path.join(
STATIC_ROOT,
`images/user-images/user-${newUser.insertId}/user-${newUser.insertId}-profile.jpg`
);
let imageThumbnailPath = path.join(
STATIC_ROOT,
`images/user-images/user-${newUser.insertId}/user-${newUser.insertId}-profile-thumbnail.jpg`
);
let prodImageUrl = imagePath.replace(
STATIC_ROOT,
process.env.DSQL_STATIC_HOST || ""
);
let prodImageThumbnailUrl = imageThumbnailPath.replace(
STATIC_ROOT,
process.env.DSQL_STATIC_HOST || ""
);
fs.copyFileSync(
path.join(ROOT_DIR, "/public/images/user-preset.png"),
imagePath
);
fs.copyFileSync(
path.join(ROOT_DIR, "/public/images/user-preset-thumbnail.png"),
imageThumbnailPath
);
execSync(`chmod 644 ${imagePath} ${imageThumbnailPath}`);
const updateImages = await updateDbEntry({
dbFullName: "datasquirel",
tableName: "users",
identifierColumnName: "id",
identifierValue: newUser.insertId,
data: {
image: prodImageUrl,
image_thumbnail: prodImageThumbnailUrl,
},
});
if (isTmpDir) {
try {
fs.unlinkSync(path.resolve(process.cwd(), tmpDir));
} catch (error) {}
}
return true;
} catch (/** @type {any} */ error) {
console.log(`Error in creating user => ${error.message}`);
return false;
}
}
createUser().then((res) => {
if (res) {
console.log("User Creation Success!!!");
} else {
console.log("User Creation Failed!");
}
process.exit();
});
+74
View File
@@ -0,0 +1,74 @@
// @ts-check
const path = require("path");
require("dotenv").config({ path: "../../../.env" });
const fs = require("fs");
const EJSON = require("../../../utils/ejson");
const hashPassword = require("../../../functions/dsql/hashPassword");
const updateDbEntry = require("../../../functions/backend/db/updateDbEntry");
const tmpDir = process.argv[process.argv.length - 1];
/**
* # Create New User
*/
async function createUser() {
/**
* Validate Form
*
* @description Check if request body is valid
*/
try {
const isTmpDir = Boolean(tmpDir?.match(/\.json$/));
const targetPath = isTmpDir
? path.resolve(process.cwd(), tmpDir)
: path.resolve(__dirname, "./update-user.json");
const updateUserObj = EJSON.parse(fs.readFileSync(targetPath, "utf-8"));
if (typeof updateUserObj !== "object" || Array.isArray(updateUserObj))
throw new Error("Update User Object Invalid!");
let hashedPassword = updateUserObj.password
? hashPassword({
encryptionKey: process.env.DSQL_ENCRYPTION_PASSWORD || "",
password: updateUserObj.password,
})
: undefined;
let updatePayload = { ...updateUserObj };
if (hashedPassword) {
updatePayload["password"] = hashedPassword;
}
/** @type {any} */
const newUser = await updateDbEntry({
dbFullName: "datasquirel",
tableName: "users",
data: { ...updatePayload, id: undefined },
identifierColumnName: "id",
identifierValue: updatePayload.id,
});
if (!newUser?.affectedRows) return false;
if (isTmpDir) {
try {
fs.unlinkSync(path.resolve(process.cwd(), tmpDir));
} catch (error) {}
}
return true;
} catch (/** @type {any} */ error) {
console.log(`Error in creating user => ${error.message}`);
return false;
}
}
createUser().then((res) => {
if (res) {
console.log("User Update Success!!!");
} else {
console.log("User Update Failed!");
}
process.exit();
});
@@ -0,0 +1,4 @@
{
"id": "1",
"verification_status": "1"
}
+24
View File
@@ -0,0 +1,24 @@
// @ts-check
const fs = require("fs");
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/**
* Grab Schema
*
* @description Grab Schema
*/
const imageBase64 = fs.readFileSync(
"./../public/images/unique-tokens-icon.png",
"base64"
);
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
+120
View File
@@ -0,0 +1,120 @@
// @ts-check
const fs = require("fs");
require("dotenv").config({ path: "./../.env" });
////////////////////////////////////////
const varDatabaseDbHandler = require("../functions/backend/varDatabaseDbHandler");
const DB_HANDLER = require("../utils/backend/global-db/DB_HANDLER");
/** ****************************************************************************** */
const userId =
process.argv.indexOf("--userId") >= 0
? process.argv[process.argv.indexOf("--userId") + 1]
: null;
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/**
* Grab Schema
*
* @description Grab Schema
*/
async function recoverMainJsonFromDb() {
if (!userId) {
console.log("No user Id provided");
return;
}
const databases = await DB_HANDLER(
`SELECT * FROM user_databases WHERE user_id='${userId}'`
);
const dbWrite = [];
for (let i = 0; i < databases.length; i++) {
const { id, db_name, db_slug, db_full_name, db_image, db_description } =
databases[i];
/** @type {any} */
const dbObject = {
dbName: db_name,
dbSlug: db_slug,
dbFullName: db_full_name,
dbDescription: db_description,
dbImage: db_image,
tables: [],
};
const tables = await DB_HANDLER(
`SELECT * FROM user_database_tables WHERE user_id='${userId}' AND db_id='${id}'`
);
for (let j = 0; j < tables.length; j++) {
const { table_name, table_slug, table_description } = tables[j];
/** @type {any} */
const tableObject = {
tableName: table_slug,
tableFullName: table_name,
fields: [],
indexes: [],
};
const tableFields = await varDatabaseDbHandler({
database: db_full_name,
queryString: `SHOW COLUMNS FROM ${table_slug}`,
});
for (let k = 0; k < tableFields.length; k++) {
const { Field, Type, Null, Default, Key } = tableFields[k];
/** @type {any} */
const fieldObject = {
fieldName: Field,
dataType: Type.toUpperCase(),
};
if (Default?.match(/./) && !Default?.match(/timestamp/i))
fieldObject["defaultValue"] = Default;
if (Key?.match(/pri/i)) {
fieldObject["primaryKey"] = true;
fieldObject["autoIncrement"] = true;
}
if (Default?.match(/timestamp/i))
fieldObject["defaultValueLiteral"] = Default;
if (Null?.match(/yes/i)) fieldObject["nullValue"] = true;
if (Null?.match(/no/i)) fieldObject["notNullValue"] = true;
tableObject.fields.push(fieldObject);
}
dbObject.tables.push(tableObject);
}
dbWrite.push(dbObject);
}
fs.writeFileSync(
`${String(
process.env.DSQL_USER_DB_SCHEMA_PATH
)}/user-${userId}/main.json`,
JSON.stringify(dbWrite, null, 4),
"utf-8"
);
process.exit();
}
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
recoverMainJsonFromDb();
+103
View File
@@ -0,0 +1,103 @@
// @ts-check
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
require("dotenv").config({ path: "./../.env" });
const generator = require("generate-password");
const noDatabaseDbHandler = require("./utils/noDatabaseDbHandler");
const dbHandler = require("./utils/dbHandler");
const encrypt = require("../functions/dsql/encrypt");
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/**
* Create database from Schema Function
* ==============================================================================
* @param {object} params - Single object params
* @param {number|string|null} params.userId - User ID or null
*/
async function resetSQLCredentials() {
/**
* @description Users
* @type {*[] | null}
*/ // @ts-ignore
const users = await dbHandler({
query: `SELECT * FROM users`,
});
if (!users) {
process.exit();
}
for (let i = 0; i < users.length; i++) {
const user = users[i];
if (!user) continue;
const defaultMariadbUserHost = process.env.DSQL_DB_HOST || "127.0.0.1";
try {
const username = `dsql_user_${user.id}`;
const password = generator.generate({
length: 16,
numbers: true,
symbols: true,
uppercase: true,
exclude: "*#.'`\"",
});
const encryptedPassword = encrypt({ data: password });
await noDatabaseDbHandler(`DROP USER IF EXISTS '${username}'@'%'`);
await noDatabaseDbHandler(
`DROP USER IF EXISTS '${username}'@'${defaultMariadbUserHost}'`
);
await noDatabaseDbHandler(
`CREATE USER IF NOT EXISTS '${username}'@'${defaultMariadbUserHost}' IDENTIFIED BY '${password}' REQUIRE SSL`
);
await noDatabaseDbHandler(
`GRANT ALL PRIVILEGES ON \`datasquirel_user_${user.id}_%\`.* TO '${username}'@'${defaultMariadbUserHost}'`
);
await noDatabaseDbHandler(`FLUSH PRIVILEGES`);
const updateUser = await dbHandler({
query: `UPDATE users SET mariadb_user = ?, mariadb_host = ?, mariadb_pass = ? WHERE id = ?`,
values: [
username,
defaultMariadbUserHost,
encryptedPassword,
user.id,
],
});
console.log(
`User ${user.id}: ${user.first_name} ${user.last_name} SQL credentials successfully added.`
);
} catch (/** @type {any} */ error) {
console.log(`Error in adding SQL user =>`, error.message);
}
}
process.exit();
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
}
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
resetSQLCredentials();
+90
View File
@@ -0,0 +1,90 @@
// @ts-check
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
require("dotenv").config({ path: "./../.env" });
const generator = require("generate-password");
const noDatabaseDbHandler = require("./utils/noDatabaseDbHandler");
const dbHandler = require("./utils/dbHandler");
const encrypt = require("../functions/dsql/encrypt");
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/**
* Create database from Schema Function
* ==============================================================================
* @param {object} params - Single object params
* @param {number|string|null} params.userId - User ID or null
*/
async function resetSQLCredentialsPasswords() {
/**
* @description Users
* @type {*[] | null}
*/ // @ts-ignore
const users = await dbHandler({
query: `SELECT * FROM users`,
});
if (!users) {
process.exit();
}
for (let i = 0; i < users.length; i++) {
const user = users[i];
if (!user) continue;
const defaultMariadbUserHost = process.env.DSQL_DB_HOST || "127.0.0.1";
try {
const username = `dsql_user_${user.id}`;
const password = generator.generate({
length: 16,
numbers: true,
symbols: true,
uppercase: true,
exclude: "*#.'`\"",
});
const encryptedPassword = encrypt({ data: password });
await noDatabaseDbHandler(
`SET PASSWORD FOR '${username}'@'${defaultMariadbUserHost}' = PASSWORD('${password}')`
);
const updateUser = await dbHandler({
query: `UPDATE users SET mariadb_pass = ? WHERE id = ?`,
values: [encryptedPassword, user.id],
});
console.log(
`User ${user.id}: ${user.first_name} ${user.last_name} Password Updated successfully added.`
);
} catch (/** @type {any} */ error) {
console.log(
`Error Updating User ${user.id} Password =>`,
error.message
);
}
}
process.exit();
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
}
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
resetSQLCredentialsPasswords();
+93
View File
@@ -0,0 +1,93 @@
// @ts-check
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
require("dotenv").config({ path: "./../.env" });
const generator = require("generate-password");
const noDatabaseDbHandler = require("./utils/noDatabaseDbHandler");
const dbHandler = require("./utils/dbHandler");
const encrypt = require("../functions/dsql/encrypt");
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/**
* Create database from Schema Function
* ==============================================================================
* @param {object} params - Single object params
* @param {number|string|null} params.userId - User ID or null
*/
async function setSQLCredentials() {
/**
* @description Users
* @type {*[] | null}
*/ // @ts-ignore
const users = await dbHandler({
query: `SELECT * FROM users`,
});
if (!users) {
process.exit();
}
for (let i = 0; i < users.length; i++) {
const user = users[i];
if (!user) continue;
if (user.mariadb_user && user.mariadb_pass) {
continue;
}
try {
const username = `dsql_user_${user.id}`;
const password = generator.generate({
length: 16,
numbers: true,
symbols: true,
uppercase: true,
exclude: "*#.'`\"",
});
const encryptedPassword = encrypt({ data: password });
await noDatabaseDbHandler(
`CREATE USER IF NOT EXISTS '${username}'@'127.0.0.1' IDENTIFIED BY '${password}' REQUIRE SSL`
);
await noDatabaseDbHandler(
`GRANT ALL PRIVILEGES ON \`datasquirel\\_user\\_${user.id}\\_%\`.* TO '${username}'@'127.0.0.1'`
);
await noDatabaseDbHandler(`FLUSH PRIVILEGES`);
const updateUser = await dbHandler({
query: `UPDATE users SET mariadb_user = ?, mariadb_host = '127.0.0.1' mariadb_pass = ? WHERE id = ?`,
values: [username, encryptedPassword, user.id],
});
console.log(
`User ${user.id}: ${user.first_name} ${user.last_name} SQL credentials successfully added.`
);
} catch (/** @type {any} */ error) {
console.log(`Error in adding SQL user =>`, error.message);
}
}
process.exit();
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
}
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
setSQLCredentials();
+29
View File
@@ -0,0 +1,29 @@
// @ts-check
const fs = require("fs");
const { exec } = require("child_process");
require("dotenv").config({ path: "./../.env" });
const sourceFile = process.argv.indexOf("--src") >= 0 ? process.argv[process.argv.indexOf("--src") + 1] : null;
const destinationFile = process.argv.indexOf("--dst") >= 0 ? process.argv[process.argv.indexOf("--dst") + 1] : null;
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
console.log("Running Tailwind CSS compiler ...");
fs.watch("./../", (curr, prev) => {
exec(`npx tailwindcss -i ./tailwind/main.css -o ./styles/tailwind.css`, (error, stdout, stderr) => {
if (error) {
console.log("ERROR =>", error.message);
return;
}
console.log("Tailwind CSS Compilation \x1b[32msuccessful\x1b[0m!");
});
});
+58
View File
@@ -0,0 +1,58 @@
// @ts-check
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
require("dotenv").config({ path: "./.env" });
const grabDbSSL = require("../utils/backend/grabDbSSL");
const mysql = require("serverless-mysql");
const connection = mysql({
config: {
host: process.env.DSQL_DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASS,
// database: process.env.DSQL_DB_NAME,
charset: "utf8mb4",
ssl: grabDbSSL(),
},
});
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
/**
* # Main DB Handler Function
* @async
*
* @param {object} params
* @param {string} params.query
* @param {string[] | object} [params.values]
* @param {string} [params.database]
*
* @returns {Promise<object|null>}
*/
(async () => {
/**
* Switch Database
*
* @description If a database is provided, switch to it
*/
try {
const result = await connection.query("SHOW DATABASES");
const parsedResults = JSON.parse(JSON.stringify(result));
console.log("parsedResults =>", parsedResults);
} catch (/** @type {any} */ error) {
console.log("Connection query ERROR =>", error.message);
} finally {
connection.end();
process.exit();
}
})();
+221
View File
@@ -0,0 +1,221 @@
require("dotenv").config({ path: "./../.env" });
const dbEngine = require("@moduletrace/datasquirel/engine");
const http = require("http");
const datasquirel = require("@moduletrace/datasquirel");
`curl http://www.dataden.tech`;
datasquirel
.get({
db: "test",
key: process.env.DATASQUIREL_READ_ONLY_KEY,
query: "SELECT title, slug, body FROM blog_posts",
})
.then((response) => {
console.log(response);
});
// dbEngine.db
// .query({
// dbFullName: "datasquirel",
// dbHost: process.env.DSQL_DB_HOST,
// dbPassword: process.env.DSQL_DB_PASSWORD,
// dbUsername: process.env.DSQL_DB_USERNAME,
// query: "SHOW TABLES",
// })
// .then((res) => {
// console.log("res =>", res);
// });
// run({
// key: "bc057a2cd57922e085739c89b4985e5e676b655d7cc0ba7604659cad0a08c252040120c06597a5d22959a502a44bd816",
// db: "showmerebates",
// query: "SELECT * FROM test_table",
// }).then((res) => {
// console.log("res =>", res);
// });
post({
key: "3115fce7ea7772eda75f8f0e55a1414c5c018b4920f4bc99a2d4d7000bac203c15a7036fd3d7ef55ae67a002d4c757895b5c58ff82079a04ba6d42d23d4353256985090959a58a9af8e03cb277fc7895413e6f28ae11b1cc15329c7f94cdcf9a795f54d6e1d319adc287dc147143e62d",
database: "showmerebates",
query: {
action: "delete",
table: "test_table",
identifierColumnName: "id",
identifierValue: 6,
},
}).then((res) => {
console.log("res =>", res);
});
async function run({ key, db, query }) {
const httpResponse = await new Promise((resolve, reject) => {
http.request(
{
method: "GET",
headers: {
"Content-Type": "application/json",
Authorization: key,
},
hostname: "localhost",
port: 7070,
path: `/api/query/get?db=${db}&query=${query
.replace(/\n|\r|\n\r/g, "")
.replace(/ {2,}/g, " ")
.replace(/ /g, "+")}`,
},
/**
* Callback Function
*
* @description https request callback
*/
(response) => {
var str = "";
response.on("data", function (chunk) {
str += chunk;
});
response.on("end", function () {
resolve(JSON.parse(str));
});
response.on("error", (err) => {
reject(err);
});
}
).end();
});
return httpResponse;
}
/**
* @typedef {Object} PostReturn
* @property {boolean} success - Did the function run successfully?
* @property {(Object[]|string)} [payload=[]] - The Y Coordinate
*/
/**
* @typedef {object} PostDataPayload
* @property {string} action - "insert" | "update" | "delete"
* @property {string} table - Table name(slug) eg "blog_posts"
* @property {string} identifierColumnName - Table identifier field name => eg. "id" OR "email"
* @property {string} identifierValue - Corresponding value of the selected field name => This
* checks identifies a the target row for "update" or "delete". Not needed for "insert"
* @property {object} data - Table insert payload object => This must have keys that match
* table fields
* @property {string?} duplicateColumnName - Duplicate column name to check for
* @property {string?} duplicateColumnValue - Duplicate column value to match. If no "update" param
* provided, function will return null
* @property {boolean?} update - Should the "insert" action update the existing entry if indeed
* the entry with "duplicateColumnValue" exists?
*/
/**
* Post request
* ==============================================================================
* @async
*
* @param {Object} params - Single object passed
* @param {string} params.key - FULL ACCESS API Key
* @param {string} params.database - Database Name
* @param {PostDataPayload} params.query - SQL query String or Request Object
*
* @returns { Promise<PostReturn> } - Return Object
*/
async function post({ key, query, database }) {
/**
* Make https request
*
* @description make a request to datasquirel.com
*/
const httpResponse = await new Promise((resolve, reject) => {
const reqPayloadString = JSON.stringify({
query,
database,
}).replace(/\n|\r|\n\r/gm, "");
try {
JSON.parse(reqPayloadString);
} catch (error) {
console.log(error);
console.log(reqPayloadString);
return {
success: false,
payload: null,
error: "Query object is invalid. Please Check query data values",
};
}
const reqPayload = reqPayloadString;
const httpsRequest = http.request(
{
method: "POST",
headers: {
"Content-Type": "application/json",
"Content-Length": Buffer.from(reqPayload).length,
Authorization: key,
},
hostname: "localhost",
port: 7070,
path: `/api/query/post`,
},
/**
* Callback Function
*
* @description https request callback
*/
(response) => {
var str = "";
response.on("data", function (chunk) {
str += chunk;
});
response.on("end", function () {
try {
resolve(JSON.parse(str));
} catch (error) {
console.log(error.message);
console.log("Fetched Payload =>", str);
resolve({
success: false,
payload: null,
error: error.message,
});
}
});
response.on("error", (err) => {
resolve({
success: false,
payload: null,
error: err.message,
});
});
}
);
httpsRequest.write(reqPayload);
httpsRequest.on("error", (error) => {
console.log("HTTPS request ERROR =>", error.message);
});
httpsRequest.end();
});
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
return httpResponse;
}
+102
View File
@@ -0,0 +1,102 @@
// @ts-check
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
require("dotenv").config({ path: "./../.env" });
const generator = require("generate-password");
const noDatabaseDbHandler = require("./utils/noDatabaseDbHandler");
const dbHandler = require("./utils/dbHandler");
const encrypt = require("../functions/dsql/encrypt");
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/**
* Create database from Schema Function
* ==============================================================================
* @param {object} params - Single object params
* @param {number|string|null} params.userId - User ID or null
*/
async function testSQLEscape() {
/**
* @description Users
* @type {*[] | null}
*/ // @ts-ignore
const users = await dbHandler({
query: `SELECT * FROM users`,
});
if (!users) {
process.exit();
}
for (let i = 0; i < users.length; i++) {
const user = users[i];
if (!user) continue;
const defaultMariadbUserHost = process.env.DSQL_DB_HOST || "127.0.0.1";
try {
const username = `dsql_user_${user.id}`;
const password = generator.generate({
length: 16,
numbers: true,
symbols: true,
uppercase: true,
exclude: "*#.'`\"",
});
const encryptedPassword = encrypt({ data: password });
await noDatabaseDbHandler(
`DROP USER '${username}'@'${defaultMariadbUserHost}'`
);
await noDatabaseDbHandler(
`CREATE USER IF NOT EXISTS '${username}'@'${defaultMariadbUserHost}' IDENTIFIED BY '${password}' REQUIRE SSL`
);
await noDatabaseDbHandler(
`GRANT ALL PRIVILEGES ON \`datasquirel\\_user\\_${user.id}\\_%\`.* TO '${username}'@'${defaultMariadbUserHost}'`
);
await noDatabaseDbHandler(`FLUSH PRIVILEGES`);
const updateUser = await dbHandler({
query: `UPDATE users SET mariadb_user = ?, mariadb_host = ? mariadb_pass = ? WHERE id = ?`,
values: [
username,
defaultMariadbUserHost,
encryptedPassword,
user.id,
],
});
console.log(
`User ${user.id}: ${user.first_name} ${user.last_name} SQL credentials successfully added.`
);
} catch (/** @type {any} */ error) {
console.log(`Error in adding SQL user =>`, error.message);
}
}
process.exit();
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
}
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
testSQLEscape();
+80
View File
@@ -0,0 +1,80 @@
// @ts-check
const DB_HANDLER = require("../utils/backend/global-db/DB_HANDLER");
const fs = require("fs");
require("dotenv").config({ path: "./../.env" });
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
async function updateChildrenTablesOnDb() {
/**
* Grab Schema
*
* @description Grab Schema
*/
try {
const rootDir = String(process.env.DSQL_USER_DB_SCHEMA_PATH);
const userFolders = fs.readdirSync(rootDir);
for (let i = 0; i < userFolders.length; i++) {
const folder = userFolders[i];
const userId = folder.replace(/user-/, "");
const databases = JSON.parse(
fs.readFileSync(`${rootDir}/${folder}/main.json`, "utf-8")
);
for (let j = 0; j < databases.length; j++) {
const db = databases[j];
const dbTables = db.tables;
for (let k = 0; k < dbTables.length; k++) {
const table = dbTables[k];
if (table?.childTable) {
const originTableName = table.childTableName;
const originDbName = table.childTableDbFullName;
const WHERE_CLAUSE = `WHERE user_id='${userId}' AND db_slug='${db.dbSlug}' AND table_slug='${table.tableName}'`;
const existingTableInDb = await DB_HANDLER(
`SELECT * FROM user_database_tables ${WHERE_CLAUSE}`
);
if (existingTableInDb && existingTableInDb[0]) {
const updateChildrenTablesInfo = await DB_HANDLER(
`UPDATE user_database_tables SET child_table='1',child_table_parent_database='${originDbName}',child_table_parent_table='${originTableName}' WHERE id='${existingTableInDb[0].id}'`
);
}
}
}
}
}
} catch (error) {
console.log(error);
}
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
process.exit();
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
}
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
// const userArg = process.argv[process.argv.indexOf("--user")];
// const externalUser = process.argv[process.argv.indexOf("--user") + 1];
updateChildrenTablesOnDb();
+60
View File
@@ -0,0 +1,60 @@
// @ts-check
require("dotenv").config({ path: "./../.env" });
////////////////////////////////////////
const varDatabaseDbHandler = require("../functions/backend/varDatabaseDbHandler");
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/**
* Grab Schema
*
* @description Grab Schema
*/
varDatabaseDbHandler({
queryString: `SELECT user_database_tables.*,user_databases.db_full_name FROM user_database_tables JOIN user_databases ON user_database_tables.db_id=user_databases.id`,
database: "datasquirel",
}).then(async (tables) => {
for (let i = 0; i < tables.length; i++) {
const table = tables[i];
const {
id,
user_id,
db_id,
db_full_name,
table_name,
table_slug,
table_description,
} = table;
const tableInfo = await varDatabaseDbHandler({
queryString: `SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA='${db_full_name}' AND TABLE_NAME='${table_slug}'`,
database: db_full_name,
});
const updateCreationDateTimestamp = await varDatabaseDbHandler({
queryString: `ALTER TABLE \`${table_slug}\` MODIFY COLUMN date_created_timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP`,
database: db_full_name,
});
const updateDateTimestamp = await varDatabaseDbHandler({
queryString: `ALTER TABLE \`${table_slug}\` MODIFY COLUMN date_updated_timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP`,
database: db_full_name,
});
console.log("Date Updated Column updated");
}
process.exit();
});
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
+56
View File
@@ -0,0 +1,56 @@
// @ts-check
require("dotenv").config({ path: "./../.env" });
const serverError = require("../functions/backend/serverError");
const varDatabaseDbHandler = require("./utils/varDatabaseDbHandler");
const DB_HANDLER = require("../utils/backend/global-db/DB_HANDLER");
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/**
* Grab Schema
*
* @description Grab Schema
*/
varDatabaseDbHandler({
queryString: `SELECT DISTINCT db_id FROM user_database_tables`,
database: "datasquirel",
}).then(async (tables) => {
// console.log(tables);
// process.exit();
for (let i = 0; i < tables.length; i++) {
const table = tables[i];
try {
const { db_id } = table;
const dbSlug = await DB_HANDLER(
`SELECT db_slug FROM user_databases WHERE id='${db_id}'`
);
const updateTableSlug = await DB_HANDLER(
`UPDATE user_database_tables SET db_slug='${dbSlug[0].db_slug}' WHERE db_id='${db_id}'`
);
} catch (/** @type {any} */ error) {
serverError({
component:
"shell/updateDbSlugsForTableRecords/main-catch-error",
message: error.message,
user: {},
});
}
}
process.exit();
});
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
+70
View File
@@ -0,0 +1,70 @@
// @ts-check
require("dotenv").config({ path: "./../.env" });
const grabDbSSL = require("../utils/backend/grabDbSSL");
const mysql = require("serverless-mysql");
const connection = mysql({
config: {
host: process.env.DSQL_DB_HOST,
user: process.env.DSQL_DB_USERNAME,
password: process.env.DSQL_DB_PASSWORD,
database: process.env.DSQL_DB_NAME,
charset: "utf8mb4",
ssl: grabDbSSL(),
},
});
/**
* # Main DB Handler Function
* @async
*
* @param {object} params
* @param {string} params.query
* @param {string[] | object} [params.values]
* @param {string} [params.database]
*
* @returns {Promise<object|null>}
*/
(async () => {
/**
* Switch Database
*
* @description If a database is provided, switch to it
*/
try {
const result = await connection.query(
"SELECT user,host,ssl_type FROM mysql.user"
);
const parsedResults = JSON.parse(JSON.stringify(result));
for (let i = 0; i < parsedResults.length; i++) {
const user = parsedResults[i];
if (
user.User !== process.env.DSQL_DB_READ_ONLY_USERNAME ||
user.User !== process.env.DSQL_DB_FULL_ACCESS_USERNAME ||
!user.User?.match(/dsql_user_.*/i)
) {
continue;
}
const { User, Host, ssl_type } = user;
if (ssl_type === "ANY") {
continue;
}
const addUserSSL = await connection.query(
`ALTER USER '${User}'@'${Host}' REQUIRE SSL`
);
console.log(`addUserSSL => ${User}@${Host}`, addUserSSL);
}
} catch (/** @type {any} */ error) {
console.log("Connection query ERROR =>", error.message);
} finally {
connection.end();
process.exit();
}
})();
+59
View File
@@ -0,0 +1,59 @@
// @ts-check
/**
* Convert Camel Joined Text to Camel Spaced Text
* ==============================================================================
* @description this function takes a camel cased text without spaces, and returns
* a camel-case-spaced text
*
* @param {string} text - text string without spaces
*
* @returns {string | null}
*/
module.exports = function camelJoinedtoCamelSpace(text) {
if (!text?.match(/./)) {
return "";
}
if (text?.match(/ /)) {
return text;
}
if (text) {
let textArray = text.split("");
let capIndexes = [];
for (let i = 0; i < textArray.length; i++) {
const char = textArray[i];
if (i === 0) continue;
if (char.match(/[A-Z]/)) {
capIndexes.push(i);
}
}
let textChunks = [
`${textArray[0].toUpperCase()}${text.substring(1, capIndexes[0])}`,
];
for (let j = 0; j < capIndexes.length; j++) {
const capIndex = capIndexes[j];
if (capIndex === 0) continue;
const startIndex = capIndex + 1;
const endIndex = capIndexes[j + 1];
textChunks.push(
`${textArray[capIndex].toUpperCase()}${text.substring(
startIndex,
endIndex
)}`
);
}
return textChunks.join(" ");
} else {
return null;
}
};
+212
View File
@@ -0,0 +1,212 @@
// @ts-check
const varDatabaseDbHandler = require("./varDatabaseDbHandler");
const generateColumnDescription = require("./generateColumnDescription");
const supplementTable = require("./supplementTable");
const dbHandler = require("./dbHandler");
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/**
*
* @param {object} params
* @param {string} params.dbFullName
* @param {string} params.tableName
* @param {any[]} params.tableInfoArray
* @param {import("../../types").DSQL_DatabaseSchemaType[]} [params.dbSchema]
* @param {import("../../types").DSQL_TableSchemaType} [params.tableSchema]
* @param {any} [params.recordedDbEntry]
* @param {boolean} [params.clone] - Is this a newly cloned table?
* @returns
*/
module.exports = async function createTable({
dbFullName,
tableName,
tableInfoArray,
dbSchema,
clone,
tableSchema,
recordedDbEntry,
}) {
/**
* Format tableInfoArray
*
* @description Format tableInfoArray
*/
const finalTable = supplementTable({ tableInfoArray: tableInfoArray });
/**
* Grab Schema
*
* @description Grab Schema
*/
const createTableQueryArray = [];
createTableQueryArray.push(`CREATE TABLE IF NOT EXISTS \`${tableName}\` (`);
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
try {
if (!recordedDbEntry) {
throw new Error("Recorded Db entry not found!");
}
const existingTable = await varDatabaseDbHandler({
database: "datasquirel",
queryString: `SELECT * FROM user_database_tables WHERE db_id = ? AND table_slug = ?`,
queryValuesArray: [recordedDbEntry.id, tableSchema?.tableName],
});
/** @type {import("../../types").MYSQL_user_database_tables_table_def} */
const table = existingTable?.[0];
if (!table?.id) {
const newTableEntry = await dbHandler({
query: `INSERT INTO user_database_tables SET ?`,
values: {
user_id: recordedDbEntry.user_id,
db_id: recordedDbEntry.id,
db_slug: recordedDbEntry.db_slug,
table_name: tableSchema?.tableFullName,
table_slug: tableSchema?.tableName,
child_table: tableSchema?.childTable ? "1" : null,
child_table_parent_database:
tableSchema?.childTableDbFullName || null,
child_table_parent_table:
tableSchema?.childTableName || null,
date_created: Date(),
date_created_code: Date.now(),
date_updated: Date(),
date_updated_code: Date.now(),
},
database: "datasquirel",
});
}
} catch (error) {}
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
let primaryKeySet = false;
let foreignKeys = [];
////////////////////////////////////////
for (let i = 0; i < finalTable.length; i++) {
const column = finalTable[i];
const {
fieldName,
dataType,
nullValue,
primaryKey,
autoIncrement,
defaultValue,
defaultValueLiteral,
foreignKey,
updatedField,
onUpdate,
onUpdateLiteral,
onDelete,
onDeleteLiteral,
defaultField,
encrypted,
json,
newTempField,
notNullValue,
originName,
plainText,
pattern,
patternFlags,
richText,
} = column;
if (foreignKey) {
foreignKeys.push({
fieldName: fieldName,
...foreignKey,
});
}
let { fieldEntryText, newPrimaryKeySet } = generateColumnDescription({
columnData: column,
primaryKeySet: primaryKeySet,
});
primaryKeySet = newPrimaryKeySet;
////////////////////////////////////////
const comma = (() => {
if (foreignKeys[0]) return ",";
if (i === finalTable.length - 1) return "";
return ",";
})();
createTableQueryArray.push(" " + fieldEntryText + comma);
////////////////////////////////////////
}
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
if (foreignKeys[0]) {
foreignKeys.forEach((foreighKey, index, array) => {
const {
fieldName,
destinationTableName,
destinationTableColumnName,
cascadeDelete,
cascadeUpdate,
foreignKeyName,
} = foreighKey;
const comma = (() => {
if (index === foreignKeys.length - 1) return "";
return ",";
})();
createTableQueryArray.push(
` CONSTRAINT \`${foreignKeyName}\` FOREIGN KEY (\`${fieldName}\`) REFERENCES \`${destinationTableName}\`(${destinationTableColumnName})${
cascadeDelete ? " ON DELETE CASCADE" : ""
}${cascadeUpdate ? " ON UPDATE CASCADE" : ""}${comma}`
);
});
}
////////////////////////////////////////
createTableQueryArray.push(
`) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;`
);
const createTableQuery = createTableQueryArray.join("\n");
////////////////////////////////////////
const newTable = await varDatabaseDbHandler({
queryString: createTableQuery,
database: dbFullName,
});
return newTable;
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
};
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
+118
View File
@@ -0,0 +1,118 @@
// @ts-check
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
const fs = require("fs");
const path = require("path");
const mysql = require("serverless-mysql");
const grabDbSSL = require("../../utils/backend/grabDbSSL");
let connection = mysql({
config: {
host: process.env.DSQL_DB_HOST,
user: process.env.DSQL_DB_USERNAME,
password: process.env.DSQL_DB_PASSWORD,
database: process.env.DSQL_DB_NAME,
charset: "utf8mb4",
ssl: grabDbSSL(),
},
});
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
/**
* # Main DB Handler Function
* @async
*
* @param {object} params
* @param {string} params.query
* @param {string[] | object} [params.values]
* @param {string} [params.database]
*
* @returns {Promise<any[] | object | null>}
*/
module.exports = async function dbHandler({ query, values, database }) {
/**
* Switch Database
*
* @description If a database is provided, switch to it
*/
let isDbCorrect = true;
if (database) {
connection = mysql({
config: {
host: process.env.DSQL_DB_HOST,
user: process.env.DSQL_DB_USERNAME,
password: process.env.DSQL_DB_PASSWORD,
database: database,
charset: "utf8mb4",
ssl: grabDbSSL(),
},
});
}
if (!isDbCorrect) {
console.log(
"Shell Db Handler ERROR in switching Database! Operation Failed!"
);
return null;
}
/**
* Declare variables
*
* @description Declare "results" variable
*/
let results;
/**
* Fetch from db
*
* @description Fetch data from db if no cache
*/
try {
if (query && values) {
results = await connection.query(query, values);
} else {
results = await connection.query(query);
}
/** ********************* Clean up */
await connection.end();
} catch (/** @type {any} */ error) {
if (process.env.FIRST_RUN) {
return null;
}
console.log("ERROR in dbHandler =>", error.message);
console.log(error);
console.log(connection.config());
fs.appendFileSync(
path.resolve(__dirname, "../.tmp/dbErrorLogs.txt"),
JSON.stringify(error, null, 4) + "\n" + Date() + "\n\n\n",
"utf8"
);
results = null;
}
/**
* Return results
*
* @description Return results add to cache if "req" param is passed
*/
if (results) {
return JSON.parse(JSON.stringify(results));
} else {
return null;
}
};
+108
View File
@@ -0,0 +1,108 @@
// @ts-check
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/**
* Generate SQL text for Field
* ==============================================================================
* @param {object} params - Single object params
* @param {import("../../types").DSQL_FieldSchemaType} params.columnData - Field object
* @param {boolean} [params.primaryKeySet] - Table Name(slug)
*
* @returns {{ fieldEntryText: string, newPrimaryKeySet: boolean }}
*/
module.exports = function generateColumnDescription({
columnData,
primaryKeySet,
}) {
/**
* Format tableInfoArray
*
* @description Format tableInfoArray
*/
const {
fieldName,
dataType,
nullValue,
primaryKey,
autoIncrement,
defaultValue,
defaultValueLiteral,
foreignKey,
updatedField,
onUpdate,
onUpdateLiteral,
onDelete,
onDeleteLiteral,
defaultField,
encrypted,
json,
newTempField,
notNullValue,
originName,
plainText,
pattern,
patternFlags,
richText,
} = columnData;
let fieldEntryText = "";
fieldEntryText += `\`${fieldName}\` ${dataType}`;
////////////////////////////////////////
// if (String(fieldEntryText).match(/ UUID$/)) {
// fieldEntryText += ` DEFAULT UUID()`;
// } else
if (nullValue) {
fieldEntryText += " DEFAULT NULL";
} else if (defaultValueLiteral) {
fieldEntryText += ` DEFAULT ${defaultValueLiteral}`;
} else if (defaultValue) {
if (String(defaultValue).match(/uuid\(\)/i)) {
fieldEntryText += ` DEFAULT UUID()`;
} else {
fieldEntryText += ` DEFAULT '${defaultValue}'`;
}
} else if (notNullValue) {
fieldEntryText += ` NOT NULL`;
}
////////////////////////////////////////
if (onUpdateLiteral) {
fieldEntryText += ` ON UPDATE ${onUpdateLiteral}`;
}
////////////////////////////////////////
if (primaryKey && !primaryKeySet) {
fieldEntryText += " PRIMARY KEY";
primaryKeySet = true;
}
////////////////////////////////////////
if (autoIncrement) {
fieldEntryText += " AUTO_INCREMENT";
primaryKeySet = true;
}
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
return { fieldEntryText, newPrimaryKeySet: primaryKeySet || false };
};
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
+45
View File
@@ -0,0 +1,45 @@
// @ts-check
const dbHandler = require("./dbHandler");
/**
* Create database from Schema Function
* ==============================================================================
* @param {string} queryString - Query String
* @returns {Promise<any>}
*/
module.exports = async function noDatabaseDbHandler(queryString) {
/**
* Declare variables
*
* @description Declare "results" variable
*/
let results;
/**
* Fetch from db
*
* @description Fetch data from db if no cache
*/
try {
/** ********************* Run Query */
results = await dbHandler({ query: queryString });
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
} catch (/** @type {any} */ error) {
console.log("ERROR in noDatabaseDbHandler =>", error.message);
}
/**
* Return results
*
* @description Return results add to cache if "req" param is passed
*/
if (results) {
return results;
} else {
return null;
}
};
+18
View File
@@ -0,0 +1,18 @@
// @ts-check
module.exports = function slugToCamelTitle(/** @type {String} */ text) {
if (text) {
let addArray = text.split("-").filter((item) => item !== "");
let camelArray = addArray.map((item) => {
return (
item.substr(0, 1).toUpperCase() + item.substr(1).toLowerCase()
);
});
let parsedAddress = camelArray.join(" ");
return parsedAddress;
} else {
return null;
}
};
+58
View File
@@ -0,0 +1,58 @@
// @ts-check
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/**
*
* @param {object} param0
* @param {import("../../types").DSQL_FieldSchemaType[]} param0.tableInfoArray
* @returns
*/
module.exports = function supplementTable({ tableInfoArray }) {
/**
* Format tableInfoArray
*
* @description Format tableInfoArray
*/
let finalTableArray = tableInfoArray;
const defaultFields = require("../../../package-shared/data/defaultFields.json");
////////////////////////////////////////
let primaryKeyExists = finalTableArray.filter(
(_field) => _field.primaryKey
);
////////////////////////////////////////
defaultFields.forEach((field) => {
let fieldExists = finalTableArray.filter(
(_field) => _field.fieldName === field.fieldName
);
if (fieldExists && fieldExists[0]) {
return;
} else if (field.fieldName === "id" && !primaryKeyExists[0]) {
finalTableArray.unshift(field);
} else {
finalTableArray.push(field);
}
});
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
return finalTableArray;
};
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
File diff suppressed because it is too large Load Diff
+71
View File
@@ -0,0 +1,71 @@
// @ts-check
const fs = require("fs");
const dbHandler = require("./dbHandler");
/**
* DB handler for specific database
* ==============================================================================
* @async
* @param {object} params - Single object params
* @param {string} params.queryString - SQL string
* @param {string[]} [params.queryValuesArray] - Values Array
* @param {string} [params.database] - Database name
* @param {import("../../types").DSQL_TableSchemaType} [params.tableSchema] - Table schema
* @returns {Promise<any>}
*/
module.exports = async function varDatabaseDbHandler({
queryString,
queryValuesArray,
database,
tableSchema,
}) {
/**
* Declare variables
*
* @description Declare "results" variable
*/
let results;
/**
* Fetch from db
*
* @description Fetch data from db if no cache
*/
try {
if (
queryString &&
queryValuesArray &&
Array.isArray(queryValuesArray) &&
queryValuesArray[0]
) {
results = await dbHandler({
query: queryString,
values: queryValuesArray,
database,
});
} else {
results = await dbHandler({
query: queryString,
database,
});
}
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
} catch (/** @type {any} */ error) {
console.log("Shell Vardb Error =>", error.message);
}
/**
* Return results
*
* @description Return results add to cache if "req" param is passed
*/
return results;
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
};
+130 -5
View File
@@ -173,6 +173,7 @@ export interface PackageUserLoginRequestBody {
token?: boolean;
social?: boolean;
dbSchema?: DSQL_DatabaseSchemaType;
skipPassword?: boolean;
}
export interface PackageUserLoginLocalBody {
@@ -184,6 +185,7 @@ export interface PackageUserLoginLocalBody {
token?: boolean;
social?: boolean;
dbSchema?: DSQL_DatabaseSchemaType;
skipPassword?: boolean;
}
type Request = IncomingMessage;
@@ -212,7 +214,7 @@ export interface SerializeQueryParams {
// @ts-check
export interface DATASQUIREL_LoggedInUser {
export type DATASQUIREL_LoggedInUser = {
id?: number;
first_name: string;
last_name: string;
@@ -220,7 +222,6 @@ export interface DATASQUIREL_LoggedInUser {
phone?: string;
user_type?: string;
username?: string;
password: string;
image?: string;
image_thumbnail?: string;
address?: string;
@@ -237,7 +238,7 @@ export interface DATASQUIREL_LoggedInUser {
is_admin?: number;
admin_level?: number;
admin_permissions?: string;
uuid: string;
uuid?: string;
temp_login_code?: string;
date_created?: string;
date_created_code?: number;
@@ -249,7 +250,9 @@ export interface DATASQUIREL_LoggedInUser {
logged_in_status?: boolean;
date?: number;
more_data?: any;
}
} & {
[key: string]: any;
};
export interface AuthenticatedUser {
success: boolean;
@@ -307,7 +310,7 @@ export interface GetUserFunctionReturn {
image: string;
image_thumbnail: string;
verification_status: [number];
};
} | null;
}
export interface ReauthUserFunctionReturn {
@@ -348,6 +351,9 @@ export type GetSchemaAPIParam = GetSchemaRequestQuery &
export interface PostReturn {
success: boolean;
payload?: Object[] | string | PostInsertReturn;
msg?: string;
error?: any;
schema?: DSQL_TableSchemaType;
}
export interface PostDataPayload {
@@ -1251,3 +1257,122 @@ export type MariadbRemoteServerUserObject = {
password: string;
host: string;
};
export type APILoginFunctionParams = {
encryptionKey: string;
email: string;
username?: string;
password?: string;
database: string;
additionalFields?: string[];
email_login?: boolean;
email_login_code?: string;
email_login_field?: string;
token?: boolean;
skipPassword?: boolean;
social?: boolean;
};
export type APILoginFunctionReturn = {
success: boolean;
msg?: string;
payload?: DATASQUIREL_LoggedInUser | null;
userId?: number | string;
};
export type APILoginFunction = (
params: APILoginFunctionParams
) => Promise<APILoginFunctionReturn>;
export type APICreateUserFunctionParams = {
encryptionKey: string;
payload: any;
database: string;
userId?: string | number;
};
export type APICreateUserFunction = (
params: APICreateUserFunctionParams
) => Promise<AddUserFunctionReturn>;
/**
* API Get User Function
*/
export type APIGetUserFunctionParams = {
fields: string[];
dbFullName: string;
userId: string | number;
};
export type APIGetUserFunction = (
params: APIGetUserFunctionParams
) => Promise<GetUserFunctionReturn>;
/**
* API Google Login Function
*/
export type APIGoogleLoginFunctionParams = {
clientId: string;
token: string;
database: string;
userId: string | number;
additionalFields?: { [key: string]: any };
res: any;
};
export type APIGoogleLoginFunctionReturn = {
dsqlUserId?: number | string;
} & HandleSocialDbFunctionReturn;
export type APIGoogleLoginFunction = (
params: APIGoogleLoginFunctionParams
) => Promise<APIGoogleLoginFunctionReturn>;
/**
* Handle Social DB Function
*/
export type HandleSocialDbFunctionParams = {
database?: string;
social_id: string | number;
email: string;
social_platform: string;
payload: any;
res?: ServerResponse;
invitation?: any;
supEmail?: string;
additionalFields?: object;
};
export type HandleSocialDbFunctionReturn = {
success: boolean;
user?: null;
msg?: string;
social_id?: string | number;
social_platform?: string;
payload?: any;
alert?: boolean;
newUser?: any;
error?: any;
} | null;
/**
* Handle Social User Auth on Datasquirel Database
* ==============================================================================
*
* @description This function handles all social login logic after the social user
* has been authenticated and userpayload is present. The payload MUST contain the
* specified fields because this funciton will create a new user if the authenticated
* user does not exist.
*
* @param {HandleSocialDbFunctionParams} params - function parameters inside an object
*
* @returns {Promise<HandleSocialDbFunctionReturn>} - Response object
*/
export type HandleSocialDbFunction = (
params: HandleSocialDbFunctionParams
) => Promise<HandleSocialDbFunctionReturn>;
export type ApiReauthUserReturn = {
success: boolean;
payload?: { [key: string]: any } | null;
msg?: string;
userId?: string | number;
};
@@ -0,0 +1,54 @@
// @ts-check
/**
* Convert Camel Joined Text to Camel Spaced Text
* ==============================================================================
* @description this function takes a camel cased text without spaces, and returns
* a camel-case-spaced text
*
* @param {string} text - text string without spaces
*
* @returns {string | null}
*/
function camelJoinedtoCamelSpace(text) {
if (!text?.match(/./)) {
return "";
}
if (text?.match(/ /)) {
return text;
}
if (text) {
let textArray = text.split("");
let capIndexes = [];
for (let i = 0; i < textArray.length; i++) {
const char = textArray[i];
if (i === 0) continue;
if (char.match(/[A-Z]/)) {
capIndexes.push(i);
}
}
let textChunks = [`${textArray[0].toUpperCase()}${text.substring(1, capIndexes[0])}`];
for (let j = 0; j < capIndexes.length; j++) {
const capIndex = capIndexes[j];
if (capIndex === 0) continue;
const startIndex = capIndex + 1;
const endIndex = capIndexes[j + 1];
textChunks.push(`${textArray[capIndex].toUpperCase()}${text.substring(startIndex, endIndex)}`);
}
return textChunks.join(" ");
} else {
return null;
}
}
module.exports = camelJoinedtoCamelSpace;
+16
View File
@@ -0,0 +1,16 @@
// @ts-check
const mysql = require("mysql");
/**
* @param {mysql.Connection} connection - the active MYSQL connection
*/
function endConnection(connection) {
if (connection.state !== "disconnected") {
connection.end((err) => {
console.log(err?.message);
});
}
}
module.exports = endConnection;
@@ -0,0 +1,80 @@
// @ts-check
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/**
* Generate SQL text for Field
* ==============================================================================
* @param {object} params - Single object params
* @param {import("../types").DSQL_FieldSchemaType} params.columnData - Field object
* @param {boolean} [params.primaryKeySet] - Table Name(slug)
*
* @returns {{fieldEntryText: string, newPrimaryKeySet: boolean}}
*/
module.exports = function generateColumnDescription({
columnData,
primaryKeySet,
}) {
/**
* Format tableInfoArray
*
* @description Format tableInfoArray
*/
const {
fieldName,
dataType,
nullValue,
primaryKey,
autoIncrement,
defaultValue,
defaultValueLiteral,
notNullValue,
} = columnData;
let fieldEntryText = "";
fieldEntryText += `\`${fieldName}\` ${dataType}`;
////////////////////////////////////////
if (nullValue) {
fieldEntryText += " DEFAULT NULL";
} else if (defaultValueLiteral) {
fieldEntryText += ` DEFAULT ${defaultValueLiteral}`;
} else if (defaultValue) {
fieldEntryText += ` DEFAULT '${defaultValue}'`;
} else if (notNullValue) {
fieldEntryText += ` NOT NULL`;
}
////////////////////////////////////////
if (primaryKey && !primaryKeySet) {
fieldEntryText += " PRIMARY KEY";
primaryKeySet = true;
}
////////////////////////////////////////
if (autoIncrement) {
fieldEntryText += " AUTO_INCREMENT";
primaryKeySet = true;
}
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
return { fieldEntryText, newPrimaryKeySet: primaryKeySet || false };
};
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
+23
View File
@@ -0,0 +1,23 @@
// @ts-check
/**
*
* @param {string} text
* @returns
*/
module.exports = function slugToCamelTitle(text) {
if (text) {
let addArray = text.split("-").filter((item) => item !== "");
let camelArray = addArray.map((item) => {
return (
item.substr(0, 1).toUpperCase() + item.substr(1).toLowerCase()
);
});
let parsedAddress = camelArray.join(" ");
return parsedAddress;
} else {
return null;
}
};