This commit is contained in:
Benjamin Toby 2024-12-09 12:45:39 +01:00
parent 7bd4b2fe65
commit 586e3cfa85
43 changed files with 216 additions and 506 deletions

View File

@ -106,7 +106,7 @@ module.exports = async function facebookLogin({ usertype, body }) {
// <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>
// <div>Site: <b>${process.env.DSQL_DB_HOST}</b></div>
// `,
// }).catch((error) => {
// console.log(

View File

@ -15,6 +15,7 @@ module.exports = async function apiCreateUser({
useLocal,
}) {
const dbFullName = database;
const API_USER_ID = userId || process.env.DSQL_API_USER_ID;
const finalEncryptionKey =
encryptionKey || process.env.DSQL_ENCRYPTION_PASSWORD;
@ -52,7 +53,7 @@ module.exports = async function apiCreateUser({
if (!fields?.[0]) {
const newTable = await addUsersTableToDb({
userId: Number(userId),
userId: Number(API_USER_ID),
database: dbFullName,
useLocal,
payload: payload,
@ -82,7 +83,7 @@ module.exports = async function apiCreateUser({
const key = Object.keys(payload)[i];
if (!fieldsTitles.includes(key)) {
await updateUsersTableSchema({
userId: Number(userId),
userId: Number(API_USER_ID),
database: dbFullName,
newPayload: {
[key]: payload[key],
@ -130,6 +131,7 @@ module.exports = async function apiCreateUser({
image: "/images/user-preset.png",
image_thumbnail: "/images/user-preset-thumbnail.png",
},
useLocal,
});
if (addUser?.insertId) {

View File

@ -10,10 +10,11 @@ module.exports = async function apiGetUser({
useLocal,
}) {
const query = `SELECT ${fields.join(",")} FROM users WHERE id=?`;
const API_USER_ID = userId || process.env.DSQL_API_USER_ID;
let foundUser = await varDatabaseDbHandler({
queryString: query,
queryValuesArray: [userId],
queryValuesArray: [API_USER_ID],
database: dbFullName.replace(/[^a-z0-9_]/g, ""),
useLocal,
});

View File

@ -1,7 +1,5 @@
// @ts-check
const LOCAL_DB_HANDLER = require("../../../utils/backend/global-db/LOCAL_DB_HANDLER");
const { writeAuthFile } = require("../../backend/auth/write-auth-files");
const varDatabaseDbHandler = require("../../backend/varDatabaseDbHandler");
const hashPassword = require("../../dsql/hashPassword");

View File

@ -2,7 +2,7 @@ declare function _exports({ existingUser, database, additionalFields, useLocal,
existingUser: {
[x: string]: any;
};
database: string;
database?: string;
additionalFields?: string[];
useLocal?: boolean;
}): Promise<import("../../../types").APILoginFunctionReturn>;

View File

@ -8,7 +8,7 @@ const nodemailer = require("nodemailer");
* # Re-authenticate API user
* @param {object} param
* @param {Object<string, any>} param.existingUser
* @param {string} param.database
* @param {string} [param.database]
* @param {string[]} [param.additionalFields]
* @param {boolean} [param.useLocal]
*
@ -22,14 +22,11 @@ module.exports = async function apiReauthUser({
}) {
let foundUser =
existingUser?.id && existingUser.id.toString().match(/./)
? useLocal
? await LOCAL_DB_HANDLER(`SELECT * FROM users WHERE id=?`, [
existingUser.id.toString(),
])
: await varDatabaseDbHandler({
? await varDatabaseDbHandler({
queryString: `SELECT * FROM users WHERE id=?`,
queryValuesArray: [existingUser.id.toString()],
database,
useLocal,
})
: null;

View File

@ -1,6 +1,5 @@
// @ts-check
const LOCAL_DB_HANDLER = require("../../../utils/backend/global-db/LOCAL_DB_HANDLER");
const updateDbEntry = require("../../backend/db/updateDbEntry");
const encrypt = require("../../dsql/encrypt");
const hashPassword = require("../../dsql/hashPassword");

View File

@ -32,7 +32,7 @@ module.exports = async function addMariadbUser({ userId, useLocal }) {
});
const encryptedPassword = encrypt({ data: password });
const createMariadbUsersQuery = `CREATE USER IF NOT EXISTS '${username}'@'127.0.0.1' IDENTIFIED BY '${password}' REQUIRE SSL`;
const createMariadbUsersQuery = `CREATE USER IF NOT EXISTS '${username}'@'127.0.0.1' IDENTIFIED BY '${password}'`;
if (useLocal) {
await LOCAL_DB_HANDLER(createMariadbUsersQuery);

View File

@ -14,14 +14,18 @@ module.exports = function getAuthCookieNames(params) {
const cookiesKeyName = process.env.DSQL_COOKIES_KEY_NAME || "key";
const cookiesCSRFName = process.env.DSQL_COOKIES_CSRF_NAME || "csrf";
const targetDatabase =
params?.database ||
process.env.DSQL_DB_NAME?.replace(/^datasquirel_user_\d+_/, "");
let keyCookieName = cookiesPrefix;
if (params?.userId) keyCookieName += `user_${params.userId}_`;
if (params?.database) keyCookieName += `${params.database}_`;
if (targetDatabase) keyCookieName += `${targetDatabase}_`;
keyCookieName += cookiesKeyName;
let csrfCookieName = cookiesPrefix;
if (params?.userId) csrfCookieName += `user_${params.userId}_`;
if (params?.database) csrfCookieName += `${params.database}_`;
if (targetDatabase) csrfCookieName += `${targetDatabase}_`;
csrfCookieName += cookiesCSRFName;
return {

View File

@ -1,163 +0,0 @@
// @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;
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
};

View File

@ -51,7 +51,9 @@ async function addDbEntry({
/**
* Initialize variables
*/
const isMaster = dbContext?.match(/dsql.user/i)
const isMaster = useLocal
? true
: dbContext?.match(/dsql.user/i)
? false
: dbFullName && !dbFullName.match(/^datasquirel$/)
? false

View File

@ -41,7 +41,9 @@ async function deleteDbEntry({
/**
* Check if data is valid
*/
const isMaster = dbContext?.match(/dsql.user/i)
const isMaster = useLocal
? true
: dbContext?.match(/dsql.user/i)
? false
: dbFullName && !dbFullName.match(/^datasquirel$/)
? false

View File

@ -1,41 +1,14 @@
// @ts-check
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
/**
* Sanitize SQL function
* ==============================================================================
* @description this function takes in a text(or number) and returns a sanitized
* text, usually without spaces
* # Path Traversal Check
*
* @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;

View File

@ -1,10 +1,4 @@
export = runQuery;
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/**
* Run DSQL users queries
* ==============================================================================

View File

@ -1,12 +1,3 @@
/** # 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");
@ -15,20 +6,12 @@ const LOCAL_DB_HANDLER = require("../../../utils/backend/global-db/LOCAL_DB_HAND
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 parseDbResults = require("../parseDbResults");
const trimSql = require("../../../utils/trim-sql");
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/**
* Run DSQL users queries
* ==============================================================================
@ -100,31 +83,19 @@ async function runQuery({
if (
readOnly &&
formattedQuery.match(
/^alter|^delete|information_schema|databases|^create/i
/^alter|^delete|information_schema|^create/i
)
) {
throw new Error("Wrong Input!");
}
if (local) {
console.log("Using Local ...");
const rawResults = await LOCAL_DB_HANDLER(
formattedQuery,
queryValuesArray
);
result = tableSchema
? parseDbResults({
unparsedResults: rawResults,
tableSchema,
})
: rawResults;
} else if (readOnly) {
if (readOnly) {
result = await varReadOnlyDatabaseDbHandler({
queryString: formattedQuery,
queryValuesArray: queryValuesArray?.map((vl) => String(vl)),
database: dbFullName,
tableSchema,
useLocal: local,
});
} else {
result = await fullAccessDbHandler({
@ -132,6 +103,7 @@ async function runQuery({
queryValuesArray: queryValuesArray?.map((vl) => String(vl)),
database: dbFullName,
tableSchema,
local,
});
}
} else if (typeof query === "object") {
@ -163,6 +135,7 @@ async function runQuery({
duplicateColumnName,
duplicateColumnValue,
tableSchema,
useLocal: local,
});
if (!result?.insertId) {
@ -181,6 +154,7 @@ async function runQuery({
identifierColumnName,
identifierValue,
tableSchema,
useLocal: local,
});
break;
@ -194,6 +168,7 @@ async function runQuery({
identifierColumnName,
identifierValue,
tableSchema,
useLocal: local,
});
break;

View File

@ -2,13 +2,6 @@
const _ = require("lodash");
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
/**
* Sanitize SQL function
* ==============================================================================
@ -22,53 +15,18 @@ const _ = require("lodash");
* @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) {
@ -83,45 +41,18 @@ function sanitizeSql(text, spaces, regex) {
.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
* ==============================================================================
@ -157,13 +88,6 @@ function sanitizeObjects(object, spaces) {
return objectUpdated;
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
/**
* Sanitize Objects Function
* ==============================================================================
@ -197,11 +121,4 @@ function sanitizeArrays(array, spaces) {
return arrayUpdated;
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
module.exports = sanitizeSql;

View File

@ -51,7 +51,9 @@ async function updateDbEntry({
*/
if (!data || !Object.keys(data).length) return null;
const isMaster = dbContext?.match(/dsql.user/i)
const isMaster = useLocal
? true
: dbContext?.match(/dsql.user/i)
? false
: dbFullName && !dbFullName.match(/^datasquirel$/)
? false

View File

@ -8,8 +8,4 @@
const defaultFieldsRegexp =
/^id$|^uuid$|^date_created$|^date_created_code$|^date_created_timestamp$|^date_updated$|^date_updated_code$|^date_updated_timestamp$/;
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
module.exports = defaultFieldsRegexp;

View File

@ -1,6 +1,7 @@
// @ts-check
const DSQL_USER_DB_HANDLER = require("../../utils/backend/global-db/DSQL_USER_DB_HANDLER");
const LOCAL_DB_HANDLER = require("../../utils/backend/global-db/LOCAL_DB_HANDLER");
const parseDbResults = require("./parseDbResults");
const serverError = require("./serverError");
@ -36,7 +37,9 @@ module.exports = async function fullAccessDbHandler({
try {
/** ********************* Run Query */
results = await DSQL_USER_DB_HANDLER({
results = local
? await LOCAL_DB_HANDLER(queryString, queryValuesArray)
: await DSQL_USER_DB_HANDLER({
paradigm: "Full Access",
database,
queryString,

View File

@ -31,7 +31,11 @@ module.exports = async function varDatabaseDbHandler({
*
* @description Declare "results" variable
*/
const isMaster = database?.match(/^datasquirel$/) ? true : false;
const isMaster = useLocal
? true
: database?.match(/^datasquirel$/)
? true
: false;
/** @type {any} */
const FINAL_DB_HANDLER = useLocal

View File

@ -1,7 +1,8 @@
declare function _exports({ queryString, database, queryValuesArray, tableSchema, }: {
declare function _exports({ queryString, database, queryValuesArray, tableSchema, useLocal, }: {
queryString: string;
database: string;
queryValuesArray?: string[];
tableSchema?: import("../../types").DSQL_TableSchemaType;
useLocal?: boolean;
}): Promise<any>;
export = _exports;

View File

@ -4,6 +4,7 @@ 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");
const LOCAL_DB_HANDLER = require("../../utils/backend/global-db/LOCAL_DB_HANDLER");
/**
*
@ -12,6 +13,7 @@ const DSQL_USER_DB_HANDLER = require("../../utils/backend/global-db/DSQL_USER_DB
* @param {string} param0.database
* @param {string[]} [param0.queryValuesArray]
* @param {import("../../types").DSQL_TableSchemaType} [param0.tableSchema]
* @param {boolean} [param0.useLocal]
* @returns
*/
module.exports = async function varReadOnlyDatabaseDbHandler({
@ -19,6 +21,7 @@ module.exports = async function varReadOnlyDatabaseDbHandler({
database,
queryValuesArray,
tableSchema,
useLocal,
}) {
/**
* Declare variables
@ -33,7 +36,9 @@ module.exports = async function varReadOnlyDatabaseDbHandler({
* @description Fetch data from db if no cache
*/
try {
results = await DSQL_USER_DB_HANDLER({
results = useLocal
? await LOCAL_DB_HANDLER(queryString, queryValuesArray)
: await DSQL_USER_DB_HANDLER({
paradigm: "Read Only",
database,
queryString,

View File

@ -110,7 +110,7 @@ async function refreshUsersAndGrants({
!mariadbUser
) {
const createNewUser = await noDatabaseDbHandler(
`CREATE USER IF NOT EXISTS '${dslUsername}'@'${defaultMariadbUserHost}' IDENTIFIED BY '${dsqlPassword}' REQUIRE SSL`
`CREATE USER IF NOT EXISTS '${dslUsername}'@'${defaultMariadbUserHost}' IDENTIFIED BY '${dsqlPassword}'`
);
console.log("createNewUser", createNewUser);
@ -223,7 +223,7 @@ async function refreshUsersAndGrants({
if (!isExtraMariadbUserExisting) {
await noDatabaseDbHandler(
`CREATE USER IF NOT EXISTS '${username}'@'${host}' IDENTIFIED BY '${decrptedPassword}' REQUIRE SSL`
`CREATE USER IF NOT EXISTS '${username}'@'${host}' IDENTIFIED BY '${decrptedPassword}'`
);
}

View File

@ -60,7 +60,7 @@ async function resetSQLCredentials() {
);
await noDatabaseDbHandler(
`CREATE USER IF NOT EXISTS '${username}'@'${defaultMariadbUserHost}' IDENTIFIED BY '${password}' REQUIRE SSL`
`CREATE USER IF NOT EXISTS '${username}'@'${defaultMariadbUserHost}' IDENTIFIED BY '${password}'`
);
await noDatabaseDbHandler(

View File

@ -56,7 +56,7 @@ async function setSQLCredentials() {
const encryptedPassword = encrypt({ data: password });
await noDatabaseDbHandler(
`CREATE USER IF NOT EXISTS '${username}'@'127.0.0.1' IDENTIFIED BY '${password}' REQUIRE SSL`
`CREATE USER IF NOT EXISTS '${username}'@'127.0.0.1' IDENTIFIED BY '${password}'`
);
await noDatabaseDbHandler(

View File

@ -59,7 +59,7 @@ async function testSQLEscape() {
);
await noDatabaseDbHandler(
`CREATE USER IF NOT EXISTS '${username}'@'${defaultMariadbUserHost}' IDENTIFIED BY '${password}' REQUIRE SSL`
`CREATE USER IF NOT EXISTS '${username}'@'${defaultMariadbUserHost}' IDENTIFIED BY '${password}'`
);
await noDatabaseDbHandler(

View File

@ -56,7 +56,7 @@ const connection = mysql({
}
const addUserSSL = await connection.query(
`ALTER USER '${User}'@'${Host}' REQUIRE SSL`
`ALTER USER '${User}'@'${Host}'`
);
console.log(`addUserSSL => ${User}@${Host}`, addUserSSL);

View File

@ -218,8 +218,8 @@ export type UserDataPayload = {
first_name: string;
last_name: string;
email: string;
password: string;
username: string;
password?: string;
username?: string;
} & {
[key: string]: any;
};

View File

@ -256,8 +256,8 @@ export type UserDataPayload = {
first_name: string;
last_name: string;
email: string;
password: string;
username: string;
password?: string;
username?: string;
} & {
[key: string]: any;
};

View File

@ -1,6 +1,6 @@
{
"name": "@moduletrace/datasquirel",
"version": "2.7.8",
"version": "2.7.9",
"description": "Cloud-based SQL data management tool",
"main": "index.js",
"bin": {

View File

@ -36,15 +36,21 @@ async function addUser({
*
* @description Look for local db settings in `.env` file and by pass the http request if available
*/
const { DSQL_HOST, DSQL_USER, DSQL_PASS, DSQL_DB_NAME } = process.env;
const {
DSQL_DB_HOST,
DSQL_DB_USERNAME,
DSQL_DB_PASSWORD,
DSQL_DB_NAME,
DSQL_API_USER_ID,
} = process.env;
const grabedHostNames = grabHostNames();
const { host, port, scheme } = grabedHostNames;
if (
DSQL_HOST?.match(/./) &&
DSQL_USER?.match(/./) &&
DSQL_PASS?.match(/./) &&
DSQL_DB_HOST?.match(/./) &&
DSQL_DB_USERNAME?.match(/./) &&
DSQL_DB_PASSWORD?.match(/./) &&
DSQL_DB_NAME?.match(/./) &&
useLocal
) {
@ -59,7 +65,6 @@ async function addUser({
dbSchema = JSON.parse(fs.readFileSync(localDbSchemaPath, "utf8"));
} catch (error) {}
if (dbSchema) {
return await apiCreateUser({
database: DSQL_DB_NAME,
encryptionKey,
@ -68,7 +73,6 @@ async function addUser({
useLocal,
});
}
}
/**
* Make https request

View File

@ -5,7 +5,7 @@ export = deleteUser;
*
* @param {object} params - API Key
* @param {String} [params.key] - API Key
* @param {String} params.database - Target Database
* @param {String} [params.database] - Target Database
* @param {String | number} params.deletedUserId - Target Database
* @param {boolean} [params.user_id] - User ID
* @param {boolean} [params.useLocal]
@ -14,7 +14,7 @@ export = deleteUser;
*/
declare function deleteUser({ key, database, user_id, useLocal, deletedUserId }: {
key?: string;
database: string;
database?: string;
deletedUserId: string | number;
user_id?: boolean;
useLocal?: boolean;

View File

@ -14,7 +14,7 @@ const apiDeleteUser = require("../package-shared/functions/api/users/api-delete-
*
* @param {object} params - API Key
* @param {String} [params.key] - API Key
* @param {String} params.database - Target Database
* @param {String} [params.database] - Target Database
* @param {String | number} params.deletedUserId - Target Database
* @param {boolean} [params.user_id] - User ID
* @param {boolean} [params.useLocal]
@ -27,15 +27,16 @@ async function deleteUser({ key, database, user_id, useLocal, deletedUserId }) {
*
* @description Look for local db settings in `.env` file and by pass the http request if available
*/
const { DSQL_HOST, DSQL_USER, DSQL_PASS, DSQL_DB_NAME } = process.env;
const { DSQL_DB_HOST, DSQL_DB_USERNAME, DSQL_DB_PASSWORD, DSQL_DB_NAME } =
process.env;
const grabedHostNames = grabHostNames();
const { host, port, scheme } = grabedHostNames;
if (
DSQL_HOST?.match(/./) &&
DSQL_USER?.match(/./) &&
DSQL_PASS?.match(/./) &&
DSQL_DB_HOST?.match(/./) &&
DSQL_DB_USERNAME?.match(/./) &&
DSQL_DB_PASSWORD?.match(/./) &&
DSQL_DB_NAME?.match(/./) &&
useLocal
) {
@ -50,14 +51,12 @@ async function deleteUser({ key, database, user_id, useLocal, deletedUserId }) {
dbSchema = JSON.parse(fs.readFileSync(localDbSchemaPath, "utf8"));
} catch (error) {}
if (dbSchema) {
return await apiDeleteUser({
dbFullName: DSQL_DB_NAME,
useLocal,
deletedUserId,
});
}
}
/**
* Make https request

View File

@ -73,12 +73,13 @@ async function getUser({ key, userId, database, fields, user_id, useLocal }) {
*
* @description Look for local db settings in `.env` file and by pass the http request if available
*/
const { DSQL_HOST, DSQL_USER, DSQL_PASS, DSQL_DB_NAME } = process.env;
const { DSQL_DB_HOST, DSQL_DB_USERNAME, DSQL_DB_PASSWORD, DSQL_DB_NAME } =
process.env;
if (
DSQL_HOST?.match(/./) &&
DSQL_USER?.match(/./) &&
DSQL_PASS?.match(/./) &&
DSQL_DB_HOST?.match(/./) &&
DSQL_DB_USERNAME?.match(/./) &&
DSQL_DB_PASSWORD?.match(/./) &&
DSQL_DB_NAME?.match(/./) &&
useLocal
) {
@ -93,7 +94,6 @@ async function getUser({ key, userId, database, fields, user_id, useLocal }) {
dbSchema = JSON.parse(fs.readFileSync(localDbSchemaPath, "utf8"));
} catch (error) {}
if (dbSchema) {
return await apiGetUser({
userId,
fields: [...new Set(updatedFields)],
@ -101,7 +101,6 @@ async function getUser({ key, userId, database, fields, user_id, useLocal }) {
useLocal,
});
}
}
/**
* Make https request

View File

@ -10,7 +10,7 @@ export = loginUser;
* @param {{
* email?: string,
* username?: string,
* password: string,
* password?: string,
* }} params.payload Login Email/Username and Password
* @param {string[]} [params.additionalFields] - Additional Fields to be added to the user object
* @param {http.ServerResponse & Object<string, any>} [params.response] - Http response object
@ -20,7 +20,7 @@ export = loginUser;
* @param {string} [params.email_login_code] - Email login code
* @param {string} [params.temp_code_field] - Database table field name for temporary code
* @param {boolean} [params.token] - Send access key as part of response body?
* @param {boolean} [params.user_id] - User ID
* @param {string | number} [params.user_id] - User ID
* @param {boolean} [params.skipPassword]
* @param {boolean} [params.useLocal]
* @param {string | number} [params.apiUserID] - Required for setting of cookies
@ -33,7 +33,7 @@ declare function loginUser({ key, payload, database, additionalFields, response,
payload: {
email?: string;
username?: string;
password: string;
password?: string;
};
additionalFields?: string[];
response?: http.ServerResponse & {
@ -45,7 +45,7 @@ declare function loginUser({ key, payload, database, additionalFields, response,
email_login_code?: string;
temp_code_field?: string;
token?: boolean;
user_id?: boolean;
user_id?: string | number;
skipPassword?: boolean;
useLocal?: boolean;
apiUserID?: string | number;

View File

@ -28,7 +28,7 @@ const {
* @param {{
* email?: string,
* username?: string,
* password: string,
* password?: string,
* }} params.payload Login Email/Username and Password
* @param {string[]} [params.additionalFields] - Additional Fields to be added to the user object
* @param {http.ServerResponse & Object<string, any>} [params.response] - Http response object
@ -38,7 +38,7 @@ const {
* @param {string} [params.email_login_code] - Email login code
* @param {string} [params.temp_code_field] - Database table field name for temporary code
* @param {boolean} [params.token] - Send access key as part of response body?
* @param {boolean} [params.user_id] - User ID
* @param {string | number} [params.user_id] - User ID
* @param {boolean} [params.skipPassword]
* @param {boolean} [params.useLocal]
* @param {string | number} [params.apiUserID] - Required for setting of cookies
@ -121,12 +121,13 @@ async function loginUser({
*
* @description Look for local db settings in `.env` file and by pass the http request if available
*/
const { DSQL_HOST, DSQL_USER, DSQL_PASS, DSQL_DB_NAME } = process.env;
const { DSQL_DB_HOST, DSQL_DB_USERNAME, DSQL_DB_PASSWORD, DSQL_DB_NAME } =
process.env;
if (
DSQL_HOST?.match(/./) &&
DSQL_USER?.match(/./) &&
DSQL_PASS?.match(/./) &&
DSQL_DB_HOST?.match(/./) &&
DSQL_DB_USERNAME?.match(/./) &&
DSQL_DB_PASSWORD?.match(/./) &&
DSQL_DB_NAME?.match(/./) &&
useLocal
) {
@ -141,7 +142,6 @@ async function loginUser({
dbSchema = JSON.parse(fs.readFileSync(localDbSchemaPath, "utf8"));
} catch (error) {}
if (dbSchema) {
httpResponse = await apiLoginUser({
database: process.env.DSQL_DB_NAME || "",
email: payload.email,
@ -156,7 +156,6 @@ async function loginUser({
token,
useLocal,
});
}
} else {
/**
* Make https request
@ -245,7 +244,7 @@ async function loginUser({
const cookieNames = getAuthCookieNames({
database,
userId: apiUserID || process.env.DSQL_API_USER_ID,
userId: apiUserID || user_id || grabedHostNames.user_id,
});
if (httpResponse.csrf) {

View File

@ -13,7 +13,7 @@ export = reauthUser;
*
* @param {object} params - Single Param object containing params
* @param {String} [params.key] - API Key
* @param {String} params.database - Target Database
* @param {String} [params.database]- Target Database slug
* @param {http.ServerResponse} [params.response] - Http response object
* @param {http.IncomingMessage} [params.request] - Http request object
* @param {("deep" | "normal")} [params.level] - Authentication level
@ -21,14 +21,14 @@ export = reauthUser;
* @param {String} [params.encryptionSalt] - Encryption Salt
* @param {string[]} [params.additionalFields] - Additional Fields to be added to the user object
* @param {string} [params.encryptedUserString] - encrypted user string to use instead of getting from cookie header
* @param {boolean} [params.user_id] - User ID
* @param {string | number} [params.user_id] - User ID
* @param {boolean} [params.useLocal]
*
* @returns { Promise<import("../package-shared/types").APILoginFunctionReturn> }
*/
declare function reauthUser({ key, database, response, request, level, encryptionKey, encryptionSalt, additionalFields, encryptedUserString, user_id, useLocal, }: {
key?: string;
database: string;
database?: string;
response?: http.ServerResponse;
request?: http.IncomingMessage;
level?: ("deep" | "normal");
@ -36,7 +36,7 @@ declare function reauthUser({ key, database, response, request, level, encryptio
encryptionSalt?: string;
additionalFields?: string[];
encryptedUserString?: string;
user_id?: boolean;
user_id?: string | number;
useLocal?: boolean;
}): Promise<import("../package-shared/types").APILoginFunctionReturn>;
import http = require("http");

View File

@ -35,7 +35,7 @@ const getAuthCookieNames = require("../package-shared/functions/backend/cookies/
*
* @param {object} params - Single Param object containing params
* @param {String} [params.key] - API Key
* @param {String} params.database - Target Database
* @param {String} [params.database]- Target Database slug
* @param {http.ServerResponse} [params.response] - Http response object
* @param {http.IncomingMessage} [params.request] - Http request object
* @param {("deep" | "normal")} [params.level] - Authentication level
@ -43,7 +43,7 @@ const getAuthCookieNames = require("../package-shared/functions/backend/cookies/
* @param {String} [params.encryptionSalt] - Encryption Salt
* @param {string[]} [params.additionalFields] - Additional Fields to be added to the user object
* @param {string} [params.encryptedUserString] - encrypted user string to use instead of getting from cookie header
* @param {boolean} [params.user_id] - User ID
* @param {string | number} [params.user_id] - User ID
* @param {boolean} [params.useLocal]
*
* @returns { Promise<import("../package-shared/types").APILoginFunctionReturn> }
@ -101,12 +101,13 @@ async function reauthUser({
*
* @description Look for local db settings in `.env` file and by pass the http request if available
*/
const { DSQL_HOST, DSQL_USER, DSQL_PASS, DSQL_DB_NAME } = process.env;
const { DSQL_DB_HOST, DSQL_DB_USERNAME, DSQL_DB_PASSWORD, DSQL_DB_NAME } =
process.env;
if (
DSQL_HOST?.match(/./) &&
DSQL_USER?.match(/./) &&
DSQL_PASS?.match(/./) &&
DSQL_DB_HOST?.match(/./) &&
DSQL_DB_USERNAME?.match(/./) &&
DSQL_DB_PASSWORD?.match(/./) &&
DSQL_DB_NAME?.match(/./) &&
useLocal
) {
@ -121,14 +122,11 @@ async function reauthUser({
dbSchema = JSON.parse(fs.readFileSync(localDbSchemaPath, "utf8"));
} catch (error) {}
if (dbSchema) {
httpResponse = await apiReauthUser({
existingUser: existingUser.payload,
additionalFields,
database: DSQL_DB_NAME,
useLocal,
});
}
} else {
/**
* Make https request
@ -203,8 +201,10 @@ async function reauthUser({
encryptionSalt: finalEncryptionSalt,
});
const { userId } = httpResponse;
const cookieNames = getAuthCookieNames({ database, userId });
const cookieNames = getAuthCookieNames({
database,
userId: user_id || grabedHostNames.user_id,
});
httpResponse["cookieNames"] = cookieNames;
httpResponse["key"] = String(encryptedPayload);

View File

@ -105,12 +105,13 @@ async function sendEmailCode({
*
* @description Look for local db settings in `.env` file and by pass the http request if available
*/
const { DSQL_HOST, DSQL_USER, DSQL_PASS, DSQL_DB_NAME } = process.env;
const { DSQL_DB_HOST, DSQL_DB_USERNAME, DSQL_DB_PASSWORD, DSQL_DB_NAME } =
process.env;
if (
DSQL_HOST?.match(/./) &&
DSQL_USER?.match(/./) &&
DSQL_PASS?.match(/./) &&
DSQL_DB_HOST?.match(/./) &&
DSQL_DB_USERNAME?.match(/./) &&
DSQL_DB_PASSWORD?.match(/./) &&
DSQL_DB_NAME?.match(/./) &&
useLocal
) {
@ -125,7 +126,6 @@ async function sendEmailCode({
dbSchema = JSON.parse(fs.readFileSync(localDbSchemaPath, "utf8"));
} catch (error) {}
if (dbSchema) {
httpResponse = await apiSendEmailCode({
database: DSQL_DB_NAME,
email,
@ -138,7 +138,6 @@ async function sendEmailCode({
sender,
useLocal,
});
}
} else {
/**
* Make https request

View File

@ -141,9 +141,9 @@ async function githubAuth({
* @description Look for local db settings in `.env` file and by pass the http request if available
*/
const {
DSQL_HOST,
DSQL_USER,
DSQL_PASS,
DSQL_DB_HOST,
DSQL_DB_USERNAME,
DSQL_DB_PASSWORD,
DSQL_DB_NAME,
DSQL_KEY,
DSQL_REF_DB_NAME,
@ -151,9 +151,9 @@ async function githubAuth({
} = process.env;
if (
DSQL_HOST?.match(/./) &&
DSQL_USER?.match(/./) &&
DSQL_PASS?.match(/./) &&
DSQL_DB_HOST?.match(/./) &&
DSQL_DB_USERNAME?.match(/./) &&
DSQL_DB_PASSWORD?.match(/./) &&
DSQL_DB_NAME?.match(/./)
) {
/** @type {import("../../package-shared/types").DSQL_DatabaseSchemaType | undefined | undefined} */
@ -167,7 +167,6 @@ async function githubAuth({
dbSchema = JSON.parse(fs.readFileSync(localDbSchemaPath, "utf8"));
} catch (error) {}
if (dbSchema) {
httpResponse = await apiGithubLogin({
code,
email: email || undefined,
@ -177,7 +176,6 @@ async function githubAuth({
res: response,
database: DSQL_DB_NAME,
});
}
} else {
/**
* Make https request

View File

@ -124,12 +124,13 @@ async function googleAuth({
*
* @description Look for local db settings in `.env` file and by pass the http request if available
*/
const { DSQL_HOST, DSQL_USER, DSQL_PASS, DSQL_DB_NAME } = process.env;
const { DSQL_DB_HOST, DSQL_DB_USERNAME, DSQL_DB_PASSWORD, DSQL_DB_NAME } =
process.env;
if (
DSQL_HOST?.match(/./) &&
DSQL_USER?.match(/./) &&
DSQL_PASS?.match(/./) &&
DSQL_DB_HOST?.match(/./) &&
DSQL_DB_USERNAME?.match(/./) &&
DSQL_DB_PASSWORD?.match(/./) &&
DSQL_DB_NAME?.match(/./) &&
useLocal
) {

View File

@ -5,7 +5,7 @@ export = updateUser;
*
* @param {object} params - API Key
* @param {String} [params.key] - API Key
* @param {String} params.database - Target Database
* @param {String} [params.database] - Target Database
* @param {String | number} params.updatedUserId - Target Database
* @param {Object.<string, any>} params.payload - User Object: ID is required
* @param {boolean} [params.user_id] - User ID
@ -15,7 +15,7 @@ export = updateUser;
*/
declare function updateUser({ key, payload, database, user_id, useLocal, updatedUserId, }: {
key?: string;
database: string;
database?: string;
updatedUserId: string | number;
payload: {
[x: string]: any;

View File

@ -13,7 +13,7 @@ const apiUpdateUser = require("../package-shared/functions/api/users/api-update-
*
* @param {object} params - API Key
* @param {String} [params.key] - API Key
* @param {String} params.database - Target Database
* @param {String} [params.database] - Target Database
* @param {String | number} params.updatedUserId - Target Database
* @param {Object.<string, any>} params.payload - User Object: ID is required
* @param {boolean} [params.user_id] - User ID
@ -34,15 +34,16 @@ async function updateUser({
*
* @description Look for local db settings in `.env` file and by pass the http request if available
*/
const { DSQL_HOST, DSQL_USER, DSQL_PASS, DSQL_DB_NAME } = process.env;
const { DSQL_DB_HOST, DSQL_DB_USERNAME, DSQL_DB_PASSWORD, DSQL_DB_NAME } =
process.env;
const grabedHostNames = grabHostNames();
const { host, port, scheme } = grabedHostNames;
if (
DSQL_HOST?.match(/./) &&
DSQL_USER?.match(/./) &&
DSQL_PASS?.match(/./) &&
DSQL_DB_HOST?.match(/./) &&
DSQL_DB_USERNAME?.match(/./) &&
DSQL_DB_PASSWORD?.match(/./) &&
DSQL_DB_NAME?.match(/./) &&
useLocal
) {
@ -57,7 +58,6 @@ async function updateUser({
dbSchema = JSON.parse(fs.readFileSync(localDbSchemaPath, "utf8"));
} catch (error) {}
if (dbSchema) {
return await apiUpdateUser({
payload: payload,
dbFullName: DSQL_DB_NAME,
@ -66,7 +66,6 @@ async function updateUser({
dbSchema,
});
}
}
/**
* Make https request