This commit is contained in:
Benjamin Toby
2024-12-06 11:31:24 +01:00
parent 6df20790f4
commit 8ca2779741
153 changed files with 6621 additions and 3899 deletions
+5 -4
View File
@@ -10,8 +10,8 @@ require("dotenv").config({
});
const datasquirel = require("../index");
const createDbFromSchema = require("./engine/createDbFromSchema");
const colors = require("../console-colors");
const createDbFromSchema = require("../package-shared/shell/createDbFromSchema");
if (!fs.existsSync(path.resolve(process.cwd(), ".env"))) {
console.log(".env file not found");
@@ -26,8 +26,6 @@ const {
DSQL_KEY,
DSQL_REF_DB_NAME,
DSQL_FULL_SYNC,
DSQL_ENCRYPTION_KEY,
DSQL_ENCRYPTION_SALT,
} = process.env;
if (!DSQL_HOST?.match(/./)) {
@@ -123,7 +121,10 @@ async function run() {
);
// deepcode ignore reDOS: <please specify a reason of ignoring this>
await createDbFromSchema(schemaData);
await createDbFromSchema({
dbSchemaData: schemaData,
});
console.log(
` - ${colors.FgGreen}Success:${colors.Reset} Databases created Successfully!`
);
+1 -11
View File
@@ -18,17 +18,7 @@ const mysqlDumpPath = process.platform?.match(/win/i)
"'"
: "mysqldump";
const {
DSQL_HOST,
DSQL_USER,
DSQL_PASS,
DSQL_DB_NAME,
DSQL_KEY,
DSQL_REF_DB_NAME,
DSQL_FULL_SYNC,
DSQL_ENCRYPTION_KEY,
DSQL_ENCRYPTION_SALT,
} = process.env;
const { DSQL_USER, DSQL_PASS, DSQL_DB_NAME } = process.env;
const dbName = DSQL_DB_NAME || "";
const dumpFilePathArg = process.argv.indexOf("--file");
-4
View File
@@ -1,4 +0,0 @@
declare function _exports({ dbSchema }: {
dbSchema: import("../../package-shared/types").DSQL_DatabaseSchemaType | undefined;
}): Promise<any>;
export = _exports;
-88
View File
@@ -1,88 +0,0 @@
// @ts-check
/**
* ==============================================================================
* Imports
* ==============================================================================
*/
const fs = require("fs");
const path = require("path");
const { execSync } = require("child_process");
const updateApiSchemaFromLocalDb = require("../query/update-api-schema-from-local-db");
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/**
* Add `users` table to user database
* ==============================================================================
*
* @param {object} params - Single object passed
* @param {import("../../package-shared/types").DSQL_DatabaseSchemaType | undefined} params.dbSchema - Database Schema Object
*
* @returns {Promise<*>} new user auth object payload
*/
module.exports = async function addUsersTableToDb({ dbSchema }) {
/**
* Initialize
*
* @description Initialize
*/
const database = process.env.DSQL_DB_NAME || "";
/** @type {import("../../package-shared/types").DSQL_TableSchemaType} */
const userPreset = require("./data/presets/users.json");
try {
/**
* Fetch user
*
* @description Fetch user from db
*/
const userSchemaMainFilePath = path.resolve(
process.cwd(),
"dsql.schema.json"
);
let targetDatabase = dbSchema;
if (!targetDatabase) throw new Error("Target database not found!");
let existingTableIndex = targetDatabase.tables.findIndex(
(table, index) => {
if (table.tableName === "users") {
existingTableIndex = index;
return true;
}
}
);
if (existingTableIndex >= 0) {
targetDatabase.tables[existingTableIndex] = userPreset;
} else {
targetDatabase.tables.push(userPreset);
}
fs.writeFileSync(
`${userSchemaMainFilePath}`,
JSON.stringify(dbSchema, null, 4),
"utf8"
);
////////////////////////////////////////
await updateApiSchemaFromLocalDb();
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
} catch (/** @type {*} */ error) {
console.log(error.message);
}
};
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
-300
View File
@@ -1,300 +0,0 @@
// @ts-check
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
const path = require("path");
////////////////////////////////////////
const noDatabaseDbHandler = require("./utils/noDatabaseDbHandler");
const varDatabaseDbHandler = require("./utils/varDatabaseDbHandler");
const createTable = require("./utils/createTable");
const updateTable = require("./utils/updateTable");
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/**
* Create database from Schema
* ==============================================================================
* @description Create database from Schema. This function is called when the user
* runs the "dsql create" command. `NOTE`: there must be a "dsql.schema.json" file
* in the root of the project for this function to work
*
* @param {import("../../package-shared/types").DSQL_DatabaseSchemaType | undefined} dbSchema - An array of database schema objects
*/
async function createDbFromSchema(dbSchema) {
try {
/**
* Grab Schema
*
* @description Grab Schema
*/
if (!dbSchema || !Array.isArray(dbSchema) || !dbSchema[0]) {
return;
}
for (let i = 0; i < dbSchema.length; i++) {
/** @type {import("../../package-shared/types").DSQL_DatabaseSchemaType | undefined} */
const database = dbSchema[i];
if (!database) {
continue;
}
const { dbFullName, tables } = database;
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
/** @type {{ dbFullName: string }[] | null} */
const dbCheck = await noDatabaseDbHandler({
query: `SELECT SCHEMA_NAME AS dbFullName FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = '${dbFullName}'`,
});
if (dbCheck && dbCheck[0]?.dbFullName) {
// Database Exists
} else {
const newDatabase = await noDatabaseDbHandler({
query: `CREATE DATABASE IF NOT EXISTS \`${dbFullName}\` CHARACTER SET utf8mb4 COLLATE utf8mb4_bin`,
});
}
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
/**
* Select all tables
* @type {{ TABLE_NAME: string }[] | null}
* @description Select All tables in target database
*/
const allTables = await noDatabaseDbHandler({
query: `SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA='${dbFullName}'`,
});
let tableDropped;
if (!allTables) {
console.log("No Tables to Update");
continue;
}
for (let tb = 0; tb < allTables.length; tb++) {
const { TABLE_NAME } = allTables[tb];
/**
* @description Check if TABLE_NAME is part of the tables contained
* in the user schema JSON. If it's not, the table is either deleted
* or the table name has been recently changed
*/
if (
!tables.filter(
(_table) => _table.tableName === TABLE_NAME
)[0]
) {
const oldTableFilteredArray = tables.filter(
(_table) =>
_table.tableNameOld &&
_table.tableNameOld === TABLE_NAME
);
/**
* @description Check if this table has been recently renamed. Rename
* table id true. Drop table if false
*/
if (oldTableFilteredArray && oldTableFilteredArray[0]) {
console.log("Renaming Table");
await varDatabaseDbHandler({
queryString: `RENAME TABLE \`${oldTableFilteredArray[0].tableNameOld}\` TO \`${oldTableFilteredArray[0].tableName}\``,
database: dbFullName,
});
} else {
console.log(`Dropping Table from ${dbFullName}`);
// deepcode ignore reDOS: <NO user input>
await varDatabaseDbHandler({
queryString: `DROP TABLE \`${TABLE_NAME}\``,
database: dbFullName,
});
tableDropped = true;
}
}
}
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
/**
* @description Iterate through each table and perform table actions
*/
for (let t = 0; t < tables.length; t++) {
const table = tables[t];
if (tableDropped) continue;
const { tableName, fields, indexes } = table;
/**
* @description Check if table exists
*/
const tableCheck = await varDatabaseDbHandler({
queryString: `
SELECT EXISTS (
SELECT
TABLE_NAME
FROM
information_schema.TABLES
WHERE
TABLE_SCHEMA = ? AND
TABLE_NAME = ?
) AS tableExists`,
queryValuesArray: [dbFullName, table.tableName],
database: dbFullName,
});
////////////////////////////////////////
if (tableCheck && tableCheck[0]?.tableExists > 0) {
/**
* @description Update table if table exists
*/
const updateExistingTable = await updateTable({
dbFullName: dbFullName,
tableName: tableName,
tableInfoArray: fields,
dbSchema,
tableIndexes: indexes,
tableIndex: t,
});
if (table.childrenTables && table.childrenTables[0]) {
for (
let ch = 0;
ch < table.childrenTables.length;
ch++
) {
const childTable = table.childrenTables[ch];
const updateExistingChildTable = await updateTable({
dbFullName: childTable.dbNameFull,
tableName: childTable.tableName,
tableInfoArray: fields,
dbSchema,
tableIndexes: indexes,
clone: true,
});
// console.log(updateExistingChildTable);
}
}
////////////////////////////////////////
} else {
////////////////////////////////////////
/**
* @description Create new Table if table doesnt exist
*/
const createNewTable = await createTable({
tableName: tableName,
tableInfoArray: fields,
varDatabaseDbHandler,
dbFullName: dbFullName,
dbSchema,
});
if (indexes && indexes[0]) {
/**
* Handle DATASQUIREL Table Indexes
* ===================================================
* @description Iterate through each datasquirel schema
* table index(if available), and perform operations
*/
if (indexes && indexes[0]) {
for (let g = 0; g < indexes.length; g++) {
const {
indexType,
indexName,
indexTableFields,
alias,
} = indexes[g];
if (!alias?.match(/./)) continue;
/**
* @type {any[] | null}
* @description All indexes from MYSQL db
*/
const allExistingIndexes =
await varDatabaseDbHandler({
queryString: `SHOW INDEXES FROM \`${tableName}\``,
database: dbFullName,
});
/**
* @description Check for existing Index in MYSQL db
*/
try {
const existingKeyInDb = allExistingIndexes
? allExistingIndexes.filter(
(indexObject) =>
indexObject.Key_name === alias
)
: null;
if (!existingKeyInDb?.[0])
throw new Error(
"This Index Does not Exist"
);
} catch (error) {
/**
* @description Create new index if determined that it
* doesn't exist in MYSQL db
*/
await varDatabaseDbHandler({
queryString: `CREATE${
indexType?.match(/fullText/i)
? " FULLTEXT"
: ""
} INDEX \`${alias}\` ON ${tableName}(${indexTableFields
?.map((nm) => nm.value)
.map((nm) => `\`${nm}\``)
.join(
","
)}) COMMENT 'schema_index'`,
database: dbFullName,
});
}
}
}
}
}
////////////////////////////////////////
}
}
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
} catch (/** @type {*} */ error) {
console.log("Error in createDbFromSchema => ", error.message);
}
}
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
module.exports = createDbFromSchema;
-73
View File
@@ -1,73 +0,0 @@
[
{
"title": "VARCHAR",
"name": "VARCHAR",
"value": "0-255",
"argument": true,
"description": "Varchar is simply letters and numbers within the range 0 - 255",
"maxValue": 255
},
{
"title": "TINYINT",
"name": "TINYINT",
"value": "0-100",
"description": "TINYINT means Integers: 0 to 100",
"maxValue": 127
},
{
"title": "SMALLINT",
"name": "SMALLINT",
"value": "0-255",
"description": "SMALLINT means Integers: 0 to 240933",
"maxValue": 32767
},
{
"title": "MEDIUMINT",
"name": "MEDIUMINT",
"value": "0-255",
"description": "MEDIUMINT means Integers: 0 to 1245568545560",
"maxValue": 8388607
},
{
"title": "INT",
"name": "INT",
"value": "0-255",
"description": "INT means Integers: 0 to 12560",
"maxValue": 2147483647
},
{
"title": "BIGINT",
"name": "BIGINT",
"value": "0-255",
"description": "BIGINT means Integers: 0 to 1245569056767568545560",
"maxValue": 2e63
},
{
"title": "TINYTEXT",
"name": "TINYTEXT",
"value": "0-255",
"description": "Text with 255 max characters",
"maxValue": 127
},
{
"title": "TEXT",
"name": "TEXT",
"value": "0-100",
"description": "MEDIUMTEXT is just text with max length 16,777,215",
"maxValue": 127
},
{
"title": "MEDIUMTEXT",
"name": "MEDIUMTEXT",
"value": "0-255",
"description": "MEDIUMTEXT is just text with max length 16,777,215",
"maxValue": 127
},
{
"title": "LONGTEXT",
"name": "LONGTEXT",
"value": "0-255",
"description": "LONGTEXT is just text with max length 4,294,967,295",
"maxValue": 127
}
]
-39
View File
@@ -1,39 +0,0 @@
[
{
"fieldName": "id",
"dataType": "BIGINT",
"notNullValue": true,
"primaryKey": true,
"autoIncrement": true
},
{
"fieldName": "date_created",
"dataType": "VARCHAR(250)",
"notNullValue": true
},
{
"fieldName": "date_created_code",
"dataType": "BIGINT",
"notNullValue": true
},
{
"fieldName": "date_created_timestamp",
"dataType": "TIMESTAMP",
"defaultValueLiteral": "CURRENT_TIMESTAMP"
},
{
"fieldName": "date_updated",
"dataType": "VARCHAR(250)",
"notNullValue": true
},
{
"fieldName": "date_updated_code",
"dataType": "BIGINT",
"notNullValue": true
},
{
"fieldName": "date_updated_timestamp",
"dataType": "TIMESTAMP",
"defaultValueLiteral": "CURRENT_TIMESTAMP"
}
]
-17
View File
@@ -1,17 +0,0 @@
{
"fieldName": "string",
"dataType": "BIGINT",
"nullValue": true,
"primaryKey": true,
"autoIncrement": true,
"defaultValue": "CURRENT_TIMESTAMP",
"defaultValueLiteral": "CURRENT_TIMESTAMP",
"notNullValue": true,
"foreignKey": {
"foreignKeyName": "Name",
"destinationTableName": "Table Name",
"destinationTableColumnName": "Column Name",
"cascadeDelete": true,
"cascadeUpdate": true
}
}
-132
View File
@@ -1,132 +0,0 @@
{
"tableName": "users",
"tableFullName": "Users",
"fields": [
{
"fieldName": "id",
"dataType": "BIGINT",
"notNullValue": true,
"primaryKey": true,
"autoIncrement": true
},
{
"fieldName": "first_name",
"dataType": "VARCHAR(100)",
"notNullValue": true
},
{
"fieldName": "last_name",
"dataType": "VARCHAR(100)",
"notNullValue": true
},
{
"fieldName": "email",
"dataType": "VARCHAR(200)",
"notNullValue": true
},
{
"fieldName": "phone",
"dataType": "VARCHAR(50)"
},
{
"fieldName": "user_type",
"dataType": "VARCHAR(20)",
"defaultValue": "default"
},
{
"fieldName": "username",
"dataType": "VARCHAR(100)",
"nullValue": true
},
{
"fieldName": "password",
"dataType": "VARCHAR(250)",
"notNullValue": true
},
{
"fieldName": "image",
"dataType": "VARCHAR(250)",
"defaultValue": "/images/user_images/user-preset.png"
},
{
"fieldName": "image_thumbnail",
"dataType": "VARCHAR(250)",
"defaultValue": "/images/user_images/user-preset-thumbnail.png"
},
{
"fieldName": "address",
"dataType": "VARCHAR(255)"
},
{
"fieldName": "city",
"dataType": "VARCHAR(50)"
},
{
"fieldName": "state",
"dataType": "VARCHAR(50)"
},
{
"fieldName": "country",
"dataType": "VARCHAR(50)"
},
{
"fieldName": "zip_code",
"dataType": "VARCHAR(50)"
},
{
"fieldName": "social_login",
"dataType": "TINYINT",
"defaultValue": "0"
},
{
"fieldName": "social_platform",
"dataType": "VARCHAR(50)",
"nullValue": true
},
{
"fieldName": "social_id",
"dataType": "VARCHAR(250)",
"nullValue": true
},
{
"fieldName": "more_user_data",
"dataType": "BIGINT",
"defaultValue": "0"
},
{
"fieldName": "verification_status",
"dataType": "TINYINT",
"defaultValue": "0"
},
{
"fieldName": "date_created",
"dataType": "VARCHAR(250)",
"notNullValue": true
},
{
"fieldName": "date_created_code",
"dataType": "BIGINT",
"notNullValue": true
},
{
"fieldName": "date_created_timestamp",
"dataType": "TIMESTAMP",
"defaultValueLiteral": "CURRENT_TIMESTAMP"
},
{
"fieldName": "date_updated",
"dataType": "VARCHAR(250)",
"notNullValue": true
},
{
"fieldName": "date_updated_code",
"dataType": "BIGINT",
"notNullValue": true
},
{
"fieldName": "date_updated_timestamp",
"dataType": "TIMESTAMP",
"defaultValueLiteral": "CURRENT_TIMESTAMP"
}
]
}
-12
View File
@@ -1,12 +0,0 @@
export = camelJoinedtoCamelSpace;
/**
* Convert Camel Joined Text to Camel Spaced Text
* ==============================================================================
* @description this function takes a camel cased text without spaces, and returns
* a camel-case-spaced text
*
* @param {string} text - text string without spaces
*
* @returns {string | null}
*/
declare function camelJoinedtoCamelSpace(text: string): string | null;
@@ -1,54 +0,0 @@
// @ts-check
/**
* Convert Camel Joined Text to Camel Spaced Text
* ==============================================================================
* @description this function takes a camel cased text without spaces, and returns
* a camel-case-spaced text
*
* @param {string} text - text string without spaces
*
* @returns {string | null}
*/
function camelJoinedtoCamelSpace(text) {
if (!text?.match(/./)) {
return "";
}
if (text?.match(/ /)) {
return text;
}
if (text) {
let textArray = text.split("");
let capIndexes = [];
for (let i = 0; i < textArray.length; i++) {
const char = textArray[i];
if (i === 0) continue;
if (char.match(/[A-Z]/)) {
capIndexes.push(i);
}
}
let textChunks = [`${textArray[0].toUpperCase()}${text.substring(1, capIndexes[0])}`];
for (let j = 0; j < capIndexes.length; j++) {
const capIndex = capIndexes[j];
if (capIndex === 0) continue;
const startIndex = capIndex + 1;
const endIndex = capIndexes[j + 1];
textChunks.push(`${textArray[capIndex].toUpperCase()}${text.substring(startIndex, endIndex)}`);
}
return textChunks.join(" ");
} else {
return null;
}
}
module.exports = camelJoinedtoCamelSpace;
-144
View File
@@ -1,144 +0,0 @@
// @ts-check
const generateColumnDescription = require("./generateColumnDescription");
const supplementTable = require("./supplementTable");
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/**
*
* @param {object} param0
* @param {string} param0.dbFullName
* @param {string} param0.tableName
* @param {any[]} param0.tableInfoArray
* @param {(params: import("./varDatabaseDbHandler").VarDbHandlerParam)=>any} param0.varDatabaseDbHandler
* @param {import("../../../package-shared/types").DSQL_DatabaseSchemaType} [param0.dbSchema]
* @returns
*/
module.exports = async function createTable({
dbFullName,
tableName,
tableInfoArray,
varDatabaseDbHandler,
dbSchema,
}) {
/**
* Format tableInfoArray
*
* @description Format tableInfoArray
*/
const finalTable = supplementTable({ tableInfoArray: tableInfoArray });
/**
* Grab Schema
*
* @description Grab Schema
*/
const createTableQueryArray = [];
createTableQueryArray.push(`CREATE TABLE IF NOT EXISTS \`${tableName}\` (`);
////////////////////////////////////////
let primaryKeySet = false;
let foreignKeys = [];
////////////////////////////////////////
for (let i = 0; i < finalTable.length; i++) {
const column = finalTable[i];
const { fieldName, foreignKey } = column;
if (foreignKey) {
foreignKeys.push({
fieldName: fieldName,
...foreignKey,
});
}
let { fieldEntryText, newPrimaryKeySet } = generateColumnDescription({
columnData: column,
primaryKeySet: primaryKeySet,
});
primaryKeySet = newPrimaryKeySet;
////////////////////////////////////////
if (fieldName?.match(/updated_timestamp/i)) {
fieldEntryText += " ON UPDATE CURRENT_TIMESTAMP";
}
////////////////////////////////////////
const comma = (() => {
if (foreignKeys[0]) return ",";
if (i === finalTable.length - 1) return "";
return ",";
})();
createTableQueryArray.push(" " + fieldEntryText + comma);
////////////////////////////////////////
}
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
if (foreignKeys[0]) {
foreignKeys.forEach((foreighKey, index, array) => {
const {
fieldName,
destinationTableName,
destinationTableColumnName,
cascadeDelete,
cascadeUpdate,
foreignKeyName,
} = foreighKey;
const comma = (() => {
if (index === foreignKeys.length - 1) return "";
return ",";
})();
createTableQueryArray.push(
` CONSTRAINT \`${foreignKeyName}\` FOREIGN KEY (\`${fieldName}\`) REFERENCES \`${destinationTableName}\`(${destinationTableColumnName})${
cascadeDelete ? " ON DELETE CASCADE" : ""
}${cascadeUpdate ? " ON UPDATE CASCADE" : ""}${comma}`
);
});
}
////////////////////////////////////////
createTableQueryArray.push(
`) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;`
);
const createTableQuery = createTableQueryArray.join("\n");
////////////////////////////////////////
const newTable = await varDatabaseDbHandler({
queryString: createTableQuery,
database: dbFullName,
});
return newTable;
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
};
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
-8
View File
@@ -1,8 +0,0 @@
declare function _exports({ query, values, database, dbSchema, tableName, }: {
query: string;
values?: (string | number)[];
dbSchema?: import("../../../package-shared/types").DSQL_DatabaseSchemaType;
database?: string;
tableName?: string;
}): Promise<any>;
export = _exports;
-173
View File
@@ -1,173 +0,0 @@
/** # MODULE TRACE
======================================================================
* Detected 8 files that call this module. The files are listed below:
======================================================================
* `require` Statement Found in [noDatabaseDbHandler.js](d:\GitHub\dsql\engine\engine\utils\noDatabaseDbHandler.js)
* `require` Statement Found in [varDatabaseDbHandler.js](d:\GitHub\dsql\engine\engine\utils\varDatabaseDbHandler.js)
* `require` Statement Found in [addDbEntry.js](d:\GitHub\dsql\engine\query\utils\addDbEntry.js)
* `require` Statement Found in [deleteDbEntry.js](d:\GitHub\dsql\engine\query\utils\deleteDbEntry.js)
* `require` Statement Found in [runQuery.js](d:\GitHub\dsql\engine\query\utils\runQuery.js)
* `require` Statement Found in [updateDbEntry.js](d:\GitHub\dsql\engine\query\utils\updateDbEntry.js)
* `require` Statement Found in [githubLogin.js](d:\GitHub\dsql\engine\user\social\utils\githubLogin.js)
* `require` Statement Found in [googleLogin.js](d:\GitHub\dsql\engine\user\social\utils\googleLogin.js)
==== MODULE TRACE END ==== */
// @ts-check
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
const fs = require("fs");
const mysql = require("mysql");
const path = require("path");
const grabDbSSL = require("../../../package-shared/utils/backend/grabDbSSL");
const connection = mysql.createConnection({
host: process.env.DSQL_HOST,
user: process.env.DSQL_USER,
database: process.env.DSQL_DB_NAME,
password: process.env.DSQL_PASS,
charset: "utf8mb4",
port: process.env.DSQL_PORT?.match(/.../)
? parseInt(process.env.DSQL_PORT)
: undefined,
timeout: 5000,
ssl: grabDbSSL(),
});
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
/**
* Main DB Handler Function
* ==============================================================================
* @async
* @param {object} params - Single Param object containing params
* @param {string} params.query - Query String
* @param {(string | number)[]} [params.values] - Values
* @param {import("../../../package-shared/types").DSQL_DatabaseSchemaType} [params.dbSchema] - Database Schema
* @param {string} [params.database] - Target Database
* @param {string} [params.tableName] - Target Table Name
*
* @returns {Promise<*>}
*/
module.exports = async function dbHandler({
query,
values,
database,
dbSchema,
tableName,
}) {
/**
* Declare variables
*
* @description Declare "results" variable
*/
let changeDbError;
if (database) {
connection.changeUser({ database: database }, (error) => {
if (error) {
console.log(
"DB handler error in switching database:",
error.message
);
changeDbError = error.message;
}
});
}
if (changeDbError) {
return { error: changeDbError };
}
/**
* Declare variables
*
* @description Declare "results" variable
*/
let results;
/**
* Fetch from db
*
* @description Fetch data from db if no cache
*/
try {
results = await new Promise((resolve, reject) => {
if (values?.[0]) {
connection.query(query, values, (error, results, fields) => {
if (error) {
console.log(
"DB handler error with values array:",
error.message
);
console.log("SQL:", error.sql);
console.log("State:", error.sqlState, error.sqlMessage);
resolve({
error: error.message,
});
} else {
resolve(JSON.parse(JSON.stringify(results)));
}
// setTimeout(() => {
// endConnection(connection);
// }, 500);
});
} else {
connection.query(query, (error, results, fields) => {
if (error) {
console.log("DB handler error:", error.message);
console.log("SQL:", error.sql);
console.log("State:", error.sqlState, error.sqlMessage);
resolve({
error: error.message,
});
} else {
resolve(JSON.parse(JSON.stringify(results)));
}
// setTimeout(() => {
// endConnection(connection);
// }, 500);
});
}
});
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
} catch (/** @type {*} */ error) {
console.log("DB handler error:", error.message);
results = null;
}
/**
* Return results
*
* @description Return results add to cache if "req" param is passed
*/
// if (results && dbSchema && tableName) {
// const tableSchema = dbSchema.tables.find((table) => table.tableName === tableName);
// const parsedResults = parseDbResults({
// unparsedResults: results,
// tableSchema: tableSchema,
// });
// return parsedResults;
// } else
if (results) {
return results;
} else {
console.log("DSQL DB handler no results received for Query =>", query);
return null;
}
};
-8
View File
@@ -1,8 +0,0 @@
export = defaultFieldsRegexp;
/**
* Regular expression to match default fields
*
* @description Regular expression to match default fields
* @type {RegExp}
*/
declare const defaultFieldsRegexp: RegExp;
@@ -1,13 +0,0 @@
/**
* Regular expression to match default fields
*
* @description Regular expression to match default fields
* @type {RegExp}
*/
const defaultFieldsRegexp = /^id$|^date_created$|^date_created_code$|^date_created_timestamp$|^date_updated$|^date_updated_code$|^date_updated_timestamp$/;
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
module.exports = defaultFieldsRegexp;
-16
View File
@@ -1,16 +0,0 @@
// @ts-check
const mysql = require("mysql");
/**
* @param {mysql.Connection} connection - the active MYSQL connection
*/
function endConnection(connection) {
if (connection.state !== "disconnected") {
connection.end((err) => {
console.log(err?.message);
});
}
}
module.exports = endConnection;
@@ -1,80 +0,0 @@
// @ts-check
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/**
* Generate SQL text for Field
* ==============================================================================
* @param {object} params - Single object params
* @param {import("../../../package-shared/types").DSQL_FieldSchemaType} params.columnData - Field object
* @param {boolean} [params.primaryKeySet] - Table Name(slug)
*
* @returns {{fieldEntryText: string, newPrimaryKeySet: boolean}}
*/
module.exports = function generateColumnDescription({
columnData,
primaryKeySet,
}) {
/**
* Format tableInfoArray
*
* @description Format tableInfoArray
*/
const {
fieldName,
dataType,
nullValue,
primaryKey,
autoIncrement,
defaultValue,
defaultValueLiteral,
notNullValue,
} = columnData;
let fieldEntryText = "";
fieldEntryText += `\`${fieldName}\` ${dataType}`;
////////////////////////////////////////
if (nullValue) {
fieldEntryText += " DEFAULT NULL";
} else if (defaultValueLiteral) {
fieldEntryText += ` DEFAULT ${defaultValueLiteral}`;
} else if (defaultValue) {
fieldEntryText += ` DEFAULT '${defaultValue}'`;
} else if (notNullValue) {
fieldEntryText += ` NOT NULL`;
}
////////////////////////////////////////
if (primaryKey && !primaryKeySet) {
fieldEntryText += " PRIMARY KEY";
primaryKeySet = true;
}
////////////////////////////////////////
if (autoIncrement) {
fieldEntryText += " AUTO_INCREMENT";
primaryKeySet = true;
}
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
return { fieldEntryText, newPrimaryKeySet: primaryKeySet || false };
};
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
@@ -1,92 +0,0 @@
// @ts-check
const fs = require("fs");
const mysql = require("mysql");
const path = require("path");
const grabDbSSL = require("../../../package-shared/utils/backend/grabDbSSL");
const connection = mysql.createConnection({
host: process.env.DSQL_HOST,
user: process.env.DSQL_USER,
password: process.env.DSQL_PASS,
charset: "utf8mb4",
port: process.env.DSQL_PORT?.match(/.../)
? parseInt(process.env.DSQL_PORT)
: undefined,
timeout: 5000,
ssl: grabDbSSL(),
});
/**
* Create database from Schema Function
* ==============================================================================
* @param {object} params - Single Param object containing params
* @param {string} params.query - Query String
* @param {string[]} [params.values] - Values
*
* @returns {Promise<any[] | null>}
*/
module.exports = async function noDatabaseDbHandler({ query, values }) {
/**
* Declare variables
*
* @description Declare "results" variable
*/
let results;
/**
* Fetch from db
*
* @description Fetch data from db if no cache
*/
try {
/** ********************* Run Query */
results = await new Promise((resolve, reject) => {
if (values) {
connection.query(query, values, (error, results, fields) => {
if (error) {
console.log("NO-DB handler error:", error.message);
resolve({
error: error.message,
});
} else {
resolve(JSON.parse(JSON.stringify(results)));
}
// setTimeout(() => {
// endConnection(connection);
// }, 500);
});
} else {
connection.query(query, (error, results, fields) => {
if (error) {
console.log("NO-DB handler error:", error.message);
resolve({
error: error.message,
});
} else {
resolve(JSON.parse(JSON.stringify(results)));
}
// setTimeout(() => {
// endConnection(connection);
// }, 500);
});
}
});
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
} catch (/** @type {*} */ error) {
console.log("ERROR in noDatabaseDbHandler =>", error.message);
}
/**
* Return results
*
* @description Return results add to cache if "req" param is passed
*/
if (results) {
return results;
} else {
return null;
}
};
-5
View File
@@ -1,5 +0,0 @@
declare function _exports({ unparsedResults, tableSchema, }: {
unparsedResults: any[];
tableSchema?: import("../../../package-shared/types").DSQL_TableSchemaType;
}): Promise<object[] | null>;
export = _exports;
-83
View File
@@ -1,83 +0,0 @@
// @ts-check
const decrypt = require("../../../functions/decrypt");
// @ts-ignore
const defaultFieldsRegexp = require("./defaultFieldsRegexp");
/**
* Parse Database results
* ==============================================================================
* @description this function takes a database results array gotten from a DB handler
* function, decrypts encrypted fields, and returns an updated array with no encrypted
* fields
*
* @param {object} params - Single object params
* @param {*[]} params.unparsedResults - Array of data objects containing Fields(keys)
* and corresponding values of the fields(values)
* @param {import("../../../package-shared/types").DSQL_TableSchemaType} [params.tableSchema] - Table schema
* @returns {Promise<object[]|null>}
*/
module.exports = async function parseDbResults({
unparsedResults,
tableSchema,
}) {
/**
* Declare variables
*
* @description Declare "results" variable
* @type {*[]}
*/
let parsedResults = [];
const encryptionKey = process.env.DSQL_ENCRYPTION_KEY || "";
const encryptionSalt = process.env.DSQL_ENCRYPTION_SALT || "";
try {
/**
* Declare variables
*
* @description Declare "results" variable
*/
for (let pr = 0; pr < unparsedResults.length; pr++) {
let result = unparsedResults[pr];
let resultFieldNames = Object.keys(result);
for (let i = 0; i < resultFieldNames.length; i++) {
const resultFieldName = resultFieldNames[i];
let resultFieldSchema = tableSchema?.fields[i];
if (resultFieldName?.match(defaultFieldsRegexp)) {
continue;
}
let value = result[resultFieldName];
if (typeof value !== "number" && !value) {
// parsedResults.push(result);
continue;
}
if (resultFieldSchema?.encrypted && value?.match(/./)) {
result[resultFieldName] = decrypt({
encryptedString: value,
encryptionKey,
encryptionSalt,
});
}
}
parsedResults.push(result);
}
/**
* Declare variables
*
* @description Declare "results" variable
*/
return parsedResults;
} catch (/** @type {*} */ error) {
console.log("ERROR in parseDbResults Function =>", error.message);
return unparsedResults;
}
};
-23
View File
@@ -1,23 +0,0 @@
// @ts-check
/**
*
* @param {string} text
* @returns
*/
module.exports = function slugToCamelTitle(text) {
if (text) {
let addArray = text.split("-").filter((item) => item !== "");
let camelArray = addArray.map((item) => {
return (
item.substr(0, 1).toUpperCase() + item.substr(1).toLowerCase()
);
});
let parsedAddress = camelArray.join(" ");
return parsedAddress;
} else {
return null;
}
};
-58
View File
@@ -1,58 +0,0 @@
// @ts-check
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/**
*
* @param {object} param0
* @param {import("../../../package-shared/types").DSQL_FieldSchemaType[]} param0.tableInfoArray
* @returns
*/
module.exports = function supplementTable({ tableInfoArray }) {
/**
* Format tableInfoArray
*
* @description Format tableInfoArray
*/
let finalTableArray = tableInfoArray;
const defaultFields = require("../data/defaultFields.json");
////////////////////////////////////////
let primaryKeyExists = finalTableArray.filter(
(_field) => _field.primaryKey
);
////////////////////////////////////////
defaultFields.forEach((field) => {
let fieldExists = finalTableArray.filter(
(_field) => _field.fieldName === field.fieldName
);
if (fieldExists && fieldExists[0]) {
return;
} else if (field.fieldName === "id" && !primaryKeyExists[0]) {
finalTableArray.unshift(field);
} else {
finalTableArray.push(field);
}
});
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
return finalTableArray;
};
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
File diff suppressed because it is too large Load Diff
-23
View File
@@ -1,23 +0,0 @@
declare namespace _exports {
export { VarDbHandlerParam };
}
declare function _exports({ queryString, queryValuesArray, database, tableSchema, }: VarDbHandlerParam): Promise<any>;
export = _exports;
type VarDbHandlerParam = {
/**
* - SQL string
*/
queryString: string;
/**
* - Values Array
*/
queryValuesArray?: string[];
/**
* - Database name
*/
database: string;
/**
* - Table schema
*/
tableSchema?: import("../../../package-shared/types").DSQL_TableSchemaType;
};
-129
View File
@@ -1,129 +0,0 @@
/** # MODULE TRACE
======================================================================
* Detected 9 files that call this module. The files are listed below:
======================================================================
* `require` Statement Found in [createDbFromSchema.js](d:\GitHub\dsql\engine\engine\createDbFromSchema.js)
* `require` Statement Found in [updateTable.js](d:\GitHub\dsql\engine\engine\utils\updateTable.js)
* `require` Statement Found in [runQuery.js](d:\GitHub\dsql\engine\query\utils\runQuery.js)
* `require` Statement Found in [add-user.js](d:\GitHub\dsql\engine\user\add-user.js)
* `require` Statement Found in [get-user.js](d:\GitHub\dsql\engine\user\get-user.js)
* `require` Statement Found in [login-user.js](d:\GitHub\dsql\engine\user\login-user.js)
* `require` Statement Found in [reauth-user.js](d:\GitHub\dsql\engine\user\reauth-user.js)
* `require` Statement Found in [handleSocialDb.js](d:\GitHub\dsql\engine\user\social\utils\handleSocialDb.js)
* `require` Statement Found in [update-user.js](d:\GitHub\dsql\engine\user\update-user.js)
==== MODULE TRACE END ==== */
// @ts-check
const fs = require("fs");
const parseDbResults = require("./parseDbResults");
const dbHandler = require("./dbHandler");
/**
* @typedef {object} VarDbHandlerParam
* @property {string} queryString - SQL string
* @property {string[]} [queryValuesArray] - Values Array
* @property {string} database - Database name
* @property {import("../../../package-shared/types").DSQL_TableSchemaType} [tableSchema] - Table schema
*/
/**
* DB handler for specific database
* ==============================================================================
* @async
* @param {VarDbHandlerParam} params
* @returns {Promise<any>}
*/
module.exports = async function varDatabaseDbHandler({
queryString,
queryValuesArray,
database,
tableSchema,
}) {
/**
* Create Connection
*
* @description Create Connection
*/
const encryptionKey = process.env.DSQL_ENCRYPTION_KEY || "";
const encryptionSalt = process.env.DSQL_ENCRYPTION_SALT || "";
/**
* Declare variables
*
* @description Declare "results" variable
* @type {*}
*/
let results;
/**
* Fetch from db
*
* @description Fetch data from db if no cache
*/
try {
if (
queryString &&
Array.isArray(queryValuesArray) &&
queryValuesArray[0]
) {
results = await dbHandler({
query: queryString,
values: queryValuesArray,
database: database,
});
} else if (queryString && !Array.isArray(queryValuesArray)) {
results = await dbHandler({
query: queryString,
database: database,
});
}
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
} catch (error) {
console.log(
"\x1b[31mvarDatabaseDbHandler ERROR\x1b[0m =>",
database,
error
);
}
/**
* Return results
*
* @description Return results add to cache if "req" param is passed
*/
if (results && tableSchema) {
try {
const unparsedResults = results;
// deepcode ignore reDOS: <please specify a reason of ignoring this>
const parsedResults = await parseDbResults({
unparsedResults: unparsedResults,
tableSchema: tableSchema,
});
return parsedResults;
} catch (error) {
console.log(
"\x1b[31mvarDatabaseDbHandler ERROR\x1b[0m =>",
database,
error
);
return null;
}
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
} else if (results) {
return results;
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
} else {
return null;
}
};
-64
View File
@@ -1,64 +0,0 @@
export = localGet;
/**
* @typedef {Object} LocalGetReturn
* @property {boolean} success - Did the function run successfully?
* @property {*} [payload] - GET request results
* @property {string} [msg] - Message
* @property {string} [error] - Error Message
*/
/**
* @typedef {Object} LocalQueryObject
* @property {string} query - Table Name
* @property {string} [tableName] - Table Name
* @property {string[]} [queryValues] - GET request results
*/
/**
* Make a get request to Datasquirel API
* ==============================================================================
* @async
*
* @param {Object} params - Single object passed
* @param {LocalQueryObject} params.options - SQL Query
* @param {import("../../package-shared/types").DSQL_DatabaseSchemaType | undefined} [params.dbSchema] - Name of the table to query
*
* @returns { Promise<LocalGetReturn> } - Return Object
*/
declare function localGet({ options, dbSchema }: {
options: LocalQueryObject;
dbSchema?: import("../../package-shared/types").DSQL_DatabaseSchemaType | undefined;
}): Promise<LocalGetReturn>;
declare namespace localGet {
export { LocalGetReturn, LocalQueryObject };
}
type LocalGetReturn = {
/**
* - Did the function run successfully?
*/
success: boolean;
/**
* - GET request results
*/
payload?: any;
/**
* - Message
*/
msg?: string;
/**
* - Error Message
*/
error?: string;
};
type LocalQueryObject = {
/**
* - Table Name
*/
query: string;
/**
* - Table Name
*/
tableName?: string;
/**
* - GET request results
*/
queryValues?: string[];
};
-94
View File
@@ -1,94 +0,0 @@
/** # MODULE TRACE
======================================================================
* No imports found for this Module
==== MODULE TRACE END ==== */
const runQuery = require("../../package-shared/functions/backend/db/runQuery");
// @ts-check
/**
* @typedef {Object} LocalGetReturn
* @property {boolean} success - Did the function run successfully?
* @property {*} [payload] - GET request results
* @property {string} [msg] - Message
* @property {string} [error] - Error Message
*/
/**
* @typedef {Object} LocalQueryObject
* @property {string} query - Table Name
* @property {string} [tableName] - Table Name
* @property {string[]} [queryValues] - GET request results
*/
/**
* Make a get request to Datasquirel API
* ==============================================================================
* @async
*
* @param {Object} params - Single object passed
* @param {LocalQueryObject} params.options - SQL Query
* @param {import("../../package-shared/types").DSQL_DatabaseSchemaType | undefined} [params.dbSchema] - Name of the table to query
*
* @returns { Promise<LocalGetReturn> } - Return Object
*/
async function localGet({ options, dbSchema }) {
try {
const { query, queryValues } = options;
/** @type {string | undefined | any } */
const tableName = options?.tableName ? options.tableName : undefined;
const dbFullName = process.env.DSQL_DB_NAME || "";
/**
* Create new user folder and file
*
* @description Create new user folder and file
*/
let results;
try {
let { result, error } = await runQuery({
dbFullName: dbFullName,
query: query,
queryValuesArray: queryValues,
dbSchema,
tableName,
local: true,
readOnly: true,
});
if (error) throw error;
if (!result)
throw new Error("No Result received for query => " + query);
if (result?.error) throw new Error(result.error);
results = result;
return { success: true, payload: results };
////////////////////////////////////////
} catch (/** @type {*} */ error) {
////////////////////////////////////////
console.log("Error in local get Request =>", error.message);
return {
success: false,
payload: null,
error: error.message,
};
}
////////////////////////////////////////
} catch (/** @type {*} */ error) {
////////////////////////////////////////
console.log("Error in local get Request =>", error.message);
return { success: false, msg: "Something went wrong!" };
////////////////////////////////////////
}
}
module.exports = localGet;
-16
View File
@@ -1,16 +0,0 @@
export = localPost;
/**
* Make a get request to Datasquirel API
* ==============================================================================
* @async
*
* @param {Object} params - Single object passed
* @param {import("../../package-shared/types").LocalPostQueryObject} params.options
* @param {import("../../package-shared/types").DSQL_DatabaseSchemaType | undefined} [params.dbSchema]
*
* @returns { Promise<import("../../package-shared/types").LocalPostReturn> }
*/
declare function localPost({ options, dbSchema }: {
options: import("../../package-shared/types").LocalPostQueryObject;
dbSchema?: import("../../package-shared/types").DSQL_DatabaseSchemaType | undefined;
}): Promise<import("../../package-shared/types").LocalPostReturn>;
-62
View File
@@ -1,62 +0,0 @@
// @ts-check
const runQuery = require("../../package-shared/functions/backend/db/runQuery");
/**
* Make a get request to Datasquirel API
* ==============================================================================
* @async
*
* @param {Object} params - Single object passed
* @param {import("../../package-shared/types").LocalPostQueryObject} params.options
* @param {import("../../package-shared/types").DSQL_DatabaseSchemaType | undefined} [params.dbSchema]
*
* @returns { Promise<import("../../package-shared/types").LocalPostReturn> }
*/
async function localPost({ options, dbSchema }) {
try {
/**
* Grab Body
*/
const { query, tableName, queryValues } = options;
const dbFullName = process.env.DSQL_DB_NAME || "";
/**
* Create new user folder and file
*
* @description Create new user folder and file
*/
try {
let { result, error } = await runQuery({
dbFullName: dbFullName,
query: query,
dbSchema: dbSchema,
queryValuesArray: queryValues,
tableName,
local: true,
});
if (error) throw error;
return {
success: true,
payload: result,
error: error,
};
} catch (/** @type {*} */ error) {
return {
success: false,
error: error.message,
};
}
} catch (/** @type {*} */ error) {
console.log("Error in local post Request =>", error.message);
return {
success: false,
msg: "Something went wrong!",
};
}
}
module.exports = localPost;
-38
View File
@@ -1,38 +0,0 @@
export = updateApiSchemaFromLocalDb;
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/**
* @typedef {Object} PostReturn
* @property {boolean} success - Did the function run successfully?
* @property {*} [payload] - The Y Coordinate
* @property {string} [error] - The Y Coordinate
*/
/**
* # Update API Schema From Local DB
*
* @async
*
* @returns { Promise<PostReturn> } - Return Object
*/
declare function updateApiSchemaFromLocalDb(): Promise<PostReturn>;
declare namespace updateApiSchemaFromLocalDb {
export { PostReturn };
}
type PostReturn = {
/**
* - Did the function run successfully?
*/
success: boolean;
/**
* - The Y Coordinate
*/
payload?: any;
/**
* - The Y Coordinate
*/
error?: string;
};
@@ -1,149 +0,0 @@
// @ts-check
/**
* Imports
*/
const https = require("https");
const http = require("http");
const path = require("path");
const fs = require("fs");
const grabHostNames = require("../../package-shared/utils/grab-host-names");
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/**
* @typedef {Object} PostReturn
* @property {boolean} success - Did the function run successfully?
* @property {*} [payload] - The Y Coordinate
* @property {string} [error] - The Y Coordinate
*/
/**
* # Update API Schema From Local DB
*
* @async
*
* @returns { Promise<PostReturn> } - Return Object
*/
async function updateApiSchemaFromLocalDb() {
try {
/**
* Initialize
*/
const dbSchemaPath = path.resolve(process.cwd(), "dsql.schema.json");
const key = process.env.DSQL_KEY || "";
const dbSchema = JSON.parse(fs.readFileSync(dbSchemaPath, "utf8"));
const { host, port, scheme, user_id } = grabHostNames();
/**
* Make https request
*
* @description make a request to datasquirel.com
*/
const httpResponse = await new Promise((resolve, reject) => {
const reqPayloadString = JSON.stringify({
schema: dbSchema,
}).replace(/\n|\r|\n\r/gm, "");
try {
JSON.parse(reqPayloadString);
} catch (error) {
console.log(error);
console.log(reqPayloadString);
return {
success: false,
payload: null,
error: "Query object is invalid. Please Check query data values",
};
}
const reqPayload = reqPayloadString;
const httpsRequest = scheme.request(
{
method: "POST",
headers: {
"Content-Type": "application/json",
"Content-Length": Buffer.from(reqPayload).length,
Authorization:
key ||
process.env.DSQL_FULL_ACCESS_API_KEY ||
process.env.DSQL_API_KEY,
},
port,
hostname: host,
path: `/api/query/${user_id}/update-schema-from-single-database`,
},
/**
* Callback Function
*
* @description https request callback
*/
(response) => {
var str = "";
response.on("data", function (chunk) {
str += chunk;
});
response.on("end", function () {
try {
resolve(JSON.parse(str));
} catch (error) {
console.log(error);
console.log("Fetched Payload =>", str);
resolve({
success: false,
payload: null,
error: error,
});
}
});
response.on("error", (err) => {
resolve({
success: false,
payload: null,
error: err.message,
});
});
}
);
httpsRequest.write(reqPayload);
httpsRequest.on("error", (error) => {
console.log("HTTPS request ERROR =>", error);
});
httpsRequest.end();
});
/** ********************************************** */
/** ********************************************** */
/** ********************************************** */
return httpResponse;
} catch (/** @type {*} */ error) {
return {
success: false,
payload: null,
error: error.message,
};
}
}
/** ********************************************** */
/** ********************************************** */
/** ********************************************** */
module.exports = updateApiSchemaFromLocalDb;
-20
View File
@@ -1,20 +0,0 @@
export = localAddUser;
/**
* Make a get request to Datasquirel API
* ==============================================================================
* @async
*
* @param {Object} params - Single object passed
* @param {import("../../package-shared/types").UserDataPayload} params.payload - SQL Query
* @param {import("../../package-shared/types").DSQL_DatabaseSchemaType | undefined} params.dbSchema - Name of the table to query
* @param {string} [params.encryptionKey]
* @param {string} [params.encryptionSalt]
*
* @returns { Promise<import("../../package-shared/types").AddUserFunctionReturn> } - Return Object
*/
declare function localAddUser({ payload, dbSchema, encryptionKey, encryptionSalt, }: {
payload: import("../../package-shared/types").UserDataPayload;
dbSchema: import("../../package-shared/types").DSQL_DatabaseSchemaType | undefined;
encryptionKey?: string;
encryptionSalt?: string;
}): Promise<import("../../package-shared/types").AddUserFunctionReturn>;
-169
View File
@@ -1,169 +0,0 @@
// @ts-check
const hashPassword = require("../../functions/hashPassword");
const addDbEntry = require("../../package-shared/functions/backend/db/addDbEntry");
const addUsersTableToDb = require("../engine/addUsersTableToDb");
const varDatabaseDbHandler = require("../engine/utils/varDatabaseDbHandler");
/**
* Make a get request to Datasquirel API
* ==============================================================================
* @async
*
* @param {Object} params - Single object passed
* @param {import("../../package-shared/types").UserDataPayload} params.payload - SQL Query
* @param {import("../../package-shared/types").DSQL_DatabaseSchemaType | undefined} params.dbSchema - Name of the table to query
* @param {string} [params.encryptionKey]
* @param {string} [params.encryptionSalt]
*
* @returns { Promise<import("../../package-shared/types").AddUserFunctionReturn> } - Return Object
*/
async function localAddUser({
payload,
dbSchema,
encryptionKey,
encryptionSalt,
}) {
try {
/**
* Initialize Variables
*/
const dbFullName = process.env.DSQL_DB_NAME || "";
const encryptionKeyFinal = process.env.DSQL_ENCRYPTION_KEY || "";
const encryptionSaltFinal = process.env.DSQL_ENCRYPTION_SALT || "";
/**
* Hash Password
*
* @description Hash Password
*/
if (!payload?.password) {
return {
success: false,
msg: `Password is required to create an account`,
};
}
const hashedPassword = hashPassword({
password: payload.password,
encryptionKey: encryptionKeyFinal,
});
payload.password = hashedPassword;
let fields = await varDatabaseDbHandler({
queryString: `SHOW COLUMNS FROM users`,
database: dbFullName,
});
if (!fields) {
const newTable = await addUsersTableToDb({ dbSchema });
console.log(newTable);
fields = await varDatabaseDbHandler({
queryString: `SHOW COLUMNS FROM users`,
database: dbFullName,
});
}
if (!fields) {
return {
success: false,
msg: "Could not create users table",
};
}
const fieldsTitles = fields.map(
(/** @type {*} */ fieldObject) => fieldObject.Field
);
let invalidField = null;
for (let i = 0; i < Object.keys(payload).length; i++) {
const key = Object.keys(payload)[i];
if (!fieldsTitles.includes(key)) {
invalidField = key;
break;
}
}
if (invalidField) {
return {
success: false,
msg: `${invalidField} is not a valid field!`,
};
}
if (!dbSchema) {
throw new Error("Db Schema not found!");
}
const tableSchema = dbSchema.tables.find(
(tb) => tb?.tableName === "users"
);
const existingUser = await varDatabaseDbHandler({
queryString: `SELECT * FROM users WHERE email = ?${
payload.username ? "OR username = ?" : ""
}}`,
queryValuesArray: payload.username
? [payload.email, payload.username]
: [payload.email],
database: dbFullName,
tableSchema: tableSchema,
});
if (existingUser && existingUser[0]) {
return {
success: false,
msg: "User Already Exists",
};
}
const addUser = await addDbEntry({
dbFullName: dbFullName,
tableName: "users",
data: {
...payload,
image: "/images/user_images/user-preset.png",
image_thumbnail:
"/images/user_images/user-preset-thumbnail.png",
},
encryptionKey: encryptionKeyFinal,
encryptionSalt: encryptionSaltFinal,
tableSchema,
});
if (addUser?.insertId) {
const newlyAddedUser = await varDatabaseDbHandler({
queryString: `SELECT id,first_name,last_name,email,username,phone,image,image_thumbnail,city,state,country,zip_code,address,verification_status,more_user_data FROM users WHERE id='${addUser.insertId}'`,
database: dbFullName,
});
return {
success: true,
payload: newlyAddedUser?.[0],
};
} else {
return {
success: false,
msg: "Could not create user",
};
}
////////////////////////////////////////
} catch (/** @type {*} */ error) {
////////////////////////////////////////
console.log("Error in local add-user Request =>", error.message);
return {
success: false,
msg: "Something went wrong!",
};
////////////////////////////////////////
}
}
module.exports = localAddUser;
-22
View File
@@ -1,22 +0,0 @@
export = getLocalUser;
/**
*
* @param {object} param0
* @param {number} param0.userId
* @param {string[]} param0.fields
* @param {import("../../package-shared/types").DSQL_DatabaseSchemaType | undefined} [param0.dbSchema]
* @returns
*/
declare function getLocalUser({ userId, fields, dbSchema }: {
userId: number;
fields: string[];
dbSchema?: import("../../package-shared/types").DSQL_DatabaseSchemaType | undefined;
}): Promise<{
success: boolean;
payload: any;
msg: string;
} | {
success: boolean;
payload: any;
msg?: undefined;
}>;
-55
View File
@@ -1,55 +0,0 @@
// @ts-check
const varDatabaseDbHandler = require("../engine/utils/varDatabaseDbHandler");
/**
*
* @param {object} param0
* @param {number} param0.userId
* @param {string[]} param0.fields
* @param {import("../../package-shared/types").DSQL_DatabaseSchemaType | undefined} [param0.dbSchema]
* @returns
*/
async function getLocalUser({ userId, fields, dbSchema }) {
/**
* GRAB user
*
* @description GRAB user
*/
const sanitizedFields = fields.map((fld) => fld.replace(/[^a-z\_]/g, ""));
const query = `SELECT ${sanitizedFields.join(",")} FROM users WHERE id = ?`;
const tableSchema = dbSchema?.tables.find(
(tb) => tb?.tableName === "users"
);
let foundUser = await varDatabaseDbHandler({
queryString: query,
queryValuesArray: [userId.toString()],
database: process.env.DSQL_DB_NAME || "",
tableSchema,
});
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
if (!foundUser || !foundUser[0])
return {
success: false,
payload: null,
msg: "User not found!",
};
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
/** ********************* Send Response */
return {
success: true,
payload: foundUser[0],
};
}
module.exports = getLocalUser;
-39
View File
@@ -1,39 +0,0 @@
export = loginLocalUser;
/**
*
* @param {import("../../package-shared/types").PackageUserLoginLocalBody} param0
* @returns
*/
declare function loginLocalUser({ payload, additionalFields, dbSchema, email_login, email_login_code, email_login_field, }: import("../../package-shared/types").PackageUserLoginLocalBody): Promise<{
success: boolean;
msg: string;
payload?: undefined;
userId?: undefined;
} | {
success: boolean;
payload: any;
msg: string;
userId?: undefined;
} | {
success: boolean;
msg: string;
payload: {
id: any;
first_name: any;
last_name: any;
username: any;
email: any;
phone: any;
social_id: any;
image: any;
image_thumbnail: any;
verification_status: any;
social_login: any;
social_platform: any;
csrf_k: string;
more_data: any;
logged_in_status: boolean;
date: number;
};
userId: string;
}>;
-188
View File
@@ -1,188 +0,0 @@
// @ts-check
const hashPassword = require("../../functions/hashPassword");
const varDatabaseDbHandler = require("../engine/utils/varDatabaseDbHandler");
/**
*
* @param {import("../../package-shared/types").PackageUserLoginLocalBody} param0
* @returns
*/
async function loginLocalUser({
payload,
additionalFields,
dbSchema,
email_login,
email_login_code,
email_login_field,
}) {
try {
/**
* User auth
*
* @description Authenticate user
*/
const email = payload.email;
const username = payload.username;
const password = payload.password;
const dbFullName = process.env.DSQL_DB_NAME || "";
const encryptionKey = process.env.DSQL_ENCRYPTION_KEY || "";
const encryptionSalt = process.env.DSQL_ENCRYPTION_SALT || "";
/**
* Check input validity
*
* @description Check input validity
*/
if (
email?.match(/ /) ||
(username && username?.match(/ /)) ||
(password && password?.match(/ /))
) {
return {
success: false,
msg: "Invalid Email/Password format",
};
}
/**
* Password hash
*
* @description Password hash
*/
let hashedPassword = password
? hashPassword({
password: password,
encryptionKey: encryptionKey,
})
: null;
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
const tableSchema = dbSchema?.tables.find(
(tb) => tb?.tableName === "users"
);
let foundUser = await varDatabaseDbHandler({
queryString: `SELECT * FROM users WHERE email = ? OR username = ?`,
queryValuesArray: [email || "", username || ""],
database: dbFullName.replace(/[^a-z0-9_]/g, ""),
tableSchema,
});
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
if (!foundUser || !foundUser[0])
return {
success: false,
payload: null,
msg: "No user found",
};
let isPasswordCorrect = false;
if (foundUser && foundUser[0] && !email_login) {
isPasswordCorrect = hashedPassword === foundUser[0].password;
} else if (
foundUser &&
foundUser[0] &&
email_login &&
email_login_code &&
email_login_field
) {
const tempCode = foundUser[0][email_login_field];
if (!tempCode) throw new Error("No code Found!");
const tempCodeArray = tempCode.split("-");
const [code, codeDate] = tempCodeArray;
const millisecond15mins = 1000 * 60 * 15;
if (Date.now() - Number(codeDate) > millisecond15mins) {
throw new Error("Code Expired");
}
isPasswordCorrect = code === email_login_code;
}
let socialUserValid = false;
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
if (!isPasswordCorrect && !socialUserValid) {
return {
success: false,
msg: "Wrong password, no social login validity",
payload: null,
};
}
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
let csrfKey =
Math.random().toString(36).substring(2) +
"-" +
Math.random().toString(36).substring(2);
let userPayload = {
id: foundUser[0].id,
first_name: foundUser[0].first_name,
last_name: foundUser[0].last_name,
username: foundUser[0].username,
email: foundUser[0].email,
phone: foundUser[0].phone,
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,
more_data: foundUser[0].more_user_data,
logged_in_status: true,
date: Date.now(),
};
if (
additionalFields &&
Array.isArray(additionalFields) &&
additionalFields.length > 0
) {
additionalFields.forEach((key) => {
// @ts-ignore
userPayload[key] = foundUser?.[0][key];
});
}
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
/** ********************* Send Response */
return {
success: true,
msg: "Login Successful",
payload: userPayload,
userId: "0",
};
////////////////////////////////////////
} catch (/** @type {*} */ error) {
console.log("Error in local login-user Request =>", error.message);
return {
success: false,
msg: "Login Failed",
};
}
}
module.exports = loginLocalUser;
-3
View File
@@ -1,3 +0,0 @@
<p>Please use this code to login</p>
<h2>{{code}}</h2>
<p>Please note that this code expires after 15 minutes</p>
-46
View File
@@ -1,46 +0,0 @@
export = localReauthUser;
/**
*
* @param {object} param0
* @param {*} param0.existingUser
* @param {string[]} [param0.additionalFields]
* @param {import("../../package-shared/types").DSQL_DatabaseSchemaType | undefined} [param0.dbSchema]
* @returns
*/
declare function localReauthUser({ existingUser, additionalFields, dbSchema }: {
existingUser: any;
additionalFields?: string[];
dbSchema?: import("../../package-shared/types").DSQL_DatabaseSchemaType | undefined;
}): Promise<{
success: boolean;
payload: any;
msg: string;
userId?: undefined;
} | {
success: boolean;
msg: string;
payload: {
id: any;
first_name: any;
last_name: any;
username: any;
email: any;
phone: any;
social_id: any;
image: any;
image_thumbnail: any;
verification_status: any;
social_login: any;
social_platform: any;
csrf_k: string;
more_data: any;
logged_in_status: boolean;
date: number;
};
userId: string;
} | {
success: boolean;
msg: string;
payload?: undefined;
userId?: undefined;
}>;
-115
View File
@@ -1,115 +0,0 @@
// @ts-check
const varDatabaseDbHandler = require("../engine/utils/varDatabaseDbHandler");
/**
*
* @param {object} param0
* @param {*} param0.existingUser
* @param {string[]} [param0.additionalFields]
* @param {import("../../package-shared/types").DSQL_DatabaseSchemaType | undefined} [param0.dbSchema]
* @returns
*/
async function localReauthUser({ existingUser, additionalFields, dbSchema }) {
try {
/**
* Grab data
*
* @description Grab data
*/
const dbFullName = process.env.DSQL_DB_NAME || "";
/**
* GRAB user
*
* @description GRAB user
*/
const tableSchema = dbSchema?.tables.find(
(tb) => tb?.tableName === "users"
);
let foundUser =
existingUser?.id && existingUser.id.toString().match(/./)
? await varDatabaseDbHandler({
queryString: `SELECT * FROM users WHERE id=?`,
queryValuesArray: [existingUser.id],
database: dbFullName.replace(/[^a-z0-9_]/g, ""),
tableSchema,
})
: null;
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
if (!foundUser || !foundUser[0])
return {
success: false,
payload: null,
msg: "No user found",
};
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
let csrfKey =
Math.random().toString(36).substring(2) +
"-" +
Math.random().toString(36).substring(2);
let userPayload = {
id: foundUser[0].id,
first_name: foundUser[0].first_name,
last_name: foundUser[0].last_name,
username: foundUser[0].username,
email: foundUser[0].email,
phone: foundUser[0].phone,
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,
more_data: foundUser[0].more_user_data,
logged_in_status: true,
date: Date.now(),
};
if (
additionalFields &&
Array.isArray(additionalFields) &&
additionalFields.length > 0
) {
additionalFields.forEach((key) => {
// @ts-ignore
userPayload[key] = foundUser?.[0][key];
});
}
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
/** ********************* Send Response */
return {
success: true,
msg: "Login Successful",
payload: userPayload,
userId: "0",
};
////////////////////////////////////////
////////////////////////////////////////
} catch (/** @type {*} */ error) {
console.log("Error in local login-user Request =>", error.message);
return {
success: false,
msg: "Login Failed",
};
}
}
module.exports = localReauthUser;
-32
View File
@@ -1,32 +0,0 @@
export = localSendEmailCode;
/**
*
* @param {object} param0
* @param {string} param0.email
* @param {import("../../package-shared/types").DSQL_DatabaseSchemaType | undefined} [param0.dbSchema]
* @param {string} param0.email_login_field
* @param {string} [param0.mail_domain]
* @param {string} [param0.mail_username]
* @param {string} [param0.mail_password]
* @param {number} [param0.mail_port]
* @param {string} [param0.sender]
* @returns
*/
declare function localSendEmailCode({ email, dbSchema, email_login_field, mail_domain, mail_username, mail_password, mail_port, sender, }: {
email: string;
dbSchema?: import("../../package-shared/types").DSQL_DatabaseSchemaType | undefined;
email_login_field: string;
mail_domain?: string;
mail_username?: string;
mail_password?: string;
mail_port?: number;
sender?: string;
}): Promise<{
success: boolean;
msg: string;
payload?: undefined;
} | {
success: boolean;
payload: any;
msg: string;
}>;
-153
View File
@@ -1,153 +0,0 @@
// @ts-check
const hashPassword = require("../../functions/hashPassword");
const varDatabaseDbHandler = require("../engine/utils/varDatabaseDbHandler");
const nodemailer = require("nodemailer");
const fs = require("fs");
const path = require("path");
/**
*
* @param {object} param0
* @param {string} param0.email
* @param {import("../../package-shared/types").DSQL_DatabaseSchemaType | undefined} [param0.dbSchema]
* @param {string} param0.email_login_field
* @param {string} [param0.mail_domain]
* @param {string} [param0.mail_username]
* @param {string} [param0.mail_password]
* @param {number} [param0.mail_port]
* @param {string} [param0.sender]
* @returns
*/
async function localSendEmailCode({
email,
dbSchema,
email_login_field,
mail_domain,
mail_username,
mail_password,
mail_port,
sender,
}) {
try {
/**
* User auth
*
* @description Authenticate user
*/
const dbFullName = process.env.DSQL_DB_NAME || "";
const encryptionKey = process.env.DSQL_ENCRYPTION_KEY || "";
const encryptionSalt = process.env.DSQL_ENCRYPTION_SALT || "";
/**
* Check input validity
*
* @description Check input validity
*/
if (email?.match(/ /)) {
return {
success: false,
msg: "Invalid Email/Password format",
};
}
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
const tableSchema = dbSchema?.tables.find(
(tb) => tb?.tableName === "users"
);
let foundUser = await varDatabaseDbHandler({
queryString: `SELECT * FROM users WHERE email = ?`,
queryValuesArray: [email],
database: dbFullName.replace(/[^a-z0-9_]/g, ""),
tableSchema,
});
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
if (!foundUser || !foundUser[0])
return {
success: false,
payload: null,
msg: "No user found",
};
if (foundUser && foundUser[0] && email_login_field) {
const tempCode = generateCode();
let transporter = nodemailer.createTransport({
host: mail_domain,
port: mail_port || 465,
secure: true,
auth: {
user: mail_username,
pass: mail_password,
},
});
let mailObject = {};
mailObject["from"] = `"Datasquirel SSO" <${
sender || "support@datasquirel.com"
}>`;
mailObject["sender"] = sender || "support@datasquirel.com";
mailObject["to"] = email;
mailObject["subject"] = "One Time Login Code";
mailObject["html"] = fs
.readFileSync(
path.resolve(__dirname, "one-time-code.html"),
"utf-8"
)
.replace(/{{code}}/, tempCode);
const info = await transporter.sendMail(mailObject);
if (!info?.accepted) throw new Error("Mail not Sent!");
/** ********************************************** */
/** ********************************************** */
/** ********************************************** */
let setTempCode = await varDatabaseDbHandler({
queryString: `UPDATE users SET ${email_login_field} = ? WHERE email = ?`,
queryValuesArray: [tempCode + `-${Date.now()}`, email],
database: dbFullName.replace(/[^a-z0-9_]/g, ""),
tableSchema,
});
}
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
/** ********************* Send Response */
return {
success: true,
msg: "Success",
};
////////////////////////////////////////
} catch (/** @type {*} */ error) {
console.log("Error in local login-user Request =>", error.message);
return {
success: false,
msg: "Failed: " + error.message,
};
}
}
function generateCode() {
const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
let code = "";
for (let i = 0; i < 8; i++) {
code += chars[Math.floor(Math.random() * chars.length)];
}
return code;
}
module.exports = localSendEmailCode;
-71
View File
@@ -1,71 +0,0 @@
export = localGithubAuth;
/**
* SERVER FUNCTION: Login with google Function
* ==============================================================================
*
* @async
*
* @param {object} params - main params object
* @param {http.ServerResponse} params.res - HTTPS response object
* @param {string} params.code
* @param {string} [params.email]
* @param {string} params.clientId
* @param {string} params.clientSecret
* @param {object} [params.additionalFields]
* @param {import("../../../package-shared/types").DSQL_DatabaseSchemaType} params.dbSchema
*/
declare function localGithubAuth({ res, code, email, clientId, clientSecret, additionalFields, dbSchema, }: {
res: http.ServerResponse;
code: string;
email?: string;
clientId: string;
clientSecret: string;
additionalFields?: object;
dbSchema: import("../../../package-shared/types").DSQL_DatabaseSchemaType;
}): Promise<{
success: boolean;
msg: string;
} | {
dsqlUserId: string;
/**
* - Did the operation complete successfully or not?
*/
success: boolean;
/**
* - User payload object: or "null"
*/
user: {
id: number;
first_name: string;
last_name: string;
} | null;
/**
* - Message
*/
msg?: string;
/**
* - Error Message
*/
error?: string;
/**
* - Social Id
*/
social_id?: string | number;
/**
* - Social Platform
*/
social_platform?: string;
/**
* - Payload
*/
payload?: object;
/**
* - Alert
*/
alert?: boolean;
/**
* - New User
*/
newUser?: any;
}>;
import http = require("http");
-151
View File
@@ -1,151 +0,0 @@
// @ts-check
/**
* ==============================================================================
* Imports
* ==============================================================================
*/
const http = require("http");
const https = require("https");
const encrypt = require("../../../functions/encrypt");
const camelJoinedtoCamelSpace = require("../../engine/utils/camelJoinedtoCamelSpace");
const githubLogin = require("./utils/githubLogin");
const handleSocialDb = require("./utils/handleSocialDb");
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
const database = process.env.DSQL_DB_NAME || "";
const encryptionKey = process.env.DSQL_ENCRYPTION_KEY || "";
const encryptionSalt = process.env.DSQL_ENCRYPTION_SALT || "";
/**
* SERVER FUNCTION: Login with google Function
* ==============================================================================
*
* @async
*
* @param {object} params - main params object
* @param {http.ServerResponse} params.res - HTTPS response object
* @param {string} params.code
* @param {string} [params.email]
* @param {string} params.clientId
* @param {string} params.clientSecret
* @param {object} [params.additionalFields]
* @param {import("../../../package-shared/types").DSQL_DatabaseSchemaType} params.dbSchema
*/
async function localGithubAuth({
res,
code,
email,
clientId,
clientSecret,
additionalFields,
dbSchema,
}) {
try {
/**
* User auth
*
* @description Authenticate user
*/
if (!code || !clientId || !clientSecret) {
return {
success: false,
msg: "Missing query params",
};
}
if (
typeof code !== "string" ||
typeof clientId !== "string" ||
typeof clientSecret !== "string" ||
typeof database !== "string"
) {
return {
success: false,
msg: "Wrong Parameters",
};
}
/**
* Create new user folder and file
*
* @description Create new user folder and file
*/
const gitHubUser = await githubLogin({
code: code,
clientId: clientId,
clientSecret: clientSecret,
});
if (!gitHubUser) {
return {
success: false,
msg: "No github user returned",
};
}
const targetDbName = database;
const socialId = gitHubUser.name || gitHubUser.id || gitHubUser.login;
const targetName = gitHubUser.name || gitHubUser.login;
const nameArray = targetName?.match(/ /)
? targetName?.split(" ")
: targetName?.match(/\-/)
? targetName?.split("-")
: [targetName];
const payload = {
email: gitHubUser.email,
first_name: camelJoinedtoCamelSpace(nameArray[0]) || "",
last_name: camelJoinedtoCamelSpace(nameArray[1]) || "",
social_id: socialId,
social_platform: "github",
image: gitHubUser.avatar_url,
image_thumbnail: gitHubUser.avatar_url,
username: "github-user-" + socialId,
};
if (additionalFields && Object.keys(additionalFields).length > 0) {
Object.keys(additionalFields).forEach((key) => {
// @ts-ignore
payload[key] = additionalFields[key];
});
}
const loggedInGithubUser = await handleSocialDb({
database: targetDbName,
email: gitHubUser.email,
payload: payload,
social_platform: "github",
res: res,
social_id: socialId,
supEmail: email,
additionalFields,
dbSchema: dbSchema,
});
////////////////////////////////////////////////
////////////////////////////////////////////////
////////////////////////////////////////////////
return { ...loggedInGithubUser, dsqlUserId: "0" };
////////////////////////////////////////
} catch (/** @type {*} */ error) {
console.log("localGithubAuth error", error.message);
return { success: false, msg: "Failed!" };
}
}
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
module.exports = localGithubAuth;
-28
View File
@@ -1,28 +0,0 @@
export = localGoogleAuth;
/**
* SERVER FUNCTION: Login with google Function
* ==============================================================================
*
* @async
*
* @param {object} params - main params object
* @param {string} params.token - Google access token gotten from the client side
* @param {string} params.clientId - Google client id
* @param {http.ServerResponse} params.response - HTTPS response object
* @param {object} [params.additionalFields] - Additional Fields to be added to the user object
* @param {import("../../../package-shared/types").DSQL_DatabaseSchemaType} [params.dbSchema] - Database Schema
*
* @returns { Promise<FunctionReturn> }
*/
declare function localGoogleAuth({ dbSchema, token, clientId, response, additionalFields, }: {
token: string;
clientId: string;
response: http.ServerResponse;
additionalFields?: object;
dbSchema?: import("../../../package-shared/types").DSQL_DatabaseSchemaType;
}): Promise<FunctionReturn>;
declare namespace localGoogleAuth {
export { FunctionReturn };
}
import http = require("http");
type FunctionReturn = object | null;
-174
View File
@@ -1,174 +0,0 @@
// @ts-check
/**
* ==============================================================================
* Imports
* ==============================================================================
*/
const http = require("http");
const handleSocialDb = require("./utils/handleSocialDb");
const httpsRequest = require("./utils/httpsRequest");
const grabHostNames = require("../../../package-shared/utils/grab-host-names");
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/**
* @typedef {object | null} FunctionReturn
* @property {boolean} success - Did the function run successfully?
* @property {import("../../types/user.td").DATASQUIREL_LoggedInUser | null} user - Returned User
* @property {number} [dsqlUserId] - Dsql User Id
* @property {string} [msg] - Response message
*/
const database = process.env.DSQL_DB_NAME || "";
const encryptionKey = process.env.DSQL_ENCRYPTION_KEY || "";
const encryptionSalt = process.env.DSQL_ENCRYPTION_SALT || "";
/**
* SERVER FUNCTION: Login with google Function
* ==============================================================================
*
* @async
*
* @param {object} params - main params object
* @param {string} params.token - Google access token gotten from the client side
* @param {string} params.clientId - Google client id
* @param {http.ServerResponse} params.response - HTTPS response object
* @param {object} [params.additionalFields] - Additional Fields to be added to the user object
* @param {import("../../../package-shared/types").DSQL_DatabaseSchemaType} [params.dbSchema] - Database Schema
*
* @returns { Promise<FunctionReturn> }
*/
async function localGoogleAuth({
dbSchema,
token,
clientId,
response,
additionalFields,
}) {
/**
* Send Response
*
* @description Send a boolean response
*/
const { host, port, scheme } = grabHostNames();
try {
/**
* Grab User data
*
* @description Grab User data
* @type {{ success: boolean, payload: any, msg: string }}
*/
const payloadResponse = await httpsRequest({
method: "POST",
hostname: host,
path: "/user/grab-google-user-from-token",
body: {
token: token,
clientId: clientId,
},
headers: {
Authorization: process.env.DSQL_API_KEY,
},
});
const payload = payloadResponse.payload;
if (!payloadResponse.success || !payload) {
console.log("payloadResponse Failed =>", payloadResponse);
return {
success: false,
msg: "User fetch Error",
};
}
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
if (!database || typeof database != "string" || database?.match(/ /)) {
return {
success: false,
user: undefined,
msg: "Please provide a database slug(database name in lowercase with no spaces)",
};
}
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
/**
* Create new user folder and file
*
* @description Create new user folder and file
*/
const targetDbName = database;
if (!payload) {
return {
success: false,
msg: "No payload",
};
}
const { given_name, family_name, email, sub, picture, email_verified } =
payload;
const payloadObject = {
email: email || "",
first_name: given_name || "",
last_name: family_name || "",
social_id: sub,
social_platform: "google",
image: picture || "",
image_thumbnail: picture || "",
username: `google-user-${sub}`,
};
if (additionalFields && Object.keys(additionalFields).length > 0) {
Object.keys(additionalFields).forEach((key) => {
// @ts-ignore
payloadObject[key] = additionalFields[key];
});
}
const loggedInGoogleUser = await handleSocialDb({
database: targetDbName,
email: email || "",
payload: payloadObject,
social_platform: "google",
res: response,
social_id: sub,
additionalFields,
dbSchema,
});
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
return { ...loggedInGoogleUser, dsqlUserId: "0" };
////////////////////////////////////////
} catch (error) {
return {
success: false,
msg: "User fetch Error",
};
////////////////////////////////////////
}
}
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
module.exports = localGoogleAuth;
-182
View File
@@ -1,182 +0,0 @@
export = githubLogin;
/**
*
* @typedef {object} GithubUserPayload
* @property {string} login - Full name merged eg. "JohnDoe"
* @property {number} id - github user id
* @property {string} node_id - Some other id
* @property {string} avatar_url - profile picture
* @property {string} gravatar_id - some other id
* @property {string} url - Github user URL
* @property {string} html_url - User html URL - whatever that means
* @property {string} followers_url - Followers URL
* @property {string} following_url - Following URL
* @property {string} gists_url - Gists URL
* @property {string} starred_url - Starred URL
* @property {string} subscriptions_url - Subscriptions URL
* @property {string} organizations_url - Organizations URL
* @property {string} repos_url - Repositories URL
* @property {string} received_events_url - Received Events URL
* @property {string} type - Common value => "User"
* @property {boolean} site_admin - Is site admin or not? Boolean
* @property {string} name - More like "username"
* @property {string} company - User company
* @property {string} blog - User blog URL
* @property {string} location - User Location
* @property {string} email - User Email
* @property {string} hireable - Is user hireable
* @property {string} bio - User bio
* @property {string} twitter_username - User twitter username
* @property {number} public_repos - Number of public repositories
* @property {number} public_gists - Number of public gists
* @property {number} followers - Number of followers
* @property {number} following - Number of following
* @property {string} created_at - Date created
* @property {string} updated_at - Date updated
*/
/**
* Login/signup a github user
* ==============================================================================
* @async
*
* @param {Object} params - foundUser if any
* @param {string} params.code - github auth token
* @param {string} params.clientId - github client Id
* @param {string} params.clientSecret - github client Secret
*
* @returns {Promise<GithubUserPayload|null>}
*/
declare function githubLogin({ code, clientId, clientSecret }: {
code: string;
clientId: string;
clientSecret: string;
}): Promise<GithubUserPayload | null>;
declare namespace githubLogin {
export { GithubUserPayload };
}
type GithubUserPayload = {
/**
* - Full name merged eg. "JohnDoe"
*/
login: string;
/**
* - github user id
*/
id: number;
/**
* - Some other id
*/
node_id: string;
/**
* - profile picture
*/
avatar_url: string;
/**
* - some other id
*/
gravatar_id: string;
/**
* - Github user URL
*/
url: string;
/**
* - User html URL - whatever that means
*/
html_url: string;
/**
* - Followers URL
*/
followers_url: string;
/**
* - Following URL
*/
following_url: string;
/**
* - Gists URL
*/
gists_url: string;
/**
* - Starred URL
*/
starred_url: string;
/**
* - Subscriptions URL
*/
subscriptions_url: string;
/**
* - Organizations URL
*/
organizations_url: string;
/**
* - Repositories URL
*/
repos_url: string;
/**
* - Received Events URL
*/
received_events_url: string;
/**
* - Common value => "User"
*/
type: string;
/**
* - Is site admin or not? Boolean
*/
site_admin: boolean;
/**
* - More like "username"
*/
name: string;
/**
* - User company
*/
company: string;
/**
* - User blog URL
*/
blog: string;
/**
* - User Location
*/
location: string;
/**
* - User Email
*/
email: string;
/**
* - Is user hireable
*/
hireable: string;
/**
* - User bio
*/
bio: string;
/**
* - User twitter username
*/
twitter_username: string;
/**
* - Number of public repositories
*/
public_repos: number;
/**
* - Number of public gists
*/
public_gists: number;
/**
* - Number of followers
*/
followers: number;
/**
* - Number of following
*/
following: number;
/**
* - Date created
*/
created_at: string;
/**
* - Date updated
*/
updated_at: string;
};
-164
View File
@@ -1,164 +0,0 @@
// @ts-check
/**
* ==============================================================================
* Imports
* ==============================================================================
*/
const fs = require("fs");
const httpsRequest = require("./httpsRequest");
const dbHandler = require("../../../engine/utils/dbHandler");
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
/**
*
* @typedef {object} GithubUserPayload
* @property {string} login - Full name merged eg. "JohnDoe"
* @property {number} id - github user id
* @property {string} node_id - Some other id
* @property {string} avatar_url - profile picture
* @property {string} gravatar_id - some other id
* @property {string} url - Github user URL
* @property {string} html_url - User html URL - whatever that means
* @property {string} followers_url - Followers URL
* @property {string} following_url - Following URL
* @property {string} gists_url - Gists URL
* @property {string} starred_url - Starred URL
* @property {string} subscriptions_url - Subscriptions URL
* @property {string} organizations_url - Organizations URL
* @property {string} repos_url - Repositories URL
* @property {string} received_events_url - Received Events URL
* @property {string} type - Common value => "User"
* @property {boolean} site_admin - Is site admin or not? Boolean
* @property {string} name - More like "username"
* @property {string} company - User company
* @property {string} blog - User blog URL
* @property {string} location - User Location
* @property {string} email - User Email
* @property {string} hireable - Is user hireable
* @property {string} bio - User bio
* @property {string} twitter_username - User twitter username
* @property {number} public_repos - Number of public repositories
* @property {number} public_gists - Number of public gists
* @property {number} followers - Number of followers
* @property {number} following - Number of following
* @property {string} created_at - Date created
* @property {string} updated_at - Date updated
*/
/**
* Login/signup a github user
* ==============================================================================
* @async
*
* @param {Object} params - foundUser if any
* @param {string} params.code - github auth token
* @param {string} params.clientId - github client Id
* @param {string} params.clientSecret - github client Secret
*
* @returns {Promise<GithubUserPayload|null>}
*/
async function githubLogin({ code, clientId, clientSecret }) {
/** @type {GithubUserPayload | null} */
let gitHubUser = null;
////////////////////////////////////////////////
////////////////////////////////////////////////
////////////////////////////////////////////////
try {
/**
* Create new user folder and file
*
* @description Create new user folder and file
*/
// const response = await fetch(`https://github.com/login/oauth/access_token?client_id=${process.env.GITHUB_ID}`);
const response = await httpsRequest({
method: "POST",
hostname: "github.com",
path: `/login/oauth/access_token?client_id=${clientId}&client_secret=${clientSecret}&code=${code}`,
headers: {
Accept: "application/json",
"User-Agent": "*",
},
});
// `https://github.com/login/oauth/access_token?client_id=${process.env.GITHUB_ID}&client_secret=${process.env.GITHUB_SECRET}&code=${code}`,
// body: JSON.stringify({
// client_id: process.env.GITHUB_ID,
// client_secret: process.env.GITHUB_SECRET,
// code: code,
// }),
const accessTokenObject = JSON.parse(response);
if (!accessTokenObject?.access_token) {
return gitHubUser;
}
////////////////////////////////////////////////
////////////////////////////////////////////////
////////////////////////////////////////////////
const userDataResponse = await httpsRequest({
method: "GET",
hostname: "api.github.com",
path: "/user",
headers: {
Authorization: `Bearer ${accessTokenObject.access_token}`,
"User-Agent": "*",
},
});
gitHubUser = JSON.parse(userDataResponse);
////////////////////////////////////////////////
////////////////////////////////////////////////
////////////////////////////////////////////////
if (!gitHubUser?.email) {
const existingGithubUser = await dbHandler({
query: `SELECT email FROM users WHERE social_login='1' AND social_platform='github' AND social_id= ?`,
values: [gitHubUser?.id || ""],
});
if (existingGithubUser && existingGithubUser[0] && gitHubUser) {
gitHubUser.email = existingGithubUser[0].email;
}
}
////////////////////////////////////////////////
////////////////////////////////////////////////
////////////////////////////////////////////////
} catch (/** @type {*} */ error) {
////////////////////////////////////////////////
////////////////////////////////////////////////
////////////////////////////////////////////////
console.log("ERROR in githubLogin.js backend function =>", error.message);
// serverError({
// component: "/api/social-login/github-auth/catch-error",
// message: error.message,
// user: user,
// });
////////////////////////////////////////////////
////////////////////////////////////////////////
////////////////////////////////////////////////
}
////////////////////////////////////////////////
////////////////////////////////////////////////
////////////////////////////////////////////////
return gitHubUser;
}
module.exports = githubLogin;
-99
View File
@@ -1,99 +0,0 @@
export = handleSocialDb;
/**
* 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|null|undefined,
* social_id: string|number,
* email: string,
* social_platform: string,
* payload: {
* social_id: string | number,
* email: string,
* social_platform: string,
* first_name: string,
* last_name: string,
* image: string,
* image_thumbnail: string,
* username: string,
* },
* res: http.ServerResponse,
* supEmail?: string | null,
* additionalFields?: object,
* dbSchema: import("../../../../package-shared/types").DSQL_DatabaseSchemaType | undefined
* }} params - function parameters inside an object
*
* @returns {Promise<FunctionReturn>} - Response object
*/
declare function handleSocialDb({ social_id, email, social_platform, payload, res, supEmail, additionalFields, dbSchema, }: {
database: string | null | undefined;
social_id: string | number;
email: string;
social_platform: string;
payload: {
social_id: string | number;
email: string;
social_platform: string;
first_name: string;
last_name: string;
image: string;
image_thumbnail: string;
username: string;
};
res: http.ServerResponse;
supEmail?: string | null;
additionalFields?: object;
dbSchema: import("../../../../package-shared/types").DSQL_DatabaseSchemaType | undefined;
}): Promise<FunctionReturn>;
declare namespace handleSocialDb {
export { FunctionReturn };
}
import http = require("http");
type FunctionReturn = {
/**
* - Did the operation complete successfully or not?
*/
success: boolean;
/**
* - User payload object: or "null"
*/
user: {
id: number;
first_name: string;
last_name: string;
} | null;
/**
* - Message
*/
msg?: string;
/**
* - Error Message
*/
error?: string;
/**
* - Social Id
*/
social_id?: string | number;
/**
* - Social Platform
*/
social_platform?: string;
/**
* - Payload
*/
payload?: object;
/**
* - Alert
*/
alert?: boolean;
/**
* - New User
*/
newUser?: any;
};
-405
View File
@@ -1,405 +0,0 @@
// @ts-check
/**
* ==============================================================================
* Imports
* ==============================================================================
*/
const fs = require("fs");
const http = require("http");
const varDatabaseDbHandler = require("../../../engine/utils/varDatabaseDbHandler");
const encrypt = require("../../../../functions/encrypt");
const addDbEntry = require("../../../../package-shared/functions/backend/db/addDbEntry");
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
/**
* @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"
* @property {string} [msg] - Message
* @property {string} [error] - Error Message
* @property {string | number} [social_id] - Social Id
* @property {string} [social_platform] - Social Platform
* @property {object} [payload] - Payload
* @property {boolean} [alert] - Alert
* @property {*} [newUser] - New User
*/
////////////////////////////////////////////////
////////////////////////////////////////////////
////////////////////////////////////////////////
const database = process.env.DSQL_DB_NAME || "";
const encryptionKey = process.env.DSQL_ENCRYPTION_KEY || "";
const encryptionSalt = process.env.DSQL_ENCRYPTION_SALT || "";
////////////////////////////////////////////////
////////////////////////////////////////////////
////////////////////////////////////////////////
/**
* 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|null|undefined,
* social_id: string|number,
* email: string,
* social_platform: string,
* payload: {
* social_id: string | number,
* email: string,
* social_platform: string,
* first_name: string,
* last_name: string,
* image: string,
* image_thumbnail: string,
* username: string,
* },
* res: http.ServerResponse,
* supEmail?: string | null,
* additionalFields?: object,
* dbSchema: import("../../../../package-shared/types").DSQL_DatabaseSchemaType | undefined
* }} params - function parameters inside an object
*
* @returns {Promise<FunctionReturn>} - Response object
*/
async function handleSocialDb({
social_id,
email,
social_platform,
payload,
res,
supEmail,
additionalFields,
dbSchema,
}) {
const tableSchema = dbSchema?.tables.find(
(tb) => tb?.tableName === "users"
);
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,
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 = ?`,
queryValuesArray: [finalEmail],
tableSchema,
});
if (existingEmailOnly && existingEmailOnly[0]) {
return {
success: false,
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,
database,
additionalFields,
});
}
////////////////////////////////////////////////
////////////////////////////////////////////////
////////////////////////////////////////////////
const socialHashedPassword = encrypt({
data: social_id.toString(),
encryptionKey,
encryptionSalt,
});
const data = {
social_login: "1",
verification_status: supEmail ? "0" : "1",
password: socialHashedPassword,
};
Object.keys(payload).forEach((key) => {
// @ts-ignore
data[key] = payload[key];
});
const newUser = await addDbEntry({
dbFullName: database ? database : "datasquirel",
tableName: "users",
duplicateColumnName: "email",
duplicateColumnValue: finalEmail,
data: {
...data,
email: finalEmail,
},
encryptionKey,
encryptionSalt,
tableSchema,
});
if (newUser?.insertId) {
const newUserQueried = await varDatabaseDbHandler({
database: database ? database : "datasquirel",
queryString: `SELECT * FROM users WHERE id='${newUser.insertId}'`,
});
if (!newUserQueried || !newUserQueried[0])
return {
success: false,
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({
data: JSON.stringify({
id: newUser.insertId,
email: supEmail,
dateCode: Date.now(),
}),
encryptionKey,
encryptionSalt,
});
}
////////////////////////////////////////////////
////////////////////////////////////////////////
////////////////////////////////////////////////
return await loginSocialUser({
user: newUserQueried[0],
social_platform,
res,
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 {*} */ 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 },
// });
}
////////////////////////////////////////////////
////////////////////////////////////////////////
////////////////////////////////////////////////
}
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
/**
* 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 {http.ServerResponse} params.res - Https response object
* @param {string|null} params.database - Target Database
* @param {object} [params.additionalFields] - Additional fields to be added to the user payload
*
* @returns {Promise<{
* success: boolean,
* user: { id: number, first_name: string, last_name: string } | null
* msg?: string
* }>}
*/
async function loginSocialUser({
user,
social_platform,
res,
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}'`,
});
let csrfKey =
Math.random().toString(36).substring(2) +
"-" +
Math.random().toString(36).substring(2);
if (!foundUser?.[0]) {
return {
success: false,
user: null,
msg: "User Not Found",
};
}
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) => {
// @ts-ignore
userPayload[key] = foundUser[0][key];
});
}
let encryptedPayload = encrypt({
data: JSON.stringify(userPayload),
encryptionKey,
encryptionSalt,
});
if (res?.setHeader) {
res.setHeader("Set-Cookie", [
`datasquirelAuthKey=${encryptedPayload};samesite=strict;path=/;HttpOnly=true;Secure=true`,
`csrf=${csrfKey};samesite=strict;path=/;HttpOnly=true`,
]);
}
////////////////////////////////////////////////
////////////////////////////////////////////////
////////////////////////////////////////////////
return {
success: true,
user: userPayload,
};
}
module.exports = handleSocialDb;
-23
View File
@@ -1,23 +0,0 @@
export = httpsRequest;
/**
* Main Function
* ==============================================================================
* @param {{
* url?: string,
* method: string,
* hostname: string,
* path?: string,
* href?: string,
* headers?: object,
* body?: object,
* }} params - params
*/
declare function httpsRequest({ url, method, hostname, path, href, headers, body }: {
url?: string;
method: string;
hostname: string;
path?: string;
href?: string;
headers?: object;
body?: object;
}): Promise<any>;
-112
View File
@@ -1,112 +0,0 @@
// @ts-check
/**
* Imports
* ==============================================================================
*/
const grabHostNames = require("../../../../package-shared/utils/grab-host-names");
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
/**
* Main Function
* ==============================================================================
* @param {{
* url?: string,
* method: string,
* hostname: string,
* path?: string,
* href?: string,
* headers?: object,
* body?: object,
* }} params - params
*/
function httpsRequest({ url, method, hostname, path, href, headers, body }) {
const reqPayloadString = body ? JSON.stringify(body) : null;
const { host, port, scheme } = grabHostNames();
////////////////////////////////////////////////
////////////////////////////////////////////////
////////////////////////////////////////////////
/** @type {any} */
let requestOptions = {
method: method,
hostname: host,
port,
headers: {},
};
if (path) requestOptions.path = path;
if (href) requestOptions.href = href;
if (headers) requestOptions.headers = headers;
if (body) {
requestOptions.headers["Content-Type"] = "application/json";
requestOptions.headers["Content-Length"] = Buffer.from(
reqPayloadString || ""
).length;
}
////////////////////////////////////////////////
////////////////////////////////////////////////
////////////////////////////////////////////////
return new Promise((res, rej) => {
const httpsRequest = scheme.request(
/* ====== Request Options object ====== */
// @ts-ignore
url ? url : requestOptions,
////////////////////////////////////////////////
////////////////////////////////////////////////
////////////////////////////////////////////////
/* ====== Callback function ====== */
(response) => {
var str = "";
// ## another chunk of data has been received, so append it to `str`
response.on("data", function (chunk) {
str += chunk;
});
// ## the whole response has been received, so we just print it out here
response.on("end", function () {
res(str);
});
response.on("error", (error) => {
console.log("HTTP response error =>", error.message);
});
}
);
if (body) httpsRequest.write(reqPayloadString);
httpsRequest.on("error", (error) => {
console.log("HTTPS request ERROR =>", error);
});
httpsRequest.end();
////////////////////////////////////////////////
////////////////////////////////////////////////
////////////////////////////////////////////////
});
}
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
module.exports = httpsRequest;
-44
View File
@@ -1,44 +0,0 @@
export = localUpdateUser;
/**
* @typedef {Object} LocalPostReturn
* @property {boolean} success - Did the function run successfully?
* @property {*} [payload] - GET request results
* @property {string} [msg] - Message
* @property {string} [error] - Error Message
*/
/**
* Make a get request to Datasquirel API
* ==============================================================================
* @async
*
* @param {Object} params - Single object passed
* @param {*} params.payload - SQL Query
* @param {import("../../package-shared/types").DSQL_DatabaseSchemaType | undefined} params.dbSchema - Name of the table to query
*
* @returns { Promise<LocalPostReturn> } - Return Object
*/
declare function localUpdateUser({ payload, dbSchema }: {
payload: any;
dbSchema: import("../../package-shared/types").DSQL_DatabaseSchemaType | undefined;
}): Promise<LocalPostReturn>;
declare namespace localUpdateUser {
export { LocalPostReturn };
}
type LocalPostReturn = {
/**
* - Did the function run successfully?
*/
success: boolean;
/**
* - GET request results
*/
payload?: any;
/**
* - Message
*/
msg?: string;
/**
* - Error Message
*/
error?: string;
};
-91
View File
@@ -1,91 +0,0 @@
// @ts-check
const updateDbEntry = require("../../package-shared/functions/backend/db/updateDbEntry");
/**
* @typedef {Object} LocalPostReturn
* @property {boolean} success - Did the function run successfully?
* @property {*} [payload] - GET request results
* @property {string} [msg] - Message
* @property {string} [error] - Error Message
*/
/**
* Make a get request to Datasquirel API
* ==============================================================================
* @async
*
* @param {Object} params - Single object passed
* @param {*} params.payload - SQL Query
* @param {import("../../package-shared/types").DSQL_DatabaseSchemaType | undefined} params.dbSchema - Name of the table to query
*
* @returns { Promise<LocalPostReturn> } - Return Object
*/
async function localUpdateUser({ payload, dbSchema }) {
try {
/**
* User auth
*
* @description Authenticate user
*/
/**
* Initialize Variables
*/
const dbFullName = process.env.DSQL_DB_NAME || "";
const encryptionKey = process.env.DSQL_ENCRYPTION_KEY || "";
const encryptionSalt = process.env.DSQL_ENCRYPTION_SALT || "";
const data = (() => {
const reqBodyKeys = Object.keys(payload);
const finalData = {};
reqBodyKeys.forEach((key) => {
if (key?.match(/^date_|^id$/)) return;
// @ts-ignore
finalData[key] = payload[key];
});
return finalData;
})();
if (!dbSchema) {
throw new Error("Db Schema not found!");
}
const tableSchema = dbSchema.tables.find(
(tb) => tb?.tableName === "users"
);
const updateUser = await updateDbEntry({
dbContext: "Dsql User",
paradigm: "Full Access",
dbFullName: dbFullName,
tableName: "users",
identifierColumnName: "id",
identifierValue: payload.id,
data: data,
encryptionKey,
encryptionSalt,
tableSchema,
});
return {
success: true,
payload: updateUser,
};
} catch (/** @type {*} */ error) {
////////////////////////////////////////
console.log("Error in local add-user Request =>", error.message);
return {
success: false,
payload: null,
msg: "Something went wrong!",
};
////////////////////////////////////////
}
}
module.exports = localUpdateUser;