Updates
This commit is contained in:
@@ -1,10 +1,11 @@
|
||||
declare function _exports({ query, user }: {
|
||||
declare function _exports({ query, user, useLocal }: {
|
||||
query: {
|
||||
invite: number;
|
||||
database_access: string;
|
||||
priviledge: string;
|
||||
email: string;
|
||||
};
|
||||
user: import("../../types").UserType;
|
||||
useLocal?: boolean;
|
||||
user: import("../../types").DATASQUIREL_LoggedInUser;
|
||||
}): Promise<any>;
|
||||
export = _exports;
|
||||
|
||||
@@ -3,13 +3,7 @@
|
||||
const serverError = require("./serverError");
|
||||
const DB_HANDLER = require("../../utils/backend/global-db/DB_HANDLER");
|
||||
const addDbEntry = require("./db/addDbEntry");
|
||||
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
const LOCAL_DB_HANDLER = require("../../utils/backend/global-db/LOCAL_DB_HANDLER");
|
||||
|
||||
/**
|
||||
* Add Admin User on Login
|
||||
@@ -27,32 +21,23 @@ const addDbEntry = require("./db/addDbEntry");
|
||||
* @param {string} params.query.priviledge - String containing databases priviledges
|
||||
* @param {string} params.query.email - Inviting user email address
|
||||
*
|
||||
* @param {import("../../types").UserType} params.user - invited user object
|
||||
* @param {boolean} [params.useLocal]
|
||||
* @param {import("../../types").DATASQUIREL_LoggedInUser} params.user - invited user object
|
||||
*
|
||||
* @returns {Promise<any>} new user auth object payload
|
||||
*/
|
||||
module.exports = async function addAdminUserOnLogin({ query, user }) {
|
||||
module.exports = async function addAdminUserOnLogin({ query, user, useLocal }) {
|
||||
try {
|
||||
/**
|
||||
* Fetch user
|
||||
*
|
||||
* @description Fetch user from db
|
||||
*/ // @ts-ignore
|
||||
const finalDbHandler = useLocal ? LOCAL_DB_HANDLER : DB_HANDLER;
|
||||
const { invite, database_access, priviledge, email } = query;
|
||||
|
||||
const lastInviteTimeArray = await DB_HANDLER(
|
||||
`SELECT date_created_code FROM invitations WHERE inviting_user_id=? AND invited_user_email=?`,
|
||||
[invite, email]
|
||||
);
|
||||
const lastInviteTimeQuery = `SELECT date_created_code FROM invitations WHERE inviting_user_id=? AND invited_user_email=?`;
|
||||
const lastInviteTimeValues = [invite, email];
|
||||
|
||||
// if (lastInviteTimeArray && lastInviteTimeArray[0]?.date_created_code) {
|
||||
// const timeSinceLastInvite = Date.now() - parseInt(lastInviteTimeArray[0].date_created_code);
|
||||
// if (timeSinceLastInvite > 21600000) {
|
||||
// throw new Error("Invitation expired");
|
||||
// }
|
||||
// } else if (!lastInviteTimeArray || !lastInviteTimeArray[0]) {
|
||||
// throw new Error("No Invitation Found");
|
||||
// }
|
||||
const lastInviteTimeArray = await finalDbHandler(
|
||||
lastInviteTimeQuery,
|
||||
lastInviteTimeValues
|
||||
);
|
||||
|
||||
if (!lastInviteTimeArray || !lastInviteTimeArray[0]) {
|
||||
throw new Error("No Invitation Found");
|
||||
@@ -62,14 +47,16 @@ module.exports = async function addAdminUserOnLogin({ query, user }) {
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
|
||||
// @ts-ignore
|
||||
const invitingUserDb = await DB_HANDLER(
|
||||
`SELECT first_name,last_name,email FROM users WHERE id=?`,
|
||||
[invite]
|
||||
const invitingUserDbQuery = `SELECT first_name,last_name,email FROM users WHERE id=?`;
|
||||
const invitingUserDbValues = [invite];
|
||||
|
||||
const invitingUserDb = await finalDbHandler(
|
||||
invitingUserDbQuery,
|
||||
invitingUserDbValues
|
||||
);
|
||||
|
||||
if (invitingUserDb?.[0]) {
|
||||
const existingUserUser = await DB_HANDLER(
|
||||
const existingUserUser = await finalDbHandler(
|
||||
`SELECT email FROM user_users WHERE user_id=? AND invited_user_id=? AND user_type='admin' AND email=?`,
|
||||
[invite, user.id, email]
|
||||
);
|
||||
@@ -77,25 +64,6 @@ module.exports = async function addAdminUserOnLogin({ query, user }) {
|
||||
if (existingUserUser?.[0]) {
|
||||
console.log("User already added");
|
||||
} else {
|
||||
// const newUserUser = await DB_HANDLER(
|
||||
// `INSERT IGNORE INTO user_users
|
||||
// (user_id, invited_user_id, database_access, first_name, last_name, phone, email, username, user_type, user_priviledge)
|
||||
// VALUES
|
||||
// (?,?,?,?,?,?,?,?,?,?)
|
||||
// )`,
|
||||
// [
|
||||
// invite,
|
||||
// user.id,
|
||||
// database_access,
|
||||
// user.first_name,
|
||||
// user.last_name,
|
||||
// user.phone,
|
||||
// user.email,
|
||||
// user.username,
|
||||
// "admin",
|
||||
// priviledge,
|
||||
// ]
|
||||
// );
|
||||
addDbEntry({
|
||||
dbFullName: "datasquirel",
|
||||
tableName: "user_users",
|
||||
@@ -113,20 +81,19 @@ module.exports = async function addAdminUserOnLogin({ query, user }) {
|
||||
image: user.image,
|
||||
image_thumbnail: user.image_thumbnail,
|
||||
},
|
||||
useLocal,
|
||||
});
|
||||
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
|
||||
// @ts-ignore
|
||||
const dbTableData = await DB_HANDLER(
|
||||
const dbTableData = await finalDbHandler(
|
||||
`SELECT db_tables_data FROM invitations WHERE inviting_user_id=? AND invited_user_email=?`,
|
||||
[invite, email]
|
||||
);
|
||||
|
||||
// @ts-ignore
|
||||
const clearEntries = await DB_HANDLER(
|
||||
const clearEntries = await finalDbHandler(
|
||||
`DELETE FROM delegated_user_tables WHERE root_user_id=? AND delegated_user_id=?`,
|
||||
[invite, user.id]
|
||||
);
|
||||
@@ -154,17 +121,13 @@ module.exports = async function addAdminUserOnLogin({ query, user }) {
|
||||
table: table_slug,
|
||||
priviledge: priviledge,
|
||||
},
|
||||
useLocal,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
}
|
||||
|
||||
// @ts-ignore
|
||||
const inviteAccepted = await DB_HANDLER(
|
||||
const inviteAccepted = await finalDbHandler(
|
||||
`UPDATE invitations SET invitation_status='Accepted' WHERE inviting_user_id=? AND invited_user_email=?`,
|
||||
[invite, email]
|
||||
);
|
||||
|
||||
+4
-1
@@ -1,6 +1,9 @@
|
||||
declare function _exports({ userId, database, useLocal, }: {
|
||||
declare function _exports({ userId, database, useLocal, payload, }: {
|
||||
userId: number;
|
||||
database: string;
|
||||
useLocal?: boolean;
|
||||
payload?: {
|
||||
[x: string]: any;
|
||||
};
|
||||
}): Promise<any>;
|
||||
export = _exports;
|
||||
|
||||
@@ -10,6 +10,7 @@ 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");
|
||||
const grabNewUsersTableSchema = require("./grabNewUsersTableSchema");
|
||||
|
||||
/**
|
||||
* # Add User Table to Database
|
||||
@@ -18,6 +19,7 @@ const LOCAL_DB_HANDLER = require("../../utils/backend/global-db/LOCAL_DB_HANDLER
|
||||
* @param {number} params.userId - user id
|
||||
* @param {string} params.database
|
||||
* @param {boolean} [params.useLocal]
|
||||
* @param {Object<string, any>} [params.payload] - payload object
|
||||
*
|
||||
* @returns {Promise<any>} new user auth object payload
|
||||
*/
|
||||
@@ -25,39 +27,30 @@ module.exports = async function addUsersTableToDb({
|
||||
userId,
|
||||
database,
|
||||
useLocal,
|
||||
payload,
|
||||
}) {
|
||||
/**
|
||||
* Initialize
|
||||
*
|
||||
* @description Initialize
|
||||
*/
|
||||
const dbFullName = `datasquirel_user_${userId}_${database}`;
|
||||
/** @type {import("../../types").DSQL_TableSchemaType} */
|
||||
const userPreset = require("../../data/presets/users.json");
|
||||
|
||||
try {
|
||||
/**
|
||||
* Fetch user
|
||||
*
|
||||
* @description Fetch user from db
|
||||
*/
|
||||
const dbFullName = database;
|
||||
|
||||
const userPreset = grabNewUsersTableSchema({ payload });
|
||||
if (!userPreset) throw new Error("Couldn't Get User Preset!");
|
||||
|
||||
const userSchemaData = grabUserSchemaData({ userId });
|
||||
if (!userSchemaData) throw new Error("User schema data not found!");
|
||||
|
||||
let targetDatabase = userSchemaData.filter(
|
||||
(db) => db.dbSlug === database
|
||||
)[0];
|
||||
let targetDatabase = userSchemaData.find(
|
||||
(db) => db.dbFullName === database
|
||||
);
|
||||
|
||||
let existingTableIndex;
|
||||
// @ts-ignore
|
||||
let existingTable = targetDatabase.tables.filter((table, index) => {
|
||||
if (table.tableName === "users") {
|
||||
existingTableIndex = index;
|
||||
return true;
|
||||
}
|
||||
});
|
||||
if (!targetDatabase) {
|
||||
throw new Error("Couldn't Find Target Database!");
|
||||
}
|
||||
|
||||
if (existingTable && existingTable[0] && existingTableIndex) {
|
||||
let existingTableIndex = targetDatabase?.tables.findIndex(
|
||||
(table) => table.tableName === "users"
|
||||
);
|
||||
|
||||
if (typeof existingTableIndex == "number" && existingTableIndex > 0) {
|
||||
targetDatabase.tables[existingTableIndex] = userPreset;
|
||||
} else {
|
||||
targetDatabase.tables.push(userPreset);
|
||||
@@ -65,6 +58,7 @@ module.exports = async function addUsersTableToDb({
|
||||
|
||||
setUserSchemaData({ schemaData: userSchemaData, userId });
|
||||
|
||||
/** @type {any[] | null} */
|
||||
const targetDb = useLocal
|
||||
? await LOCAL_DB_HANDLER(
|
||||
`SELECT id FROM user_databases WHERE user_id=? AND db_slug=?`,
|
||||
@@ -75,14 +69,14 @@ module.exports = async function addUsersTableToDb({
|
||||
[userId, database]
|
||||
);
|
||||
|
||||
if (targetDb && targetDb[0]) {
|
||||
if (targetDb?.[0]) {
|
||||
const newTableEntry = await addDbEntry({
|
||||
dbFullName: "datasquirel",
|
||||
tableName: "user_database_tables",
|
||||
data: {
|
||||
user_id: userId,
|
||||
db_id: targetDb[0].id,
|
||||
db_slug: database,
|
||||
db_slug: targetDatabase.dbSlug,
|
||||
table_name: "Users",
|
||||
table_slug: "users",
|
||||
},
|
||||
@@ -97,6 +91,8 @@ module.exports = async function addUsersTableToDb({
|
||||
|
||||
return `Done!`;
|
||||
} catch (/** @type {any} */ error) {
|
||||
console.log(`addUsersTableToDb.js ERROR: ${error.message}`);
|
||||
|
||||
serverError({
|
||||
component: "addUsersTableToDb",
|
||||
message: error.message,
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
export function grabAuthDirs(): {
|
||||
root: string;
|
||||
auth: string;
|
||||
};
|
||||
export function initAuthFiles(): boolean;
|
||||
/**
|
||||
* # Write Auth Files
|
||||
* @param {string} name
|
||||
* @param {string} data
|
||||
*/
|
||||
export function writeAuthFile(name: string, data: string): boolean;
|
||||
/**
|
||||
* # Get Auth Files
|
||||
* @param {string} name
|
||||
*/
|
||||
export function getAuthFile(name: string): string;
|
||||
/**
|
||||
* # Delete Auth Files
|
||||
* @param {string} name
|
||||
*/
|
||||
export function deleteAuthFile(name: string): void;
|
||||
/**
|
||||
* # Delete Auth Files
|
||||
* @param {string} name
|
||||
*/
|
||||
export function checkAuthFile(name: string): boolean;
|
||||
@@ -0,0 +1,90 @@
|
||||
// @ts-check
|
||||
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
|
||||
const grabAuthDirs = () => {
|
||||
const ROOT_DIR = path.resolve(process.cwd(), "./.tmp");
|
||||
const AUTH_DIR = path.join(ROOT_DIR, "logins");
|
||||
|
||||
return { root: ROOT_DIR, auth: AUTH_DIR };
|
||||
};
|
||||
|
||||
const initAuthFiles = () => {
|
||||
try {
|
||||
const authDirs = grabAuthDirs();
|
||||
|
||||
if (!fs.existsSync(authDirs.root))
|
||||
fs.mkdirSync(authDirs.root, { recursive: true });
|
||||
if (!fs.existsSync(authDirs.auth))
|
||||
fs.mkdirSync(authDirs.auth, { recursive: true });
|
||||
return true;
|
||||
} catch (/** @type {any} */ error) {
|
||||
console.log(`Error initializing Auth Files: ${error.message}`);
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* # Write Auth Files
|
||||
* @param {string} name
|
||||
* @param {string} data
|
||||
*/
|
||||
const writeAuthFile = (name, data) => {
|
||||
initAuthFiles();
|
||||
try {
|
||||
fs.writeFileSync(path.join(grabAuthDirs().auth, name), data);
|
||||
return true;
|
||||
} catch (/** @type {any} */ error) {
|
||||
console.log(`Error writing Auth File: ${error.message}`);
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* # Get Auth Files
|
||||
* @param {string} name
|
||||
*/
|
||||
const getAuthFile = (name) => {
|
||||
try {
|
||||
const authFilePath = path.join(grabAuthDirs().auth, name);
|
||||
return fs.readFileSync(authFilePath, "utf-8");
|
||||
} catch (/** @type {any} */ error) {
|
||||
console.log(`Error getting Auth File: ${error.message}`);
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* # Delete Auth Files
|
||||
* @param {string} name
|
||||
*/
|
||||
const deleteAuthFile = (name) => {
|
||||
try {
|
||||
return fs.rmSync(path.join(grabAuthDirs().auth, name));
|
||||
} catch (/** @type {any} */ error) {
|
||||
console.log(`Error deleting Auth File: ${error.message}`);
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* # Delete Auth Files
|
||||
* @param {string} name
|
||||
*/
|
||||
const checkAuthFile = (name) => {
|
||||
try {
|
||||
return fs.existsSync(path.join(grabAuthDirs().auth, name));
|
||||
return true;
|
||||
} catch (/** @type {any} */ error) {
|
||||
console.log(`Error checking Auth File: ${error.message}`);
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
exports.grabAuthDirs = grabAuthDirs;
|
||||
exports.initAuthFiles = initAuthFiles;
|
||||
exports.writeAuthFile = writeAuthFile;
|
||||
exports.getAuthFile = getAuthFile;
|
||||
exports.deleteAuthFile = deleteAuthFile;
|
||||
exports.checkAuthFile = checkAuthFile;
|
||||
@@ -1,4 +1,7 @@
|
||||
declare function _exports(): {
|
||||
declare function _exports(params?: {
|
||||
database?: string;
|
||||
userId?: string | number;
|
||||
}): {
|
||||
keyCookieName: string;
|
||||
csrfCookieName: string;
|
||||
};
|
||||
|
||||
@@ -1,10 +1,28 @@
|
||||
module.exports = function getAuthCookieNames() {
|
||||
// @ts-check
|
||||
|
||||
/**
|
||||
* # Grab Auth Cookie Names
|
||||
*
|
||||
* @param {object} [params]
|
||||
* @param {string} [params.database]
|
||||
* @param {string | number} [params.userId]
|
||||
*
|
||||
* @returns {{ keyCookieName: string, csrfCookieName: string }}
|
||||
*/
|
||||
module.exports = function getAuthCookieNames(params) {
|
||||
const cookiesPrefix = process.env.DSQL_COOKIES_PREFIX || "dsql_";
|
||||
const cookiesKeyName = process.env.DSQL_COOKIES_KEY_NAME || "key";
|
||||
const cookiesCSRFName = process.env.DSQL_COOKIES_CSRF_NAME || "csrf";
|
||||
|
||||
const keyCookieName = cookiesPrefix + cookiesKeyName;
|
||||
const csrfCookieName = cookiesPrefix + cookiesCSRFName;
|
||||
let keyCookieName = cookiesPrefix;
|
||||
if (params?.userId) keyCookieName += `user_${params.userId}_`;
|
||||
if (params?.database) keyCookieName += `${params.database}_`;
|
||||
keyCookieName += cookiesKeyName;
|
||||
|
||||
let csrfCookieName = cookiesPrefix;
|
||||
if (params?.userId) csrfCookieName += `user_${params.userId}_`;
|
||||
if (params?.database) csrfCookieName += `${params.database}_`;
|
||||
csrfCookieName += cookiesCSRFName;
|
||||
|
||||
return {
|
||||
keyCookieName,
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
declare function _exports(params?: {
|
||||
payload?: {
|
||||
[x: string]: any;
|
||||
};
|
||||
}): import("../../types").DSQL_TableSchemaType | null;
|
||||
export = _exports;
|
||||
@@ -0,0 +1,54 @@
|
||||
// @ts-check
|
||||
|
||||
const grabSchemaFieldsFromData = require("./grabSchemaFieldsFromData");
|
||||
const serverError = require("./serverError");
|
||||
|
||||
/**
|
||||
* # Add User Table to Database
|
||||
*
|
||||
* @param {object} [params]
|
||||
* @param {Object<string,any>} [params.payload] - fields to add to the table
|
||||
*
|
||||
* @returns {import("../../types").DSQL_TableSchemaType | null} new user auth object payload
|
||||
*/
|
||||
module.exports = function grabNewUsersTableSchema(params) {
|
||||
try {
|
||||
/** @type {import("../../types").DSQL_TableSchemaType} */
|
||||
const userPreset = require("../../data/presets/users.json");
|
||||
/** @type {import("../../types").DSQL_FieldSchemaType[]} */
|
||||
const defaultFields = require("../../data/defaultFields.json");
|
||||
|
||||
const supplementalFields = params?.payload
|
||||
? grabSchemaFieldsFromData({
|
||||
data: params?.payload,
|
||||
excludeData: defaultFields,
|
||||
excludeFields: userPreset.fields,
|
||||
})
|
||||
: [];
|
||||
|
||||
console.log("supplementalFields", supplementalFields);
|
||||
|
||||
const allFields = [...userPreset.fields, ...supplementalFields];
|
||||
|
||||
console.log("allFields", allFields);
|
||||
|
||||
const finalFields = [
|
||||
...defaultFields.slice(0, 2),
|
||||
...allFields,
|
||||
...defaultFields.slice(2),
|
||||
];
|
||||
|
||||
userPreset.fields = [...finalFields];
|
||||
|
||||
return userPreset;
|
||||
} catch (/** @type {any} */ error) {
|
||||
console.log(`grabNewUsersTableSchema.js ERROR: ${error.message}`);
|
||||
|
||||
serverError({
|
||||
component: "grabNewUsersTableSchema",
|
||||
message: error.message,
|
||||
});
|
||||
|
||||
return null;
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,11 @@
|
||||
declare function _exports({ data, fields, excludeData, excludeFields, }: {
|
||||
data?: {
|
||||
[x: string]: any;
|
||||
};
|
||||
fields?: string[];
|
||||
excludeData?: {
|
||||
[x: string]: any;
|
||||
};
|
||||
excludeFields?: import("../../types").DSQL_FieldSchemaType[];
|
||||
}): import("../../types").DSQL_FieldSchemaType[];
|
||||
export = _exports;
|
||||
@@ -0,0 +1,94 @@
|
||||
// @ts-check
|
||||
|
||||
const serverError = require("./serverError");
|
||||
|
||||
/**
|
||||
* # Add User Table to Database
|
||||
*
|
||||
* @param {object} params
|
||||
* @param {Object<string,any>} [params.data]
|
||||
* @param {string[]} [params.fields]
|
||||
* @param {Object<string,any>} [params.excludeData]
|
||||
* @param {import("../../types").DSQL_FieldSchemaType[]} [params.excludeFields]
|
||||
*
|
||||
* @returns {import("../../types").DSQL_FieldSchemaType[]} new user auth object payload
|
||||
*/
|
||||
module.exports = function grabSchemaFieldsFromData({
|
||||
data,
|
||||
fields,
|
||||
excludeData,
|
||||
excludeFields,
|
||||
}) {
|
||||
try {
|
||||
const possibleFields = require("../../data/possibleFields.json");
|
||||
const dataTypes = require("../../data/dataTypes.json");
|
||||
|
||||
/** @type {import("../../types").DSQL_FieldSchemaType[]} */
|
||||
const finalFields = [];
|
||||
|
||||
/** @type {string[]} */
|
||||
let filteredFields = [];
|
||||
|
||||
if (data && Object.keys(data)?.[0]) {
|
||||
filteredFields = Object.keys(data);
|
||||
}
|
||||
|
||||
if (fields) {
|
||||
filteredFields = [...filteredFields, ...fields];
|
||||
filteredFields = [...new Set(filteredFields)];
|
||||
}
|
||||
|
||||
filteredFields = filteredFields
|
||||
.filter(
|
||||
(fld) => !excludeData || !Object.keys(excludeData).includes(fld)
|
||||
)
|
||||
.filter(
|
||||
(fld) =>
|
||||
!excludeFields ||
|
||||
!excludeFields.find((exlFld) => exlFld.fieldName == fld)
|
||||
);
|
||||
|
||||
filteredFields.forEach((fld) => {
|
||||
const value = data ? data[fld] : null;
|
||||
|
||||
if (typeof value == "string") {
|
||||
const newField =
|
||||
/** @type {import("../../types").DSQL_FieldSchemaType} */ ({
|
||||
fieldName: fld,
|
||||
dataType: value.length > 255 ? "TEXT" : "VARCHAR(255)",
|
||||
});
|
||||
|
||||
if (Boolean(value.match(/<[^>]+>/g))) {
|
||||
newField.richText = true;
|
||||
}
|
||||
|
||||
finalFields.push(newField);
|
||||
} else if (typeof value == "number") {
|
||||
finalFields.push(
|
||||
/** @type {import("../../types").DSQL_FieldSchemaType} */ ({
|
||||
fieldName: fld,
|
||||
dataType: "INT",
|
||||
})
|
||||
);
|
||||
} else {
|
||||
finalFields.push(
|
||||
/** @type {import("../../types").DSQL_FieldSchemaType} */ ({
|
||||
fieldName: fld,
|
||||
dataType: "VARCHAR(255)",
|
||||
})
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
return finalFields;
|
||||
} catch (/** @type {any} */ error) {
|
||||
console.log(`grabSchemaFieldsFromData.js ERROR: ${error.message}`);
|
||||
|
||||
serverError({
|
||||
component: "grabSchemaFieldsFromData.js",
|
||||
message: error.message,
|
||||
});
|
||||
|
||||
return [];
|
||||
}
|
||||
};
|
||||
@@ -1,31 +0,0 @@
|
||||
// @ts-check
|
||||
|
||||
const { createHmac } = require("crypto");
|
||||
//
|
||||
|
||||
/**
|
||||
* # Password Hash function
|
||||
* @param {string} password
|
||||
* @returns
|
||||
*/
|
||||
function hashPassword(password) {
|
||||
const hmac = createHmac(
|
||||
"sha512",
|
||||
process.env.DSQL_ENCRYPTION_PASSWORD || ""
|
||||
);
|
||||
hmac.update(password);
|
||||
let hashed = hmac.digest("base64");
|
||||
return hashed;
|
||||
}
|
||||
|
||||
exports.hashPassword = hashPassword;
|
||||
|
||||
// export const comparePasswords = async (password) => {
|
||||
// const hmac = createHmac("sha512", process.env.DSQL_ENCRYPTION_PASSWORD);
|
||||
// hmac.update(password);
|
||||
// let hashed = hmac.digest("base64");
|
||||
|
||||
// let dbPass = await global.DB_HANDLER(`SELECT * FROM users WHERE password = '${hashed}'`);
|
||||
// console.log(dbPass);
|
||||
// return dbPass;
|
||||
// };
|
||||
@@ -1,24 +1,11 @@
|
||||
// @ts-check
|
||||
|
||||
/**
|
||||
* ==============================================================================
|
||||
* Imports
|
||||
* ==============================================================================
|
||||
*/
|
||||
const fs = require("fs");
|
||||
const { IncomingMessage } = require("http");
|
||||
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
|
||||
/**
|
||||
* ==============================================================================
|
||||
* Main Function
|
||||
* ==============================================================================
|
||||
* # Server Error
|
||||
*
|
||||
* @param {{
|
||||
* user?: { id?: number | string, first_name?: string, last_name?: string, email?: string } & *,
|
||||
* message: string,
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
declare function _exports({ userId, database, newFields, newPayload, }: {
|
||||
userId: number | string;
|
||||
database: string;
|
||||
newFields?: string[];
|
||||
newPayload?: {
|
||||
[x: string]: any;
|
||||
};
|
||||
}): Promise<any>;
|
||||
export = _exports;
|
||||
@@ -0,0 +1,80 @@
|
||||
// @ts-check
|
||||
|
||||
const serverError = require("./serverError");
|
||||
const { default: grabUserSchemaData } = require("./grabUserSchemaData");
|
||||
const { default: setUserSchemaData } = require("./setUserSchemaData");
|
||||
const createDbFromSchema = require("../../shell/createDbFromSchema");
|
||||
const grabSchemaFieldsFromData = require("./grabSchemaFieldsFromData");
|
||||
|
||||
/**
|
||||
* # Add User Table to Database
|
||||
*
|
||||
* @param {object} params
|
||||
* @param {number | string} params.userId - user id
|
||||
* @param {string} params.database
|
||||
* @param {string[]} [params.newFields] - new fields to add to the users table
|
||||
* @param {Object<string, any>} [params.newPayload]
|
||||
*
|
||||
* @returns {Promise<any>} new user auth object payload
|
||||
*/
|
||||
module.exports = async function updateUsersTableSchema({
|
||||
userId,
|
||||
database,
|
||||
newFields,
|
||||
newPayload,
|
||||
}) {
|
||||
try {
|
||||
const dbFullName = database;
|
||||
|
||||
const userSchemaData = grabUserSchemaData({ userId });
|
||||
if (!userSchemaData) throw new Error("User schema data not found!");
|
||||
|
||||
let targetDatabaseIndex = userSchemaData.findIndex(
|
||||
(db) => db.dbFullName === database
|
||||
);
|
||||
|
||||
if (targetDatabaseIndex < 0) {
|
||||
throw new Error("Couldn't Find Target Database!");
|
||||
}
|
||||
|
||||
let existingTableIndex = userSchemaData[
|
||||
targetDatabaseIndex
|
||||
]?.tables.findIndex((table) => table.tableName === "users");
|
||||
|
||||
const usersTable =
|
||||
userSchemaData[targetDatabaseIndex].tables[existingTableIndex];
|
||||
|
||||
if (!usersTable?.fields?.[0]) throw new Error("Users Table Not Found!");
|
||||
|
||||
const additionalFields = grabSchemaFieldsFromData({
|
||||
fields: newFields,
|
||||
data: newPayload,
|
||||
});
|
||||
|
||||
const spliceStartIndex = usersTable.fields.findIndex(
|
||||
(field) => field.fieldName === "date_created"
|
||||
);
|
||||
const finalSpliceStartIndex =
|
||||
spliceStartIndex >= 0 ? spliceStartIndex : 0;
|
||||
|
||||
usersTable.fields.splice(finalSpliceStartIndex, 0, ...additionalFields);
|
||||
|
||||
setUserSchemaData({ schemaData: userSchemaData, userId });
|
||||
|
||||
const dbShellUpdate = await createDbFromSchema({
|
||||
userId,
|
||||
targetDatabase: dbFullName,
|
||||
});
|
||||
|
||||
return `Done!`;
|
||||
} catch (/** @type {any} */ error) {
|
||||
console.log(`addUsersTableToDb.js ERROR: ${error.message}`);
|
||||
|
||||
serverError({
|
||||
component: "addUsersTableToDb",
|
||||
message: error.message,
|
||||
user: { id: userId },
|
||||
});
|
||||
return error.message;
|
||||
}
|
||||
};
|
||||
@@ -1,7 +1,8 @@
|
||||
declare function _exports({ queryString, queryValuesArray, database, tableSchema, }: {
|
||||
declare function _exports({ queryString, queryValuesArray, database, tableSchema, useLocal, }: {
|
||||
queryString: string;
|
||||
queryValuesArray?: any[];
|
||||
database?: string;
|
||||
tableSchema?: import("../../types").DSQL_TableSchemaType;
|
||||
useLocal?: boolean;
|
||||
}): Promise<any>;
|
||||
export = _exports;
|
||||
|
||||
@@ -5,6 +5,7 @@ const parseDbResults = require("./parseDbResults");
|
||||
const serverError = require("./serverError");
|
||||
const DB_HANDLER = require("../../utils/backend/global-db/DB_HANDLER");
|
||||
const DSQL_USER_DB_HANDLER = require("../../utils/backend/global-db/DSQL_USER_DB_HANDLER");
|
||||
const LOCAL_DB_HANDLER = require("../../utils/backend/global-db/LOCAL_DB_HANDLER");
|
||||
|
||||
/**
|
||||
* DB handler for specific database
|
||||
@@ -15,6 +16,7 @@ const DSQL_USER_DB_HANDLER = require("../../utils/backend/global-db/DSQL_USER_DB
|
||||
* @param {*[]} [params.queryValuesArray] - Values Array
|
||||
* @param {string} [params.database] - Database name
|
||||
* @param {import("../../types").DSQL_TableSchemaType} [params.tableSchema] - Table schema
|
||||
* @param {boolean} [params.useLocal]
|
||||
* @returns {Promise<any>}
|
||||
*/
|
||||
module.exports = async function varDatabaseDbHandler({
|
||||
@@ -22,6 +24,7 @@ module.exports = async function varDatabaseDbHandler({
|
||||
queryValuesArray,
|
||||
database,
|
||||
tableSchema,
|
||||
useLocal,
|
||||
}) {
|
||||
/**
|
||||
* Declare variables
|
||||
@@ -31,7 +34,11 @@ module.exports = async function varDatabaseDbHandler({
|
||||
const isMaster = database?.match(/^datasquirel$/) ? true : false;
|
||||
|
||||
/** @type {any} */
|
||||
const FINAL_DB_HANDLER = isMaster ? DB_HANDLER : DSQL_USER_DB_HANDLER;
|
||||
const FINAL_DB_HANDLER = useLocal
|
||||
? LOCAL_DB_HANDLER
|
||||
: isMaster
|
||||
? DB_HANDLER
|
||||
: DSQL_USER_DB_HANDLER;
|
||||
|
||||
let results;
|
||||
|
||||
|
||||
Reference in New Issue
Block a user