Updates
This commit is contained in:
@@ -0,0 +1,66 @@
|
||||
// @ts-check
|
||||
|
||||
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");
|
||||
|
||||
/**
|
||||
* # Add Mariadb User
|
||||
*
|
||||
* @description this function adds a Mariadb user to the database server
|
||||
*
|
||||
* @param {object} params - parameters object *
|
||||
* @param {number | string} params.userId - invited user object
|
||||
*
|
||||
* @returns {Promise<any>} new user auth object payload
|
||||
*/
|
||||
module.exports = async function addMariadbUser({ userId }) {
|
||||
try {
|
||||
const defaultMariadbUserHost = process.env.DSQL_DB_HOST || "127.0.0.1";
|
||||
|
||||
const username = `dsql_user_${userId}`;
|
||||
const password = generator.generate({
|
||||
length: 16,
|
||||
numbers: true,
|
||||
symbols: true,
|
||||
uppercase: true,
|
||||
exclude: "*#.'`\"",
|
||||
});
|
||||
const encryptedPassword = encrypt(password);
|
||||
|
||||
await NO_DB_HANDLER(
|
||||
`CREATE USER IF NOT EXISTS '${username}'@'127.0.0.1' IDENTIFIED BY '${password}' REQUIRE SSL`
|
||||
);
|
||||
|
||||
const updateUser = await DB_HANDLER(
|
||||
`UPDATE users SET mariadb_user = ?, mariadb_host = '127.0.0.1', mariadb_pass = ? WHERE id = ?`,
|
||||
[username, encryptedPassword, userId]
|
||||
);
|
||||
|
||||
const addMariadbUser = await addDbEntry({
|
||||
tableName: "mariadb_users",
|
||||
data: {
|
||||
user_id: userId,
|
||||
username,
|
||||
host: defaultMariadbUserHost,
|
||||
password: encryptedPassword,
|
||||
primary: "1",
|
||||
grants: '[{"database":"*","table":"*","privileges":["ALL"]}]',
|
||||
},
|
||||
dbContext: "Master",
|
||||
});
|
||||
|
||||
console.log(`User ${userId} SQL credentials successfully added.`);
|
||||
} catch (/** @type {any} */ error) {
|
||||
console.log(
|
||||
`Error in adding SQL user in 'addMariadbUser' function =>`,
|
||||
error.message
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
@@ -0,0 +1,43 @@
|
||||
// @ts-check
|
||||
|
||||
const fs = require("fs");
|
||||
const decrypt = require("./decrypt");
|
||||
|
||||
/** @type {import("../../types").CheckApiCredentialsFn} */
|
||||
const grabApiCred = ({ key, database, table }) => {
|
||||
try {
|
||||
const allowedKeysPath = process.env.DSQL_API_KEYS_PATH;
|
||||
|
||||
if (!allowedKeysPath)
|
||||
throw new Error(
|
||||
"process.env.DSQL_API_KEYS_PATH variable not found"
|
||||
);
|
||||
|
||||
const ApiJSON = decrypt(key);
|
||||
/** @type {import("../../types").ApiKeyObject} */
|
||||
const ApiObject = JSON.parse(ApiJSON || "");
|
||||
const isApiKeyValid = fs.existsSync(
|
||||
`${allowedKeysPath}/${ApiObject.sign}`
|
||||
);
|
||||
|
||||
if (!isApiKeyValid) return null;
|
||||
if (!ApiObject.target_database) return ApiObject;
|
||||
if (!database && ApiObject.target_database) return null;
|
||||
const isDatabaseAllowed = ApiObject.target_database
|
||||
?.split(",")
|
||||
.includes(String(database));
|
||||
|
||||
if (isDatabaseAllowed && !ApiObject.target_table) return ApiObject;
|
||||
if (isDatabaseAllowed && !table && ApiObject.target_table) return null;
|
||||
const isTableAllowed = ApiObject.target_table
|
||||
?.split(",")
|
||||
.includes(String(table));
|
||||
if (isTableAllowed) return ApiObject;
|
||||
return null;
|
||||
} catch (/** @type {any} */ error) {
|
||||
console.log(`api-cred ERROR: ${error.message}`);
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = grabApiCred;
|
||||
@@ -0,0 +1,163 @@
|
||||
// @ts-check
|
||||
|
||||
const fs = require("fs");
|
||||
const DB_HANDLER = require("../../../utils/backend/global-db/DB_HANDLER");
|
||||
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
|
||||
/**
|
||||
* Add Database Entry
|
||||
* ==============================================================================
|
||||
* @param {object} params - foundUser if any
|
||||
* @param {string} params.tableName - Table Name
|
||||
* @param {any} params.data - Data to be added
|
||||
* @param {string} [params.duplicateColumnName] - Duplicate Column Name
|
||||
* @param {string | number} [params.duplicateColumnValue] - Duplicate Column Value
|
||||
*/
|
||||
module.exports = async function addDbEntry({
|
||||
tableName,
|
||||
data,
|
||||
duplicateColumnName,
|
||||
duplicateColumnValue,
|
||||
}) {
|
||||
/**
|
||||
* Check Duplicate if specified
|
||||
*
|
||||
* @description Check Duplicate if specified
|
||||
*/
|
||||
if (duplicateColumnName) {
|
||||
let duplicateEntry = await DB_HANDLER(
|
||||
`SELECT ${duplicateColumnName} FROM ${tableName} WHERE ${duplicateColumnName}='${duplicateColumnValue}'`
|
||||
);
|
||||
|
||||
if (duplicateEntry && duplicateEntry[0]) return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Declare variables
|
||||
*
|
||||
* @description Declare "results" variable
|
||||
*/
|
||||
const dataKeys = Object.keys(data);
|
||||
|
||||
let insertKeysArray = [];
|
||||
let insertValuesArray = [];
|
||||
|
||||
for (let i = 0; i < dataKeys.length; i++) {
|
||||
const dataKey = dataKeys[i];
|
||||
let dataValue = data[dataKey];
|
||||
// const correspondingColumnObject = dbColumns.filter((col) => col.Field === dataKey);
|
||||
// const { Field, Type, Null, Key, Default, Extra } = correspondingColumnObject;
|
||||
|
||||
if (!dataValue) continue;
|
||||
|
||||
insertKeysArray.push("`" + dataKey + "`");
|
||||
|
||||
if (typeof dataValue === "object") {
|
||||
dataValue = JSON.stringify(data[dataKey]);
|
||||
}
|
||||
|
||||
// let parsedDataValue = dataValue.toString().replace(/\'/g, "\\'");
|
||||
|
||||
insertValuesArray.push(dataValue);
|
||||
}
|
||||
|
||||
////////////////////////////////////////
|
||||
// @ts-ignore
|
||||
let existingDateCreatedColumn = await DB_HANDLER(
|
||||
`SHOW COLUMNS FROM \`${tableName}\` WHERE Field = 'date_created'`
|
||||
);
|
||||
if (!existingDateCreatedColumn || !existingDateCreatedColumn[0]) {
|
||||
// @ts-ignore
|
||||
await DB_HANDLER(
|
||||
`ALTER TABLE ${tableName} ADD COLUMN date_created VARCHAR(255) NOT NULL`
|
||||
);
|
||||
}
|
||||
|
||||
insertKeysArray.push("date_created");
|
||||
insertValuesArray.push(Date());
|
||||
|
||||
////////////////////////////////////////
|
||||
|
||||
// @ts-ignore
|
||||
let existingDateCreatedCodeColumn = await DB_HANDLER(
|
||||
`SHOW COLUMNS FROM ${tableName} WHERE Field = 'date_created_code'`
|
||||
);
|
||||
if (!existingDateCreatedCodeColumn || !existingDateCreatedCodeColumn[0]) {
|
||||
// @ts-ignore
|
||||
await DB_HANDLER(
|
||||
`ALTER TABLE ${tableName} ADD COLUMN date_created_code BIGINT NOT NULL`
|
||||
);
|
||||
}
|
||||
|
||||
insertKeysArray.push("date_created_code");
|
||||
insertValuesArray.push(Date.now());
|
||||
|
||||
////////////////////////////////////////
|
||||
|
||||
// @ts-ignore
|
||||
let existingDateCodeColumn = await DB_HANDLER(
|
||||
`SHOW COLUMNS FROM ${tableName} WHERE Field = 'date_code'`
|
||||
);
|
||||
if (existingDateCodeColumn && existingDateCodeColumn[0]) {
|
||||
insertKeysArray.push("date_code");
|
||||
insertValuesArray.push(Date.now());
|
||||
}
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
// @ts-ignore
|
||||
let existingDateUpdatedColumn = await DB_HANDLER(
|
||||
`SHOW COLUMNS FROM ${tableName} WHERE Field = 'date_updated'`
|
||||
);
|
||||
if (!existingDateUpdatedColumn || !existingDateUpdatedColumn[0]) {
|
||||
// @ts-ignore
|
||||
await DB_HANDLER(
|
||||
`ALTER TABLE ${tableName} ADD COLUMN date_updated VARCHAR(255) NOT NULL`
|
||||
);
|
||||
}
|
||||
|
||||
insertKeysArray.push("date_updated");
|
||||
insertValuesArray.push(Date());
|
||||
|
||||
////////////////////////////////////////
|
||||
|
||||
// @ts-ignore
|
||||
let existingDateUpdatedCodeColumn = await DB_HANDLER(
|
||||
`SHOW COLUMNS FROM ${tableName} WHERE Field = 'date_updated_code'`
|
||||
);
|
||||
if (!existingDateUpdatedCodeColumn || !existingDateUpdatedCodeColumn[0]) {
|
||||
// @ts-ignore
|
||||
await DB_HANDLER(
|
||||
`ALTER TABLE ${tableName} ADD COLUMN date_updated_code BIGINT NOT NULL`
|
||||
);
|
||||
}
|
||||
|
||||
insertKeysArray.push("date_updated_code");
|
||||
insertValuesArray.push(Date.now());
|
||||
|
||||
////////////////////////////////////////
|
||||
|
||||
const query = `INSERT INTO ${tableName} (${insertKeysArray.join(
|
||||
","
|
||||
)}) VALUES (${insertValuesArray.map((val) => "?").join(",")})`;
|
||||
const queryValuesArray = insertValuesArray;
|
||||
|
||||
// @ts-ignore
|
||||
const newInsert = await DB_HANDLER(query, queryValuesArray);
|
||||
|
||||
////////////////////////////////////////
|
||||
|
||||
return newInsert;
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
};
|
||||
@@ -0,0 +1,232 @@
|
||||
// @ts-check
|
||||
|
||||
/**
|
||||
* Imports: Handle imports
|
||||
*/
|
||||
const encrypt = require("../encrypt");
|
||||
const sanitizeHtml = require("sanitize-html");
|
||||
const sanitizeHtmlOptions = require("../html/sanitizeHtmlOptions");
|
||||
const updateDb = require("./updateDbEntry");
|
||||
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");
|
||||
|
||||
/**
|
||||
* Add a db Entry Function
|
||||
* ==============================================================================
|
||||
* @description Description
|
||||
* @async
|
||||
*
|
||||
* @param {object} params - An object containing the function parameters.
|
||||
* @param {("Master" | "Dsql User")} [params.dbContext] - What is the database context? "Master"
|
||||
* or "Dsql User". Defaults to "Master"
|
||||
* @param {("Read Only" | "Full Access")} [params.paradigm] - What is the paradigm for "Dsql User"?
|
||||
* "Read only" or "Full Access"? Defaults to "Read Only"
|
||||
* @param {string} [params.dbFullName] - Database full name
|
||||
* @param {string} params.tableName - Table name
|
||||
* @param {any} params.data - Data to add
|
||||
* @param {import("../../../types").DSQL_TableSchemaType} [params.tableSchema] - Table schema
|
||||
* @param {string} [params.duplicateColumnName] - Duplicate column name
|
||||
* @param {string} [params.duplicateColumnValue] - Duplicate column value
|
||||
* @param {boolean} [params.update] - Update this row if it exists
|
||||
* @param {string} [params.encryptionKey] - Update this row if it exists
|
||||
* @param {string} [params.encryptionSalt] - Update this row if it exists
|
||||
*
|
||||
* @returns {Promise<any>}
|
||||
*/
|
||||
async function addDbEntry({
|
||||
dbContext,
|
||||
paradigm,
|
||||
dbFullName,
|
||||
tableName,
|
||||
data,
|
||||
tableSchema,
|
||||
duplicateColumnName,
|
||||
duplicateColumnValue,
|
||||
update,
|
||||
encryptionKey,
|
||||
encryptionSalt,
|
||||
}) {
|
||||
/**
|
||||
* Initialize variables
|
||||
*/
|
||||
const isMaster = dbContext?.match(/dsql.user/i)
|
||||
? false
|
||||
: dbFullName && !dbFullName.match(/^datasquirel$/)
|
||||
? false
|
||||
: true;
|
||||
|
||||
/** @type { any } */
|
||||
const dbHandler = isMaster ? DB_HANDLER : DSQL_USER_DB_HANDLER;
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
if (data?.["date_created_timestamp"]) delete data["date_created_timestamp"];
|
||||
if (data?.["date_updated_timestamp"]) delete data["date_updated_timestamp"];
|
||||
if (data?.["date_updated"]) delete data["date_updated"];
|
||||
if (data?.["date_updated_code"]) delete data["date_updated_code"];
|
||||
if (data?.["date_created"]) delete data["date_created"];
|
||||
if (data?.["date_created_code"]) delete data["date_created_code"];
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
/**
|
||||
* Handle function logic
|
||||
*/
|
||||
|
||||
if (duplicateColumnName && typeof duplicateColumnName === "string") {
|
||||
const duplicateValue = isMaster
|
||||
? await dbHandler(
|
||||
`SELECT * FROM \`${tableName}\` WHERE \`${duplicateColumnName}\`=?`,
|
||||
[duplicateColumnValue]
|
||||
)
|
||||
: await dbHandler({
|
||||
paradigm: "Read Only",
|
||||
database: dbFullName,
|
||||
queryString: `SELECT * FROM \`${tableName}\` WHERE \`${duplicateColumnName}\`=?`,
|
||||
queryValues: [duplicateColumnValue],
|
||||
});
|
||||
|
||||
if (duplicateValue?.[0] && !update) {
|
||||
return null;
|
||||
} else if (duplicateValue && duplicateValue[0] && update) {
|
||||
return await updateDbEntry({
|
||||
dbContext,
|
||||
paradigm,
|
||||
dbFullName,
|
||||
tableName,
|
||||
data,
|
||||
tableSchema,
|
||||
encryptionKey,
|
||||
encryptionSalt,
|
||||
identifierColumnName: duplicateColumnName,
|
||||
identifierValue: duplicateColumnValue || "",
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Declare variables
|
||||
*
|
||||
* @description Declare "results" variable
|
||||
*/
|
||||
const dataKeys = Object.keys(data);
|
||||
|
||||
let insertKeysArray = [];
|
||||
let insertValuesArray = [];
|
||||
|
||||
for (let i = 0; i < dataKeys.length; i++) {
|
||||
try {
|
||||
const dataKey = dataKeys[i];
|
||||
// @ts-ignore
|
||||
let value = data?.[dataKey];
|
||||
|
||||
const targetFieldSchemaArray = tableSchema
|
||||
? tableSchema?.fields?.filter(
|
||||
(field) => field.fieldName == dataKey
|
||||
)
|
||||
: null;
|
||||
const targetFieldSchema =
|
||||
targetFieldSchemaArray && targetFieldSchemaArray[0]
|
||||
? targetFieldSchemaArray[0]
|
||||
: null;
|
||||
|
||||
if (value == null || value == undefined) continue;
|
||||
|
||||
if (targetFieldSchema?.encrypted) {
|
||||
value = encrypt(value, encryptionKey, encryptionSalt);
|
||||
console.log("DSQL: Encrypted value =>", value);
|
||||
}
|
||||
|
||||
if (targetFieldSchema?.richText) {
|
||||
value = sanitizeHtml(value, sanitizeHtmlOptions);
|
||||
}
|
||||
|
||||
if (targetFieldSchema?.pattern) {
|
||||
const pattern = new RegExp(
|
||||
targetFieldSchema.pattern,
|
||||
targetFieldSchema.patternFlags || ""
|
||||
);
|
||||
if (!pattern.test(value)) {
|
||||
console.log("DSQL: Pattern not matched =>", value);
|
||||
value = "";
|
||||
}
|
||||
}
|
||||
|
||||
insertKeysArray.push("`" + dataKey + "`");
|
||||
|
||||
if (typeof value === "object") {
|
||||
value = JSON.stringify(value);
|
||||
}
|
||||
|
||||
if (typeof value == "number") {
|
||||
insertValuesArray.push(String(value));
|
||||
} else {
|
||||
insertValuesArray.push(value);
|
||||
}
|
||||
} catch (/** @type {any} */ error) {
|
||||
console.log("DSQL: Error in parsing data keys =>", error.message);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
////////////////////////////////////////
|
||||
|
||||
if (!data?.["date_created"]) {
|
||||
insertKeysArray.push("`date_created`");
|
||||
insertValuesArray.push(Date());
|
||||
}
|
||||
|
||||
if (!data?.["date_created_code"]) {
|
||||
insertKeysArray.push("`date_created_code`");
|
||||
insertValuesArray.push(Date.now());
|
||||
}
|
||||
|
||||
////////////////////////////////////////
|
||||
|
||||
if (!data?.["date_updated"]) {
|
||||
insertKeysArray.push("`date_updated`");
|
||||
insertValuesArray.push(Date());
|
||||
}
|
||||
|
||||
if (!data?.["date_updated_code"]) {
|
||||
insertKeysArray.push("`date_updated_code`");
|
||||
insertValuesArray.push(Date.now());
|
||||
}
|
||||
|
||||
////////////////////////////////////////
|
||||
|
||||
const query = `INSERT INTO \`${tableName}\` (${insertKeysArray.join(
|
||||
","
|
||||
)}) VALUES (${insertValuesArray.map(() => "?").join(",")})`;
|
||||
const queryValuesArray = insertValuesArray;
|
||||
|
||||
const newInsert = isMaster
|
||||
? await dbHandler(query, queryValuesArray)
|
||||
: await dbHandler({
|
||||
paradigm,
|
||||
database: dbFullName,
|
||||
queryString: query,
|
||||
queryValues: queryValuesArray,
|
||||
});
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
/**
|
||||
* Return statement
|
||||
*/
|
||||
return newInsert;
|
||||
}
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
module.exports = addDbEntry;
|
||||
@@ -0,0 +1,95 @@
|
||||
// @ts-check
|
||||
|
||||
const DB_HANDLER = require("../../../utils/backend/global-db/DB_HANDLER");
|
||||
const DSQL_USER_DB_HANDLER = require("../../../utils/backend/global-db/DSQL_USER_DB_HANDLER");
|
||||
|
||||
/**
|
||||
* Imports: Handle imports
|
||||
*/
|
||||
|
||||
/**
|
||||
* Delete DB Entry Function
|
||||
* ==============================================================================
|
||||
* @description Description
|
||||
* @async
|
||||
*
|
||||
* @param {object} params - An object containing the function parameters.
|
||||
* @param {string} [params.dbContext] - What is the database context? "Master"
|
||||
* or "Dsql User". Defaults to "Master"
|
||||
* @param {("Read Only" | "Full Access")} [params.paradigm] - What is the paradigm for "Dsql User"?
|
||||
* "Read only" or "Full Access"? Defaults to "Read Only"
|
||||
* @param {string} params.dbFullName - Database full name
|
||||
* @param {string} params.tableName - Table name
|
||||
* @param {import("../../../types").DSQL_TableSchemaType} [params.tableSchema] - Table schema
|
||||
* @param {string} params.identifierColumnName - Update row identifier column name
|
||||
* @param {string|number} params.identifierValue - Update row identifier column value
|
||||
*
|
||||
* @returns {Promise<object|null>}
|
||||
*/
|
||||
async function deleteDbEntry({
|
||||
dbContext,
|
||||
paradigm,
|
||||
dbFullName,
|
||||
tableName,
|
||||
identifierColumnName,
|
||||
identifierValue,
|
||||
}) {
|
||||
try {
|
||||
/**
|
||||
* Check if data is valid
|
||||
*/
|
||||
const isMaster = dbContext?.match(/dsql.user/i)
|
||||
? false
|
||||
: dbFullName && !dbFullName.match(/^datasquirel$/)
|
||||
? false
|
||||
: true;
|
||||
|
||||
/** @type { (a1:any, a2?:any) => any } */
|
||||
const dbHandler = isMaster ? DB_HANDLER : DSQL_USER_DB_HANDLER;
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
/**
|
||||
* Execution
|
||||
*
|
||||
* @description
|
||||
*/
|
||||
const query = `DELETE FROM ${tableName} WHERE \`${identifierColumnName}\`=?`;
|
||||
|
||||
const deletedEntry = isMaster
|
||||
? await dbHandler(query, [identifierValue])
|
||||
: await dbHandler({
|
||||
paradigm,
|
||||
queryString: query,
|
||||
database: dbFullName,
|
||||
queryValues: [identifierValue],
|
||||
});
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
/**
|
||||
* Return statement
|
||||
*/
|
||||
return deletedEntry;
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
} catch (error) {
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
module.exports = deleteDbEntry;
|
||||
@@ -0,0 +1,41 @@
|
||||
// @ts-check
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
/**
|
||||
* Sanitize SQL function
|
||||
* ==============================================================================
|
||||
* @description this function takes in a text(or number) and returns a sanitized
|
||||
* text, usually without spaces
|
||||
*
|
||||
* @param {string|number} text - Text or number or object
|
||||
*
|
||||
* @returns {string}
|
||||
*/
|
||||
function pathTraversalCheck(text) {
|
||||
/**
|
||||
* Initial Checks
|
||||
*
|
||||
* @description Initial Checks
|
||||
*/
|
||||
|
||||
return text.toString().replace(/\//g, "");
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
module.exports = pathTraversalCheck;
|
||||
@@ -0,0 +1,208 @@
|
||||
/** # MODULE TRACE
|
||||
======================================================================
|
||||
* Detected 3 files that call this module. The files are listed below:
|
||||
======================================================================
|
||||
* `import` Statement Found in [get.js] => file:///d:\GitHub\datasquirel\pages\api\query\get.js
|
||||
* `import` Statement Found in [post.js] => file:///d:\GitHub\datasquirel\pages\api\query\post.js
|
||||
* `import` Statement Found in [add-user.js] => file:///d:\GitHub\datasquirel\pages\api\user\add-user.js
|
||||
==== MODULE TRACE END ==== */
|
||||
|
||||
// @ts-check
|
||||
|
||||
const fs = require("fs");
|
||||
|
||||
const fullAccessDbHandler = require("../fullAccessDbHandler");
|
||||
const varReadOnlyDatabaseDbHandler = require("../varReadOnlyDatabaseDbHandler");
|
||||
const serverError = require("../serverError");
|
||||
|
||||
const addDbEntry = require("./addDbEntry");
|
||||
const updateDbEntry = require("./updateDbEntry");
|
||||
const deleteDbEntry = require("./deleteDbEntry");
|
||||
const DB_HANDLER = require("../../../utils/backend/global-db/DB_HANDLER");
|
||||
const parseDbResults = require("../parseDbResults");
|
||||
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
|
||||
/**
|
||||
* 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>}
|
||||
*/
|
||||
async function runQuery({
|
||||
dbFullName,
|
||||
query,
|
||||
readOnly,
|
||||
dbSchema,
|
||||
queryValuesArray,
|
||||
tableName,
|
||||
local,
|
||||
}) {
|
||||
/**
|
||||
* Declare variables
|
||||
*
|
||||
* @description Declare "results" variable
|
||||
*/
|
||||
|
||||
/** @type {any} */
|
||||
let result;
|
||||
/** @type {any} */
|
||||
let error;
|
||||
/** @type {import("../../../types").DSQL_TableSchemaType | undefined} */
|
||||
let tableSchema;
|
||||
|
||||
if (dbSchema) {
|
||||
try {
|
||||
const table = tableName
|
||||
? tableName
|
||||
: typeof query == "string"
|
||||
? null
|
||||
: query
|
||||
? query?.table
|
||||
: null;
|
||||
if (!table) throw new Error("No table name provided");
|
||||
tableSchema = dbSchema.tables.filter(
|
||||
(tb) => tb?.tableName === table
|
||||
)[0];
|
||||
} catch (_err) {
|
||||
// console.log("ERROR getting tableSchema: ", _err.message);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Declare variables
|
||||
*
|
||||
* @description Declare "results" variable
|
||||
*/
|
||||
try {
|
||||
if (typeof query === "string") {
|
||||
if (local) {
|
||||
const rawResults = await DB_HANDLER(query, queryValuesArray);
|
||||
result = tableSchema
|
||||
? parseDbResults({
|
||||
unparsedResults: rawResults,
|
||||
tableSchema,
|
||||
})
|
||||
: rawResults;
|
||||
} else if (readOnly) {
|
||||
result = await varReadOnlyDatabaseDbHandler({
|
||||
queryString: query,
|
||||
queryValuesArray,
|
||||
database: dbFullName,
|
||||
tableSchema,
|
||||
});
|
||||
} else {
|
||||
result = await fullAccessDbHandler({
|
||||
queryString: query,
|
||||
queryValuesArray,
|
||||
database: dbFullName,
|
||||
tableSchema,
|
||||
});
|
||||
}
|
||||
} else if (typeof query === "object") {
|
||||
/**
|
||||
* Declare variables
|
||||
*
|
||||
* @description Declare "results" variable
|
||||
*/
|
||||
const {
|
||||
data,
|
||||
action,
|
||||
table,
|
||||
identifierColumnName,
|
||||
identifierValue,
|
||||
update,
|
||||
duplicateColumnName,
|
||||
duplicateColumnValue,
|
||||
} = query;
|
||||
|
||||
switch (action.toLowerCase()) {
|
||||
case "insert":
|
||||
result = await addDbEntry({
|
||||
dbContext: local ? "Master" : "Dsql User",
|
||||
paradigm: "Full Access",
|
||||
dbFullName: dbFullName,
|
||||
tableName: table,
|
||||
data: data,
|
||||
update,
|
||||
duplicateColumnName,
|
||||
duplicateColumnValue,
|
||||
tableSchema,
|
||||
});
|
||||
|
||||
if (!result?.insertId) {
|
||||
error = new Error("Couldn't insert data");
|
||||
}
|
||||
|
||||
break;
|
||||
|
||||
case "update":
|
||||
result = await updateDbEntry({
|
||||
dbContext: local ? "Master" : "Dsql User",
|
||||
paradigm: "Full Access",
|
||||
dbFullName: dbFullName,
|
||||
tableName: table,
|
||||
data: data,
|
||||
identifierColumnName,
|
||||
identifierValue,
|
||||
tableSchema,
|
||||
});
|
||||
|
||||
break;
|
||||
|
||||
case "delete":
|
||||
result = await deleteDbEntry({
|
||||
dbContext: local ? "Master" : "Dsql User",
|
||||
paradigm: "Full Access",
|
||||
dbFullName: dbFullName,
|
||||
tableName: table,
|
||||
identifierColumnName,
|
||||
identifierValue,
|
||||
tableSchema,
|
||||
});
|
||||
|
||||
break;
|
||||
|
||||
default:
|
||||
result = null;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
} catch (/** @type {any} */ error) {
|
||||
serverError({
|
||||
component: "functions/backend/runQuery",
|
||||
message: error.message,
|
||||
});
|
||||
result = null;
|
||||
error = error.message;
|
||||
}
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
return { result, error };
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
}
|
||||
|
||||
module.exports = runQuery;
|
||||
@@ -0,0 +1,207 @@
|
||||
// @ts-check
|
||||
|
||||
const _ = require("lodash");
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
/**
|
||||
* Sanitize SQL function
|
||||
* ==============================================================================
|
||||
* @description this function takes in a text(or number) and returns a sanitized
|
||||
* text, usually without spaces
|
||||
*
|
||||
* @param {any} text - Text or number or object
|
||||
* @param {boolean} [spaces] - Allow spaces
|
||||
* @param {RegExp?} [regex] - Regular expression, removes any match
|
||||
*
|
||||
* @returns {any}
|
||||
*/
|
||||
function sanitizeSql(text, spaces, regex) {
|
||||
/**
|
||||
* Initial Checks
|
||||
*
|
||||
* @description Initial Checks
|
||||
*/
|
||||
if (!text) return "";
|
||||
if (typeof text == "number" || typeof text == "boolean") return text;
|
||||
if (typeof text == "string" && !text?.toString()?.match(/./)) return "";
|
||||
|
||||
if (typeof text == "object" && !Array.isArray(text)) {
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
const newObject = sanitizeObjects(text, spaces);
|
||||
return newObject;
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
} else if (typeof text == "object" && Array.isArray(text)) {
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
const newArray = sanitizeArrays(text, spaces);
|
||||
return newArray;
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
}
|
||||
|
||||
// if (text?.toString()?.match(/\'|\"/)) {
|
||||
// console.log("TEXT containing commas =>", text);
|
||||
// return "";
|
||||
// }
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
/**
|
||||
* Declare variables
|
||||
*
|
||||
* @description Declare "results" variable
|
||||
*/
|
||||
let finalText = text;
|
||||
|
||||
if (regex) {
|
||||
finalText = text.toString().replace(regex, "");
|
||||
}
|
||||
|
||||
if (spaces) {
|
||||
} else {
|
||||
finalText = text
|
||||
.toString()
|
||||
.replace(/\n|\r|\n\r|\r\n/g, "")
|
||||
.replace(/ /g, "");
|
||||
}
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
const escapeRegex =
|
||||
/select |insert |drop |delete |alter |create |exec | union | or | like | concat|LOAD_FILE|ASCII| COLLATE | HAVING | information_schema|DECLARE |\#|WAITFOR |delay |BENCHMARK |\/\*.*\*\//gi;
|
||||
|
||||
finalText = finalText
|
||||
.replace(/(?<!\\)\'/g, "\\'")
|
||||
.replace(/(?<!\\)\`/g, "\\`")
|
||||
// .replace(/(?<!\\)\"/g, '\\"')
|
||||
.replace(/\/\*\*\//g, "")
|
||||
.replace(escapeRegex, "\\$&");
|
||||
|
||||
// const injectionRegexp = /select .* from|\*|delete from|drop database|drop table|update .* set/i;
|
||||
|
||||
// if (text?.toString()?.match(injectionRegexp)) {
|
||||
// console.log("ATTEMPTED INJECTION =>", text);
|
||||
// return "";
|
||||
// }
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
return finalText;
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
/**
|
||||
* Sanitize Objects Function
|
||||
* ==============================================================================
|
||||
* @description Sanitize objects in the form { key: "value" }
|
||||
*
|
||||
* @param {any} object - Database Full Name
|
||||
* @param {boolean} [spaces] - Allow spaces
|
||||
*
|
||||
* @returns {object}
|
||||
*/
|
||||
function sanitizeObjects(object, spaces) {
|
||||
/** @type {any} */
|
||||
let objectUpdated = { ...object };
|
||||
const keys = Object.keys(objectUpdated);
|
||||
|
||||
keys.forEach((key) => {
|
||||
const value = objectUpdated[key];
|
||||
|
||||
if (!value) {
|
||||
delete objectUpdated[key];
|
||||
return;
|
||||
}
|
||||
|
||||
if (typeof value == "string" || typeof value == "number") {
|
||||
objectUpdated[key] = sanitizeSql(value, spaces);
|
||||
} else if (typeof value == "object" && !Array.isArray(value)) {
|
||||
objectUpdated[key] = sanitizeObjects(value, spaces);
|
||||
} else if (typeof value == "object" && Array.isArray(value)) {
|
||||
objectUpdated[key] = sanitizeArrays(value, spaces);
|
||||
}
|
||||
});
|
||||
|
||||
return objectUpdated;
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
/**
|
||||
* Sanitize Objects Function
|
||||
* ==============================================================================
|
||||
* @description Sanitize objects in the form { key: "value" }
|
||||
*
|
||||
* @param {any[]} array - Database Full Name
|
||||
* @param {boolean} [spaces] - Allow spaces
|
||||
*
|
||||
* @returns {string[]|number[]|object[]}
|
||||
*/
|
||||
function sanitizeArrays(array, spaces) {
|
||||
let arrayUpdated = _.cloneDeep(array);
|
||||
|
||||
arrayUpdated.forEach((item, index) => {
|
||||
const value = item;
|
||||
|
||||
if (!value) {
|
||||
arrayUpdated.splice(index, 1);
|
||||
return;
|
||||
}
|
||||
|
||||
if (typeof item == "string" || typeof item == "number") {
|
||||
arrayUpdated[index] = sanitizeSql(value, spaces);
|
||||
} else if (typeof item == "object" && !Array.isArray(value)) {
|
||||
arrayUpdated[index] = sanitizeObjects(value, spaces);
|
||||
} else if (typeof item == "object" && Array.isArray(value)) {
|
||||
arrayUpdated[index] = sanitizeArrays(item, spaces);
|
||||
}
|
||||
});
|
||||
|
||||
return arrayUpdated;
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
module.exports = sanitizeSql;
|
||||
@@ -0,0 +1,191 @@
|
||||
// @ts-check
|
||||
|
||||
/**
|
||||
* 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");
|
||||
|
||||
/**
|
||||
* Update DB Function
|
||||
* ==============================================================================
|
||||
* @description Description
|
||||
* @async
|
||||
*
|
||||
* @param {object} params - An object containing the function parameters.
|
||||
* @param {("Master" | "Dsql User")} [params.dbContext] - What is the database context? "Master"
|
||||
* or "Dsql User". Defaults to "Master"
|
||||
* @param {("Read Only" | "Full Access")} [params.paradigm] - What is the paradigm for "Dsql User"?
|
||||
* "Read only" or "Full Access"? Defaults to "Read Only"
|
||||
* @param {string} [params.dbFullName] - Database full name
|
||||
* @param {string} params.tableName - Table name
|
||||
* @param {string} [params.encryptionKey]
|
||||
* @param {string} [params.encryptionSalt]
|
||||
* @param {any} params.data - Data to add
|
||||
* @param {import("../../../types").DSQL_TableSchemaType} [params.tableSchema] - Table schema
|
||||
* @param {string} params.identifierColumnName - Update row identifier column name
|
||||
* @param {string | number} params.identifierValue - Update row identifier column value
|
||||
*
|
||||
* @returns {Promise<object|null>}
|
||||
*/
|
||||
async function updateDbEntry({
|
||||
dbContext,
|
||||
paradigm,
|
||||
dbFullName,
|
||||
tableName,
|
||||
data,
|
||||
tableSchema,
|
||||
identifierColumnName,
|
||||
identifierValue,
|
||||
encryptionKey,
|
||||
encryptionSalt,
|
||||
}) {
|
||||
/**
|
||||
* Check if data is valid
|
||||
*/
|
||||
if (!data || !Object.keys(data).length) return null;
|
||||
|
||||
const isMaster = dbContext?.match(/dsql.user/i)
|
||||
? false
|
||||
: dbFullName && !dbFullName.match(/^datasquirel$/)
|
||||
? false
|
||||
: true;
|
||||
|
||||
/** @type {(a1:any, a2?:any)=> any } */
|
||||
const dbHandler = isMaster ? DB_HANDLER : DSQL_USER_DB_HANDLER;
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
/**
|
||||
* Declare variables
|
||||
*
|
||||
* @description Declare "results" variable
|
||||
*/
|
||||
const dataKeys = Object.keys(data);
|
||||
|
||||
let updateKeyValueArray = [];
|
||||
let updateValues = [];
|
||||
|
||||
for (let i = 0; i < dataKeys.length; i++) {
|
||||
try {
|
||||
const dataKey = dataKeys[i];
|
||||
// @ts-ignore
|
||||
let value = data[dataKey];
|
||||
|
||||
const targetFieldSchemaArray = tableSchema
|
||||
? tableSchema?.fields?.filter(
|
||||
(field) => field.fieldName === dataKey
|
||||
)
|
||||
: null;
|
||||
const targetFieldSchema =
|
||||
targetFieldSchemaArray && targetFieldSchemaArray[0]
|
||||
? targetFieldSchemaArray[0]
|
||||
: null;
|
||||
|
||||
if (value == null || value == undefined) continue;
|
||||
|
||||
if (targetFieldSchema?.richText) {
|
||||
value = sanitizeHtml(value, sanitizeHtmlOptions);
|
||||
}
|
||||
|
||||
if (targetFieldSchema?.encrypted) {
|
||||
value = encrypt(value, encryptionKey, encryptionSalt);
|
||||
}
|
||||
|
||||
if (typeof value === "object") {
|
||||
value = JSON.stringify(value);
|
||||
}
|
||||
|
||||
if (targetFieldSchema?.pattern) {
|
||||
const pattern = new RegExp(
|
||||
targetFieldSchema.pattern,
|
||||
targetFieldSchema.patternFlags || ""
|
||||
);
|
||||
if (!pattern.test(value)) {
|
||||
console.log("DSQL: Pattern not matched =>", value);
|
||||
value = "";
|
||||
}
|
||||
}
|
||||
|
||||
if (typeof value === "string" && value.match(/^null$/i)) {
|
||||
value = {
|
||||
toSqlString: function () {
|
||||
return "NULL";
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
if (typeof value === "string" && !value.match(/./i)) {
|
||||
value = {
|
||||
toSqlString: function () {
|
||||
return "NULL";
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
updateKeyValueArray.push(`\`${dataKey}\`=?`);
|
||||
|
||||
if (typeof value == "number") {
|
||||
updateValues.push(String(value));
|
||||
} else {
|
||||
updateValues.push(value);
|
||||
}
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
} catch (/** @type {any} */ error) {
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
console.log(
|
||||
"DSQL: Error in parsing data keys in update function =>",
|
||||
error.message
|
||||
);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
updateKeyValueArray.push(`date_updated='${Date()}'`);
|
||||
updateKeyValueArray.push(`date_updated_code='${Date.now()}'`);
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
const query = `UPDATE ${tableName} SET ${updateKeyValueArray.join(
|
||||
","
|
||||
)} WHERE \`${identifierColumnName}\`=?`;
|
||||
|
||||
updateValues.push(identifierValue);
|
||||
|
||||
const updatedEntry = isMaster
|
||||
? await dbHandler(query, updateValues)
|
||||
: await dbHandler({
|
||||
paradigm,
|
||||
database: dbFullName,
|
||||
queryString: query,
|
||||
queryValues: updateValues,
|
||||
});
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
/**
|
||||
* Return statement
|
||||
*/
|
||||
return updatedEntry;
|
||||
}
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
module.exports = updateDbEntry;
|
||||
@@ -0,0 +1,90 @@
|
||||
// @ts-check
|
||||
|
||||
const fs = require("fs");
|
||||
const serverError = require("./serverError");
|
||||
|
||||
const mysql = require("serverless-mysql");
|
||||
const path = require("path");
|
||||
|
||||
const SSL_DIR = "/app/ssl";
|
||||
|
||||
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: {
|
||||
ca: fs.readFileSync(`${SSL_DIR}/ca-cert.pem`),
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
/**
|
||||
* Main DB Handler Function
|
||||
* ==============================================================================
|
||||
* @async
|
||||
*
|
||||
* @param {any} args
|
||||
* @returns {Promise<object|null>}
|
||||
*/
|
||||
module.exports = async function dbHandler(...args) {
|
||||
process.env.NODE_ENV?.match(/dev/) &&
|
||||
fs.appendFileSync(
|
||||
"./.tmp/sqlQuery.sql",
|
||||
args[0] + "\n" + Date() + "\n\n\n",
|
||||
"utf8"
|
||||
);
|
||||
|
||||
/**
|
||||
* Declare variables
|
||||
*
|
||||
* @description Declare "results" variable
|
||||
*/
|
||||
let results;
|
||||
|
||||
/**
|
||||
* Fetch from db
|
||||
*
|
||||
* @description Fetch data from db if no cache
|
||||
*/
|
||||
try {
|
||||
results = await new Promise((resolve, reject) => {
|
||||
// @ts-ignore
|
||||
connection.query(...args, (error, result, fields) => {
|
||||
if (error) {
|
||||
resolve({ error: error.message });
|
||||
} else {
|
||||
resolve(result);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
await connection.end();
|
||||
} catch (/** @type {any} */ error) {
|
||||
fs.appendFileSync(
|
||||
"./.tmp/dbErrorLogs.txt",
|
||||
JSON.stringify(error, null, 4) + "\n" + Date() + "\n\n\n",
|
||||
"utf8"
|
||||
);
|
||||
|
||||
results = null;
|
||||
|
||||
serverError({
|
||||
component: "dbHandler",
|
||||
message: error.message,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Return results
|
||||
*
|
||||
* @description Return results add to cache if "req" param is passed
|
||||
*/
|
||||
if (results) {
|
||||
return JSON.parse(JSON.stringify(results));
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,29 @@
|
||||
// @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;
|
||||
@@ -0,0 +1,15 @@
|
||||
// @ts-check
|
||||
|
||||
/**
|
||||
* Regular expression to match default fields
|
||||
*
|
||||
* @description Regular expression to match default fields
|
||||
*/
|
||||
const defaultFieldsRegexp =
|
||||
/^id$|^uuid$|^date_created$|^date_created_code$|^date_created_timestamp$|^date_updated$|^date_updated_code$|^date_updated_timestamp$/;
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
module.exports = defaultFieldsRegexp;
|
||||
@@ -0,0 +1,43 @@
|
||||
// @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;
|
||||
@@ -0,0 +1,78 @@
|
||||
// @ts-check
|
||||
|
||||
const DSQL_USER_DB_HANDLER = require("../../utils/backend/global-db/DSQL_USER_DB_HANDLER");
|
||||
const parseDbResults = require("./parseDbResults");
|
||||
const serverError = require("./serverError");
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {object} param0
|
||||
* @param {string} param0.queryString
|
||||
* @param {string} param0.database
|
||||
* @param {boolean} [param0.local]
|
||||
* @param {import("../../types").DSQL_TableSchemaType | null} [param0.tableSchema]
|
||||
* @param {string[]} [param0.queryValuesArray]
|
||||
* @returns
|
||||
*/
|
||||
module.exports = async function fullAccessDbHandler({
|
||||
queryString,
|
||||
database,
|
||||
tableSchema,
|
||||
queryValuesArray,
|
||||
local,
|
||||
}) {
|
||||
/**
|
||||
* Declare variables
|
||||
*
|
||||
* @description Declare "results" variable
|
||||
*/
|
||||
let results;
|
||||
|
||||
/**
|
||||
* Fetch from db
|
||||
*
|
||||
* @description Fetch data from db if no cache
|
||||
*/
|
||||
try {
|
||||
/** ********************* Run Query */
|
||||
|
||||
results = await DSQL_USER_DB_HANDLER({
|
||||
paradigm: "Full Access",
|
||||
database,
|
||||
queryString,
|
||||
queryValues: queryValuesArray,
|
||||
});
|
||||
|
||||
////////////////////////////////////////
|
||||
} catch (/** @type {any} */ error) {
|
||||
////////////////////////////////////////
|
||||
|
||||
serverError({
|
||||
component: "fullAccessDbHandler",
|
||||
message: error.message,
|
||||
});
|
||||
|
||||
/**
|
||||
* Return error
|
||||
*/
|
||||
return error.message;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return results
|
||||
*
|
||||
* @description Return results add to cache if "req" param is passed
|
||||
*/
|
||||
if (results && tableSchema) {
|
||||
const unparsedResults = results;
|
||||
const parsedResults = await parseDbResults({
|
||||
unparsedResults: unparsedResults,
|
||||
tableSchema: tableSchema,
|
||||
});
|
||||
return parsedResults;
|
||||
} else if (results) {
|
||||
return results;
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,12 @@
|
||||
// @ts-check
|
||||
|
||||
const sanitizeHtmlOptions = {
|
||||
allowedTags: ["b", "i", "em", "strong", "a", "p", "span", "ul", "ol", "li", "h1", "h2", "h3", "h4", "h5", "h6", "img", "div", "button", "pre", "code", "br"],
|
||||
allowedAttributes: {
|
||||
a: ["href"],
|
||||
img: ["src", "alt", "width", "height", "class", "style"],
|
||||
"*": ["style", "class"],
|
||||
},
|
||||
};
|
||||
|
||||
module.exports = sanitizeHtmlOptions;
|
||||
@@ -0,0 +1,59 @@
|
||||
// @ts-check
|
||||
|
||||
const fs = require("fs");
|
||||
const serverError = require("./serverError");
|
||||
const NO_DB_HANDLER = require("../../../package-shared/utils/backend/global-db/NO_DB_HANDLER");
|
||||
|
||||
/**
|
||||
* Create database from Schema Function
|
||||
* ==============================================================================
|
||||
* @param {string} queryString - Query String
|
||||
* @returns {Promise<any>}
|
||||
*/
|
||||
module.exports = async function noDatabaseDbHandler(queryString) {
|
||||
process.env.NODE_ENV?.match(/dev/) &&
|
||||
fs.appendFileSync(
|
||||
"./.tmp/sqlQuery.sql",
|
||||
queryString + "\n" + Date() + "\n\n\n",
|
||||
"utf8"
|
||||
);
|
||||
|
||||
/**
|
||||
* Declare variables
|
||||
*
|
||||
* @description Declare "results" variable
|
||||
*/
|
||||
let results;
|
||||
|
||||
/**
|
||||
* Fetch from db
|
||||
*
|
||||
* @description Fetch data from db if no cache
|
||||
*/
|
||||
try {
|
||||
/** ********************* Run Query */
|
||||
results = await NO_DB_HANDLER(queryString);
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
} catch (/** @type {any} */ error) {
|
||||
serverError({
|
||||
component: "noDatabaseDbHandler",
|
||||
message: error.message,
|
||||
});
|
||||
|
||||
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;
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,76 @@
|
||||
// @ts-check
|
||||
|
||||
const decrypt = require("./decrypt");
|
||||
const defaultFieldsRegexp = require("./defaultFieldsRegexp");
|
||||
|
||||
/**
|
||||
* Parse Database results
|
||||
* ==============================================================================
|
||||
* @description this function takes a database results array gotten from a DB handler
|
||||
* function, decrypts encrypted fields, and returns an updated array with no encrypted
|
||||
* fields
|
||||
*
|
||||
* @param {object} params - Single object params
|
||||
* @param {any[]} params.unparsedResults - Array of data objects containing Fields(keys)
|
||||
* and corresponding values of the fields(values)
|
||||
* @param {import("../../types").DSQL_TableSchemaType} [params.tableSchema] - Table schema
|
||||
* @returns {Promise<object[]|null>}
|
||||
*/
|
||||
module.exports = async function parseDbResults({
|
||||
unparsedResults,
|
||||
tableSchema,
|
||||
}) {
|
||||
/**
|
||||
* Declare variables
|
||||
*
|
||||
* @description Declare "results" variable
|
||||
*/
|
||||
let parsedResults = [];
|
||||
|
||||
try {
|
||||
/**
|
||||
* Declare variables
|
||||
*
|
||||
* @description Declare "results" variable
|
||||
*/
|
||||
for (let pr = 0; pr < unparsedResults.length; pr++) {
|
||||
let result = unparsedResults[pr];
|
||||
|
||||
let resultFieldNames = Object.keys(result);
|
||||
|
||||
for (let i = 0; i < resultFieldNames.length; i++) {
|
||||
const resultFieldName = resultFieldNames[i];
|
||||
let resultFieldSchema = tableSchema?.fields[i];
|
||||
|
||||
if (resultFieldName?.match(defaultFieldsRegexp)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
let value = result[resultFieldName];
|
||||
|
||||
if (typeof value !== "number" && !value) {
|
||||
// parsedResults.push(result);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (resultFieldSchema?.encrypted) {
|
||||
if (value?.match(/./)) {
|
||||
result[resultFieldName] = decrypt(value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
parsedResults.push(result);
|
||||
}
|
||||
|
||||
/**
|
||||
* Declare variables
|
||||
*
|
||||
* @description Declare "results" variable
|
||||
*/
|
||||
return parsedResults;
|
||||
} catch (/** @type {any} */ error) {
|
||||
console.log("ERROR in parseDbResults Function =>", error.message);
|
||||
return unparsedResults;
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,31 @@
|
||||
// @ts-check
|
||||
|
||||
const { createHmac } = require("crypto");
|
||||
//
|
||||
|
||||
/**
|
||||
* # Password Hash function
|
||||
* @param {string} password
|
||||
* @returns
|
||||
*/
|
||||
function hashPassword(password) {
|
||||
const hmac = createHmac(
|
||||
"sha512",
|
||||
process.env.DSQL_ENCRYPTION_PASSWORD || ""
|
||||
);
|
||||
hmac.update(password);
|
||||
let hashed = hmac.digest("base64");
|
||||
return hashed;
|
||||
}
|
||||
|
||||
exports.hashPassword = hashPassword;
|
||||
|
||||
// export const comparePasswords = async (password) => {
|
||||
// const hmac = createHmac("sha512", process.env.DSQL_ENCRYPTION_PASSWORD);
|
||||
// hmac.update(password);
|
||||
// let hashed = hmac.digest("base64");
|
||||
|
||||
// let dbPass = await global.DB_HANDLER(`SELECT * FROM users WHERE password = '${hashed}'`);
|
||||
// console.log(dbPass);
|
||||
// return dbPass;
|
||||
// };
|
||||
@@ -0,0 +1,55 @@
|
||||
// @ts-check
|
||||
|
||||
/**
|
||||
* ==============================================================================
|
||||
* Imports
|
||||
* ==============================================================================
|
||||
*/
|
||||
const fs = require("fs");
|
||||
// const handleNodemailer = require("./handleNodemailer");
|
||||
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
|
||||
/**
|
||||
* ==============================================================================
|
||||
* Main Function
|
||||
* ==============================================================================
|
||||
* @param {{
|
||||
* user?: { id?: number | string, first_name?: string, last_name?: string, email?: string } & *,
|
||||
* message: string,
|
||||
* component?: string,
|
||||
* noMail?: boolean,
|
||||
* }} params - user id
|
||||
*
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
module.exports = async function serverError({
|
||||
user,
|
||||
message,
|
||||
component,
|
||||
noMail,
|
||||
}) {
|
||||
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========================================`;
|
||||
|
||||
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}`);
|
||||
};
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
@@ -0,0 +1,38 @@
|
||||
// @ts-check
|
||||
|
||||
const { IncomingMessage } = require("http");
|
||||
const decrypt = require("./decrypt");
|
||||
const parseCookies = require("../../../utils/functions/parseCookies");
|
||||
|
||||
/**
|
||||
* @async
|
||||
* @param {IncomingMessage} req - https request object
|
||||
*
|
||||
* @returns {Promise<({ email: string, password: string, authKey: string, logged_in_status: boolean, date: number } | null)>}
|
||||
*/
|
||||
module.exports = async function (req) {
|
||||
const cookies = parseCookies({ request: req });
|
||||
/** ********************* Check for existence of required cookie */
|
||||
if (!cookies?.datasquirelSuAdminUserAuthKey) {
|
||||
return null;
|
||||
}
|
||||
|
||||
/** ********************* Grab the payload */
|
||||
let userPayload = decrypt(cookies.datasquirelSuAdminUserAuthKey);
|
||||
|
||||
/** ********************* Return if no payload */
|
||||
if (!userPayload) return null;
|
||||
|
||||
/** ********************* Parse the payload */
|
||||
let userObject = JSON.parse(userPayload);
|
||||
|
||||
if (userObject.password !== process.env.DSQL_USER_KEY) return null;
|
||||
if (userObject.authKey !== process.env.DSQL_SPECIAL_KEY) return null;
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
/** ********************* return user object */
|
||||
return userObject;
|
||||
};
|
||||
@@ -0,0 +1,116 @@
|
||||
// @ts-check
|
||||
|
||||
const fs = require("fs");
|
||||
const parseDbResults = require("./parseDbResults");
|
||||
const serverError = require("./serverError");
|
||||
const DB_HANDLER = require("../../utils/backend/global-db/DB_HANDLER");
|
||||
const DSQL_USER_DB_HANDLER = require("../../utils/backend/global-db/DSQL_USER_DB_HANDLER");
|
||||
|
||||
/**
|
||||
* DB handler for specific database
|
||||
* ==============================================================================
|
||||
* @async
|
||||
* @param {object} params - Single object params
|
||||
* @param {string} params.queryString - SQL string
|
||||
* @param {*[]} [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
|
||||
*/
|
||||
const isMaster = database?.match(/^datasquirel$/) ? true : false;
|
||||
|
||||
/** @type {any} */
|
||||
const FINAL_DB_HANDLER = isMaster ? DB_HANDLER : DSQL_USER_DB_HANDLER;
|
||||
|
||||
let results;
|
||||
|
||||
/**
|
||||
* Fetch from db
|
||||
*
|
||||
* @description Fetch data from db if no cache
|
||||
*/
|
||||
try {
|
||||
if (
|
||||
queryString &&
|
||||
queryValuesArray &&
|
||||
Array.isArray(queryValuesArray) &&
|
||||
queryValuesArray[0]
|
||||
) {
|
||||
results = isMaster
|
||||
? await FINAL_DB_HANDLER(queryString, queryValuesArray)
|
||||
: await FINAL_DB_HANDLER({
|
||||
paradigm: "Full Access",
|
||||
database,
|
||||
queryString,
|
||||
queryValues: queryValuesArray,
|
||||
});
|
||||
} else {
|
||||
results = isMaster
|
||||
? await FINAL_DB_HANDLER(queryString)
|
||||
: await FINAL_DB_HANDLER({
|
||||
paradigm: "Full Access",
|
||||
database,
|
||||
queryString,
|
||||
});
|
||||
}
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
} catch (/** @type {any} */ error) {
|
||||
serverError({
|
||||
component: "varDatabaseDbHandler/lines-29-32",
|
||||
message: error.message,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Return results
|
||||
*
|
||||
* @description Return results add to cache if "req" param is passed
|
||||
*/
|
||||
if (results && tableSchema) {
|
||||
try {
|
||||
const unparsedResults = results;
|
||||
const parsedResults = await parseDbResults({
|
||||
unparsedResults: unparsedResults,
|
||||
tableSchema: tableSchema,
|
||||
});
|
||||
return parsedResults;
|
||||
} catch (/** @type {any} */ error) {
|
||||
console.log(
|
||||
"\x1b[31mvarDatabaseDbHandler ERROR\x1b[0m =>",
|
||||
database,
|
||||
error
|
||||
);
|
||||
serverError({
|
||||
component: "varDatabaseDbHandler/lines-52-53",
|
||||
message: error.message,
|
||||
});
|
||||
return null;
|
||||
}
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
} else if (results) {
|
||||
return results;
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,74 @@
|
||||
// @ts-check
|
||||
|
||||
const fs = require("fs");
|
||||
const serverError = require("./serverError");
|
||||
const parseDbResults = require("./parseDbResults");
|
||||
const DSQL_USER_DB_HANDLER = require("../../utils/backend/global-db/DSQL_USER_DB_HANDLER");
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {object} param0
|
||||
* @param {string} param0.queryString
|
||||
* @param {string} param0.database
|
||||
* @param {string[]} [param0.queryValuesArray]
|
||||
* @param {import("../../types").DSQL_TableSchemaType} [param0.tableSchema]
|
||||
* @returns
|
||||
*/
|
||||
module.exports = async function varReadOnlyDatabaseDbHandler({
|
||||
queryString,
|
||||
database,
|
||||
queryValuesArray,
|
||||
tableSchema,
|
||||
}) {
|
||||
/**
|
||||
* Declare variables
|
||||
*
|
||||
* @description Declare "results" variable
|
||||
*/
|
||||
let results;
|
||||
|
||||
/**
|
||||
* Fetch from db
|
||||
*
|
||||
* @description Fetch data from db if no cache
|
||||
*/
|
||||
try {
|
||||
results = await DSQL_USER_DB_HANDLER({
|
||||
paradigm: "Read Only",
|
||||
database,
|
||||
queryString,
|
||||
queryValues: queryValuesArray,
|
||||
});
|
||||
|
||||
////////////////////////////////////////
|
||||
} catch (/** @type {any} */ error) {
|
||||
////////////////////////////////////////
|
||||
|
||||
serverError({
|
||||
component: "varReadOnlyDatabaseDbHandler",
|
||||
message: error.message,
|
||||
noMail: true,
|
||||
});
|
||||
|
||||
/**
|
||||
* Return error
|
||||
*/
|
||||
return error.message;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return results
|
||||
*
|
||||
* @description Return results add to cache if "req" param is passed
|
||||
*/
|
||||
if (results) {
|
||||
const unparsedResults = results;
|
||||
const parsedResults = await parseDbResults({
|
||||
unparsedResults: unparsedResults,
|
||||
tableSchema: tableSchema,
|
||||
});
|
||||
return parsedResults;
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
Reference in New Issue
Block a user