diff --git a/package-shared/functions/api/query/get.d.ts b/package-shared/functions/api/query/get.d.ts index 44265cd..2caa093 100644 --- a/package-shared/functions/api/query/get.d.ts +++ b/package-shared/functions/api/query/get.d.ts @@ -1,8 +1,9 @@ -declare function _exports({ query, dbFullName, queryValues, tableName, dbSchema, }: { +declare function _exports({ query, dbFullName, queryValues, tableName, dbSchema, useLocal, }: { query: string; queryValues?: (string | number)[]; dbFullName: string; tableName?: string; dbSchema?: import("../../../types").DSQL_DatabaseSchemaType; + useLocal?: boolean; }): Promise; export = _exports; diff --git a/package-shared/functions/api/query/get.js b/package-shared/functions/api/query/get.js index 4227ad7..f992669 100644 --- a/package-shared/functions/api/query/get.js +++ b/package-shared/functions/api/query/get.js @@ -13,6 +13,7 @@ const runQuery = require("../../backend/db/runQuery"); * @param {string} params.dbFullName * @param {string} [params.tableName] * @param {import("../../../types").DSQL_DatabaseSchemaType} [params.dbSchema] + * @param {boolean} [params.useLocal] * * @returns {Promise} */ @@ -22,6 +23,7 @@ module.exports = async function apiGet({ queryValues, tableName, dbSchema, + useLocal, }) { if ( typeof query == "string" && @@ -46,6 +48,7 @@ module.exports = async function apiGet({ readOnly: true, dbSchema, tableName, + local: useLocal, }); /** @type {import("../../../types").DSQL_TableSchemaType | undefined} */ diff --git a/package-shared/functions/api/query/post.d.ts b/package-shared/functions/api/query/post.d.ts index c2f3f6c..b80a593 100644 --- a/package-shared/functions/api/query/post.d.ts +++ b/package-shared/functions/api/query/post.d.ts @@ -1,8 +1,9 @@ -declare function _exports({ query, dbFullName, queryValues, tableName, dbSchema, }: { +declare function _exports({ query, dbFullName, queryValues, tableName, dbSchema, useLocal, }: { query: any; queryValues?: (string | number)[]; dbFullName: string; tableName?: string; dbSchema?: import("../../../types").DSQL_DatabaseSchemaType; + useLocal?: boolean; }): Promise; export = _exports; diff --git a/package-shared/functions/api/query/post.js b/package-shared/functions/api/query/post.js index a197f88..c78fbfb 100644 --- a/package-shared/functions/api/query/post.js +++ b/package-shared/functions/api/query/post.js @@ -13,6 +13,7 @@ const runQuery = require("../../backend/db/runQuery"); * @param {string} params.dbFullName * @param {string} [params.tableName] * @param {import("../../../types").DSQL_DatabaseSchemaType} [params.dbSchema] + * @param {boolean} [params.useLocal] * * @returns {Promise} */ @@ -22,6 +23,7 @@ module.exports = async function apiPost({ queryValues, tableName, dbSchema, + useLocal, }) { if (typeof query === "string" && query?.match(/^create |^alter |^drop /i)) { return { success: false, msg: "Wrong Input" }; @@ -49,6 +51,7 @@ module.exports = async function apiPost({ dbSchema: dbSchema, queryValuesArray: queryValues, tableName, + local: useLocal, }); results = result; diff --git a/package-shared/functions/api/social-login/handleSocialDb.js b/package-shared/functions/api/social-login/handleSocialDb.js index f57474e..10c8655 100755 --- a/package-shared/functions/api/social-login/handleSocialDb.js +++ b/package-shared/functions/api/social-login/handleSocialDb.js @@ -20,6 +20,7 @@ const varDatabaseDbHandler = require("../../backend/varDatabaseDbHandler"); const encrypt = require("../../dsql/encrypt"); const addDbEntry = require("../../backend/db/addDbEntry"); const getAuthCookieNames = require("../../backend/cookies/get-auth-cookie-names"); +const LOCAL_DB_HANDLER = require("../../../utils/backend/global-db/LOCAL_DB_HANDLER"); ////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////// @@ -51,6 +52,7 @@ module.exports = async function handleSocialDb({ invitation, supEmail, additionalFields, + useLocal, }) { //////////////////////////////////////////////// //////////////////////////////////////////////// @@ -61,11 +63,22 @@ module.exports = async function handleSocialDb({ //////////////////////////////////////////////// //////////////////////////////////////////////// - let existingSocialIdUser = await varDatabaseDbHandler({ - database: database ? database : "datasquirel", - queryString: `SELECT * FROM users WHERE social_id = ? AND social_login='1' AND social_platform = ? `, - queryValuesArray: [social_id.toString(), social_platform], - }); + const existingSocialIdUserQuery = `SELECT * FROM users WHERE social_id = ? AND social_login='1' AND social_platform = ? `; + const existingSocialIdUserValues = [ + social_id.toString(), + social_platform, + ]; + + let existingSocialIdUser = useLocal + ? await LOCAL_DB_HANDLER( + existingSocialIdUserQuery, + existingSocialIdUserValues + ) + : await varDatabaseDbHandler({ + database: database ? database : "datasquirel", + queryString: existingSocialIdUserQuery, + queryValuesArray: existingSocialIdUserValues, + }); if (existingSocialIdUser && existingSocialIdUser[0]) { return await loginSocialUser({ @@ -75,6 +88,7 @@ module.exports = async function handleSocialDb({ invitation, database, additionalFields, + useLocal, }); } @@ -99,10 +113,14 @@ module.exports = async function handleSocialDb({ //////////////////////////////////////////////// //////////////////////////////////////////////// - let existingEmailOnly = await varDatabaseDbHandler({ - database: database ? database : "datasquirel", - queryString: `SELECT * FROM users WHERE email='${finalEmail}'`, - }); + const existingEmailOnlyQuery = `SELECT * FROM users WHERE email='${finalEmail}'`; + + let existingEmailOnly = useLocal + ? await LOCAL_DB_HANDLER(existingEmailOnlyQuery) + : await varDatabaseDbHandler({ + database: database ? database : "datasquirel", + queryString: existingEmailOnlyQuery, + }); if (existingEmailOnly && existingEmailOnly[0]) { return { @@ -117,10 +135,14 @@ module.exports = async function handleSocialDb({ //////////////////////////////////////////////// //////////////////////////////////////////////// - const foundUser = await varDatabaseDbHandler({ - database: database ? database : "datasquirel", - queryString: `SELECT * FROM users WHERE email='${finalEmail}' AND social_login='1' AND social_platform='${social_platform}' AND social_id='${social_id}'`, - }); + const foundUserQuery = `SELECT * FROM users WHERE email='${finalEmail}' AND social_login='1' AND social_platform='${social_platform}' AND social_id='${social_id}'`; + + const foundUser = useLocal + ? await LOCAL_DB_HANDLER(foundUserQuery) + : await varDatabaseDbHandler({ + database: database ? database : "datasquirel", + queryString: foundUserQuery, + }); if (foundUser && foundUser[0]) { return await loginSocialUser({ @@ -130,6 +152,7 @@ module.exports = async function handleSocialDb({ invitation, database, additionalFields, + useLocal, }); } @@ -164,6 +187,7 @@ module.exports = async function handleSocialDb({ ...data, email: finalEmail, }, + useLocal, }); if (newUser?.insertId) { @@ -171,13 +195,17 @@ module.exports = async function handleSocialDb({ /** * Add a Mariadb User for this User */ - await addMariadbUser({ userId: newUser.insertId }); + await addMariadbUser({ userId: newUser.insertId, useLocal }); } - const newUserQueried = await varDatabaseDbHandler({ - database: database ? database : "datasquirel", - queryString: `SELECT * FROM users WHERE id='${newUser.insertId}'`, - }); + const newUserQueriedQuery = `SELECT * FROM users WHERE id='${newUser.insertId}'`; + + const newUserQueried = useLocal + ? await LOCAL_DB_HANDLER(newUserQueriedQuery) + : await varDatabaseDbHandler({ + database: database ? database : "datasquirel", + queryString: newUserQueriedQuery, + }); if (!newUserQueried || !newUserQueried[0]) return { @@ -263,6 +291,7 @@ module.exports = async function handleSocialDb({ invitation, database, additionalFields, + useLocal, }); //////////////////////////////////////////////// @@ -326,6 +355,7 @@ module.exports = async function handleSocialDb({ * @param {any} [params.invitation] - A query object if user was invited * @param {string} [params.database] - Target Database * @param {object} [params.additionalFields] - Additional fields to be added to the user payload + * @param {boolean} [params.useLocal] * * @returns {Promise} */ @@ -336,11 +366,16 @@ async function loginSocialUser({ invitation, database, additionalFields, + useLocal, }) { - const foundUser = await varDatabaseDbHandler({ - database: database ? database : "datasquirel", - queryString: `SELECT * FROM users WHERE email='${user.email}' AND social_id='${user.social_id}' AND social_platform='${social_platform}'`, - }); + const foundUserQuery = `SELECT * FROM users WHERE email='${user.email}' AND social_id='${user.social_id}' AND social_platform='${social_platform}'`; + + const foundUser = useLocal + ? await LOCAL_DB_HANDLER(foundUserQuery) + : await varDatabaseDbHandler({ + database: database ? database : "datasquirel", + queryString: foundUserQuery, + }); if (!foundUser?.[0]) return { diff --git a/package-shared/functions/api/users/api-create-user.js b/package-shared/functions/api/users/api-create-user.js index 63a0cdc..6bff8be 100644 --- a/package-shared/functions/api/users/api-create-user.js +++ b/package-shared/functions/api/users/api-create-user.js @@ -1,5 +1,6 @@ // @ts-check +const LOCAL_DB_HANDLER = require("../../../utils/backend/global-db/LOCAL_DB_HANDLER"); const addUsersTableToDb = require("../../backend/addUsersTableToDb"); const addDbEntry = require("../../backend/db/addDbEntry"); const varDatabaseDbHandler = require("../../backend/varDatabaseDbHandler"); @@ -11,25 +12,48 @@ module.exports = async function apiCreateUser({ payload, database, userId, + useLocal, }) { const dbFullName = database; + const finalEncryptionKey = + encryptionKey || process.env.DSQL_ENCRYPTION_PASSWORD; + + if (!finalEncryptionKey) { + return { + success: false, + msg: "No encryption key provided", + payload: null, + }; + } + + if (!finalEncryptionKey?.match(/.{8,}/)) { + return { + success: false, + msg: "Encryption key must be at least 8 characters long", + payload: null, + }; + } + const hashedPassword = hashPassword({ - encryptionKey: encryptionKey, + encryptionKey: finalEncryptionKey, password: String(payload.password), }); payload.password = hashedPassword; - let fields = await varDatabaseDbHandler({ - queryString: `SHOW COLUMNS FROM users`, - database: dbFullName, - }); + let fields = useLocal + ? await LOCAL_DB_HANDLER(`SHOW COLUMNS FROM users`) + : await varDatabaseDbHandler({ + queryString: `SHOW COLUMNS FROM users`, + database: dbFullName, + }); if (!fields) { const newTable = await addUsersTableToDb({ userId: Number(userId), database: database, + useLocal, }); fields = await varDatabaseDbHandler({ diff --git a/package-shared/functions/api/users/api-get-user.js b/package-shared/functions/api/users/api-get-user.js index daf7d7f..88a6b32 100644 --- a/package-shared/functions/api/users/api-get-user.js +++ b/package-shared/functions/api/users/api-get-user.js @@ -1,16 +1,24 @@ // @ts-check +const LOCAL_DB_HANDLER = require("../../../utils/backend/global-db/LOCAL_DB_HANDLER"); const varDatabaseDbHandler = require("../../backend/varDatabaseDbHandler"); /** @type {import("../../../types").APIGetUserFunction} */ -module.exports = async function apiGetUser({ fields, dbFullName, userId }) { +module.exports = async function apiGetUser({ + fields, + dbFullName, + userId, + useLocal, +}) { const query = `SELECT ${fields.join(",")} FROM users WHERE id=?`; - let foundUser = await varDatabaseDbHandler({ - queryString: query, - queryValuesArray: [userId], - database: dbFullName.replace(/[^a-z0-9_]/g, ""), - }); + let foundUser = useLocal + ? await LOCAL_DB_HANDLER(query, [userId]) + : await varDatabaseDbHandler({ + queryString: query, + queryValuesArray: [userId], + database: dbFullName.replace(/[^a-z0-9_]/g, ""), + }); if (!foundUser || !foundUser[0]) { return { diff --git a/package-shared/functions/api/users/api-login.js b/package-shared/functions/api/users/api-login.js index c45a000..f5e6c13 100644 --- a/package-shared/functions/api/users/api-login.js +++ b/package-shared/functions/api/users/api-login.js @@ -1,5 +1,6 @@ // @ts-check +const LOCAL_DB_HANDLER = require("../../../utils/backend/global-db/LOCAL_DB_HANDLER"); const varDatabaseDbHandler = require("../../backend/varDatabaseDbHandler"); const hashPassword = require("../../dsql/hashPassword"); @@ -17,6 +18,7 @@ module.exports = async function apiLoginUser({ token, skipPassword, social, + useLocal, }) { const dbFullName = database; @@ -48,14 +50,16 @@ module.exports = async function apiLoginUser({ }) : null; - let isSocialValidated = false; - let loginFailureReason = null; - - let foundUser = await varDatabaseDbHandler({ - queryString: `SELECT * FROM users WHERE email = ? OR username = ?`, - queryValuesArray: [email, username], - database: dbFullName.replace(/[^a-z0-9_]/g, ""), - }); + let foundUser = useLocal + ? await LOCAL_DB_HANDLER( + `SELECT * FROM users WHERE email = ? OR username = ?`, + [email, username] + ) + : await varDatabaseDbHandler({ + queryString: `SELECT * FROM users WHERE email = ? OR username = ?`, + queryValuesArray: [email, username], + database: dbFullName.replace(/[^a-z0-9_]/g, ""), + }); if ((!foundUser || !foundUser[0]) && !social) return { @@ -103,11 +107,16 @@ module.exports = async function apiLoginUser({ } if (isPasswordCorrect && email_login) { - const resetTempCode = await varDatabaseDbHandler({ - queryString: `UPDATE users SET ${email_login_field} = ? WHERE email = ? OR username = ?`, - queryValuesArray: ["", email, username], - database: dbFullName.replace(/[^a-z0-9_]/g, ""), - }); + const resetTempCode = useLocal + ? await LOCAL_DB_HANDLER( + `UPDATE users SET ${email_login_field} = ? WHERE email = ? OR username = ?`, + ["", email, username] + ) + : await varDatabaseDbHandler({ + queryString: `UPDATE users SET ${email_login_field} = ? WHERE email = ? OR username = ?`, + queryValuesArray: ["", email, username], + database: dbFullName.replace(/[^a-z0-9_]/g, ""), + }); } let csrfKey = 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 0c6d928..9dad88c 100644 --- a/package-shared/functions/api/users/api-reauth-user.d.ts +++ b/package-shared/functions/api/users/api-reauth-user.d.ts @@ -1,9 +1,10 @@ -declare function _exports({ existingUser, database, userId, additionalFields, }: { +declare function _exports({ existingUser, database, userId, additionalFields, useLocal, }: { existingUser: { [x: string]: any; }; database: string; userId?: string | number; additionalFields?: string[]; + useLocal?: boolean; }): Promise; export = _exports; diff --git a/package-shared/functions/api/users/api-reauth-user.js b/package-shared/functions/api/users/api-reauth-user.js index e3be35e..52e5801 100644 --- a/package-shared/functions/api/users/api-reauth-user.js +++ b/package-shared/functions/api/users/api-reauth-user.js @@ -1,5 +1,6 @@ // @ts-check +const LOCAL_DB_HANDLER = require("../../../utils/backend/global-db/LOCAL_DB_HANDLER"); const varDatabaseDbHandler = require("../../backend/varDatabaseDbHandler"); const nodemailer = require("nodemailer"); @@ -10,6 +11,7 @@ const nodemailer = require("nodemailer"); * @param {string} param.database * @param {string | number} [param.userId] * @param {string[]} [param.additionalFields] + * @param {boolean} [param.useLocal] * * @returns {Promise} */ @@ -18,14 +20,19 @@ module.exports = async function apiReauthUser({ database, userId, additionalFields, + useLocal, }) { let foundUser = existingUser?.id && existingUser.id.toString().match(/./) - ? await varDatabaseDbHandler({ - queryString: `SELECT * FROM users WHERE id=?`, - queryValuesArray: [existingUser.id.toString()], - database, - }) + ? 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, + }) : null; //////////////////////////////////////// diff --git a/package-shared/functions/api/users/api-send-email-code.d.ts b/package-shared/functions/api/users/api-send-email-code.d.ts index 84f3daa..aeabe6b 100644 --- a/package-shared/functions/api/users/api-send-email-code.d.ts +++ b/package-shared/functions/api/users/api-send-email-code.d.ts @@ -1,4 +1,4 @@ -declare function _exports({ email, database, email_login_field, mail_domain, mail_port, sender, mail_username, mail_password, html, }: { +declare function _exports({ email, database, email_login_field, mail_domain, mail_port, sender, mail_username, mail_password, html, useLocal, }: { email: string; database: string; email_login_field?: string; @@ -8,6 +8,7 @@ declare function _exports({ email, database, email_login_field, mail_domain, mai mail_username?: string; mail_password?: string; html: string; + useLocal?: boolean; }): Promise<{ success: boolean; msg?: string; diff --git a/package-shared/functions/api/users/api-send-email-code.js b/package-shared/functions/api/users/api-send-email-code.js index 3e93870..445639d 100644 --- a/package-shared/functions/api/users/api-send-email-code.js +++ b/package-shared/functions/api/users/api-send-email-code.js @@ -1,5 +1,6 @@ // @ts-check +const LOCAL_DB_HANDLER = require("../../../utils/backend/global-db/LOCAL_DB_HANDLER"); const varDatabaseDbHandler = require("../../backend/varDatabaseDbHandler"); const nodemailer = require("nodemailer"); @@ -16,6 +17,7 @@ const nodemailer = require("nodemailer"); * @param {string} [param.mail_username] * @param {string} [param.mail_password] * @param {string} param.html + * @param {boolean} [param.useLocal] * * @returns {Promise<{success: boolean, msg?: string}>} */ @@ -29,6 +31,7 @@ module.exports = async function apiSendEmailCode({ mail_username, mail_password, html, + useLocal, }) { if (email?.match(/ /)) { return { @@ -41,11 +44,16 @@ module.exports = async function apiSendEmailCode({ //////////////////////////////////////// //////////////////////////////////////// - let foundUser = await varDatabaseDbHandler({ - queryString: `SELECT * FROM users WHERE email = ?`, - queryValuesArray: [email], - database, - }); + const foundUserQuery = `SELECT * FROM users WHERE email = ?`; + const foundUserValues = [email]; + + let foundUser = useLocal + ? await LOCAL_DB_HANDLER(foundUserQuery, foundUserValues) + : await varDatabaseDbHandler({ + queryString: foundUserQuery, + queryValuesArray: foundUserValues, + database, + }); //////////////////////////////////////// //////////////////////////////////////// @@ -94,21 +102,18 @@ module.exports = async function apiSendEmailCode({ if (!info?.accepted) throw new Error("Mail not Sent!"); - //////////////////////////////////////// - //////////////////////////////////////// - //////////////////////////////////////// + const setTempCodeQuery = `UPDATE users SET ${email_login_field} = ? WHERE email = ?`; + const setTempCodeValues = [tempCode + `-${Date.now()}`, email]; - let setTempCode = await varDatabaseDbHandler({ - queryString: `UPDATE users SET ${email_login_field} = ? WHERE email = ?`, - queryValuesArray: [tempCode + `-${Date.now()}`, email], - database: database, - }); + let setTempCode = useLocal + ? await LOCAL_DB_HANDLER(setTempCodeQuery, setTempCodeValues) + : await varDatabaseDbHandler({ + queryString: setTempCodeQuery, + queryValuesArray: setTempCodeValues, + database: database, + }); } - //////////////////////////////////////// - //////////////////////////////////////// - //////////////////////////////////////// - return { success: true, msg: "Success", diff --git a/package-shared/functions/api/users/api-update-user.d.ts b/package-shared/functions/api/users/api-update-user.d.ts index ce42a55..883de4f 100644 --- a/package-shared/functions/api/users/api-update-user.d.ts +++ b/package-shared/functions/api/users/api-update-user.d.ts @@ -1,10 +1,11 @@ -declare function _exports({ payload, dbFullName }: { +declare function _exports({ payload, dbFullName, useLocal, }: { payload: { id: string | number; } & { [x: string]: (string | number | null | undefined); }; dbFullName: string; + useLocal?: boolean; }): Promise<{ success: boolean; payload: any; diff --git a/package-shared/functions/api/users/api-update-user.js b/package-shared/functions/api/users/api-update-user.js index 9a52d63..3086984 100644 --- a/package-shared/functions/api/users/api-update-user.js +++ b/package-shared/functions/api/users/api-update-user.js @@ -8,10 +8,15 @@ const updateDbEntry = require("../../backend/db/updateDbEntry"); * @param {object} params * @param {{ id: string | number } & Object} params.payload * @param {string} params.dbFullName + * @param {boolean} [params.useLocal] * * @returns {Promise<{ success: boolean, payload: any }>} */ -module.exports = async function apiUpdateUser({ payload, dbFullName }) { +module.exports = async function apiUpdateUser({ + payload, + dbFullName, + useLocal, +}) { const data = (() => { const reqBodyKeys = Object.keys(payload); @@ -34,6 +39,7 @@ module.exports = async function apiUpdateUser({ payload, dbFullName }) { identifierColumnName: "id", identifierValue: payload.id, data: data, + useLocal, }); return { diff --git a/package-shared/functions/backend/addMariadbUser.d.ts b/package-shared/functions/backend/addMariadbUser.d.ts index c843885..f8e228f 100644 --- a/package-shared/functions/backend/addMariadbUser.d.ts +++ b/package-shared/functions/backend/addMariadbUser.d.ts @@ -1,4 +1,5 @@ -declare function _exports({ userId }: { +declare function _exports({ userId, useLocal }: { userId: number | string; + useLocal?: boolean; }): Promise; export = _exports; diff --git a/package-shared/functions/backend/addMariadbUser.js b/package-shared/functions/backend/addMariadbUser.js index 0b1de05..597e5bd 100644 --- a/package-shared/functions/backend/addMariadbUser.js +++ b/package-shared/functions/backend/addMariadbUser.js @@ -5,6 +5,7 @@ const DB_HANDLER = require("../../utils/backend/global-db/DB_HANDLER"); const NO_DB_HANDLER = require("../../utils/backend/global-db/NO_DB_HANDLER"); const addDbEntry = require("./db/addDbEntry"); const encrypt = require("../dsql/encrypt"); +const LOCAL_DB_HANDLER = require("../../utils/backend/global-db/LOCAL_DB_HANDLER"); /** * # Add Mariadb User @@ -13,10 +14,11 @@ const encrypt = require("../dsql/encrypt"); * * @param {object} params - parameters object * * @param {number | string} params.userId - invited user object + * @param {boolean} [params.useLocal] * * @returns {Promise} new user auth object payload */ -module.exports = async function addMariadbUser({ userId }) { +module.exports = async function addMariadbUser({ userId, useLocal }) { try { const defaultMariadbUserHost = process.env.DSQL_DB_HOST || "127.0.0.1"; @@ -30,14 +32,20 @@ module.exports = async function addMariadbUser({ userId }) { }); const encryptedPassword = encrypt({ data: password }); - await NO_DB_HANDLER( - `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}' REQUIRE SSL`; - const updateUser = await DB_HANDLER( - `UPDATE users SET mariadb_user = ?, mariadb_host = '127.0.0.1', mariadb_pass = ? WHERE id = ?`, - [username, encryptedPassword, userId] - ); + if (useLocal) { + await LOCAL_DB_HANDLER(createMariadbUsersQuery); + } else { + await NO_DB_HANDLER(createMariadbUsersQuery); + } + + const updateUserQuery = `UPDATE users SET mariadb_user = ?, mariadb_host = '127.0.0.1', mariadb_pass = ? WHERE id = ?`; + const updateUserValues = [username, encryptedPassword, userId]; + + const updateUser = useLocal + ? await LOCAL_DB_HANDLER(updateUserQuery, updateUserValues) + : await DB_HANDLER(updateUserQuery, updateUserValues); const addMariadbUser = await addDbEntry({ tableName: "mariadb_users", @@ -50,6 +58,7 @@ module.exports = async function addMariadbUser({ userId }) { grants: '[{"database":"*","table":"*","privileges":["ALL"]}]', }, dbContext: "Master", + useLocal, }); console.log(`User ${userId} SQL credentials successfully added.`); diff --git a/package-shared/functions/backend/addUsersTableToDb.d.ts b/package-shared/functions/backend/addUsersTableToDb.d.ts index 2751d4e..d2073bf 100644 --- a/package-shared/functions/backend/addUsersTableToDb.d.ts +++ b/package-shared/functions/backend/addUsersTableToDb.d.ts @@ -1,5 +1,6 @@ -declare function _exports({ userId, database }: { +declare function _exports({ userId, database, useLocal, }: { userId: number; database: string; + useLocal?: boolean; }): Promise; export = _exports; diff --git a/package-shared/functions/backend/addUsersTableToDb.js b/package-shared/functions/backend/addUsersTableToDb.js index a34cbf4..5c17278 100755 --- a/package-shared/functions/backend/addUsersTableToDb.js +++ b/package-shared/functions/backend/addUsersTableToDb.js @@ -9,6 +9,7 @@ const { default: grabUserSchemaData } = require("./grabUserSchemaData"); const { default: setUserSchemaData } = require("./setUserSchemaData"); const addDbEntry = require("./db/addDbEntry"); const createDbFromSchema = require("../../shell/createDbFromSchema"); +const LOCAL_DB_HANDLER = require("../../utils/backend/global-db/LOCAL_DB_HANDLER"); /** * # Add User Table to Database @@ -16,10 +17,15 @@ const createDbFromSchema = require("../../shell/createDbFromSchema"); * @param {object} params * @param {number} params.userId - user id * @param {string} params.database + * @param {boolean} [params.useLocal] * * @returns {Promise} new user auth object payload */ -module.exports = async function addUsersTableToDb({ userId, database }) { +module.exports = async function addUsersTableToDb({ + userId, + database, + useLocal, +}) { /** * Initialize * @@ -59,10 +65,15 @@ module.exports = async function addUsersTableToDb({ userId, database }) { setUserSchemaData({ schemaData: userSchemaData, userId }); - const targetDb = await DB_HANDLER( - `SELECT id FROM user_databases WHERE user_id=? AND db_slug=?`, - [userId, database] - ); + const targetDb = useLocal + ? await LOCAL_DB_HANDLER( + `SELECT id FROM user_databases WHERE user_id=? AND db_slug=?`, + [userId, database] + ) + : await DB_HANDLER( + `SELECT id FROM user_databases WHERE user_id=? AND db_slug=?`, + [userId, database] + ); if (targetDb && targetDb[0]) { const newTableEntry = await addDbEntry({ @@ -75,6 +86,7 @@ module.exports = async function addUsersTableToDb({ userId, database }) { table_name: "Users", table_slug: "users", }, + useLocal, }); } diff --git a/package-shared/functions/backend/db/addDbEntry.d.ts b/package-shared/functions/backend/db/addDbEntry.d.ts index 5b7f08c..602330b 100644 --- a/package-shared/functions/backend/db/addDbEntry.d.ts +++ b/package-shared/functions/backend/db/addDbEntry.d.ts @@ -19,10 +19,11 @@ export = addDbEntry; * @param {boolean} [params.update] - Update this row if it exists * @param {string} [params.encryptionKey] - Update this row if it exists * @param {string} [params.encryptionSalt] - Update this row if it exists + * @param {boolean} [params.useLocal] * * @returns {Promise} */ -declare function addDbEntry({ dbContext, paradigm, dbFullName, tableName, data, tableSchema, duplicateColumnName, duplicateColumnValue, update, encryptionKey, encryptionSalt, }: { +declare function addDbEntry({ dbContext, paradigm, dbFullName, tableName, data, tableSchema, duplicateColumnName, duplicateColumnValue, update, encryptionKey, encryptionSalt, useLocal, }: { dbContext?: ("Master" | "Dsql User"); paradigm?: ("Read Only" | "Full Access"); dbFullName?: string; @@ -34,4 +35,5 @@ declare function addDbEntry({ dbContext, paradigm, dbFullName, tableName, data, update?: boolean; encryptionKey?: string; encryptionSalt?: string; + useLocal?: boolean; }): Promise; diff --git a/package-shared/functions/backend/db/addDbEntry.js b/package-shared/functions/backend/db/addDbEntry.js index 7434a74..38d99c8 100644 --- a/package-shared/functions/backend/db/addDbEntry.js +++ b/package-shared/functions/backend/db/addDbEntry.js @@ -8,6 +8,7 @@ const _ = require("lodash"); const DB_HANDLER = require("../../../utils/backend/global-db/DB_HANDLER"); const DSQL_USER_DB_HANDLER = require("../../../utils/backend/global-db/DSQL_USER_DB_HANDLER"); const encrypt = require("../../dsql/encrypt"); +const LOCAL_DB_HANDLER = require("../../../utils/backend/global-db/LOCAL_DB_HANDLER"); /** * Add a db Entry Function @@ -29,6 +30,7 @@ const encrypt = require("../../dsql/encrypt"); * @param {boolean} [params.update] - Update this row if it exists * @param {string} [params.encryptionKey] - Update this row if it exists * @param {string} [params.encryptionSalt] - Update this row if it exists + * @param {boolean} [params.useLocal] * * @returns {Promise} */ @@ -44,6 +46,7 @@ async function addDbEntry({ update, encryptionKey, encryptionSalt, + useLocal, }) { /** * Initialize variables @@ -55,7 +58,11 @@ async function addDbEntry({ : true; /** @type { any } */ - const dbHandler = isMaster ? DB_HANDLER : DSQL_USER_DB_HANDLER; + const dbHandler = useLocal + ? LOCAL_DB_HANDLER + : isMaster + ? DB_HANDLER + : DSQL_USER_DB_HANDLER; //////////////////////////////////////// //////////////////////////////////////// diff --git a/package-shared/functions/backend/db/deleteDbEntry.d.ts b/package-shared/functions/backend/db/deleteDbEntry.d.ts index 630b4bd..5392da5 100644 --- a/package-shared/functions/backend/db/deleteDbEntry.d.ts +++ b/package-shared/functions/backend/db/deleteDbEntry.d.ts @@ -18,10 +18,11 @@ export = deleteDbEntry; * @param {import("../../../types").DSQL_TableSchemaType} [params.tableSchema] - Table schema * @param {string} params.identifierColumnName - Update row identifier column name * @param {string|number} params.identifierValue - Update row identifier column value + * @param {boolean} [params.useLocal] * * @returns {Promise} */ -declare function deleteDbEntry({ dbContext, paradigm, dbFullName, tableName, identifierColumnName, identifierValue, }: { +declare function deleteDbEntry({ dbContext, paradigm, dbFullName, tableName, identifierColumnName, identifierValue, useLocal, }: { dbContext?: string; paradigm?: ("Read Only" | "Full Access"); dbFullName: string; @@ -29,4 +30,5 @@ declare function deleteDbEntry({ dbContext, paradigm, dbFullName, tableName, ide tableSchema?: import("../../../types").DSQL_TableSchemaType; identifierColumnName: string; identifierValue: string | number; + useLocal?: boolean; }): Promise; diff --git a/package-shared/functions/backend/db/deleteDbEntry.js b/package-shared/functions/backend/db/deleteDbEntry.js index 355c8db..944ce50 100644 --- a/package-shared/functions/backend/db/deleteDbEntry.js +++ b/package-shared/functions/backend/db/deleteDbEntry.js @@ -2,6 +2,7 @@ const DB_HANDLER = require("../../../utils/backend/global-db/DB_HANDLER"); const DSQL_USER_DB_HANDLER = require("../../../utils/backend/global-db/DSQL_USER_DB_HANDLER"); +const LOCAL_DB_HANDLER = require("../../../utils/backend/global-db/LOCAL_DB_HANDLER"); /** * Imports: Handle imports @@ -23,6 +24,7 @@ const DSQL_USER_DB_HANDLER = require("../../../utils/backend/global-db/DSQL_USER * @param {import("../../../types").DSQL_TableSchemaType} [params.tableSchema] - Table schema * @param {string} params.identifierColumnName - Update row identifier column name * @param {string|number} params.identifierValue - Update row identifier column value + * @param {boolean} [params.useLocal] * * @returns {Promise} */ @@ -33,6 +35,7 @@ async function deleteDbEntry({ tableName, identifierColumnName, identifierValue, + useLocal, }) { try { /** @@ -45,7 +48,11 @@ async function deleteDbEntry({ : true; /** @type { (a1:any, a2?:any) => any } */ - const dbHandler = isMaster ? DB_HANDLER : DSQL_USER_DB_HANDLER; + const dbHandler = useLocal + ? LOCAL_DB_HANDLER + : isMaster + ? DB_HANDLER + : DSQL_USER_DB_HANDLER; //////////////////////////////////////// //////////////////////////////////////// diff --git a/package-shared/functions/backend/db/runQuery.js b/package-shared/functions/backend/db/runQuery.js index 1e5b767..7a64702 100644 --- a/package-shared/functions/backend/db/runQuery.js +++ b/package-shared/functions/backend/db/runQuery.js @@ -107,6 +107,8 @@ async function runQuery({ } if (local) { + console.log("Using Local ..."); + const rawResults = await LOCAL_DB_HANDLER( formattedQuery, queryValuesArray diff --git a/package-shared/functions/backend/db/updateDbEntry.d.ts b/package-shared/functions/backend/db/updateDbEntry.d.ts index 5446d6e..8c2345d 100644 --- a/package-shared/functions/backend/db/updateDbEntry.d.ts +++ b/package-shared/functions/backend/db/updateDbEntry.d.ts @@ -18,10 +18,11 @@ export = updateDbEntry; * @param {import("../../../types").DSQL_TableSchemaType} [params.tableSchema] - Table schema * @param {string} params.identifierColumnName - Update row identifier column name * @param {string | number} params.identifierValue - Update row identifier column value + * @param {boolean} [params.useLocal] * * @returns {Promise} */ -declare function updateDbEntry({ dbContext, paradigm, dbFullName, tableName, data, tableSchema, identifierColumnName, identifierValue, encryptionKey, encryptionSalt, }: { +declare function updateDbEntry({ dbContext, paradigm, dbFullName, tableName, data, tableSchema, identifierColumnName, identifierValue, encryptionKey, encryptionSalt, useLocal, }: { dbContext?: ("Master" | "Dsql User"); paradigm?: ("Read Only" | "Full Access"); dbFullName?: string; @@ -32,4 +33,5 @@ declare function updateDbEntry({ dbContext, paradigm, dbFullName, tableName, dat tableSchema?: import("../../../types").DSQL_TableSchemaType; identifierColumnName: string; identifierValue: string | number; + useLocal?: boolean; }): Promise; diff --git a/package-shared/functions/backend/db/updateDbEntry.js b/package-shared/functions/backend/db/updateDbEntry.js index d85e323..3330114 100644 --- a/package-shared/functions/backend/db/updateDbEntry.js +++ b/package-shared/functions/backend/db/updateDbEntry.js @@ -8,6 +8,7 @@ const sanitizeHtmlOptions = require("../html/sanitizeHtmlOptions"); const DB_HANDLER = require("../../../utils/backend/global-db/DB_HANDLER"); const DSQL_USER_DB_HANDLER = require("../../../utils/backend/global-db/DSQL_USER_DB_HANDLER"); const encrypt = require("../../dsql/encrypt"); +const LOCAL_DB_HANDLER = require("../../../utils/backend/global-db/LOCAL_DB_HANDLER"); /** * Update DB Function @@ -28,6 +29,7 @@ const encrypt = require("../../dsql/encrypt"); * @param {import("../../../types").DSQL_TableSchemaType} [params.tableSchema] - Table schema * @param {string} params.identifierColumnName - Update row identifier column name * @param {string | number} params.identifierValue - Update row identifier column value + * @param {boolean} [params.useLocal] * * @returns {Promise} */ @@ -42,6 +44,7 @@ async function updateDbEntry({ identifierValue, encryptionKey, encryptionSalt, + useLocal, }) { /** * Check if data is valid @@ -55,7 +58,11 @@ async function updateDbEntry({ : true; /** @type {(a1:any, a2?:any)=> any } */ - const dbHandler = isMaster ? DB_HANDLER : DSQL_USER_DB_HANDLER; + const dbHandler = useLocal + ? LOCAL_DB_HANDLER + : isMaster + ? DB_HANDLER + : DSQL_USER_DB_HANDLER; //////////////////////////////////////// //////////////////////////////////////// diff --git a/package-shared/types/index.d.ts b/package-shared/types/index.d.ts index 77c873b..3375fe1 100644 --- a/package-shared/types/index.d.ts +++ b/package-shared/types/index.d.ts @@ -1054,6 +1054,7 @@ export type APILoginFunctionParams = { token?: boolean; skipPassword?: boolean; social?: boolean; + useLocal?: boolean; }; export type APILoginFunctionReturn = { success: boolean; @@ -1063,10 +1064,11 @@ export type APILoginFunctionReturn = { }; export type APILoginFunction = (params: APILoginFunctionParams) => Promise; export type APICreateUserFunctionParams = { - encryptionKey: string; + encryptionKey?: string; payload: any; database: string; userId?: string | number; + useLocal?: boolean; }; export type APICreateUserFunction = (params: APICreateUserFunctionParams) => Promise; /** @@ -1076,6 +1078,7 @@ export type APIGetUserFunctionParams = { fields: string[]; dbFullName: string; userId: string | number; + useLocal?: boolean; }; export type APIGetUserFunction = (params: APIGetUserFunctionParams) => Promise; /** @@ -1108,6 +1111,7 @@ export type HandleSocialDbFunctionParams = { invitation?: any; supEmail?: string; additionalFields?: object; + useLocal?: boolean; }; export type HandleSocialDbFunctionReturn = { success: boolean; diff --git a/package-shared/types/index.ts b/package-shared/types/index.ts index 0b2714c..25f4a35 100644 --- a/package-shared/types/index.ts +++ b/package-shared/types/index.ts @@ -1271,6 +1271,7 @@ export type APILoginFunctionParams = { token?: boolean; skipPassword?: boolean; social?: boolean; + useLocal?: boolean; }; export type APILoginFunctionReturn = { success: boolean; @@ -1283,10 +1284,11 @@ export type APILoginFunction = ( ) => Promise; export type APICreateUserFunctionParams = { - encryptionKey: string; + encryptionKey?: string; payload: any; database: string; userId?: string | number; + useLocal?: boolean; }; export type APICreateUserFunction = ( @@ -1300,6 +1302,7 @@ export type APIGetUserFunctionParams = { fields: string[]; dbFullName: string; userId: string | number; + useLocal?: boolean; }; export type APIGetUserFunction = ( @@ -1339,6 +1342,7 @@ export type HandleSocialDbFunctionParams = { invitation?: any; supEmail?: string; additionalFields?: object; + useLocal?: boolean; }; export type HandleSocialDbFunctionReturn = { diff --git a/package.json b/package.json index 05d3896..1d43987 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@moduletrace/datasquirel", - "version": "2.7.6", + "version": "2.7.7", "description": "Cloud-based SQL data management tool", "main": "index.js", "bin": { @@ -8,6 +8,7 @@ "dsql-dump": "./engine/dump.js" }, "scripts": { + "delete-ts": "find . -name \"*.d.ts\" -type f -not -path \"./node_modules/*\" -delete", "compile": "find . -name \"*.d.ts\" -type f -not -path \"./node_modules/*\" -delete && tsc --declaration --allowJs --emitDeclarationOnly --resolveJsonModule index.js", "compile:full": "rm -rf dist && tsc --declaration --allowJs --outDir dist --emitDeclarationOnly --resolveJsonModule index.js && cat ./dist/index.d.ts > ./index.d.ts" }, diff --git a/publish.sh b/publish.sh index 2e7085f..28bf7c3 100755 --- a/publish.sh +++ b/publish.sh @@ -8,3 +8,4 @@ fi npm run compile git add . && git commit -m "$msg" && git push && npm publish +npm run delete-ts diff --git a/users/add-user.d.ts b/users/add-user.d.ts index 1f279c1..180886b 100644 --- a/users/add-user.d.ts +++ b/users/add-user.d.ts @@ -8,7 +8,7 @@ export = addUser; * @param {string} param.key - FULL ACCESS API Key * @param {string} param.database - Database Name * @param {import("../package-shared/types").UserDataPayload} param.payload - User Data Payload - * @param {string} param.encryptionKey + * @param {string} [param.encryptionKey] * @param {string} [param.encryptionSalt] * @param {string | number} [param.user_id] * @param {string | number} [param.apiUserId] @@ -20,7 +20,7 @@ declare function addUser({ key, payload, database, encryptionKey, user_id, useLo key: string; database: string; payload: import("../package-shared/types").UserDataPayload; - encryptionKey: string; + encryptionKey?: string; encryptionSalt?: string; user_id?: string | number; apiUserId?: string | number; diff --git a/users/add-user.js b/users/add-user.js index 99dcb35..e972311 100644 --- a/users/add-user.js +++ b/users/add-user.js @@ -14,7 +14,7 @@ const apiCreateUser = require("../package-shared/functions/api/users/api-create- * @param {string} param.key - FULL ACCESS API Key * @param {string} param.database - Database Name * @param {import("../package-shared/types").UserDataPayload} param.payload - User Data Payload - * @param {string} param.encryptionKey + * @param {string} [param.encryptionKey] * @param {string} [param.encryptionSalt] * @param {string | number} [param.user_id] * @param {string | number} [param.apiUserId] @@ -65,6 +65,7 @@ async function addUser({ encryptionKey, payload, userId: apiUserId, + useLocal, }); } } diff --git a/users/get-token.d.ts b/users/get-token.d.ts index 4a6ed0f..081537e 100644 --- a/users/get-token.d.ts +++ b/users/get-token.d.ts @@ -16,14 +16,16 @@ export = getToken; * @param {string} params.encryptionKey - Encryption Key * @param {string} params.encryptionSalt - Encryption Salt * @param {string} params.database - Database Name + * @param {boolean} [params.useLocal] * * @returns {{ key: string | undefined, csrf: string | undefined }} */ -declare function getToken({ request, encryptionKey, encryptionSalt, database }: { +declare function getToken({ request, encryptionKey, encryptionSalt, database, useLocal, }: { request: http.IncomingMessage; encryptionKey: string; encryptionSalt: string; database: string; + useLocal?: boolean; }): { key: string | undefined; csrf: string | undefined; diff --git a/users/get-token.js b/users/get-token.js index 1a86fc4..9f9a42d 100644 --- a/users/get-token.js +++ b/users/get-token.js @@ -8,6 +8,7 @@ const http = require("http"); const decrypt = require("../package-shared/functions/dsql/decrypt"); const parseCookies = require("../utils/functions/parseCookies"); +const getAuthCookieNames = require("../package-shared/functions/backend/cookies/get-auth-cookie-names"); /** ****************************************************************************** */ /** ****************************************************************************** */ @@ -27,10 +28,17 @@ const parseCookies = require("../utils/functions/parseCookies"); * @param {string} params.encryptionKey - Encryption Key * @param {string} params.encryptionSalt - Encryption Salt * @param {string} params.database - Database Name + * @param {boolean} [params.useLocal] * * @returns {{ key: string | undefined, csrf: string | undefined }} */ -function getToken({ request, encryptionKey, encryptionSalt, database }) { +function getToken({ + request, + encryptionKey, + encryptionSalt, + database, + useLocal, +}) { try { /** * Grab the payload @@ -38,9 +46,9 @@ function getToken({ request, encryptionKey, encryptionSalt, database }) { * @description Grab the payload */ const cookies = parseCookies({ request }); - const dsqluid = cookies.dsqluid; - const authKeyName = `datasquirel_${dsqluid}_${database}_auth_key`; - const csrfName = `datasquirel_${dsqluid}_${database}_csrf`; + const keynames = getAuthCookieNames(); + const authKeyName = keynames.keyCookieName; + const csrfName = keynames.csrfCookieName; const key = cookies[authKeyName]; const csrf = cookies[csrfName]; diff --git a/users/get-user.js b/users/get-user.js index 28dcb50..b40983d 100644 --- a/users/get-user.js +++ b/users/get-user.js @@ -98,6 +98,7 @@ async function getUser({ key, userId, database, fields, user_id, useLocal }) { userId, fields: [...new Set(updatedFields)], dbFullName: DSQL_DB_NAME, + useLocal, }); } } diff --git a/users/login-user.js b/users/login-user.js index 29cd514..b5287fe 100644 --- a/users/login-user.js +++ b/users/login-user.js @@ -12,6 +12,7 @@ const path = require("path"); const encrypt = require("../package-shared/functions/dsql/encrypt"); const grabHostNames = require("../package-shared/utils/grab-host-names"); const apiLoginUser = require("../package-shared/functions/api/users/api-login"); +const getAuthCookieNames = require("../package-shared/functions/backend/cookies/get-auth-cookie-names"); /** * Login A user @@ -155,6 +156,7 @@ async function loginUser({ email_login_code, email_login_field: emailLoginTempCodeFieldName, token, + useLocal, }); } } else { @@ -244,13 +246,14 @@ async function loginUser({ const { userId } = httpResponse; - const authKeyName = `datasquirel_${userId}_${database}_auth_key`; - const csrfName = `datasquirel_${userId}_${database}_csrf`; + const cookieNames = getAuthCookieNames(); + + const authKeyName = cookieNames.keyCookieName; + const csrfName = cookieNames.csrfCookieName; response.setHeader("Set-Cookie", [ `${authKeyName}=${encryptedPayload};samesite=strict;path=/;HttpOnly=true;Secure=true`, `${csrfName}=${httpResponse.payload?.csrf_k};samesite=strict;path=/;HttpOnly=true`, - `dsqluid=${userId};samesite=strict;path=/;HttpOnly=true`, ]); } diff --git a/users/logout-user.js b/users/logout-user.js index 5c348b5..0c4bfed 100644 --- a/users/logout-user.js +++ b/users/logout-user.js @@ -2,6 +2,7 @@ const http = require("http"); const parseCookies = require("../utils/functions/parseCookies"); +const getAuthCookieNames = require("../package-shared/functions/backend/cookies/get-auth-cookie-names"); /** * Logout user @@ -25,34 +26,48 @@ function logoutUser({ request, response, database }) { const cookies = parseCookies({ request }); const cookiesKeys = Object.keys(cookies); - const dbUid = cookies.dsqluid; - const keyRegexp = new RegExp(`datasquirel_${dbUid}_${database}_auth_key`); - const csrfRegexp = new RegExp(`datasquirel_${dbUid}_${database}_csrf`); + const keyNames = getAuthCookieNames(); - const authKeyName = cookiesKeys.filter((cookieKey) => cookieKey.match(keyRegexp))[0]; - const csrfName = cookiesKeys.filter((cookieKey) => cookieKey.match(csrfRegexp))[0]; + const keyRegexp = new RegExp(keyNames.keyCookieName); + const csrfRegexp = new RegExp(keyNames.csrfCookieName); + + const authKeyName = cookiesKeys.filter((cookieKey) => + cookieKey.match(keyRegexp) + )[0]; + const csrfName = cookiesKeys.filter((cookieKey) => + cookieKey.match(csrfRegexp) + )[0]; if (authKeyName && csrfName) { - response.setHeader("Set-Cookie", [`${authKeyName}=null;samesite=strict;path=/;HttpOnly=true;Secure=true`, `${csrfName}=null;samesite=strict;path=/;HttpOnly=true`, `dsqluid=null;samesite=strict;path=/;HttpOnly=true`]); + response.setHeader("Set-Cookie", [ + `${authKeyName}=null;max-age=0`, + `${csrfName}=null;max-age=0`, + ]); } else { - const allKeys = cookiesKeys.filter((cookieKey) => cookieKey.match(/datasquirel_.*_auth_key/)); - const allCsrfs = cookiesKeys.filter((cookieKey) => cookieKey.match(/datasquirel_.*_csrf/)); + const allKeys = cookiesKeys.filter((cookieKey) => + cookieKey.match(/datasquirel_.*_auth_key/) + ); + const allCsrfs = cookiesKeys.filter((cookieKey) => + cookieKey.match(/datasquirel_.*_csrf/) + ); - response.setHeader("Set-Cookie", [...allKeys.map((key) => `${key}=null;samesite=strict;path=/;HttpOnly=true;Secure=true`), ...allCsrfs.map((csrf) => `${csrf}=null;samesite=strict;path=/;HttpOnly=true`), `dsqluid=null;samesite=strict;path=/;HttpOnly=true`]); + response.setHeader("Set-Cookie", [ + ...allKeys.map( + (key) => + `${key}=null;samesite=strict;path=/;HttpOnly=true;Secure=true` + ), + ...allCsrfs.map( + (csrf) => + `${csrf}=null;samesite=strict;path=/;HttpOnly=true` + ), + `dsqluid=null;samesite=strict;path=/;HttpOnly=true`, + ]); } - /** ********************************************** */ - /** ********************************************** */ - /** ********************************************** */ - return { success: true, payload: "User Logged Out", }; - - /** ********************************************** */ - /** ********************************************** */ - /** ********************************************** */ } catch (error) { console.log(error); diff --git a/users/reauth-user.d.ts b/users/reauth-user.d.ts index 22adde0..f3c2c90 100644 --- a/users/reauth-user.d.ts +++ b/users/reauth-user.d.ts @@ -22,10 +22,11 @@ export = reauthUser; * @param {string[]} [params.additionalFields] - Additional Fields to be added to the user object * @param {string} [params.token] - access token to use instead of getting from cookie header * @param {boolean} [params.user_id] - User ID + * @param {boolean} [params.useLocal] * * @returns { Promise } */ -declare function reauthUser({ key, database, response, request, level, encryptionKey, encryptionSalt, additionalFields, token, user_id, }: { +declare function reauthUser({ key, database, response, request, level, encryptionKey, encryptionSalt, additionalFields, token, user_id, useLocal, }: { key: string; database: string; response: http.ServerResponse; @@ -36,5 +37,6 @@ declare function reauthUser({ key, database, response, request, level, encryptio additionalFields?: string[]; token?: string; user_id?: boolean; + useLocal?: boolean; }): Promise; import http = require("http"); diff --git a/users/reauth-user.js b/users/reauth-user.js index 6ef7d8c..20b74ad 100644 --- a/users/reauth-user.js +++ b/users/reauth-user.js @@ -39,6 +39,7 @@ const apiReauthUser = require("../package-shared/functions/api/users/api-reauth- * @param {string[]} [params.additionalFields] - Additional Fields to be added to the user object * @param {string} [params.token] - access token to use instead of getting from cookie header * @param {boolean} [params.user_id] - User ID + * @param {boolean} [params.useLocal] * * @returns { Promise } */ @@ -53,6 +54,7 @@ async function reauthUser({ additionalFields, token, user_id, + useLocal, }) { /** * Check Encryption Keys @@ -89,21 +91,14 @@ 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, - DSQL_KEY, - DSQL_REF_DB_NAME, - DSQL_FULL_SYNC, - } = process.env; + const { DSQL_HOST, DSQL_USER, DSQL_PASS, DSQL_DB_NAME } = process.env; if ( DSQL_HOST?.match(/./) && DSQL_USER?.match(/./) && DSQL_PASS?.match(/./) && - DSQL_DB_NAME?.match(/./) + DSQL_DB_NAME?.match(/./) && + useLocal ) { /** @type {import("../package-shared/types").DSQL_DatabaseSchemaType | undefined} */ let dbSchema; @@ -121,6 +116,7 @@ async function reauthUser({ existingUser: existingUser.payload, additionalFields, database: DSQL_DB_NAME, + useLocal, }); } } else { diff --git a/users/send-email-code.d.ts b/users/send-email-code.d.ts index e877a24..fee2e78 100644 --- a/users/send-email-code.d.ts +++ b/users/send-email-code.d.ts @@ -24,10 +24,11 @@ export = sendEmailCode; * @param {number} [params.mail_port] * @param {string} [params.sender] * @param {boolean} [params.user_id] - User ID + * @param {boolean} [params.useLocal] * * @returns { Promise} */ -declare function sendEmailCode({ key, email, database, encryptionKey, encryptionSalt, temp_code_field, mail_domain, mail_password, mail_username, mail_port, sender, user_id, }: { +declare function sendEmailCode({ key, email, database, encryptionKey, encryptionSalt, temp_code_field, mail_domain, mail_password, mail_username, mail_port, sender, user_id, useLocal, }: { key: string; database: string; email: string; @@ -41,5 +42,6 @@ declare function sendEmailCode({ key, email, database, encryptionKey, encryption mail_port?: number; sender?: string; user_id?: boolean; + useLocal?: boolean; }): Promise; import http = require("http"); diff --git a/users/send-email-code.js b/users/send-email-code.js index 035d610..d5edd72 100644 --- a/users/send-email-code.js +++ b/users/send-email-code.js @@ -38,6 +38,7 @@ const apiSendEmailCode = require("../package-shared/functions/api/users/api-send * @param {number} [params.mail_port] * @param {string} [params.sender] * @param {boolean} [params.user_id] - User ID + * @param {boolean} [params.useLocal] * * @returns { Promise} */ @@ -54,6 +55,7 @@ async function sendEmailCode({ mail_port, sender, user_id, + useLocal, }) { const grabedHostNames = grabHostNames(); const { host, port, scheme } = grabedHostNames; @@ -103,21 +105,14 @@ 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, - DSQL_KEY, - DSQL_REF_DB_NAME, - DSQL_FULL_SYNC, - } = process.env; + const { DSQL_HOST, DSQL_USER, DSQL_PASS, DSQL_DB_NAME } = process.env; if ( DSQL_HOST?.match(/./) && DSQL_USER?.match(/./) && DSQL_PASS?.match(/./) && - DSQL_DB_NAME?.match(/./) + DSQL_DB_NAME?.match(/./) && + useLocal ) { /** @type {import("../package-shared/types").DSQL_DatabaseSchemaType | undefined} */ let dbSchema; @@ -141,6 +136,7 @@ async function sendEmailCode({ mail_port, mail_username, sender, + useLocal, }); } } else { diff --git a/users/update-user.d.ts b/users/update-user.d.ts index 1c4b091..cc18071 100644 --- a/users/update-user.d.ts +++ b/users/update-user.d.ts @@ -8,10 +8,11 @@ export = updateUser; * @param {String} params.database - Target Database * @param {{ id: number } & Object.} params.payload - User Object: ID is required * @param {boolean} [params.user_id] - User ID + * @param {boolean} [params.useLocal] * * @returns { Promise} */ -declare function updateUser({ key, payload, database, user_id }: { +declare function updateUser({ key, payload, database, user_id, useLocal }: { key: string; database: string; payload: { @@ -20,4 +21,5 @@ declare function updateUser({ key, payload, database, user_id }: { [x: string]: any; }; user_id?: boolean; + useLocal?: boolean; }): Promise; diff --git a/users/update-user.js b/users/update-user.js index 7262384..2e70003 100644 --- a/users/update-user.js +++ b/users/update-user.js @@ -16,24 +16,17 @@ const apiUpdateUser = require("../package-shared/functions/api/users/api-update- * @param {String} params.database - Target Database * @param {{ id: number } & Object.} params.payload - User Object: ID is required * @param {boolean} [params.user_id] - User ID + * @param {boolean} [params.useLocal] * * @returns { Promise} */ -async function updateUser({ key, payload, database, user_id }) { +async function updateUser({ key, payload, database, user_id, useLocal }) { /** * Check for local DB settings * * @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, - DSQL_KEY, - DSQL_REF_DB_NAME, - DSQL_FULL_SYNC, - } = process.env; + const { DSQL_HOST, DSQL_USER, DSQL_PASS, DSQL_DB_NAME } = process.env; const grabedHostNames = grabHostNames(); const { host, port, scheme } = grabedHostNames; @@ -42,7 +35,8 @@ async function updateUser({ key, payload, database, user_id }) { DSQL_HOST?.match(/./) && DSQL_USER?.match(/./) && DSQL_PASS?.match(/./) && - DSQL_DB_NAME?.match(/./) + DSQL_DB_NAME?.match(/./) && + useLocal ) { /** @type {import("../package-shared/types").DSQL_DatabaseSchemaType | undefined} */ let dbSchema; @@ -59,6 +53,7 @@ async function updateUser({ key, payload, database, user_id }) { return await apiUpdateUser({ payload: payload, dbFullName: DSQL_DB_NAME, + useLocal, }); } } diff --git a/users/user-auth.d.ts b/users/user-auth.d.ts index 0f8e88e..623730f 100644 --- a/users/user-auth.d.ts +++ b/users/user-auth.d.ts @@ -1,10 +1,4 @@ export = userAuth; -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ /** * Authenticate User from request * ============================================================================== diff --git a/users/user-auth.js b/users/user-auth.js index 360d227..1fa2ebe 100644 --- a/users/user-auth.js +++ b/users/user-auth.js @@ -1,20 +1,9 @@ // @ts-check -/** - * ============================================================================== - * Imports - * ============================================================================== - */ const http = require("http"); const decrypt = require("../package-shared/functions/dsql/decrypt"); const parseCookies = require("../utils/functions/parseCookies"); - -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ +const getAuthCookieNames = require("../package-shared/functions/backend/cookies/get-auth-cookie-names"); /** * Authenticate User from request @@ -47,9 +36,11 @@ function userAuth({ * @description Grab the payload */ const cookies = parseCookies({ request }); - const dsqluid = cookies.dsqluid; - const authKeyName = `datasquirel_${dsqluid}_${database}_auth_key`; - const csrfName = `datasquirel_${dsqluid}_${database}_csrf`; + + const keyNames = getAuthCookieNames(); + + const authKeyName = keyNames.keyCookieName; + const csrfName = keyNames.csrfCookieName; const key = token ? token : cookies[authKeyName]; const csrf = cookies[csrfName]; @@ -93,10 +84,6 @@ function userAuth({ }; } - /** ********************************************** */ - /** ********************************************** */ - /** ********************************************** */ - /** * Grab the payload * @@ -113,10 +100,6 @@ function userAuth({ }; } - /** ********************************************** */ - /** ********************************************** */ - /** ********************************************** */ - /** * Return User Object * @@ -140,8 +123,4 @@ function userAuth({ } } -/** ********************************************** */ -/** ********************************************** */ -/** ********************************************** */ - module.exports = userAuth; diff --git a/users/validate-token.d.ts b/users/validate-token.d.ts index dd37a03..f52925c 100644 --- a/users/validate-token.d.ts +++ b/users/validate-token.d.ts @@ -1,13 +1,7 @@ export = validateToken; -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ /** * Validate Token - * ============================================================================== + * ====================================== * @description This Function takes in a encrypted token and returns a user object * * @param {Object} params - Arg diff --git a/users/validate-token.js b/users/validate-token.js index 300c67e..090a719 100644 --- a/users/validate-token.js +++ b/users/validate-token.js @@ -1,23 +1,11 @@ // @ts-check -/** - * ============================================================================== - * Imports - * ============================================================================== - */ const http = require("http"); const decrypt = require("../package-shared/functions/dsql/decrypt"); -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ -/** ****************************************************************************** */ - /** * Validate Token - * ============================================================================== + * ====================================== * @description This Function takes in a encrypted token and returns a user object * * @param {Object} params - Arg @@ -69,10 +57,6 @@ function validateToken({ token, encryptionKey, encryptionSalt }) { return null; } - /** ********************************************** */ - /** ********************************************** */ - /** ********************************************** */ - /** * Return User Object * @@ -89,8 +73,4 @@ function validateToken({ token, encryptionKey, encryptionSalt }) { } } -/** ********************************************** */ -/** ********************************************** */ -/** ********************************************** */ - module.exports = validateToken; diff --git a/utils/get.js b/utils/get.js index 1c15bbf..111dd42 100644 --- a/utils/get.js +++ b/utils/get.js @@ -67,6 +67,7 @@ async function get({ queryValues, tableName, dbSchema, + useLocal, }); } diff --git a/utils/post.js b/utils/post.js index 8fbaab8..bba67a7 100644 --- a/utils/post.js +++ b/utils/post.js @@ -64,6 +64,7 @@ async function post({ dbSchema, queryValues, tableName, + useLocal, }); }