This commit is contained in:
Benjamin Toby 2024-12-06 12:55:03 +01:00
parent 34868ee0cf
commit 8a8257d17e
48 changed files with 360 additions and 221 deletions

View File

@ -1,8 +1,9 @@
declare function _exports({ query, dbFullName, queryValues, tableName, dbSchema, }: { declare function _exports({ query, dbFullName, queryValues, tableName, dbSchema, useLocal, }: {
query: string; query: string;
queryValues?: (string | number)[]; queryValues?: (string | number)[];
dbFullName: string; dbFullName: string;
tableName?: string; tableName?: string;
dbSchema?: import("../../../types").DSQL_DatabaseSchemaType; dbSchema?: import("../../../types").DSQL_DatabaseSchemaType;
useLocal?: boolean;
}): Promise<import("../../../types").GetReturn>; }): Promise<import("../../../types").GetReturn>;
export = _exports; export = _exports;

View File

@ -13,6 +13,7 @@ const runQuery = require("../../backend/db/runQuery");
* @param {string} params.dbFullName * @param {string} params.dbFullName
* @param {string} [params.tableName] * @param {string} [params.tableName]
* @param {import("../../../types").DSQL_DatabaseSchemaType} [params.dbSchema] * @param {import("../../../types").DSQL_DatabaseSchemaType} [params.dbSchema]
* @param {boolean} [params.useLocal]
* *
* @returns {Promise<import("../../../types").GetReturn>} * @returns {Promise<import("../../../types").GetReturn>}
*/ */
@ -22,6 +23,7 @@ module.exports = async function apiGet({
queryValues, queryValues,
tableName, tableName,
dbSchema, dbSchema,
useLocal,
}) { }) {
if ( if (
typeof query == "string" && typeof query == "string" &&
@ -46,6 +48,7 @@ module.exports = async function apiGet({
readOnly: true, readOnly: true,
dbSchema, dbSchema,
tableName, tableName,
local: useLocal,
}); });
/** @type {import("../../../types").DSQL_TableSchemaType | undefined} */ /** @type {import("../../../types").DSQL_TableSchemaType | undefined} */

View File

@ -1,8 +1,9 @@
declare function _exports({ query, dbFullName, queryValues, tableName, dbSchema, }: { declare function _exports({ query, dbFullName, queryValues, tableName, dbSchema, useLocal, }: {
query: any; query: any;
queryValues?: (string | number)[]; queryValues?: (string | number)[];
dbFullName: string; dbFullName: string;
tableName?: string; tableName?: string;
dbSchema?: import("../../../types").DSQL_DatabaseSchemaType; dbSchema?: import("../../../types").DSQL_DatabaseSchemaType;
useLocal?: boolean;
}): Promise<import("../../../types").PostReturn>; }): Promise<import("../../../types").PostReturn>;
export = _exports; export = _exports;

View File

@ -13,6 +13,7 @@ const runQuery = require("../../backend/db/runQuery");
* @param {string} params.dbFullName * @param {string} params.dbFullName
* @param {string} [params.tableName] * @param {string} [params.tableName]
* @param {import("../../../types").DSQL_DatabaseSchemaType} [params.dbSchema] * @param {import("../../../types").DSQL_DatabaseSchemaType} [params.dbSchema]
* @param {boolean} [params.useLocal]
* *
* @returns {Promise<import("../../../types").PostReturn>} * @returns {Promise<import("../../../types").PostReturn>}
*/ */
@ -22,6 +23,7 @@ module.exports = async function apiPost({
queryValues, queryValues,
tableName, tableName,
dbSchema, dbSchema,
useLocal,
}) { }) {
if (typeof query === "string" && query?.match(/^create |^alter |^drop /i)) { if (typeof query === "string" && query?.match(/^create |^alter |^drop /i)) {
return { success: false, msg: "Wrong Input" }; return { success: false, msg: "Wrong Input" };
@ -49,6 +51,7 @@ module.exports = async function apiPost({
dbSchema: dbSchema, dbSchema: dbSchema,
queryValuesArray: queryValues, queryValuesArray: queryValues,
tableName, tableName,
local: useLocal,
}); });
results = result; results = result;

View File

@ -20,6 +20,7 @@ const varDatabaseDbHandler = require("../../backend/varDatabaseDbHandler");
const encrypt = require("../../dsql/encrypt"); const encrypt = require("../../dsql/encrypt");
const addDbEntry = require("../../backend/db/addDbEntry"); const addDbEntry = require("../../backend/db/addDbEntry");
const getAuthCookieNames = require("../../backend/cookies/get-auth-cookie-names"); 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, invitation,
supEmail, supEmail,
additionalFields, additionalFields,
useLocal,
}) { }) {
//////////////////////////////////////////////// ////////////////////////////////////////////////
//////////////////////////////////////////////// ////////////////////////////////////////////////
@ -61,11 +63,22 @@ module.exports = async function handleSocialDb({
//////////////////////////////////////////////// ////////////////////////////////////////////////
//////////////////////////////////////////////// ////////////////////////////////////////////////
let existingSocialIdUser = await varDatabaseDbHandler({ const existingSocialIdUserQuery = `SELECT * FROM users WHERE social_id = ? AND social_login='1' AND social_platform = ? `;
database: database ? database : "datasquirel", const existingSocialIdUserValues = [
queryString: `SELECT * FROM users WHERE social_id = ? AND social_login='1' AND social_platform = ? `, social_id.toString(),
queryValuesArray: [social_id.toString(), social_platform], 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]) { if (existingSocialIdUser && existingSocialIdUser[0]) {
return await loginSocialUser({ return await loginSocialUser({
@ -75,6 +88,7 @@ module.exports = async function handleSocialDb({
invitation, invitation,
database, database,
additionalFields, additionalFields,
useLocal,
}); });
} }
@ -99,10 +113,14 @@ module.exports = async function handleSocialDb({
//////////////////////////////////////////////// ////////////////////////////////////////////////
//////////////////////////////////////////////// ////////////////////////////////////////////////
let existingEmailOnly = await varDatabaseDbHandler({ const existingEmailOnlyQuery = `SELECT * FROM users WHERE email='${finalEmail}'`;
database: database ? database : "datasquirel",
queryString: `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]) { if (existingEmailOnly && existingEmailOnly[0]) {
return { return {
@ -117,10 +135,14 @@ module.exports = async function handleSocialDb({
//////////////////////////////////////////////// ////////////////////////////////////////////////
//////////////////////////////////////////////// ////////////////////////////////////////////////
const foundUser = await varDatabaseDbHandler({ const foundUserQuery = `SELECT * FROM users WHERE email='${finalEmail}' AND social_login='1' AND social_platform='${social_platform}' AND social_id='${social_id}'`;
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 foundUser = useLocal
}); ? await LOCAL_DB_HANDLER(foundUserQuery)
: await varDatabaseDbHandler({
database: database ? database : "datasquirel",
queryString: foundUserQuery,
});
if (foundUser && foundUser[0]) { if (foundUser && foundUser[0]) {
return await loginSocialUser({ return await loginSocialUser({
@ -130,6 +152,7 @@ module.exports = async function handleSocialDb({
invitation, invitation,
database, database,
additionalFields, additionalFields,
useLocal,
}); });
} }
@ -164,6 +187,7 @@ module.exports = async function handleSocialDb({
...data, ...data,
email: finalEmail, email: finalEmail,
}, },
useLocal,
}); });
if (newUser?.insertId) { if (newUser?.insertId) {
@ -171,13 +195,17 @@ module.exports = async function handleSocialDb({
/** /**
* Add a Mariadb User for this User * Add a Mariadb User for this User
*/ */
await addMariadbUser({ userId: newUser.insertId }); await addMariadbUser({ userId: newUser.insertId, useLocal });
} }
const newUserQueried = await varDatabaseDbHandler({ const newUserQueriedQuery = `SELECT * FROM users WHERE id='${newUser.insertId}'`;
database: database ? database : "datasquirel",
queryString: `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]) if (!newUserQueried || !newUserQueried[0])
return { return {
@ -263,6 +291,7 @@ module.exports = async function handleSocialDb({
invitation, invitation,
database, database,
additionalFields, additionalFields,
useLocal,
}); });
//////////////////////////////////////////////// ////////////////////////////////////////////////
@ -326,6 +355,7 @@ module.exports = async function handleSocialDb({
* @param {any} [params.invitation] - A query object if user was invited * @param {any} [params.invitation] - A query object if user was invited
* @param {string} [params.database] - Target Database * @param {string} [params.database] - Target Database
* @param {object} [params.additionalFields] - Additional fields to be added to the user payload * @param {object} [params.additionalFields] - Additional fields to be added to the user payload
* @param {boolean} [params.useLocal]
* *
* @returns {Promise<any>} * @returns {Promise<any>}
*/ */
@ -336,11 +366,16 @@ async function loginSocialUser({
invitation, invitation,
database, database,
additionalFields, additionalFields,
useLocal,
}) { }) {
const foundUser = await varDatabaseDbHandler({ const foundUserQuery = `SELECT * FROM users WHERE email='${user.email}' AND social_id='${user.social_id}' AND social_platform='${social_platform}'`;
database: database ? database : "datasquirel",
queryString: `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]) if (!foundUser?.[0])
return { return {

View File

@ -1,5 +1,6 @@
// @ts-check // @ts-check
const LOCAL_DB_HANDLER = require("../../../utils/backend/global-db/LOCAL_DB_HANDLER");
const addUsersTableToDb = require("../../backend/addUsersTableToDb"); const addUsersTableToDb = require("../../backend/addUsersTableToDb");
const addDbEntry = require("../../backend/db/addDbEntry"); const addDbEntry = require("../../backend/db/addDbEntry");
const varDatabaseDbHandler = require("../../backend/varDatabaseDbHandler"); const varDatabaseDbHandler = require("../../backend/varDatabaseDbHandler");
@ -11,25 +12,48 @@ module.exports = async function apiCreateUser({
payload, payload,
database, database,
userId, userId,
useLocal,
}) { }) {
const dbFullName = database; 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({ const hashedPassword = hashPassword({
encryptionKey: encryptionKey, encryptionKey: finalEncryptionKey,
password: String(payload.password), password: String(payload.password),
}); });
payload.password = hashedPassword; payload.password = hashedPassword;
let fields = await varDatabaseDbHandler({ let fields = useLocal
queryString: `SHOW COLUMNS FROM users`, ? await LOCAL_DB_HANDLER(`SHOW COLUMNS FROM users`)
database: dbFullName, : await varDatabaseDbHandler({
}); queryString: `SHOW COLUMNS FROM users`,
database: dbFullName,
});
if (!fields) { if (!fields) {
const newTable = await addUsersTableToDb({ const newTable = await addUsersTableToDb({
userId: Number(userId), userId: Number(userId),
database: database, database: database,
useLocal,
}); });
fields = await varDatabaseDbHandler({ fields = await varDatabaseDbHandler({

View File

@ -1,16 +1,24 @@
// @ts-check // @ts-check
const LOCAL_DB_HANDLER = require("../../../utils/backend/global-db/LOCAL_DB_HANDLER");
const varDatabaseDbHandler = require("../../backend/varDatabaseDbHandler"); const varDatabaseDbHandler = require("../../backend/varDatabaseDbHandler");
/** @type {import("../../../types").APIGetUserFunction} */ /** @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=?`; const query = `SELECT ${fields.join(",")} FROM users WHERE id=?`;
let foundUser = await varDatabaseDbHandler({ let foundUser = useLocal
queryString: query, ? await LOCAL_DB_HANDLER(query, [userId])
queryValuesArray: [userId], : await varDatabaseDbHandler({
database: dbFullName.replace(/[^a-z0-9_]/g, ""), queryString: query,
}); queryValuesArray: [userId],
database: dbFullName.replace(/[^a-z0-9_]/g, ""),
});
if (!foundUser || !foundUser[0]) { if (!foundUser || !foundUser[0]) {
return { return {

View File

@ -1,5 +1,6 @@
// @ts-check // @ts-check
const LOCAL_DB_HANDLER = require("../../../utils/backend/global-db/LOCAL_DB_HANDLER");
const varDatabaseDbHandler = require("../../backend/varDatabaseDbHandler"); const varDatabaseDbHandler = require("../../backend/varDatabaseDbHandler");
const hashPassword = require("../../dsql/hashPassword"); const hashPassword = require("../../dsql/hashPassword");
@ -17,6 +18,7 @@ module.exports = async function apiLoginUser({
token, token,
skipPassword, skipPassword,
social, social,
useLocal,
}) { }) {
const dbFullName = database; const dbFullName = database;
@ -48,14 +50,16 @@ module.exports = async function apiLoginUser({
}) })
: null; : null;
let isSocialValidated = false; let foundUser = useLocal
let loginFailureReason = null; ? await LOCAL_DB_HANDLER(
`SELECT * FROM users WHERE email = ? OR username = ?`,
let foundUser = await varDatabaseDbHandler({ [email, username]
queryString: `SELECT * FROM users WHERE email = ? OR username = ?`, )
queryValuesArray: [email, username], : await varDatabaseDbHandler({
database: dbFullName.replace(/[^a-z0-9_]/g, ""), queryString: `SELECT * FROM users WHERE email = ? OR username = ?`,
}); queryValuesArray: [email, username],
database: dbFullName.replace(/[^a-z0-9_]/g, ""),
});
if ((!foundUser || !foundUser[0]) && !social) if ((!foundUser || !foundUser[0]) && !social)
return { return {
@ -103,11 +107,16 @@ module.exports = async function apiLoginUser({
} }
if (isPasswordCorrect && email_login) { if (isPasswordCorrect && email_login) {
const resetTempCode = await varDatabaseDbHandler({ const resetTempCode = useLocal
queryString: `UPDATE users SET ${email_login_field} = ? WHERE email = ? OR username = ?`, ? await LOCAL_DB_HANDLER(
queryValuesArray: ["", email, username], `UPDATE users SET ${email_login_field} = ? WHERE email = ? OR username = ?`,
database: dbFullName.replace(/[^a-z0-9_]/g, ""), ["", 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 = let csrfKey =

View File

@ -1,9 +1,10 @@
declare function _exports({ existingUser, database, userId, additionalFields, }: { declare function _exports({ existingUser, database, userId, additionalFields, useLocal, }: {
existingUser: { existingUser: {
[x: string]: any; [x: string]: any;
}; };
database: string; database: string;
userId?: string | number; userId?: string | number;
additionalFields?: string[]; additionalFields?: string[];
useLocal?: boolean;
}): Promise<import("../../../types").ApiReauthUserReturn>; }): Promise<import("../../../types").ApiReauthUserReturn>;
export = _exports; export = _exports;

View File

@ -1,5 +1,6 @@
// @ts-check // @ts-check
const LOCAL_DB_HANDLER = require("../../../utils/backend/global-db/LOCAL_DB_HANDLER");
const varDatabaseDbHandler = require("../../backend/varDatabaseDbHandler"); const varDatabaseDbHandler = require("../../backend/varDatabaseDbHandler");
const nodemailer = require("nodemailer"); const nodemailer = require("nodemailer");
@ -10,6 +11,7 @@ const nodemailer = require("nodemailer");
* @param {string} param.database * @param {string} param.database
* @param {string | number} [param.userId] * @param {string | number} [param.userId]
* @param {string[]} [param.additionalFields] * @param {string[]} [param.additionalFields]
* @param {boolean} [param.useLocal]
* *
* @returns {Promise<import("../../../types").ApiReauthUserReturn>} * @returns {Promise<import("../../../types").ApiReauthUserReturn>}
*/ */
@ -18,14 +20,19 @@ module.exports = async function apiReauthUser({
database, database,
userId, userId,
additionalFields, additionalFields,
useLocal,
}) { }) {
let foundUser = let foundUser =
existingUser?.id && existingUser.id.toString().match(/./) existingUser?.id && existingUser.id.toString().match(/./)
? await varDatabaseDbHandler({ ? useLocal
queryString: `SELECT * FROM users WHERE id=?`, ? await LOCAL_DB_HANDLER(`SELECT * FROM users WHERE id=?`, [
queryValuesArray: [existingUser.id.toString()], existingUser.id.toString(),
database, ])
}) : await varDatabaseDbHandler({
queryString: `SELECT * FROM users WHERE id=?`,
queryValuesArray: [existingUser.id.toString()],
database,
})
: null; : null;
//////////////////////////////////////// ////////////////////////////////////////

View File

@ -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; email: string;
database: string; database: string;
email_login_field?: string; email_login_field?: string;
@ -8,6 +8,7 @@ declare function _exports({ email, database, email_login_field, mail_domain, mai
mail_username?: string; mail_username?: string;
mail_password?: string; mail_password?: string;
html: string; html: string;
useLocal?: boolean;
}): Promise<{ }): Promise<{
success: boolean; success: boolean;
msg?: string; msg?: string;

View File

@ -1,5 +1,6 @@
// @ts-check // @ts-check
const LOCAL_DB_HANDLER = require("../../../utils/backend/global-db/LOCAL_DB_HANDLER");
const varDatabaseDbHandler = require("../../backend/varDatabaseDbHandler"); const varDatabaseDbHandler = require("../../backend/varDatabaseDbHandler");
const nodemailer = require("nodemailer"); const nodemailer = require("nodemailer");
@ -16,6 +17,7 @@ const nodemailer = require("nodemailer");
* @param {string} [param.mail_username] * @param {string} [param.mail_username]
* @param {string} [param.mail_password] * @param {string} [param.mail_password]
* @param {string} param.html * @param {string} param.html
* @param {boolean} [param.useLocal]
* *
* @returns {Promise<{success: boolean, msg?: string}>} * @returns {Promise<{success: boolean, msg?: string}>}
*/ */
@ -29,6 +31,7 @@ module.exports = async function apiSendEmailCode({
mail_username, mail_username,
mail_password, mail_password,
html, html,
useLocal,
}) { }) {
if (email?.match(/ /)) { if (email?.match(/ /)) {
return { return {
@ -41,11 +44,16 @@ module.exports = async function apiSendEmailCode({
//////////////////////////////////////// ////////////////////////////////////////
//////////////////////////////////////// ////////////////////////////////////////
let foundUser = await varDatabaseDbHandler({ const foundUserQuery = `SELECT * FROM users WHERE email = ?`;
queryString: `SELECT * FROM users WHERE email = ?`, const foundUserValues = [email];
queryValuesArray: [email],
database, 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!"); 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({ let setTempCode = useLocal
queryString: `UPDATE users SET ${email_login_field} = ? WHERE email = ?`, ? await LOCAL_DB_HANDLER(setTempCodeQuery, setTempCodeValues)
queryValuesArray: [tempCode + `-${Date.now()}`, email], : await varDatabaseDbHandler({
database: database, queryString: setTempCodeQuery,
}); queryValuesArray: setTempCodeValues,
database: database,
});
} }
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
return { return {
success: true, success: true,
msg: "Success", msg: "Success",

View File

@ -1,10 +1,11 @@
declare function _exports({ payload, dbFullName }: { declare function _exports({ payload, dbFullName, useLocal, }: {
payload: { payload: {
id: string | number; id: string | number;
} & { } & {
[x: string]: (string | number | null | undefined); [x: string]: (string | number | null | undefined);
}; };
dbFullName: string; dbFullName: string;
useLocal?: boolean;
}): Promise<{ }): Promise<{
success: boolean; success: boolean;
payload: any; payload: any;

View File

@ -8,10 +8,15 @@ const updateDbEntry = require("../../backend/db/updateDbEntry");
* @param {object} params * @param {object} params
* @param {{ id: string | number } & Object<string, (string | number | null | undefined)>} params.payload * @param {{ id: string | number } & Object<string, (string | number | null | undefined)>} params.payload
* @param {string} params.dbFullName * @param {string} params.dbFullName
* @param {boolean} [params.useLocal]
* *
* @returns {Promise<{ success: boolean, payload: any }>} * @returns {Promise<{ success: boolean, payload: any }>}
*/ */
module.exports = async function apiUpdateUser({ payload, dbFullName }) { module.exports = async function apiUpdateUser({
payload,
dbFullName,
useLocal,
}) {
const data = (() => { const data = (() => {
const reqBodyKeys = Object.keys(payload); const reqBodyKeys = Object.keys(payload);
@ -34,6 +39,7 @@ module.exports = async function apiUpdateUser({ payload, dbFullName }) {
identifierColumnName: "id", identifierColumnName: "id",
identifierValue: payload.id, identifierValue: payload.id,
data: data, data: data,
useLocal,
}); });
return { return {

View File

@ -1,4 +1,5 @@
declare function _exports({ userId }: { declare function _exports({ userId, useLocal }: {
userId: number | string; userId: number | string;
useLocal?: boolean;
}): Promise<any>; }): Promise<any>;
export = _exports; export = _exports;

View File

@ -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 NO_DB_HANDLER = require("../../utils/backend/global-db/NO_DB_HANDLER");
const addDbEntry = require("./db/addDbEntry"); const addDbEntry = require("./db/addDbEntry");
const encrypt = require("../dsql/encrypt"); const encrypt = require("../dsql/encrypt");
const LOCAL_DB_HANDLER = require("../../utils/backend/global-db/LOCAL_DB_HANDLER");
/** /**
* # Add Mariadb User * # Add Mariadb User
@ -13,10 +14,11 @@ const encrypt = require("../dsql/encrypt");
* *
* @param {object} params - parameters object * * @param {object} params - parameters object *
* @param {number | string} params.userId - invited user object * @param {number | string} params.userId - invited user object
* @param {boolean} [params.useLocal]
* *
* @returns {Promise<any>} new user auth object payload * @returns {Promise<any>} new user auth object payload
*/ */
module.exports = async function addMariadbUser({ userId }) { module.exports = async function addMariadbUser({ userId, useLocal }) {
try { try {
const defaultMariadbUserHost = process.env.DSQL_DB_HOST || "127.0.0.1"; 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 }); const encryptedPassword = encrypt({ data: password });
await NO_DB_HANDLER( const createMariadbUsersQuery = `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}' REQUIRE SSL`
);
const updateUser = await DB_HANDLER( if (useLocal) {
`UPDATE users SET mariadb_user = ?, mariadb_host = '127.0.0.1', mariadb_pass = ? WHERE id = ?`, await LOCAL_DB_HANDLER(createMariadbUsersQuery);
[username, encryptedPassword, userId] } 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({ const addMariadbUser = await addDbEntry({
tableName: "mariadb_users", tableName: "mariadb_users",
@ -50,6 +58,7 @@ module.exports = async function addMariadbUser({ userId }) {
grants: '[{"database":"*","table":"*","privileges":["ALL"]}]', grants: '[{"database":"*","table":"*","privileges":["ALL"]}]',
}, },
dbContext: "Master", dbContext: "Master",
useLocal,
}); });
console.log(`User ${userId} SQL credentials successfully added.`); console.log(`User ${userId} SQL credentials successfully added.`);

View File

@ -1,5 +1,6 @@
declare function _exports({ userId, database }: { declare function _exports({ userId, database, useLocal, }: {
userId: number; userId: number;
database: string; database: string;
useLocal?: boolean;
}): Promise<any>; }): Promise<any>;
export = _exports; export = _exports;

View File

@ -9,6 +9,7 @@ const { default: grabUserSchemaData } = require("./grabUserSchemaData");
const { default: setUserSchemaData } = require("./setUserSchemaData"); const { default: setUserSchemaData } = require("./setUserSchemaData");
const addDbEntry = require("./db/addDbEntry"); const addDbEntry = require("./db/addDbEntry");
const createDbFromSchema = require("../../shell/createDbFromSchema"); const createDbFromSchema = require("../../shell/createDbFromSchema");
const LOCAL_DB_HANDLER = require("../../utils/backend/global-db/LOCAL_DB_HANDLER");
/** /**
* # Add User Table to Database * # Add User Table to Database
@ -16,10 +17,15 @@ const createDbFromSchema = require("../../shell/createDbFromSchema");
* @param {object} params * @param {object} params
* @param {number} params.userId - user id * @param {number} params.userId - user id
* @param {string} params.database * @param {string} params.database
* @param {boolean} [params.useLocal]
* *
* @returns {Promise<any>} new user auth object payload * @returns {Promise<any>} new user auth object payload
*/ */
module.exports = async function addUsersTableToDb({ userId, database }) { module.exports = async function addUsersTableToDb({
userId,
database,
useLocal,
}) {
/** /**
* Initialize * Initialize
* *
@ -59,10 +65,15 @@ module.exports = async function addUsersTableToDb({ userId, database }) {
setUserSchemaData({ schemaData: userSchemaData, userId }); setUserSchemaData({ schemaData: userSchemaData, userId });
const targetDb = await DB_HANDLER( const targetDb = useLocal
`SELECT id FROM user_databases WHERE user_id=? AND db_slug=?`, ? await LOCAL_DB_HANDLER(
[userId, database] `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]) { if (targetDb && targetDb[0]) {
const newTableEntry = await addDbEntry({ const newTableEntry = await addDbEntry({
@ -75,6 +86,7 @@ module.exports = async function addUsersTableToDb({ userId, database }) {
table_name: "Users", table_name: "Users",
table_slug: "users", table_slug: "users",
}, },
useLocal,
}); });
} }

View File

@ -19,10 +19,11 @@ export = addDbEntry;
* @param {boolean} [params.update] - Update this row if it exists * @param {boolean} [params.update] - Update this row if it exists
* @param {string} [params.encryptionKey] - 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 {string} [params.encryptionSalt] - Update this row if it exists
* @param {boolean} [params.useLocal]
* *
* @returns {Promise<any>} * @returns {Promise<any>}
*/ */
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"); dbContext?: ("Master" | "Dsql User");
paradigm?: ("Read Only" | "Full Access"); paradigm?: ("Read Only" | "Full Access");
dbFullName?: string; dbFullName?: string;
@ -34,4 +35,5 @@ declare function addDbEntry({ dbContext, paradigm, dbFullName, tableName, data,
update?: boolean; update?: boolean;
encryptionKey?: string; encryptionKey?: string;
encryptionSalt?: string; encryptionSalt?: string;
useLocal?: boolean;
}): Promise<any>; }): Promise<any>;

View File

@ -8,6 +8,7 @@ const _ = require("lodash");
const DB_HANDLER = require("../../../utils/backend/global-db/DB_HANDLER"); 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 DSQL_USER_DB_HANDLER = require("../../../utils/backend/global-db/DSQL_USER_DB_HANDLER");
const encrypt = require("../../dsql/encrypt"); const encrypt = require("../../dsql/encrypt");
const LOCAL_DB_HANDLER = require("../../../utils/backend/global-db/LOCAL_DB_HANDLER");
/** /**
* Add a db Entry Function * 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 {boolean} [params.update] - Update this row if it exists
* @param {string} [params.encryptionKey] - 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 {string} [params.encryptionSalt] - Update this row if it exists
* @param {boolean} [params.useLocal]
* *
* @returns {Promise<any>} * @returns {Promise<any>}
*/ */
@ -44,6 +46,7 @@ async function addDbEntry({
update, update,
encryptionKey, encryptionKey,
encryptionSalt, encryptionSalt,
useLocal,
}) { }) {
/** /**
* Initialize variables * Initialize variables
@ -55,7 +58,11 @@ async function addDbEntry({
: true; : true;
/** @type { any } */ /** @type { any } */
const dbHandler = isMaster ? DB_HANDLER : DSQL_USER_DB_HANDLER; const dbHandler = useLocal
? LOCAL_DB_HANDLER
: isMaster
? DB_HANDLER
: DSQL_USER_DB_HANDLER;
//////////////////////////////////////// ////////////////////////////////////////
//////////////////////////////////////// ////////////////////////////////////////

View File

@ -18,10 +18,11 @@ export = deleteDbEntry;
* @param {import("../../../types").DSQL_TableSchemaType} [params.tableSchema] - Table schema * @param {import("../../../types").DSQL_TableSchemaType} [params.tableSchema] - Table schema
* @param {string} params.identifierColumnName - Update row identifier column name * @param {string} params.identifierColumnName - Update row identifier column name
* @param {string|number} params.identifierValue - Update row identifier column value * @param {string|number} params.identifierValue - Update row identifier column value
* @param {boolean} [params.useLocal]
* *
* @returns {Promise<object|null>} * @returns {Promise<object|null>}
*/ */
declare function deleteDbEntry({ dbContext, paradigm, dbFullName, tableName, identifierColumnName, identifierValue, }: { declare function deleteDbEntry({ dbContext, paradigm, dbFullName, tableName, identifierColumnName, identifierValue, useLocal, }: {
dbContext?: string; dbContext?: string;
paradigm?: ("Read Only" | "Full Access"); paradigm?: ("Read Only" | "Full Access");
dbFullName: string; dbFullName: string;
@ -29,4 +30,5 @@ declare function deleteDbEntry({ dbContext, paradigm, dbFullName, tableName, ide
tableSchema?: import("../../../types").DSQL_TableSchemaType; tableSchema?: import("../../../types").DSQL_TableSchemaType;
identifierColumnName: string; identifierColumnName: string;
identifierValue: string | number; identifierValue: string | number;
useLocal?: boolean;
}): Promise<object | null>; }): Promise<object | null>;

View File

@ -2,6 +2,7 @@
const DB_HANDLER = require("../../../utils/backend/global-db/DB_HANDLER"); 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 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 * 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 {import("../../../types").DSQL_TableSchemaType} [params.tableSchema] - Table schema
* @param {string} params.identifierColumnName - Update row identifier column name * @param {string} params.identifierColumnName - Update row identifier column name
* @param {string|number} params.identifierValue - Update row identifier column value * @param {string|number} params.identifierValue - Update row identifier column value
* @param {boolean} [params.useLocal]
* *
* @returns {Promise<object|null>} * @returns {Promise<object|null>}
*/ */
@ -33,6 +35,7 @@ async function deleteDbEntry({
tableName, tableName,
identifierColumnName, identifierColumnName,
identifierValue, identifierValue,
useLocal,
}) { }) {
try { try {
/** /**
@ -45,7 +48,11 @@ async function deleteDbEntry({
: true; : true;
/** @type { (a1:any, a2?:any) => any } */ /** @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;
//////////////////////////////////////// ////////////////////////////////////////
//////////////////////////////////////// ////////////////////////////////////////

View File

@ -107,6 +107,8 @@ async function runQuery({
} }
if (local) { if (local) {
console.log("Using Local ...");
const rawResults = await LOCAL_DB_HANDLER( const rawResults = await LOCAL_DB_HANDLER(
formattedQuery, formattedQuery,
queryValuesArray queryValuesArray

View File

@ -18,10 +18,11 @@ export = updateDbEntry;
* @param {import("../../../types").DSQL_TableSchemaType} [params.tableSchema] - Table schema * @param {import("../../../types").DSQL_TableSchemaType} [params.tableSchema] - Table schema
* @param {string} params.identifierColumnName - Update row identifier column name * @param {string} params.identifierColumnName - Update row identifier column name
* @param {string | number} params.identifierValue - Update row identifier column value * @param {string | number} params.identifierValue - Update row identifier column value
* @param {boolean} [params.useLocal]
* *
* @returns {Promise<object|null>} * @returns {Promise<object|null>}
*/ */
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"); dbContext?: ("Master" | "Dsql User");
paradigm?: ("Read Only" | "Full Access"); paradigm?: ("Read Only" | "Full Access");
dbFullName?: string; dbFullName?: string;
@ -32,4 +33,5 @@ declare function updateDbEntry({ dbContext, paradigm, dbFullName, tableName, dat
tableSchema?: import("../../../types").DSQL_TableSchemaType; tableSchema?: import("../../../types").DSQL_TableSchemaType;
identifierColumnName: string; identifierColumnName: string;
identifierValue: string | number; identifierValue: string | number;
useLocal?: boolean;
}): Promise<object | null>; }): Promise<object | null>;

View File

@ -8,6 +8,7 @@ const sanitizeHtmlOptions = require("../html/sanitizeHtmlOptions");
const DB_HANDLER = require("../../../utils/backend/global-db/DB_HANDLER"); 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 DSQL_USER_DB_HANDLER = require("../../../utils/backend/global-db/DSQL_USER_DB_HANDLER");
const encrypt = require("../../dsql/encrypt"); const encrypt = require("../../dsql/encrypt");
const LOCAL_DB_HANDLER = require("../../../utils/backend/global-db/LOCAL_DB_HANDLER");
/** /**
* Update DB Function * Update DB Function
@ -28,6 +29,7 @@ const encrypt = require("../../dsql/encrypt");
* @param {import("../../../types").DSQL_TableSchemaType} [params.tableSchema] - Table schema * @param {import("../../../types").DSQL_TableSchemaType} [params.tableSchema] - Table schema
* @param {string} params.identifierColumnName - Update row identifier column name * @param {string} params.identifierColumnName - Update row identifier column name
* @param {string | number} params.identifierValue - Update row identifier column value * @param {string | number} params.identifierValue - Update row identifier column value
* @param {boolean} [params.useLocal]
* *
* @returns {Promise<object|null>} * @returns {Promise<object|null>}
*/ */
@ -42,6 +44,7 @@ async function updateDbEntry({
identifierValue, identifierValue,
encryptionKey, encryptionKey,
encryptionSalt, encryptionSalt,
useLocal,
}) { }) {
/** /**
* Check if data is valid * Check if data is valid
@ -55,7 +58,11 @@ async function updateDbEntry({
: true; : true;
/** @type {(a1:any, a2?:any)=> any } */ /** @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;
//////////////////////////////////////// ////////////////////////////////////////
//////////////////////////////////////// ////////////////////////////////////////

View File

@ -1054,6 +1054,7 @@ export type APILoginFunctionParams = {
token?: boolean; token?: boolean;
skipPassword?: boolean; skipPassword?: boolean;
social?: boolean; social?: boolean;
useLocal?: boolean;
}; };
export type APILoginFunctionReturn = { export type APILoginFunctionReturn = {
success: boolean; success: boolean;
@ -1063,10 +1064,11 @@ export type APILoginFunctionReturn = {
}; };
export type APILoginFunction = (params: APILoginFunctionParams) => Promise<APILoginFunctionReturn>; export type APILoginFunction = (params: APILoginFunctionParams) => Promise<APILoginFunctionReturn>;
export type APICreateUserFunctionParams = { export type APICreateUserFunctionParams = {
encryptionKey: string; encryptionKey?: string;
payload: any; payload: any;
database: string; database: string;
userId?: string | number; userId?: string | number;
useLocal?: boolean;
}; };
export type APICreateUserFunction = (params: APICreateUserFunctionParams) => Promise<AddUserFunctionReturn>; export type APICreateUserFunction = (params: APICreateUserFunctionParams) => Promise<AddUserFunctionReturn>;
/** /**
@ -1076,6 +1078,7 @@ export type APIGetUserFunctionParams = {
fields: string[]; fields: string[];
dbFullName: string; dbFullName: string;
userId: string | number; userId: string | number;
useLocal?: boolean;
}; };
export type APIGetUserFunction = (params: APIGetUserFunctionParams) => Promise<GetUserFunctionReturn>; export type APIGetUserFunction = (params: APIGetUserFunctionParams) => Promise<GetUserFunctionReturn>;
/** /**
@ -1108,6 +1111,7 @@ export type HandleSocialDbFunctionParams = {
invitation?: any; invitation?: any;
supEmail?: string; supEmail?: string;
additionalFields?: object; additionalFields?: object;
useLocal?: boolean;
}; };
export type HandleSocialDbFunctionReturn = { export type HandleSocialDbFunctionReturn = {
success: boolean; success: boolean;

View File

@ -1271,6 +1271,7 @@ export type APILoginFunctionParams = {
token?: boolean; token?: boolean;
skipPassword?: boolean; skipPassword?: boolean;
social?: boolean; social?: boolean;
useLocal?: boolean;
}; };
export type APILoginFunctionReturn = { export type APILoginFunctionReturn = {
success: boolean; success: boolean;
@ -1283,10 +1284,11 @@ export type APILoginFunction = (
) => Promise<APILoginFunctionReturn>; ) => Promise<APILoginFunctionReturn>;
export type APICreateUserFunctionParams = { export type APICreateUserFunctionParams = {
encryptionKey: string; encryptionKey?: string;
payload: any; payload: any;
database: string; database: string;
userId?: string | number; userId?: string | number;
useLocal?: boolean;
}; };
export type APICreateUserFunction = ( export type APICreateUserFunction = (
@ -1300,6 +1302,7 @@ export type APIGetUserFunctionParams = {
fields: string[]; fields: string[];
dbFullName: string; dbFullName: string;
userId: string | number; userId: string | number;
useLocal?: boolean;
}; };
export type APIGetUserFunction = ( export type APIGetUserFunction = (
@ -1339,6 +1342,7 @@ export type HandleSocialDbFunctionParams = {
invitation?: any; invitation?: any;
supEmail?: string; supEmail?: string;
additionalFields?: object; additionalFields?: object;
useLocal?: boolean;
}; };
export type HandleSocialDbFunctionReturn = { export type HandleSocialDbFunctionReturn = {

View File

@ -1,6 +1,6 @@
{ {
"name": "@moduletrace/datasquirel", "name": "@moduletrace/datasquirel",
"version": "2.7.6", "version": "2.7.7",
"description": "Cloud-based SQL data management tool", "description": "Cloud-based SQL data management tool",
"main": "index.js", "main": "index.js",
"bin": { "bin": {
@ -8,6 +8,7 @@
"dsql-dump": "./engine/dump.js" "dsql-dump": "./engine/dump.js"
}, },
"scripts": { "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": "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" "compile:full": "rm -rf dist && tsc --declaration --allowJs --outDir dist --emitDeclarationOnly --resolveJsonModule index.js && cat ./dist/index.d.ts > ./index.d.ts"
}, },

View File

@ -8,3 +8,4 @@ fi
npm run compile npm run compile
git add . && git commit -m "$msg" && git push && npm publish git add . && git commit -m "$msg" && git push && npm publish
npm run delete-ts

4
users/add-user.d.ts vendored
View File

@ -8,7 +8,7 @@ export = addUser;
* @param {string} param.key - FULL ACCESS API Key * @param {string} param.key - FULL ACCESS API Key
* @param {string} param.database - Database Name * @param {string} param.database - Database Name
* @param {import("../package-shared/types").UserDataPayload} param.payload - User Data Payload * @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} [param.encryptionSalt]
* @param {string | number} [param.user_id] * @param {string | number} [param.user_id]
* @param {string | number} [param.apiUserId] * @param {string | number} [param.apiUserId]
@ -20,7 +20,7 @@ declare function addUser({ key, payload, database, encryptionKey, user_id, useLo
key: string; key: string;
database: string; database: string;
payload: import("../package-shared/types").UserDataPayload; payload: import("../package-shared/types").UserDataPayload;
encryptionKey: string; encryptionKey?: string;
encryptionSalt?: string; encryptionSalt?: string;
user_id?: string | number; user_id?: string | number;
apiUserId?: string | number; apiUserId?: string | number;

View File

@ -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.key - FULL ACCESS API Key
* @param {string} param.database - Database Name * @param {string} param.database - Database Name
* @param {import("../package-shared/types").UserDataPayload} param.payload - User Data Payload * @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} [param.encryptionSalt]
* @param {string | number} [param.user_id] * @param {string | number} [param.user_id]
* @param {string | number} [param.apiUserId] * @param {string | number} [param.apiUserId]
@ -65,6 +65,7 @@ async function addUser({
encryptionKey, encryptionKey,
payload, payload,
userId: apiUserId, userId: apiUserId,
useLocal,
}); });
} }
} }

View File

@ -16,14 +16,16 @@ export = getToken;
* @param {string} params.encryptionKey - Encryption Key * @param {string} params.encryptionKey - Encryption Key
* @param {string} params.encryptionSalt - Encryption Salt * @param {string} params.encryptionSalt - Encryption Salt
* @param {string} params.database - Database Name * @param {string} params.database - Database Name
* @param {boolean} [params.useLocal]
* *
* @returns {{ key: string | undefined, csrf: string | undefined }} * @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; request: http.IncomingMessage;
encryptionKey: string; encryptionKey: string;
encryptionSalt: string; encryptionSalt: string;
database: string; database: string;
useLocal?: boolean;
}): { }): {
key: string | undefined; key: string | undefined;
csrf: string | undefined; csrf: string | undefined;

View File

@ -8,6 +8,7 @@
const http = require("http"); const http = require("http");
const decrypt = require("../package-shared/functions/dsql/decrypt"); const decrypt = require("../package-shared/functions/dsql/decrypt");
const parseCookies = require("../utils/functions/parseCookies"); 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.encryptionKey - Encryption Key
* @param {string} params.encryptionSalt - Encryption Salt * @param {string} params.encryptionSalt - Encryption Salt
* @param {string} params.database - Database Name * @param {string} params.database - Database Name
* @param {boolean} [params.useLocal]
* *
* @returns {{ key: string | undefined, csrf: string | undefined }} * @returns {{ key: string | undefined, csrf: string | undefined }}
*/ */
function getToken({ request, encryptionKey, encryptionSalt, database }) { function getToken({
request,
encryptionKey,
encryptionSalt,
database,
useLocal,
}) {
try { try {
/** /**
* Grab the payload * Grab the payload
@ -38,9 +46,9 @@ function getToken({ request, encryptionKey, encryptionSalt, database }) {
* @description Grab the payload * @description Grab the payload
*/ */
const cookies = parseCookies({ request }); const cookies = parseCookies({ request });
const dsqluid = cookies.dsqluid; const keynames = getAuthCookieNames();
const authKeyName = `datasquirel_${dsqluid}_${database}_auth_key`; const authKeyName = keynames.keyCookieName;
const csrfName = `datasquirel_${dsqluid}_${database}_csrf`; const csrfName = keynames.csrfCookieName;
const key = cookies[authKeyName]; const key = cookies[authKeyName];
const csrf = cookies[csrfName]; const csrf = cookies[csrfName];

View File

@ -98,6 +98,7 @@ async function getUser({ key, userId, database, fields, user_id, useLocal }) {
userId, userId,
fields: [...new Set(updatedFields)], fields: [...new Set(updatedFields)],
dbFullName: DSQL_DB_NAME, dbFullName: DSQL_DB_NAME,
useLocal,
}); });
} }
} }

View File

@ -12,6 +12,7 @@ const path = require("path");
const encrypt = require("../package-shared/functions/dsql/encrypt"); const encrypt = require("../package-shared/functions/dsql/encrypt");
const grabHostNames = require("../package-shared/utils/grab-host-names"); const grabHostNames = require("../package-shared/utils/grab-host-names");
const apiLoginUser = require("../package-shared/functions/api/users/api-login"); 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 * Login A user
@ -155,6 +156,7 @@ async function loginUser({
email_login_code, email_login_code,
email_login_field: emailLoginTempCodeFieldName, email_login_field: emailLoginTempCodeFieldName,
token, token,
useLocal,
}); });
} }
} else { } else {
@ -244,13 +246,14 @@ async function loginUser({
const { userId } = httpResponse; const { userId } = httpResponse;
const authKeyName = `datasquirel_${userId}_${database}_auth_key`; const cookieNames = getAuthCookieNames();
const csrfName = `datasquirel_${userId}_${database}_csrf`;
const authKeyName = cookieNames.keyCookieName;
const csrfName = cookieNames.csrfCookieName;
response.setHeader("Set-Cookie", [ response.setHeader("Set-Cookie", [
`${authKeyName}=${encryptedPayload};samesite=strict;path=/;HttpOnly=true;Secure=true`, `${authKeyName}=${encryptedPayload};samesite=strict;path=/;HttpOnly=true;Secure=true`,
`${csrfName}=${httpResponse.payload?.csrf_k};samesite=strict;path=/;HttpOnly=true`, `${csrfName}=${httpResponse.payload?.csrf_k};samesite=strict;path=/;HttpOnly=true`,
`dsqluid=${userId};samesite=strict;path=/;HttpOnly=true`,
]); ]);
} }

View File

@ -2,6 +2,7 @@
const http = require("http"); const http = require("http");
const parseCookies = require("../utils/functions/parseCookies"); const parseCookies = require("../utils/functions/parseCookies");
const getAuthCookieNames = require("../package-shared/functions/backend/cookies/get-auth-cookie-names");
/** /**
* Logout user * Logout user
@ -25,34 +26,48 @@ function logoutUser({ request, response, database }) {
const cookies = parseCookies({ request }); const cookies = parseCookies({ request });
const cookiesKeys = Object.keys(cookies); const cookiesKeys = Object.keys(cookies);
const dbUid = cookies.dsqluid; const keyNames = getAuthCookieNames();
const keyRegexp = new RegExp(`datasquirel_${dbUid}_${database}_auth_key`);
const csrfRegexp = new RegExp(`datasquirel_${dbUid}_${database}_csrf`);
const authKeyName = cookiesKeys.filter((cookieKey) => cookieKey.match(keyRegexp))[0]; const keyRegexp = new RegExp(keyNames.keyCookieName);
const csrfName = cookiesKeys.filter((cookieKey) => cookieKey.match(csrfRegexp))[0]; 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) { 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 { } else {
const allKeys = cookiesKeys.filter((cookieKey) => cookieKey.match(/datasquirel_.*_auth_key/)); const allKeys = cookiesKeys.filter((cookieKey) =>
const allCsrfs = cookiesKeys.filter((cookieKey) => cookieKey.match(/datasquirel_.*_csrf/)); 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 { return {
success: true, success: true,
payload: "User Logged Out", payload: "User Logged Out",
}; };
/** ********************************************** */
/** ********************************************** */
/** ********************************************** */
} catch (error) { } catch (error) {
console.log(error); console.log(error);

View File

@ -22,10 +22,11 @@ export = reauthUser;
* @param {string[]} [params.additionalFields] - Additional Fields to be added to the user object * @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 {string} [params.token] - access token to use instead of getting from cookie header
* @param {boolean} [params.user_id] - User ID * @param {boolean} [params.user_id] - User ID
* @param {boolean} [params.useLocal]
* *
* @returns { Promise<import("../package-shared/types").ReauthUserFunctionReturn> } * @returns { Promise<import("../package-shared/types").ReauthUserFunctionReturn> }
*/ */
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; key: string;
database: string; database: string;
response: http.ServerResponse; response: http.ServerResponse;
@ -36,5 +37,6 @@ declare function reauthUser({ key, database, response, request, level, encryptio
additionalFields?: string[]; additionalFields?: string[];
token?: string; token?: string;
user_id?: boolean; user_id?: boolean;
useLocal?: boolean;
}): Promise<import("../package-shared/types").ReauthUserFunctionReturn>; }): Promise<import("../package-shared/types").ReauthUserFunctionReturn>;
import http = require("http"); import http = require("http");

View File

@ -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.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 {string} [params.token] - access token to use instead of getting from cookie header
* @param {boolean} [params.user_id] - User ID * @param {boolean} [params.user_id] - User ID
* @param {boolean} [params.useLocal]
* *
* @returns { Promise<import("../package-shared/types").ReauthUserFunctionReturn> } * @returns { Promise<import("../package-shared/types").ReauthUserFunctionReturn> }
*/ */
@ -53,6 +54,7 @@ async function reauthUser({
additionalFields, additionalFields,
token, token,
user_id, user_id,
useLocal,
}) { }) {
/** /**
* Check Encryption Keys * 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 * @description Look for local db settings in `.env` file and by pass the http request if available
*/ */
const { const { DSQL_HOST, DSQL_USER, DSQL_PASS, DSQL_DB_NAME } = process.env;
DSQL_HOST,
DSQL_USER,
DSQL_PASS,
DSQL_DB_NAME,
DSQL_KEY,
DSQL_REF_DB_NAME,
DSQL_FULL_SYNC,
} = process.env;
if ( if (
DSQL_HOST?.match(/./) && DSQL_HOST?.match(/./) &&
DSQL_USER?.match(/./) && DSQL_USER?.match(/./) &&
DSQL_PASS?.match(/./) && DSQL_PASS?.match(/./) &&
DSQL_DB_NAME?.match(/./) DSQL_DB_NAME?.match(/./) &&
useLocal
) { ) {
/** @type {import("../package-shared/types").DSQL_DatabaseSchemaType | undefined} */ /** @type {import("../package-shared/types").DSQL_DatabaseSchemaType | undefined} */
let dbSchema; let dbSchema;
@ -121,6 +116,7 @@ async function reauthUser({
existingUser: existingUser.payload, existingUser: existingUser.payload,
additionalFields, additionalFields,
database: DSQL_DB_NAME, database: DSQL_DB_NAME,
useLocal,
}); });
} }
} else { } else {

View File

@ -24,10 +24,11 @@ export = sendEmailCode;
* @param {number} [params.mail_port] * @param {number} [params.mail_port]
* @param {string} [params.sender] * @param {string} [params.sender]
* @param {boolean} [params.user_id] - User ID * @param {boolean} [params.user_id] - User ID
* @param {boolean} [params.useLocal]
* *
* @returns { Promise<boolean>} * @returns { Promise<boolean>}
*/ */
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; key: string;
database: string; database: string;
email: string; email: string;
@ -41,5 +42,6 @@ declare function sendEmailCode({ key, email, database, encryptionKey, encryption
mail_port?: number; mail_port?: number;
sender?: string; sender?: string;
user_id?: boolean; user_id?: boolean;
useLocal?: boolean;
}): Promise<boolean>; }): Promise<boolean>;
import http = require("http"); import http = require("http");

View File

@ -38,6 +38,7 @@ const apiSendEmailCode = require("../package-shared/functions/api/users/api-send
* @param {number} [params.mail_port] * @param {number} [params.mail_port]
* @param {string} [params.sender] * @param {string} [params.sender]
* @param {boolean} [params.user_id] - User ID * @param {boolean} [params.user_id] - User ID
* @param {boolean} [params.useLocal]
* *
* @returns { Promise<boolean>} * @returns { Promise<boolean>}
*/ */
@ -54,6 +55,7 @@ async function sendEmailCode({
mail_port, mail_port,
sender, sender,
user_id, user_id,
useLocal,
}) { }) {
const grabedHostNames = grabHostNames(); const grabedHostNames = grabHostNames();
const { host, port, scheme } = grabedHostNames; 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 * @description Look for local db settings in `.env` file and by pass the http request if available
*/ */
const { const { DSQL_HOST, DSQL_USER, DSQL_PASS, DSQL_DB_NAME } = process.env;
DSQL_HOST,
DSQL_USER,
DSQL_PASS,
DSQL_DB_NAME,
DSQL_KEY,
DSQL_REF_DB_NAME,
DSQL_FULL_SYNC,
} = process.env;
if ( if (
DSQL_HOST?.match(/./) && DSQL_HOST?.match(/./) &&
DSQL_USER?.match(/./) && DSQL_USER?.match(/./) &&
DSQL_PASS?.match(/./) && DSQL_PASS?.match(/./) &&
DSQL_DB_NAME?.match(/./) DSQL_DB_NAME?.match(/./) &&
useLocal
) { ) {
/** @type {import("../package-shared/types").DSQL_DatabaseSchemaType | undefined} */ /** @type {import("../package-shared/types").DSQL_DatabaseSchemaType | undefined} */
let dbSchema; let dbSchema;
@ -141,6 +136,7 @@ async function sendEmailCode({
mail_port, mail_port,
mail_username, mail_username,
sender, sender,
useLocal,
}); });
} }
} else { } else {

View File

@ -8,10 +8,11 @@ export = updateUser;
* @param {String} params.database - Target Database * @param {String} params.database - Target Database
* @param {{ id: number } & Object.<string, any>} params.payload - User Object: ID is required * @param {{ id: number } & Object.<string, any>} params.payload - User Object: ID is required
* @param {boolean} [params.user_id] - User ID * @param {boolean} [params.user_id] - User ID
* @param {boolean} [params.useLocal]
* *
* @returns { Promise<import("../package-shared/types").UpdateUserFunctionReturn>} * @returns { Promise<import("../package-shared/types").UpdateUserFunctionReturn>}
*/ */
declare function updateUser({ key, payload, database, user_id }: { declare function updateUser({ key, payload, database, user_id, useLocal }: {
key: string; key: string;
database: string; database: string;
payload: { payload: {
@ -20,4 +21,5 @@ declare function updateUser({ key, payload, database, user_id }: {
[x: string]: any; [x: string]: any;
}; };
user_id?: boolean; user_id?: boolean;
useLocal?: boolean;
}): Promise<import("../package-shared/types").UpdateUserFunctionReturn>; }): Promise<import("../package-shared/types").UpdateUserFunctionReturn>;

View File

@ -16,24 +16,17 @@ const apiUpdateUser = require("../package-shared/functions/api/users/api-update-
* @param {String} params.database - Target Database * @param {String} params.database - Target Database
* @param {{ id: number } & Object.<string, any>} params.payload - User Object: ID is required * @param {{ id: number } & Object.<string, any>} params.payload - User Object: ID is required
* @param {boolean} [params.user_id] - User ID * @param {boolean} [params.user_id] - User ID
* @param {boolean} [params.useLocal]
* *
* @returns { Promise<import("../package-shared/types").UpdateUserFunctionReturn>} * @returns { Promise<import("../package-shared/types").UpdateUserFunctionReturn>}
*/ */
async function updateUser({ key, payload, database, user_id }) { async function updateUser({ key, payload, database, user_id, useLocal }) {
/** /**
* Check for local DB settings * Check for local DB settings
* *
* @description Look for local db settings in `.env` file and by pass the http request if available * @description Look for local db settings in `.env` file and by pass the http request if available
*/ */
const { const { DSQL_HOST, DSQL_USER, DSQL_PASS, DSQL_DB_NAME } = process.env;
DSQL_HOST,
DSQL_USER,
DSQL_PASS,
DSQL_DB_NAME,
DSQL_KEY,
DSQL_REF_DB_NAME,
DSQL_FULL_SYNC,
} = process.env;
const grabedHostNames = grabHostNames(); const grabedHostNames = grabHostNames();
const { host, port, scheme } = grabedHostNames; const { host, port, scheme } = grabedHostNames;
@ -42,7 +35,8 @@ async function updateUser({ key, payload, database, user_id }) {
DSQL_HOST?.match(/./) && DSQL_HOST?.match(/./) &&
DSQL_USER?.match(/./) && DSQL_USER?.match(/./) &&
DSQL_PASS?.match(/./) && DSQL_PASS?.match(/./) &&
DSQL_DB_NAME?.match(/./) DSQL_DB_NAME?.match(/./) &&
useLocal
) { ) {
/** @type {import("../package-shared/types").DSQL_DatabaseSchemaType | undefined} */ /** @type {import("../package-shared/types").DSQL_DatabaseSchemaType | undefined} */
let dbSchema; let dbSchema;
@ -59,6 +53,7 @@ async function updateUser({ key, payload, database, user_id }) {
return await apiUpdateUser({ return await apiUpdateUser({
payload: payload, payload: payload,
dbFullName: DSQL_DB_NAME, dbFullName: DSQL_DB_NAME,
useLocal,
}); });
} }
} }

View File

@ -1,10 +1,4 @@
export = userAuth; export = userAuth;
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** /**
* Authenticate User from request * Authenticate User from request
* ============================================================================== * ==============================================================================

View File

@ -1,20 +1,9 @@
// @ts-check // @ts-check
/**
* ==============================================================================
* Imports
* ==============================================================================
*/
const http = require("http"); const http = require("http");
const decrypt = require("../package-shared/functions/dsql/decrypt"); const decrypt = require("../package-shared/functions/dsql/decrypt");
const parseCookies = require("../utils/functions/parseCookies"); const parseCookies = require("../utils/functions/parseCookies");
const getAuthCookieNames = require("../package-shared/functions/backend/cookies/get-auth-cookie-names");
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** /**
* Authenticate User from request * Authenticate User from request
@ -47,9 +36,11 @@ function userAuth({
* @description Grab the payload * @description Grab the payload
*/ */
const cookies = parseCookies({ request }); const cookies = parseCookies({ request });
const dsqluid = cookies.dsqluid;
const authKeyName = `datasquirel_${dsqluid}_${database}_auth_key`; const keyNames = getAuthCookieNames();
const csrfName = `datasquirel_${dsqluid}_${database}_csrf`;
const authKeyName = keyNames.keyCookieName;
const csrfName = keyNames.csrfCookieName;
const key = token ? token : cookies[authKeyName]; const key = token ? token : cookies[authKeyName];
const csrf = cookies[csrfName]; const csrf = cookies[csrfName];
@ -93,10 +84,6 @@ function userAuth({
}; };
} }
/** ********************************************** */
/** ********************************************** */
/** ********************************************** */
/** /**
* Grab the payload * Grab the payload
* *
@ -113,10 +100,6 @@ function userAuth({
}; };
} }
/** ********************************************** */
/** ********************************************** */
/** ********************************************** */
/** /**
* Return User Object * Return User Object
* *
@ -140,8 +123,4 @@ function userAuth({
} }
} }
/** ********************************************** */
/** ********************************************** */
/** ********************************************** */
module.exports = userAuth; module.exports = userAuth;

View File

@ -1,13 +1,7 @@
export = validateToken; export = validateToken;
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** /**
* Validate Token * Validate Token
* ============================================================================== * ======================================
* @description This Function takes in a encrypted token and returns a user object * @description This Function takes in a encrypted token and returns a user object
* *
* @param {Object} params - Arg * @param {Object} params - Arg

View File

@ -1,23 +1,11 @@
// @ts-check // @ts-check
/**
* ==============================================================================
* Imports
* ==============================================================================
*/
const http = require("http"); const http = require("http");
const decrypt = require("../package-shared/functions/dsql/decrypt"); const decrypt = require("../package-shared/functions/dsql/decrypt");
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** /**
* Validate Token * Validate Token
* ============================================================================== * ======================================
* @description This Function takes in a encrypted token and returns a user object * @description This Function takes in a encrypted token and returns a user object
* *
* @param {Object} params - Arg * @param {Object} params - Arg
@ -69,10 +57,6 @@ function validateToken({ token, encryptionKey, encryptionSalt }) {
return null; return null;
} }
/** ********************************************** */
/** ********************************************** */
/** ********************************************** */
/** /**
* Return User Object * Return User Object
* *
@ -89,8 +73,4 @@ function validateToken({ token, encryptionKey, encryptionSalt }) {
} }
} }
/** ********************************************** */
/** ********************************************** */
/** ********************************************** */
module.exports = validateToken; module.exports = validateToken;

View File

@ -67,6 +67,7 @@ async function get({
queryValues, queryValues,
tableName, tableName,
dbSchema, dbSchema,
useLocal,
}); });
} }

View File

@ -64,6 +64,7 @@ async function post({
dbSchema, dbSchema,
queryValues, queryValues,
tableName, tableName,
useLocal,
}); });
} }