Bug Fixes

This commit is contained in:
Benjamin Toby
2024-11-05 15:18:40 +01:00
parent 3cdf78e58d
commit 748ff55092
507 changed files with 3719 additions and 1231 deletions
+2 -1
View File
@@ -26,7 +26,8 @@ const decrypt = __webpack_require__(5425);
const isTableAllowed = ApiObject.target_table?.split(",").includes(String(table));
if (isTableAllowed) return ApiObject;
return null;
} catch (error) {
} catch (/** @type {any} */ error) {
console.log(`api-cred ERROR: ${error.message}`);
return null;
}
};
+1 -69
View File
@@ -115,29 +115,6 @@ const connection = mysql({
}
}
});
// const connection = mysql.createConnection({
// host: process.env.DSQL_DB_HOST,
// user: process.env.DSQL_DB_USERNAME,
// password: process.env.DSQL_DB_PASSWORD,
// database: process.env.DSQL_DB_NAME,
// charset: "utf8mb4",
// });
// connection.on("error", (err) => {
// console.log("CONNECTION STATE: ", connection.state);
// console.log(err.message);
// });
// connection.on("connect", () => {
// console.log("CONNECTION ACTIVE: ", connection.state);
// });
// connection.on("end", () => {
// console.log("CONNECTION DISCONNECTED: ", connection.state);
// });
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
/**
* Main DB Handler Function
* ==============================================================================
@@ -168,48 +145,8 @@ const connection = mysql({
resolve(result);
}
});
// connection.on("error", (err) => {
// console.log("CONNECTION STATE: ", connection.state);
// console.log(err.message);
// });
// connection.on("connect", () => {
// console.log("CONNECTION ACTIVE: ", connection.state);
// });
// connection.on("end", () => {
// console.log("CONNECTION DISCONNECTED: ", connection.state);
// });
/** ********************* Clean up */ });
});
await connection.end();
// connection.query(...args, (error, result, fields) => {
// if (error) {
// resolve({ error: error.message });
// } else {
// resolve(result);
// }
// connection.end()
// });
// connectionPool.query(...args, (error, result, fields) => {
// if (error) {
// resolve({ error: error.message });
// } else {
// resolve(result);
// }
// });
// connectionPool.getConnection(function (err, connection) {
// if (err) {
// resolve({ error: err.message });
// connection.release();
// return;
// }
// connection.query(...args, (error, result, fields) => {
// if (error) {
// resolve({ error: error.message });
// } else {
// resolve(result);
// }
// connection.release();
// });
// });
} catch (/** @type {any} */ error) {
fs.appendFileSync("./.tmp/dbErrorLogs.txt", JSON.stringify(error, null, 4) + "\n" + Date() + "\n\n\n", "utf8");
results = null;
@@ -217,11 +154,6 @@ const connection = mysql({
component: "dbHandler",
message: error.message
});
// try {
// connection.end();
// } catch (error) {
// console.log("ERROR in dbHandler Function =>", error.message);
// }
}
/**
* Return results
+2 -2
View File
@@ -17,10 +17,10 @@ const path = __webpack_require__(1017);
* ==============================================================================
* @param {Object} params
* @param {string | number} params.userId
* @returns {DSQL_DatabaseSchemaType[] | null}
* @returns {import("@/package-shared/types").DSQL_DatabaseSchemaType[] | null}
*/ function grabUserSchemaData({ userId }) {
try {
const userSchemaFilePath = path.resolve(process.cwd(), `./jsonData/dbSchemas/users/user-${userId}/main.json`);
const userSchemaFilePath = path.resolve(process.cwd(), `${process.env.DSQL_USER_DB_SCHEMA_PATH}/user-${userId}/main.json`);
const userSchemaData = JSON.parse(fs.readFileSync(userSchemaFilePath, "utf-8"));
return userSchemaData;
} catch (/** @type {any} */ error) {
+1 -3
View File
@@ -15,8 +15,7 @@ const fs = __webpack_require__(7147);
const EXPIRY_TIME = 1000 * 60 * 60 * 24 * 1 * 7; // 7 days
/**
* @async
* @param {import("next").NextApiRequest | http.IncomingMessage & { cookies: Partial<{ [key: string]: string; }>;
}} req - https request object
* @param {import("next").NextApiRequest | http.IncomingMessage & { cookies: Partial<{ [key: string]: string; }>; }} req - https request object
* @param {import("next").NextApiResponse | http.ServerResponse} res - https response object
* @param {boolean | null} [csrf] - csrf key
* @param {any} [query] - query object
@@ -33,7 +32,6 @@ const EXPIRY_TIME = 1000 * 60 * 60 * 24 * 1 * 7; // 7 days
return null;
}
/** ********************* Parse the payload */ let userObject = JSON.parse(userPayload);
const { user_type } = userObject;
if (!userObject.csrf_k) {
// console.log("No CSRF_K in decrypted payload");
return null;
+1 -1
View File
@@ -27,7 +27,7 @@ const { ServerResponse } = __webpack_require__(3685);
/** @type {import("child_process").ExecSyncOptions} */ let execSyncOptions = {
cwd: process.cwd()
};
const filePath = `./jsonData/dbSchemas/users/user-${user.id}/export.sql`;
const filePath = `${process.env.DSQL_USER_DB_SCHEMA_PATH}/user-${user.id}/export.sql`;
if (os.platform().match(/win/i)) execSyncOptions.shell = "bash.exe";
const exe = `${mysqlDumpPath} -u ${process.env.DSQL_DB_USERNAME} -h ${process.env.DSQL_DB_HOST} -p${process.env.DSQL_DB_PASSWORD} ${dbName} > ${filePath}`;
console.log(`exportDb.js exe => ${exe}`);
@@ -31,6 +31,37 @@ const decrypt = __webpack_require__(5425);
};
/***/ }),
/***/ 5425:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
// @ts-check
const { scryptSync , createDecipheriv } = __webpack_require__(6113);
const { Buffer } = __webpack_require__(4300);
/**
* @param {string} encryptedString
* @returns {string | null}
*/ const decrypt = (encryptedString)=>{
const algorithm = "aes-192-cbc";
const password = process.env.DSQL_ENCRYPTION_PASSWORD || "";
const salt = process.env.DSQL_ENCRYPTION_SALT || "";
let key = scryptSync(password, salt, 24);
let iv = Buffer.alloc(16, 0);
// @ts-ignore
const decipher = createDecipheriv(algorithm, key, iv);
try {
let decrypted = decipher.update(encryptedString, "hex", "utf8");
decrypted += decipher.final("utf8");
return decrypted;
} catch (error) {
return null;
}
};
module.exports = decrypt;
/***/ })
};
@@ -0,0 +1,86 @@
"use strict";
exports.id = 4480;
exports.ids = [4480];
exports.modules = {
/***/ 5304:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
// @ts-check
const { scryptSync , createDecipheriv } = __webpack_require__(6113);
const { Buffer } = __webpack_require__(4300);
/**
* @param {string} encryptedString
* @returns {string | null}
*/ const decrypt = (encryptedString)=>{
const algorithm = "aes-192-cbc";
const password = process.env.DSQL_ENCRYPTION_PASSWORD || "";
const salt = process.env.DSQL_ENCRYPTION_SALT || "";
let key = scryptSync(password, salt, 24);
let iv = Buffer.alloc(16, 0);
// @ts-ignore
const decipher = createDecipheriv(algorithm, key, iv);
try {
let decrypted = decipher.update(encryptedString, "hex", "utf8");
decrypted += decipher.final("utf8");
return decrypted;
} catch (error) {
return null;
}
};
module.exports = decrypt;
/***/ }),
/***/ 9395:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
// @ts-check
const fs = __webpack_require__(7147);
const path = __webpack_require__(1017);
const mysql = __webpack_require__(2261);
const SSL_DIR = "/app/ssl";
const MASTER = mysql({
config: {
host: process.env.DSQL_DB_HOST,
user: process.env.DSQL_DB_USERNAME,
password: process.env.DSQL_DB_PASSWORD,
database: process.env.DSQL_DB_NAME,
port: process.env.DB_PORT ? Number(process.env.DB_PORT) : undefined,
charset: "utf8mb4",
ssl: {
ca: fs.readFileSync(`${SSL_DIR}/ca-cert.pem`)
}
}
});
/**
* DSQL user read-only DB handler
* @param {object} params
* @param {string} params.paradigm
* @param {string} params.database
* @param {string} params.queryString
* @param {string[]} [params.queryValues]
*/ // @ts-ignore
async function DB_HANDLER(...args) {
try {
const results = await MASTER.query(...args);
/** ********************* Clean up */ await MASTER.end();
return JSON.parse(JSON.stringify(results));
} catch (/** @type {any} */ error) {
console.log("DB Error =>", error);
return {
success: false,
error: error.message
};
}
}
module.exports = DB_HANDLER;
/***/ })
};
;
File diff suppressed because it is too large Load Diff
+315
View File
@@ -0,0 +1,315 @@
"use strict";
exports.id = 4733;
exports.ids = [4733];
exports.modules = {
/***/ 8499:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
/** # MODULE TRACE
======================================================================
* Detected 3 files that call this module. The files are listed below:
======================================================================
* `import` Statement Found in [get.js] => file:///d:\GitHub\datasquirel\pages\api\query\get.js
* `import` Statement Found in [post.js] => file:///d:\GitHub\datasquirel\pages\api\query\post.js
* `import` Statement Found in [add-user.js] => file:///d:\GitHub\datasquirel\pages\api\user\add-user.js
==== MODULE TRACE END ==== */ // @ts-check
const fs = __webpack_require__(7147);
const fullAccessDbHandler = __webpack_require__(8539);
const varReadOnlyDatabaseDbHandler = __webpack_require__(3118);
const serverError = __webpack_require__(3017);
const addDbEntry = __webpack_require__(5338);
const updateDbEntry = __webpack_require__(5886);
const deleteDbEntry = __webpack_require__(6147);
/** ****************************************************************************** */ /** ****************************************************************************** */ /** ****************************************************************************** */ /** ****************************************************************************** */ /** ****************************************************************************** */ /** ****************************************************************************** */ /**
* Run DSQL users queries
* ==============================================================================
* @param {object} params - An object containing the function parameters.
* @param {string} params.dbFullName - Database full name. Eg. "datasquire_user_2_test"
* @param {string|any} params.query - Query string or object
* @param {boolean} [params.readOnly] - Is this operation read only?
* @param {import("../../../types").DSQL_DatabaseSchemaType} [params.dbSchema] - Database schema
* @param {string[]} [params.queryValuesArray] - An optional array of query values if "?" is used in the query string
* @param {string} [params.tableName] - Table Name
*
* @return {Promise<any>}
*/ async function runQuery({ dbFullName , query , readOnly , dbSchema , queryValuesArray , tableName , }) {
/**
* Declare variables
*
* @description Declare "results" variable
*/ /** @type {any} */ let result;
/** @type {any} */ let error;
/** @type {import("../../../types").DSQL_TableSchemaType | undefined} */ let tableSchema;
if (dbSchema) {
try {
const table = tableName ? tableName : typeof query == "string" ? null : query ? query?.table : null;
if (!table) throw new Error("No table name provided");
tableSchema = dbSchema.tables.filter((tb)=>tb?.tableName === table)[0];
} catch (_err) {
// console.log("ERROR getting tableSchema: ", _err.message);
}
}
/**
* Declare variables
*
* @description Declare "results" variable
*/ try {
if (typeof query === "string") {
if (readOnly) {
result = await varReadOnlyDatabaseDbHandler({
queryString: query,
queryValuesArray,
database: dbFullName,
tableSchema
});
} else {
result = await fullAccessDbHandler({
queryString: query,
queryValuesArray,
database: dbFullName,
tableSchema
});
}
} else if (typeof query === "object") {
/**
* Declare variables
*
* @description Declare "results" variable
*/ const { data , action , table: table1 , identifierColumnName , identifierValue , update , duplicateColumnName , duplicateColumnValue , } = query;
switch(action.toLowerCase()){
case "insert":
result = await addDbEntry({
dbContext: "Dsql User",
paradigm: "Full Access",
dbFullName: dbFullName,
tableName: table1,
data: data,
update,
duplicateColumnName,
duplicateColumnValue,
tableSchema
});
if (!result?.insertId) {
error = new Error("Couldn't insert data");
}
break;
case "update":
result = await updateDbEntry({
dbContext: "Dsql User",
paradigm: "Full Access",
dbFullName: dbFullName,
tableName: table1,
data: data,
identifierColumnName,
identifierValue,
tableSchema
});
break;
case "delete":
result = await deleteDbEntry({
dbContext: "Dsql User",
paradigm: "Full Access",
dbFullName: dbFullName,
tableName: table1,
identifierColumnName,
identifierValue,
tableSchema
});
break;
default:
result = null;
break;
}
}
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
} catch (/** @type {any} */ error1) {
serverError({
component: "functions/backend/runQuery",
message: error1.message
});
result = null;
error1 = error1.message;
}
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
return {
result,
error
};
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
}
module.exports = runQuery;
/***/ }),
/***/ 5425:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
// @ts-check
const { scryptSync , createDecipheriv } = __webpack_require__(6113);
const { Buffer } = __webpack_require__(4300);
/**
* @param {string} encryptedString
* @returns {string | null}
*/ const decrypt = (encryptedString)=>{
const algorithm = "aes-192-cbc";
const password = process.env.DSQL_ENCRYPTION_PASSWORD || "";
const salt = process.env.DSQL_ENCRYPTION_SALT || "";
let key = scryptSync(password, salt, 24);
let iv = Buffer.alloc(16, 0);
// @ts-ignore
const decipher = createDecipheriv(algorithm, key, iv);
try {
let decrypted = decipher.update(encryptedString, "hex", "utf8");
decrypted += decipher.final("utf8");
return decrypted;
} catch (error) {
return null;
}
};
module.exports = decrypt;
/***/ }),
/***/ 8539:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
// @ts-check
const DSQL_USER_DB_HANDLER = __webpack_require__(3403);
const parseDbResults = __webpack_require__(8326);
const serverError = __webpack_require__(3017);
/**
*
* @param {object} param0
* @param {string} param0.queryString
* @param {string} param0.database
* @param {import("../../types").DSQL_TableSchemaType | null} [param0.tableSchema]
* @param {string[]} [param0.queryValuesArray]
* @returns
*/ module.exports = async function fullAccessDbHandler({ queryString , database , tableSchema , queryValuesArray , }) {
/**
* Declare variables
*
* @description Declare "results" variable
*/ let results;
/**
* Fetch from db
*
* @description Fetch data from db if no cache
*/ try {
/** ********************* Run Query */ results = await DSQL_USER_DB_HANDLER({
paradigm: "Full Access",
database,
queryString,
queryValues: queryValuesArray
});
////////////////////////////////////////
} catch (/** @type {any} */ error) {
////////////////////////////////////////
serverError({
component: "fullAccessDbHandler",
message: error.message
});
/**
* Return error
*/ return error.message;
}
/**
* Return results
*
* @description Return results add to cache if "req" param is passed
*/ if (results && tableSchema) {
const unparsedResults = results;
const parsedResults = await parseDbResults({
unparsedResults: unparsedResults,
tableSchema: tableSchema
});
return parsedResults;
} else if (results) {
return results;
} else {
return null;
}
};
/***/ }),
/***/ 3118:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
// @ts-check
const fs = __webpack_require__(7147);
const serverError = __webpack_require__(3017);
const parseDbResults = __webpack_require__(8326);
const DSQL_USER_DB_HANDLER = __webpack_require__(3403);
/**
*
* @param {object} param0
* @param {string} param0.queryString
* @param {string} param0.database
* @param {string[]} [param0.queryValuesArray]
* @param {import("../../types").DSQL_TableSchemaType} [param0.tableSchema]
* @returns
*/ module.exports = async function varReadOnlyDatabaseDbHandler({ queryString , database , queryValuesArray , tableSchema , }) {
/**
* Declare variables
*
* @description Declare "results" variable
*/ let results;
/**
* Fetch from db
*
* @description Fetch data from db if no cache
*/ try {
results = await DSQL_USER_DB_HANDLER({
paradigm: "Read Only",
database,
queryString,
queryValues: queryValuesArray
});
////////////////////////////////////////
} catch (/** @type {any} */ error) {
////////////////////////////////////////
serverError({
component: "varReadOnlyDatabaseDbHandler",
message: error.message,
noMail: true
});
/**
* Return error
*/ return error.message;
}
/**
* Return results
*
* @description Return results add to cache if "req" param is passed
*/ if (results) {
const unparsedResults = results;
const parsedResults = await parseDbResults({
unparsedResults: unparsedResults,
tableSchema: tableSchema
});
return parsedResults;
} else {
return null;
}
};
/***/ })
};
;
+1 -1
View File
@@ -41,7 +41,7 @@ const path = __webpack_require__(1017);
return null;
}
const relativePath = isPrivate ? `@/${video ? "videos" : "media"}/${folder ? folder + "/" : ""}` : video ? `/videos/user-videos/user-${userId}/${folder ? folder + "/" : ""}` : `/images/user-images/user-${userId}/${folder ? folder + "/" : ""}`;
const fileRootPath = isPrivate ? `./jsonData/dbSchemas/users/user-${userId}/media/${folder ? folder + "/" : ""}` : path.join(STATIC_ROOT, relativePath);
const fileRootPath = isPrivate ? `${process.env.DSQL_USER_DB_SCHEMA_PATH}/user-${userId}/media/${folder ? folder + "/" : ""}` : path.join(STATIC_ROOT, relativePath);
if (!fs.existsSync(fileRootPath) && !pathOnly) {
fs.mkdirSync(fileRootPath, {
recursive: true
+32 -3
View File
@@ -15,8 +15,7 @@ const fs = __webpack_require__(7147);
const EXPIRY_TIME = 1000 * 60 * 60 * 24 * 1 * 7; // 7 days
/**
* @async
* @param {import("next").NextApiRequest | http.IncomingMessage & { cookies: Partial<{ [key: string]: string; }>;
}} req - https request object
* @param {import("next").NextApiRequest | http.IncomingMessage & { cookies: Partial<{ [key: string]: string; }>; }} req - https request object
* @param {import("next").NextApiResponse | http.ServerResponse} res - https response object
* @param {boolean | null} [csrf] - csrf key
* @param {any} [query] - query object
@@ -33,7 +32,6 @@ const EXPIRY_TIME = 1000 * 60 * 60 * 24 * 1 * 7; // 7 days
return null;
}
/** ********************* Parse the payload */ let userObject = JSON.parse(userPayload);
const { user_type } = userObject;
if (!userObject.csrf_k) {
// console.log("No CSRF_K in decrypted payload");
return null;
@@ -80,6 +78,37 @@ const EXPIRY_TIME = 1000 * 60 * 60 * 24 * 1 * 7; // 7 days
};
/***/ }),
/***/ 5425:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
// @ts-check
const { scryptSync , createDecipheriv } = __webpack_require__(6113);
const { Buffer } = __webpack_require__(4300);
/**
* @param {string} encryptedString
* @returns {string | null}
*/ const decrypt = (encryptedString)=>{
const algorithm = "aes-192-cbc";
const password = process.env.DSQL_ENCRYPTION_PASSWORD || "";
const salt = process.env.DSQL_ENCRYPTION_SALT || "";
let key = scryptSync(password, salt, 24);
let iv = Buffer.alloc(16, 0);
// @ts-ignore
const decipher = createDecipheriv(algorithm, key, iv);
try {
let decrypted = decipher.update(encryptedString, "hex", "utf8");
decrypted += decipher.final("utf8");
return decrypted;
} catch (error) {
return null;
}
};
module.exports = decrypt;
/***/ })
};
+381
View File
@@ -0,0 +1,381 @@
"use strict";
exports.id = 6968;
exports.ids = [6968];
exports.modules = {
/***/ 7839:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
// @ts-check
/**
* ==============================================================================
* Imports
* ==============================================================================
*/
const fs = __webpack_require__(7147);
////////////////////////////////////////////////
////////////////////////////////////////////////
////////////////////////////////////////////////
const addAdminUserOnLogin = __webpack_require__(613);
const handleNodemailer = __webpack_require__(6926);
const { ServerResponse } = __webpack_require__(3685);
const path = __webpack_require__(1017);
const addMariadbUser = __webpack_require__(4294);
const varDatabaseDbHandler = __webpack_require__(1311);
const encrypt = __webpack_require__(7547);
const addDbEntry = __webpack_require__(5338);
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
/**
* @typedef {object} FunctionReturn
* @property {boolean} success - Did the operation complete successfully or not?
* @property {{
* id: number,
* first_name: string,
* last_name: string,
* }|null} user - User payload object: or "null"
*/ /**
* Handle Social User Auth on Datasquirel Database
* ==============================================================================
*
* @description This function handles all social login logic after the social user
* has been authenticated and userpayload is present. The payload MUST contain the
* specified fields because this funciton will create a new user if the authenticated
* user does not exist.
*
* @param {{
* database?: string,
* social_id: string|number,
* email: string,
* social_platform: string,
* payload: any,
* res?: ServerResponse,
* invitation?: any,
* supEmail?: string,
* additionalFields?: object,
* }} params - function parameters inside an object
*
* @returns {Promise<any>} - Response object
*/ module.exports = async function handleSocialDb({ database , social_id , email , social_platform , payload , res , invitation , supEmail , additionalFields , }) {
////////////////////////////////////////////////
////////////////////////////////////////////////
////////////////////////////////////////////////
try {
////////////////////////////////////////////////
////////////////////////////////////////////////
////////////////////////////////////////////////
let existingSocialIdUser = await varDatabaseDbHandler({
database: database ? database : "datasquirel",
queryString: `SELECT * FROM users WHERE social_id = ? AND social_login='1' AND social_platform = ? `,
queryValuesArray: [
social_id.toString(),
social_platform
]
});
if (existingSocialIdUser && existingSocialIdUser[0]) {
return await loginSocialUser({
user: existingSocialIdUser[0],
social_platform,
res,
invitation,
database,
additionalFields
});
}
////////////////////////////////////////////////
////////////////////////////////////////////////
////////////////////////////////////////////////
const finalEmail = email ? email : supEmail ? supEmail : null;
if (!finalEmail) {
return {
success: false,
user: null,
msg: "No Email Present",
social_id,
social_platform,
payload
};
}
////////////////////////////////////////////////
////////////////////////////////////////////////
////////////////////////////////////////////////
let existingEmailOnly = await varDatabaseDbHandler({
database: database ? database : "datasquirel",
queryString: `SELECT * FROM users WHERE email='${finalEmail}'`
});
if (existingEmailOnly && existingEmailOnly[0]) {
return {
user: null,
msg: "This Email is already taken",
alert: true
};
}
////////////////////////////////////////////////
////////////////////////////////////////////////
////////////////////////////////////////////////
const foundUser = await varDatabaseDbHandler({
database: database ? database : "datasquirel",
queryString: `SELECT * FROM users WHERE email='${finalEmail}' AND social_login='1' AND social_platform='${social_platform}' AND social_id='${social_id}'`
});
if (foundUser && foundUser[0]) {
return await loginSocialUser({
user: payload,
social_platform,
res,
invitation,
database,
additionalFields
});
}
////////////////////////////////////////////////
////////////////////////////////////////////////
////////////////////////////////////////////////
const socialHashedPassword = encrypt(social_id.toString());
/** @type {any} */ const data = {
social_login: "1",
verification_status: supEmail ? "0" : "1",
password: socialHashedPassword
};
Object.keys(payload).forEach((key)=>{
data[key] = payload[key];
});
/** @type {any} */ const newUser = await addDbEntry({
dbContext: database ? "Dsql User" : undefined,
paradigm: database ? "Full Access" : undefined,
dbFullName: database ? database : "datasquirel",
tableName: "users",
duplicateColumnName: "email",
duplicateColumnValue: finalEmail,
data: {
...data,
email: finalEmail
}
});
if (newUser?.insertId) {
if (!database) {
/**
* Add a Mariadb User for this User
*/ await addMariadbUser({
userId: newUser.insertId
});
}
const newUserQueried = await varDatabaseDbHandler({
database: database ? database : "datasquirel",
queryString: `SELECT * FROM users WHERE id='${newUser.insertId}'`
});
if (!newUserQueried || !newUserQueried[0]) return {
user: null,
msg: "User Insertion Failed!"
};
////////////////////////////////////////////////
////////////////////////////////////////////////
////////////////////////////////////////////////
if (supEmail && database?.match(/^datasquirel$/)) {
/**
* Send email Verification
*
* @description Send verification email to newly created agent
*/ let generatedToken = encrypt(JSON.stringify({
id: newUser.insertId,
email: supEmail,
dateCode: Date.now()
}));
handleNodemailer({
to: supEmail,
subject: "Verify Email Address",
text: "Please click the link to verify your email address",
html: fs.readFileSync("./email/send-email-verification-link.html", "utf8").replace(/{{host}}/, process.env.DSQL_HOST || "").replace(/{{token}}/, generatedToken || "")
}).then((mail)=>{});
}
////////////////////////////////////////////////
////////////////////////////////////////////////
////////////////////////////////////////////////
const STATIC_ROOT = process.env.DSQL_STATIC_SERVER_DIR;
if (!STATIC_ROOT) {
console.log("Static File ENV not Found!");
return null;
}
/**
* Create new user folder and file
*
* @description Create new user folder and file
*/ if (!database || database?.match(/^datasquirel$/)) {
let newUserSchemaFolderPath = `${process.env.DSQL_USER_DB_SCHEMA_PATH}/user-${newUser.insertId}`;
let newUserMediaFolderPath = path.join(STATIC_ROOT, `images/user-images/user-${newUser.insertId}`);
fs.mkdirSync(newUserSchemaFolderPath);
fs.mkdirSync(newUserMediaFolderPath);
fs.writeFileSync(`${newUserSchemaFolderPath}/main.json`, JSON.stringify([]), "utf8");
}
////////////////////////////////////////////////
////////////////////////////////////////////////
////////////////////////////////////////////////
return await loginSocialUser({
user: newUserQueried[0],
social_platform,
res,
invitation,
database,
additionalFields
});
////////////////////////////////////////////////
////////////////////////////////////////////////
////////////////////////////////////////////////
} else {
console.log("Social User Failed to insert in 'handleSocialDb.js' backend function =>", newUser);
return {
success: false,
user: null,
msg: "Social User Failed to insert in 'handleSocialDb.js' backend function => ",
newUser: newUser
};
}
////////////////////////////////////////////////
////////////////////////////////////////////////
////////////////////////////////////////////////
} catch (/** @type {any} */ error) {
console.log("ERROR in 'handleSocialDb.js' backend function =>", error.message);
return {
success: false,
user: null,
error: error.message
};
// serverError({
// component: "/functions/backend/social-login/handleSocialDb.js - main-catch-error",
// message: error.message,
// user: { first_name, last_name },
// });
}
////////////////////////////////////////////////
////////////////////////////////////////////////
////////////////////////////////////////////////
return {
user: null,
msg: "User Login Failed!"
};
};
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
/**
* Function to login social user
* ==============================================================================
* @description This function logs in the user after 'handleSocialDb' function finishes
* the user creation or confirmation process
*
* @async
*
* @param {object} params - function parameters inside an object
* @param {{
* first_name: string,
* last_name: string,
* email: string,
* social_id: string|number,
* }} params.user - user object
* @param {string} params.social_platform - Whether its "google" or "facebook" or "github"
* @param {ServerResponse} [params.res] - Https response object
* @param {any} [params.invitation] - A query object if user was invited
* @param {string} [params.database] - Target Database
* @param {object} [params.additionalFields] - Additional fields to be added to the user payload
*
* @returns {Promise<any>}
*/ async function loginSocialUser({ user , social_platform , res , invitation , database , additionalFields , }) {
const foundUser = await varDatabaseDbHandler({
database: database ? database : "datasquirel",
queryString: `SELECT * FROM users WHERE email='${user.email}' AND social_id='${user.social_id}' AND social_platform='${social_platform}'`
});
if (!foundUser?.[0]) return {
success: false,
user: null
};
let csrfKey = Math.random().toString(36).substring(2) + "-" + Math.random().toString(36).substring(2);
/** @type {any} */ let userPayload = {
id: foundUser[0].id,
type: foundUser[0].type || "",
stripe_id: foundUser[0].stripe_id || "",
first_name: foundUser[0].first_name,
last_name: foundUser[0].last_name,
username: foundUser[0].username,
email: foundUser[0].email,
social_id: foundUser[0].social_id,
image: foundUser[0].image,
image_thumbnail: foundUser[0].image_thumbnail,
verification_status: foundUser[0].verification_status,
social_login: foundUser[0].social_login,
social_platform: foundUser[0].social_platform,
csrf_k: csrfKey,
logged_in_status: true,
date: Date.now()
};
if (additionalFields && Object.keys(additionalFields).length > 0) {
Object.keys(additionalFields).forEach((key)=>{
userPayload[key] = foundUser[0][key];
});
}
let encryptedPayload = encrypt(JSON.stringify(userPayload));
if (res?.setHeader) {
res.setHeader("Set-Cookie", [
`datasquirelAuthKey=${encryptedPayload};samesite=strict;path=/;HttpOnly=true;Secure=true`,
`csrf=${csrfKey};samesite=strict;path=/;HttpOnly=true`,
]);
}
////////////////////////////////////////////////
////////////////////////////////////////////////
////////////////////////////////////////////////
if (invitation && (!database || database?.match(/^datasquirel$/))) {
addAdminUserOnLogin({
query: invitation,
user: userPayload
});
}
////////////////////////////////////////////////
////////////////////////////////////////////////
////////////////////////////////////////////////
return {
success: true,
user: userPayload
};
}
/***/ }),
/***/ 5425:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
// @ts-check
const { scryptSync , createDecipheriv } = __webpack_require__(6113);
const { Buffer } = __webpack_require__(4300);
/**
* @param {string} encryptedString
* @returns {string | null}
*/ const decrypt = (encryptedString)=>{
const algorithm = "aes-192-cbc";
const password = process.env.DSQL_ENCRYPTION_PASSWORD || "";
const salt = process.env.DSQL_ENCRYPTION_SALT || "";
let key = scryptSync(password, salt, 24);
let iv = Buffer.alloc(16, 0);
// @ts-ignore
const decipher = createDecipheriv(algorithm, key, iv);
try {
let decrypted = decipher.update(encryptedString, "hex", "utf8");
decrypted += decipher.final("utf8");
return decrypted;
} catch (error) {
return null;
}
};
module.exports = decrypt;
/***/ })
};
;
+1 -1
View File
@@ -487,7 +487,7 @@ const SingleDbUserContext = /*#__PURE__*/ external_react_default().createContext
* Page/Site Data Data Fetching
*
* @description Fetch data on the server before returning
*/ /** @type {import("@/package-shared/types").DSQL_DatabaseSchemaType[]} */ const dbSchemaData = JSON.parse(fs.readFileSync(`./jsonData/dbSchemas/users/user-${dbUserId}/main.json`, "utf-8"));
*/ /** @type {import("@/package-shared/types").DSQL_DatabaseSchemaType[]} */ const dbSchemaData = JSON.parse(fs.readFileSync(`${process.env.DSQL_USER_DB_SCHEMA_PATH}/user-${dbUserId}/main.json`, "utf-8"));
const tables = dbSchemaData.filter((db)=>db.dbFullName === database[0].db_full_name)[0]?.tables;
const targetTable = tables.filter((table)=>table.tableName === "users")[0];
const singleUser = await varDatabaseDbHandler_default()({
+2 -2
View File
@@ -18,11 +18,11 @@ const path = __webpack_require__(1017);
* ==============================================================================
* @param {Object} params
* @param {string | number} params.userId
* @param {DSQL_DatabaseSchemaType[]} params.schemaData
* @param {import("@/package-shared/types").DSQL_DatabaseSchemaType[]} params.schemaData
* @returns {boolean}
*/ function setUserSchemaData({ userId , schemaData }) {
try {
const userSchemaFilePath = path.resolve(process.cwd(), `./jsonData/dbSchemas/users/user-${userId}/main.json`);
const userSchemaFilePath = path.resolve(process.cwd(), `${process.env.DSQL_USER_DB_SCHEMA_PATH}/user-${userId}/main.json`);
fs.writeFileSync(userSchemaFilePath, JSON.stringify(schemaData), "utf8");
return true;
} catch (/** @type {any} */ error) {
+173
View File
@@ -0,0 +1,173 @@
"use strict";
exports.id = 7838;
exports.ids = [7838];
exports.modules = {
/***/ 6251:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ "Z": () => (/* binding */ SuErrorLogsContent)
/* harmony export */ });
/* harmony import */ var react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(997);
/* harmony import */ var react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(6689);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _functions_frontend_fetchApi__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(6729);
/* harmony import */ var _general_LoadingBlock__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(5264);
// @ts-check
/**
* ==============================================================================
* Imports
* ==============================================================================
*/
/** ****************************************************************************** */ /** ****************************************************************************** */ /** ****************************************************************************** */ /** ****************************************************************************** */ /** ****************************************************************************** */ /** ****************************************************************************** */ /**
* ==============================================================================
* Main Component { Functional }
* ==============================================================================
* @param {Object} props - Server props
*/ function SuErrorLogsContent(props) {
/**
* Get Contexts
*
* @abstract { React.useContext }
*/ ////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
/**
* Javascript Variables
*
* @abstract Non hook variables and functions
*/ ////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
/**
* React Hooks
*
* @abstract { useState, useEffect, useRef, etc ... }
*/ /** @type {[ errorLog: string | null, setErrorLog: React.Dispatch<React.SetStateAction<string | null>> ]} */ // @ts-ignore
const [errorLog, setErrorLog] = react__WEBPACK_IMPORTED_MODULE_1___default().useState(null);
const [loading, setLoading] = react__WEBPACK_IMPORTED_MODULE_1___default().useState(false);
const [refresh, setRefresh] = react__WEBPACK_IMPORTED_MODULE_1___default().useState(0);
function fetchErrorLogs() {
(0,_functions_frontend_fetchApi__WEBPACK_IMPORTED_MODULE_3__/* ["default"] */ .Z)("/api/admin/grabErrorLogs").then((res)=>{
if (typeof res.log === "string" && !res.log?.match(/./)) {
setErrorLog("No Logs Yet");
return;
} else {
setErrorLog("");
}
setErrorLog(res.log.replace(/\n|\r|\n\r|\\n/gm, "<br/>"));
});
}
react__WEBPACK_IMPORTED_MODULE_1___default().useEffect(()=>{
fetchErrorLogs();
if (refresh === 0) {
setInterval(()=>{
fetchErrorLogs();
}, 10000);
}
}, [
refresh
]);
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
/**
* Function Return
*
* @abstract Main Function Return
*/ return /*#__PURE__*/ (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsxs)((react__WEBPACK_IMPORTED_MODULE_1___default().Fragment), {
children: [
/*#__PURE__*/ (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsxs)("div", {
className: "w-full justify-between",
children: [
/*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("h2", {
className: "text-xl m-0",
children: "Error Logs"
}),
/*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("div", {
children: /*#__PURE__*/ (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsxs)("button", {
onClick: (e)=>{
if (window.confirm("Clear Error Logs?")) {
setLoading(true);
(0,_functions_frontend_fetchApi__WEBPACK_IMPORTED_MODULE_3__/* ["default"] */ .Z)("/api/admin/clearErrorLogs", "post").then((res)=>{
console.log(res);
setRefresh((prev)=>prev + 1);
});
setTimeout(()=>{
setLoading(false);
}, 2000);
}
},
className: "outlined gray relative",
children: [
loading && /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx(_general_LoadingBlock__WEBPACK_IMPORTED_MODULE_2__/* ["default"] */ .Z, {
width: "20px"
}),
"Clear Error Log"
]
})
})
]
}),
/*#__PURE__*/ (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsxs)("section", {
className: "paper",
children: [
errorLog && /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("p", {
dangerouslySetInnerHTML: {
__html: errorLog ? errorLog : "No Log"
}
}),
!errorLog && /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx(_general_LoadingBlock__WEBPACK_IMPORTED_MODULE_2__/* ["default"] */ .Z, {
position: "relative",
width: "25px"
})
]
})
]
});
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
} /** ****************************************************************************** */ /** ****************************************************************************** */ /** ****************************************************************************** */ /** ****************************************************************************** */ /** ****************************************************************************** */ /** ****************************************************************************** */
/***/ }),
/***/ 5304:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
// @ts-check
const { scryptSync , createDecipheriv } = __webpack_require__(6113);
const { Buffer } = __webpack_require__(4300);
/**
* @param {string} encryptedString
* @returns {string | null}
*/ const decrypt = (encryptedString)=>{
const algorithm = "aes-192-cbc";
const password = process.env.DSQL_ENCRYPTION_PASSWORD || "";
const salt = process.env.DSQL_ENCRYPTION_SALT || "";
let key = scryptSync(password, salt, 24);
let iv = Buffer.alloc(16, 0);
// @ts-ignore
const decipher = createDecipheriv(algorithm, key, iv);
try {
let decrypted = decipher.update(encryptedString, "hex", "utf8");
decrypted += decipher.final("utf8");
return decrypted;
} catch (error) {
return null;
}
};
module.exports = decrypt;
/***/ })
};
;
+1 -1
View File
@@ -204,7 +204,7 @@ const addDbEntry = __webpack_require__(5338);
*
* @description Create new user folder and file
*/ if (!database || database?.match(/^datasquirel$/)) {
let newUserSchemaFolderPath = `./jsonData/dbSchemas/users/user-${newUser.insertId}`;
let newUserSchemaFolderPath = `${process.env.DSQL_USER_DB_SCHEMA_PATH}/user-${newUser.insertId}`;
let newUserMediaFolderPath = path.join(STATIC_ROOT, `images/user-images/user-${newUser.insertId}`);
fs.mkdirSync(newUserSchemaFolderPath);
fs.mkdirSync(newUserMediaFolderPath);
+2 -2
View File
@@ -18,10 +18,10 @@ const path = __webpack_require__(1017);
* ==============================================================================
* @param {Object} params
* @param {string | number} params.userId
* @returns {DSQL_DatabaseSchemaType[] | null}
* @returns {import("@/package-shared/types").DSQL_DatabaseSchemaType[] | null}
*/ function grabUserSchemaData({ userId }) {
try {
const userSchemaFilePath = path.resolve(process.cwd(), `./jsonData/dbSchemas/users/user-${userId}/main.json`);
const userSchemaFilePath = path.resolve(process.cwd(), `${process.env.DSQL_USER_DB_SCHEMA_PATH}/user-${userId}/main.json`);
const userSchemaData = JSON.parse(fs.readFileSync(userSchemaFilePath, "utf-8"));
return userSchemaData;
} catch (/** @type {any} */ error) {
+129
View File
@@ -0,0 +1,129 @@
"use strict";
exports.id = 8515;
exports.ids = [8515];
exports.modules = {
/***/ 8515:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ "Z": () => (/* binding */ ActiveCloneTableBanner)
/* harmony export */ });
/* harmony import */ var react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(997);
/* harmony import */ var react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(6689);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _mui_icons_material_MenuBookTwoTone__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(5557);
/* harmony import */ var _mui_icons_material_MenuBookTwoTone__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_mui_icons_material_MenuBookTwoTone__WEBPACK_IMPORTED_MODULE_2__);
// @ts-check
/**
* ==============================================================================
* Imports
* ==============================================================================
*/
/** ****************************************************************************** */ /** ****************************************************************************** */ /** ****************************************************************************** */ /** ****************************************************************************** */ /** ****************************************************************************** */ /** ****************************************************************************** */ /**
* ==============================================================================
* Main Component { Functional }
* ==============================================================================
* @param {Object} props
* @param {import("@/package-shared/types").DSQL_TableSchemaType} props.table
* @param {import("@/package-shared/types").DSQL_MYSQL_user_databases_Type} props.database
* @param {number} [props.activeDbClone]
* @param {import("@/package-shared/types").UserType} props.user
*/ function ActiveCloneTableBanner({ table , database , user , activeDbClone , }) {
/**
* Get Contexts
*
* @abstract { React.useContext }
*/ ////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
/**
* Javascript Variables
*
* @abstract Non hook variables and functions
*/ const cloneParentDb = table?.childTableDbFullName ? table.childTableDbFullName.replace(new RegExp(/datasquirel_user_\d+_/), "") : null;
const isCurrentDb = table.childTableDbFullName === database.db_full_name;
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
/**
* React Hooks
*
* @abstract { useState, useEffect, useRef, etc ... }
*/ ////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
/**
* Function Return
*
* @abstract Main Function Return
*/ if (!cloneParentDb) return /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx((react__WEBPACK_IMPORTED_MODULE_1___default().Fragment), {});
return /*#__PURE__*/ (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsxs)("span", {
className: "info small green gap-1" + (database?.active_clone ? " -mt-6" : ""),
style: {
fontWeight: "500"
},
children: [
"This Table is an active clone of",
" ",
/*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("a", {
href: `/admin/${user?.id}/databases/${cloneParentDb}/tables/${table.childTableName}`,
target: "_blank",
className: "button gray outlined small-text",
style: {
display: "inline-block",
fontSize: "12px",
padding: "3px 7px"
},
children: /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("b", {
children: table.childTableName
})
}),
" ",
"in",
" ",
isCurrentDb ? /*#__PURE__*/ (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsxs)("span", {
children: [
"this current database(",
/*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("b", {
children: database.db_name
}),
")."
]
}) : /*#__PURE__*/ (0,react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsxs)((react__WEBPACK_IMPORTED_MODULE_1___default().Fragment), {
children: [
/*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("a", {
href: `/admin/${user?.id}/databases/${cloneParentDb}`,
target: "_blank",
className: "button gray outlined small-text",
style: {
display: "inline-block",
fontSize: "12px",
padding: "3px 7px"
},
children: /*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("b", {
children: cloneParentDb
})
}),
/*#__PURE__*/ react_jsx_runtime__WEBPACK_IMPORTED_MODULE_0__.jsx("span", {
children: "database."
})
]
}),
" ",
database?.active_clone ? "" : "Only Foreign keys and Entries can be updated."
]
});
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
}
/***/ })
};
;
+1 -1
View File
@@ -2154,7 +2154,7 @@ const TableEntriesContext = /*#__PURE__*/ external_react_default().createContext
* Page/Site Data Data Fetching
*
* @description Fetch data on the server before returning
*/ /** @type {import("@/package-shared/types").DSQL_DatabaseSchemaType[]} */ const dbSchemaData = JSON.parse(fs.readFileSync(`./jsonData/dbSchemas/users/user-${dbUserId}/main.json`, "utf-8"));
*/ /** @type {import("@/package-shared/types").DSQL_DatabaseSchemaType[]} */ const dbSchemaData = JSON.parse(fs.readFileSync(`${process.env.DSQL_USER_DB_SCHEMA_PATH}/user-${dbUserId}/main.json`, "utf-8"));
const tables = dbSchemaData.filter((db)=>db.dbFullName === database[0].db_full_name)[0]?.tables;
const targetTable = tables.filter((table)=>table.tableName === query.single_table)[0];
const tableEntries = await varDatabaseDbHandler_default()({