From 586e3cfa856d961c4073fbf701089f9cf930b7ea Mon Sep 17 00:00:00 2001 From: Benjamin Toby Date: Mon, 9 Dec 2024 12:45:39 +0100 Subject: [PATCH] Updates --- .../api/social-login/facebookLogin.js | 2 +- .../functions/api/users/api-create-user.js | 6 +- .../functions/api/users/api-get-user.js | 3 +- .../functions/api/users/api-login.js | 2 - .../functions/api/users/api-reauth-user.d.ts | 2 +- .../functions/api/users/api-reauth-user.js | 17 +- .../functions/api/users/api-update-user.js | 1 - .../functions/backend/addMariadbUser.js | 2 +- .../backend/cookies/get-auth-cookie-names.js | 8 +- package-shared/functions/backend/db/add.js | 163 ------------------ .../functions/backend/db/addDbEntry.js | 4 +- .../functions/backend/db/deleteDbEntry.js | 4 +- .../backend/db/pathTraversalCheck.js | 29 +--- .../functions/backend/db/runQuery.d.ts | 6 - .../functions/backend/db/runQuery.js | 39 +---- .../functions/backend/db/sanitizeSql.js | 83 --------- .../functions/backend/db/updateDbEntry.js | 4 +- .../functions/backend/defaultFieldsRegexp.js | 4 - .../functions/backend/fullAccessDbHandler.js | 15 +- .../functions/backend/varDatabaseDbHandler.js | 6 +- .../backend/varReadOnlyDatabaseDbHandler.d.ts | 3 +- .../backend/varReadOnlyDatabaseDbHandler.js | 17 +- .../mariadb-users/refreshUsersAndGrants.js | 4 +- package-shared/shell/resetSQLCredentials.js | 2 +- package-shared/shell/setSQLCredentials.js | 2 +- package-shared/shell/testSQLEscape.js | 2 +- package-shared/shell/updateSSLUsers.js | 2 +- package-shared/types/index.d.ts | 4 +- package-shared/types/index.ts | 4 +- package.json | 2 +- users/add-user.js | 30 ++-- users/delete-user.d.ts | 4 +- users/delete-user.js | 23 ++- users/get-user.js | 23 ++- users/login-user.d.ts | 8 +- users/login-user.js | 45 +++-- users/reauth-user.d.ts | 8 +- users/reauth-user.js | 32 ++-- users/send-email-code.js | 35 ++-- users/social/github-auth.js | 32 ++-- users/social/google-auth.js | 9 +- users/update-user.d.ts | 4 +- users/update-user.js | 27 ++- 43 files changed, 216 insertions(+), 506 deletions(-) delete mode 100644 package-shared/functions/backend/db/add.js diff --git a/package-shared/functions/api/social-login/facebookLogin.js b/package-shared/functions/api/social-login/facebookLogin.js index 7ca8996..f17a161 100755 --- a/package-shared/functions/api/social-login/facebookLogin.js +++ b/package-shared/functions/api/social-login/facebookLogin.js @@ -106,7 +106,7 @@ module.exports = async function facebookLogin({ usertype, body }) { //

We have a new buyer registration

//
Name: ${newFoundUser[0].first_name} ${newFoundUser[0].last_name}
//
Email: ${newFoundUser[0].email}
- //
Site: ${process.env.DSQL_HOST}
+ //
Site: ${process.env.DSQL_DB_HOST}
// `, // }).catch((error) => { // console.log( diff --git a/package-shared/functions/api/users/api-create-user.js b/package-shared/functions/api/users/api-create-user.js index 2580d5d..a22baa3 100644 --- a/package-shared/functions/api/users/api-create-user.js +++ b/package-shared/functions/api/users/api-create-user.js @@ -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) { diff --git a/package-shared/functions/api/users/api-get-user.js b/package-shared/functions/api/users/api-get-user.js index b086e26..ab0025b 100644 --- a/package-shared/functions/api/users/api-get-user.js +++ b/package-shared/functions/api/users/api-get-user.js @@ -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, }); diff --git a/package-shared/functions/api/users/api-login.js b/package-shared/functions/api/users/api-login.js index d721937..87f0603 100644 --- a/package-shared/functions/api/users/api-login.js +++ b/package-shared/functions/api/users/api-login.js @@ -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"); diff --git a/package-shared/functions/api/users/api-reauth-user.d.ts b/package-shared/functions/api/users/api-reauth-user.d.ts index e7e8b74..c5b9f99 100644 --- a/package-shared/functions/api/users/api-reauth-user.d.ts +++ b/package-shared/functions/api/users/api-reauth-user.d.ts @@ -2,7 +2,7 @@ declare function _exports({ existingUser, database, additionalFields, useLocal, existingUser: { [x: string]: any; }; - database: string; + database?: string; additionalFields?: string[]; useLocal?: boolean; }): Promise; diff --git a/package-shared/functions/api/users/api-reauth-user.js b/package-shared/functions/api/users/api-reauth-user.js index a47d5cb..3386bbb 100644 --- a/package-shared/functions/api/users/api-reauth-user.js +++ b/package-shared/functions/api/users/api-reauth-user.js @@ -8,7 +8,7 @@ const nodemailer = require("nodemailer"); * # Re-authenticate API user * @param {object} param * @param {Object} param.existingUser - * @param {string} param.database + * @param {string} [param.database] * @param {string[]} [param.additionalFields] * @param {boolean} [param.useLocal] * @@ -22,15 +22,12 @@ 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({ - queryString: `SELECT * FROM users WHERE id=?`, - queryValuesArray: [existingUser.id.toString()], - database, - }) + ? await varDatabaseDbHandler({ + queryString: `SELECT * FROM users WHERE id=?`, + queryValuesArray: [existingUser.id.toString()], + database, + useLocal, + }) : null; //////////////////////////////////////// diff --git a/package-shared/functions/api/users/api-update-user.js b/package-shared/functions/api/users/api-update-user.js index a03c158..2214210 100644 --- a/package-shared/functions/api/users/api-update-user.js +++ b/package-shared/functions/api/users/api-update-user.js @@ -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"); diff --git a/package-shared/functions/backend/addMariadbUser.js b/package-shared/functions/backend/addMariadbUser.js index 597e5bd..b07700d 100644 --- a/package-shared/functions/backend/addMariadbUser.js +++ b/package-shared/functions/backend/addMariadbUser.js @@ -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); diff --git a/package-shared/functions/backend/cookies/get-auth-cookie-names.js b/package-shared/functions/backend/cookies/get-auth-cookie-names.js index 5168adc..b9c498e 100644 --- a/package-shared/functions/backend/cookies/get-auth-cookie-names.js +++ b/package-shared/functions/backend/cookies/get-auth-cookie-names.js @@ -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 { diff --git a/package-shared/functions/backend/db/add.js b/package-shared/functions/backend/db/add.js deleted file mode 100644 index e091924..0000000 --- a/package-shared/functions/backend/db/add.js +++ /dev/null @@ -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; - - //////////////////////////////////////// - //////////////////////////////////////// - //////////////////////////////////////// -}; diff --git a/package-shared/functions/backend/db/addDbEntry.js b/package-shared/functions/backend/db/addDbEntry.js index 38d99c8..7370157 100644 --- a/package-shared/functions/backend/db/addDbEntry.js +++ b/package-shared/functions/backend/db/addDbEntry.js @@ -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 diff --git a/package-shared/functions/backend/db/deleteDbEntry.js b/package-shared/functions/backend/db/deleteDbEntry.js index 944ce50..ca450b8 100644 --- a/package-shared/functions/backend/db/deleteDbEntry.js +++ b/package-shared/functions/backend/db/deleteDbEntry.js @@ -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 diff --git a/package-shared/functions/backend/db/pathTraversalCheck.js b/package-shared/functions/backend/db/pathTraversalCheck.js index 2ac73b9..ee66714 100644 --- a/package-shared/functions/backend/db/pathTraversalCheck.js +++ b/package-shared/functions/backend/db/pathTraversalCheck.js @@ -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; diff --git a/package-shared/functions/backend/db/runQuery.d.ts b/package-shared/functions/backend/db/runQuery.d.ts index 4f1cc05..3353d87 100644 --- a/package-shared/functions/backend/db/runQuery.d.ts +++ b/package-shared/functions/backend/db/runQuery.d.ts @@ -1,10 +1,4 @@ export = runQuery; -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ /** * Run DSQL users queries * ============================================================================== diff --git a/package-shared/functions/backend/db/runQuery.js b/package-shared/functions/backend/db/runQuery.js index 7a64702..1c4eb3b 100644 --- a/package-shared/functions/backend/db/runQuery.js +++ b/package-shared/functions/backend/db/runQuery.js @@ -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; diff --git a/package-shared/functions/backend/db/sanitizeSql.js b/package-shared/functions/backend/db/sanitizeSql.js index 360d7d6..9cc6fdd 100644 --- a/package-shared/functions/backend/db/sanitizeSql.js +++ b/package-shared/functions/backend/db/sanitizeSql.js @@ -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(/(?", 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; diff --git a/package-shared/functions/backend/db/updateDbEntry.js b/package-shared/functions/backend/db/updateDbEntry.js index 3330114..95fa8cb 100644 --- a/package-shared/functions/backend/db/updateDbEntry.js +++ b/package-shared/functions/backend/db/updateDbEntry.js @@ -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 diff --git a/package-shared/functions/backend/defaultFieldsRegexp.js b/package-shared/functions/backend/defaultFieldsRegexp.js index 080dea6..acbcde7 100644 --- a/package-shared/functions/backend/defaultFieldsRegexp.js +++ b/package-shared/functions/backend/defaultFieldsRegexp.js @@ -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; diff --git a/package-shared/functions/backend/fullAccessDbHandler.js b/package-shared/functions/backend/fullAccessDbHandler.js index d789f1d..beb7b5a 100644 --- a/package-shared/functions/backend/fullAccessDbHandler.js +++ b/package-shared/functions/backend/fullAccessDbHandler.js @@ -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,12 +37,14 @@ module.exports = async function fullAccessDbHandler({ try { /** ********************* Run Query */ - results = await DSQL_USER_DB_HANDLER({ - paradigm: "Full Access", - database, - queryString, - queryValues: queryValuesArray, - }); + results = local + ? await LOCAL_DB_HANDLER(queryString, queryValuesArray) + : await DSQL_USER_DB_HANDLER({ + paradigm: "Full Access", + database, + queryString, + queryValues: queryValuesArray, + }); //////////////////////////////////////// } catch (/** @type {any} */ error) { diff --git a/package-shared/functions/backend/varDatabaseDbHandler.js b/package-shared/functions/backend/varDatabaseDbHandler.js index c58d67e..5e225dd 100644 --- a/package-shared/functions/backend/varDatabaseDbHandler.js +++ b/package-shared/functions/backend/varDatabaseDbHandler.js @@ -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 diff --git a/package-shared/functions/backend/varReadOnlyDatabaseDbHandler.d.ts b/package-shared/functions/backend/varReadOnlyDatabaseDbHandler.d.ts index 4bd2b65..a698c12 100644 --- a/package-shared/functions/backend/varReadOnlyDatabaseDbHandler.d.ts +++ b/package-shared/functions/backend/varReadOnlyDatabaseDbHandler.d.ts @@ -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; export = _exports; diff --git a/package-shared/functions/backend/varReadOnlyDatabaseDbHandler.js b/package-shared/functions/backend/varReadOnlyDatabaseDbHandler.js index 6b8d9e5..5910b67 100644 --- a/package-shared/functions/backend/varReadOnlyDatabaseDbHandler.js +++ b/package-shared/functions/backend/varReadOnlyDatabaseDbHandler.js @@ -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,12 +36,14 @@ module.exports = async function varReadOnlyDatabaseDbHandler({ * @description Fetch data from db if no cache */ try { - results = await DSQL_USER_DB_HANDLER({ - paradigm: "Read Only", - database, - queryString, - queryValues: queryValuesArray, - }); + results = useLocal + ? await LOCAL_DB_HANDLER(queryString, queryValuesArray) + : await DSQL_USER_DB_HANDLER({ + paradigm: "Read Only", + database, + queryString, + queryValues: queryValuesArray, + }); //////////////////////////////////////// } catch (/** @type {any} */ error) { diff --git a/package-shared/shell/mariadb-users/refreshUsersAndGrants.js b/package-shared/shell/mariadb-users/refreshUsersAndGrants.js index eb18bca..b38395d 100755 --- a/package-shared/shell/mariadb-users/refreshUsersAndGrants.js +++ b/package-shared/shell/mariadb-users/refreshUsersAndGrants.js @@ -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}'` ); } diff --git a/package-shared/shell/resetSQLCredentials.js b/package-shared/shell/resetSQLCredentials.js index cfb6aaf..8ad39ac 100755 --- a/package-shared/shell/resetSQLCredentials.js +++ b/package-shared/shell/resetSQLCredentials.js @@ -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( diff --git a/package-shared/shell/setSQLCredentials.js b/package-shared/shell/setSQLCredentials.js index c76b6e1..ca12fc6 100755 --- a/package-shared/shell/setSQLCredentials.js +++ b/package-shared/shell/setSQLCredentials.js @@ -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( diff --git a/package-shared/shell/testSQLEscape.js b/package-shared/shell/testSQLEscape.js index 32b8176..eea4405 100755 --- a/package-shared/shell/testSQLEscape.js +++ b/package-shared/shell/testSQLEscape.js @@ -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( diff --git a/package-shared/shell/updateSSLUsers.js b/package-shared/shell/updateSSLUsers.js index 01a7b76..a0a406d 100755 --- a/package-shared/shell/updateSSLUsers.js +++ b/package-shared/shell/updateSSLUsers.js @@ -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); diff --git a/package-shared/types/index.d.ts b/package-shared/types/index.d.ts index 5ca394b..b7ca79b 100644 --- a/package-shared/types/index.d.ts +++ b/package-shared/types/index.d.ts @@ -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; }; diff --git a/package-shared/types/index.ts b/package-shared/types/index.ts index 5250930..2a26ad9 100644 --- a/package-shared/types/index.ts +++ b/package-shared/types/index.ts @@ -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; }; diff --git a/package.json b/package.json index 2cfdc2b..586be4d 100644 --- a/package.json +++ b/package.json @@ -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": { diff --git a/users/add-user.js b/users/add-user.js index 6ea6beb..24174fa 100644 --- a/users/add-user.js +++ b/users/add-user.js @@ -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,15 +65,13 @@ async function addUser({ dbSchema = JSON.parse(fs.readFileSync(localDbSchemaPath, "utf8")); } catch (error) {} - if (dbSchema) { - return await apiCreateUser({ - database: DSQL_DB_NAME, - encryptionKey, - payload, - userId: apiUserId, - useLocal, - }); - } + return await apiCreateUser({ + database: DSQL_DB_NAME, + encryptionKey, + payload, + userId: apiUserId, + useLocal, + }); } /** diff --git a/users/delete-user.d.ts b/users/delete-user.d.ts index a905cf8..33678f8 100644 --- a/users/delete-user.d.ts +++ b/users/delete-user.d.ts @@ -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; diff --git a/users/delete-user.js b/users/delete-user.js index 217ad72..160ec93 100644 --- a/users/delete-user.js +++ b/users/delete-user.js @@ -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,13 +51,11 @@ 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, - }); - } + return await apiDeleteUser({ + dbFullName: DSQL_DB_NAME, + useLocal, + deletedUserId, + }); } /** diff --git a/users/get-user.js b/users/get-user.js index b40983d..032893a 100644 --- a/users/get-user.js +++ b/users/get-user.js @@ -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,14 +94,12 @@ 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)], - dbFullName: DSQL_DB_NAME, - useLocal, - }); - } + return await apiGetUser({ + userId, + fields: [...new Set(updatedFields)], + dbFullName: DSQL_DB_NAME, + useLocal, + }); } /** diff --git a/users/login-user.d.ts b/users/login-user.d.ts index 44819af..2e677ce 100644 --- a/users/login-user.d.ts +++ b/users/login-user.d.ts @@ -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} [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; diff --git a/users/login-user.js b/users/login-user.js index 771a905..c116cf0 100644 --- a/users/login-user.js +++ b/users/login-user.js @@ -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} [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,22 +142,20 @@ 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, - username: payload.username, - password: payload.password, - skipPassword, - encryptionKey: finalEncryptionKey, - additionalFields, - email_login, - email_login_code, - email_login_field: emailLoginTempCodeFieldName, - token, - useLocal, - }); - } + httpResponse = await apiLoginUser({ + database: process.env.DSQL_DB_NAME || "", + email: payload.email, + username: payload.username, + password: payload.password, + skipPassword, + encryptionKey: finalEncryptionKey, + additionalFields, + email_login, + email_login_code, + email_login_field: emailLoginTempCodeFieldName, + 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) { diff --git a/users/reauth-user.d.ts b/users/reauth-user.d.ts index de9b170..d6a4d12 100644 --- a/users/reauth-user.d.ts +++ b/users/reauth-user.d.ts @@ -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 } */ 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 http = require("http"); diff --git a/users/reauth-user.js b/users/reauth-user.js index 0403283..0145fbe 100644 --- a/users/reauth-user.js +++ b/users/reauth-user.js @@ -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 } @@ -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, - }); - } + httpResponse = await apiReauthUser({ + existingUser: existingUser.payload, + additionalFields, + 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); diff --git a/users/send-email-code.js b/users/send-email-code.js index d5edd72..0dfbd98 100644 --- a/users/send-email-code.js +++ b/users/send-email-code.js @@ -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,20 +126,18 @@ async function sendEmailCode({ dbSchema = JSON.parse(fs.readFileSync(localDbSchemaPath, "utf8")); } catch (error) {} - if (dbSchema) { - httpResponse = await apiSendEmailCode({ - database: DSQL_DB_NAME, - email, - email_login_field: emailLoginTempCodeFieldName, - html: emailHtml, - mail_domain, - mail_password, - mail_port, - mail_username, - sender, - useLocal, - }); - } + httpResponse = await apiSendEmailCode({ + database: DSQL_DB_NAME, + email, + email_login_field: emailLoginTempCodeFieldName, + html: emailHtml, + mail_domain, + mail_password, + mail_port, + mail_username, + sender, + useLocal, + }); } else { /** * Make https request diff --git a/users/social/github-auth.js b/users/social/github-auth.js index 894f553..48a064c 100644 --- a/users/social/github-auth.js +++ b/users/social/github-auth.js @@ -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,17 +167,15 @@ async function githubAuth({ dbSchema = JSON.parse(fs.readFileSync(localDbSchemaPath, "utf8")); } catch (error) {} - if (dbSchema) { - httpResponse = await apiGithubLogin({ - code, - email: email || undefined, - clientId, - clientSecret, - additionalFields, - res: response, - database: DSQL_DB_NAME, - }); - } + httpResponse = await apiGithubLogin({ + code, + email: email || undefined, + clientId, + clientSecret, + additionalFields, + res: response, + database: DSQL_DB_NAME, + }); } else { /** * Make https request diff --git a/users/social/google-auth.js b/users/social/google-auth.js index 3ab8221..24c39c1 100644 --- a/users/social/google-auth.js +++ b/users/social/google-auth.js @@ -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 ) { diff --git a/users/update-user.d.ts b/users/update-user.d.ts index cb8886b..1fe448a 100644 --- a/users/update-user.d.ts +++ b/users/update-user.d.ts @@ -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.} 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; diff --git a/users/update-user.js b/users/update-user.js index 3ed61be..e12aae0 100644 --- a/users/update-user.js +++ b/users/update-user.js @@ -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.} 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,15 +58,13 @@ async function updateUser({ dbSchema = JSON.parse(fs.readFileSync(localDbSchemaPath, "utf8")); } catch (error) {} - if (dbSchema) { - return await apiUpdateUser({ - payload: payload, - dbFullName: DSQL_DB_NAME, - useLocal, - updatedUserId, - dbSchema, - }); - } + return await apiUpdateUser({ + payload: payload, + dbFullName: DSQL_DB_NAME, + useLocal, + updatedUserId, + dbSchema, + }); } /**