Updates
This commit is contained in:
@@ -3,6 +3,7 @@ import {
|
||||
APILoginFunctionReturn,
|
||||
DATASQUIREL_LoggedInUser,
|
||||
} from "../../../types";
|
||||
import grabDbFullName from "../../../utils/grab-db-full-name";
|
||||
import varDatabaseDbHandler from "../../backend/varDatabaseDbHandler";
|
||||
import hashPassword from "../../dsql/hashPassword";
|
||||
|
||||
@@ -23,8 +24,10 @@ export default async function apiLoginUser({
|
||||
skipPassword,
|
||||
social,
|
||||
useLocal,
|
||||
dbUserId,
|
||||
debug,
|
||||
}: APILoginFunctionParams): Promise<APILoginFunctionReturn> {
|
||||
const dbFullName = database.replace(/[^a-z0-9_]/g, "");
|
||||
const dbFullName = grabDbFullName({ dbName: database, userId: dbUserId });
|
||||
|
||||
/**
|
||||
* Check input validity
|
||||
@@ -54,13 +57,23 @@ export default async function apiLoginUser({
|
||||
})
|
||||
: null;
|
||||
|
||||
if (debug) {
|
||||
console.log("apiLoginUser:database:", dbFullName);
|
||||
console.log("apiLoginUser:Finding User ...");
|
||||
}
|
||||
|
||||
let foundUser = await varDatabaseDbHandler({
|
||||
queryString: `SELECT * FROM ${dbFullName}.users WHERE email = ? OR username = ?`,
|
||||
queryValuesArray: [email, username],
|
||||
database: dbFullName,
|
||||
useLocal,
|
||||
debug,
|
||||
});
|
||||
|
||||
if (debug) {
|
||||
console.log("apiLoginUser:foundUser:", foundUser);
|
||||
}
|
||||
|
||||
if ((!foundUser || !foundUser[0]) && !social)
|
||||
return {
|
||||
success: false,
|
||||
@@ -70,9 +83,20 @@ export default async function apiLoginUser({
|
||||
|
||||
let isPasswordCorrect = false;
|
||||
|
||||
if (debug) {
|
||||
console.log("apiLoginUser:isPasswordCorrect:", isPasswordCorrect);
|
||||
}
|
||||
|
||||
if (foundUser?.[0] && !email_login && skipPassword) {
|
||||
isPasswordCorrect = true;
|
||||
} else if (foundUser?.[0] && !email_login) {
|
||||
if (debug) {
|
||||
console.log("apiLoginUser:hashedPassword:", hashedPassword);
|
||||
console.log(
|
||||
"apiLoginUser:foundUser[0].password:",
|
||||
foundUser[0].password
|
||||
);
|
||||
}
|
||||
isPasswordCorrect = hashedPassword === foundUser[0].password;
|
||||
} else if (
|
||||
foundUser &&
|
||||
@@ -81,8 +105,11 @@ export default async function apiLoginUser({
|
||||
email_login_code &&
|
||||
email_login_field
|
||||
) {
|
||||
/** @type {string} */
|
||||
const tempCode = foundUser[0][email_login_field];
|
||||
const tempCode: string = foundUser[0][email_login_field];
|
||||
|
||||
if (debug) {
|
||||
console.log("apiLoginUser:tempCode:", tempCode);
|
||||
}
|
||||
|
||||
if (!tempCode) throw new Error("No code Found!");
|
||||
|
||||
@@ -106,6 +133,11 @@ export default async function apiLoginUser({
|
||||
};
|
||||
}
|
||||
|
||||
if (debug) {
|
||||
console.log("apiLoginUser:isPasswordCorrect:", isPasswordCorrect);
|
||||
console.log("apiLoginUser:email_login:", email_login);
|
||||
}
|
||||
|
||||
if (isPasswordCorrect && email_login) {
|
||||
const resetTempCode = await varDatabaseDbHandler({
|
||||
queryString: `UPDATE ${dbFullName}.users SET ${email_login_field} = '' WHERE email = ? OR username = ?`,
|
||||
@@ -139,6 +171,11 @@ export default async function apiLoginUser({
|
||||
date: Date.now(),
|
||||
};
|
||||
|
||||
if (debug) {
|
||||
console.log("apiLoginUser:userPayload:", userPayload);
|
||||
console.log("apiLoginUser:Sending Response Object ...");
|
||||
}
|
||||
|
||||
const resposeObject: APILoginFunctionReturn = {
|
||||
success: true,
|
||||
msg: "Login Successful",
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
import EJSON from "../../../../../utils/ejson";
|
||||
import encrypt from "../../../../dsql/encrypt";
|
||||
|
||||
type Param = {
|
||||
email: string;
|
||||
encryptionKey?: string;
|
||||
encryptionSalt?: string;
|
||||
};
|
||||
|
||||
export type EncryptResetPasswordObject = {
|
||||
email: string;
|
||||
createdAt: number;
|
||||
};
|
||||
|
||||
export default function encryptReserPasswordUrl({
|
||||
email,
|
||||
encryptionKey,
|
||||
encryptionSalt,
|
||||
}: Param) {
|
||||
const encryptObject: EncryptResetPasswordObject = {
|
||||
email,
|
||||
createdAt: Date.now(),
|
||||
};
|
||||
|
||||
const encryptStr = encrypt({
|
||||
data: EJSON.stringify(encryptObject) as string,
|
||||
encryptionKey,
|
||||
encryptionSalt,
|
||||
});
|
||||
|
||||
const defaultUrlOrigin = `https://datasquirel.com`;
|
||||
let urlOrigin = process.env.DSQL_HOST || defaultUrlOrigin;
|
||||
|
||||
const url = `${defaultUrlOrigin}`;
|
||||
}
|
||||
+77
@@ -0,0 +1,77 @@
|
||||
import { DSQL_MYSQL_user_databases_Type } from "../../../../types";
|
||||
import grabDbFullName from "../../../../utils/grab-db-full-name";
|
||||
import varDatabaseDbHandler from "../../../backend/varDatabaseDbHandler";
|
||||
|
||||
type Return = {
|
||||
success: boolean;
|
||||
msg?: string;
|
||||
error?: string;
|
||||
};
|
||||
|
||||
type Param = {
|
||||
key?: string;
|
||||
database: string;
|
||||
email: string;
|
||||
encryptionKey?: string;
|
||||
encryptionSalt?: string;
|
||||
useLocal?: boolean;
|
||||
debug?: boolean;
|
||||
apiUserID?: string | number;
|
||||
dbUserId?: string | number;
|
||||
};
|
||||
|
||||
/**
|
||||
* # API Login
|
||||
*/
|
||||
export default async function apiSendResetPasswordLink({
|
||||
database,
|
||||
email,
|
||||
apiUserID,
|
||||
dbUserId,
|
||||
debug,
|
||||
encryptionKey,
|
||||
encryptionSalt,
|
||||
key,
|
||||
useLocal,
|
||||
}: Param): Promise<Return> {
|
||||
const dbFullName = grabDbFullName({ dbName: database, userId: dbUserId });
|
||||
|
||||
/**
|
||||
* Check input validity
|
||||
*
|
||||
* @description Check input validity
|
||||
*/
|
||||
if (email?.match(/ /)) {
|
||||
return {
|
||||
success: false,
|
||||
msg: "Invalid Email/Password format",
|
||||
};
|
||||
}
|
||||
|
||||
let foundUser = await varDatabaseDbHandler({
|
||||
queryString: `SELECT * FROM ${dbFullName}.users WHERE email = ? OR username = ?`,
|
||||
queryValuesArray: [email, email],
|
||||
database: dbFullName,
|
||||
useLocal,
|
||||
debug,
|
||||
});
|
||||
|
||||
if (debug) {
|
||||
console.log("apiSendResetPassword:foundUser:", foundUser);
|
||||
}
|
||||
|
||||
const targetUser = foundUser?.[0] as
|
||||
| DSQL_MYSQL_user_databases_Type
|
||||
| undefined;
|
||||
|
||||
if (!targetUser)
|
||||
return {
|
||||
success: false,
|
||||
msg: "No user found",
|
||||
};
|
||||
|
||||
return { success: true };
|
||||
}
|
||||
|
||||
export type SendResetPasswordParam = Param;
|
||||
export type SendResetPasswordReturn = Return;
|
||||
@@ -1,5 +1,7 @@
|
||||
import fs from "fs";
|
||||
import serverError from "./serverError";
|
||||
import mysql from "serverless-mysql";
|
||||
import grabDSQLConnection from "../../utils/grab-dsql-connection";
|
||||
|
||||
/**
|
||||
* # Main DB Handler Function
|
||||
@@ -12,6 +14,8 @@ export default async function dbHandler(...args: any[]) {
|
||||
"utf8"
|
||||
);
|
||||
|
||||
const CONNECTION = grabDSQLConnection();
|
||||
|
||||
let results;
|
||||
|
||||
/**
|
||||
@@ -20,10 +24,8 @@ export default async function dbHandler(...args: any[]) {
|
||||
* @description Fetch data from db if no cache
|
||||
*/
|
||||
try {
|
||||
const connection = global.DSQL_DB_CONN;
|
||||
|
||||
results = await new Promise((resolve, reject) => {
|
||||
connection.query(
|
||||
CONNECTION.query(
|
||||
...args,
|
||||
(error: any, result: any, fields: any) => {
|
||||
if (error) {
|
||||
@@ -34,8 +36,6 @@ export default async function dbHandler(...args: any[]) {
|
||||
}
|
||||
);
|
||||
});
|
||||
|
||||
await connection.end();
|
||||
} catch (error: any) {
|
||||
fs.appendFileSync(
|
||||
"./.tmp/dbErrorLogs.txt",
|
||||
@@ -49,6 +49,8 @@ export default async function dbHandler(...args: any[]) {
|
||||
component: "dbHandler",
|
||||
message: error.message,
|
||||
});
|
||||
} finally {
|
||||
await CONNECTION?.end();
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
import parseDbResults from "./parseDbResults";
|
||||
import serverError from "./serverError";
|
||||
import DB_HANDLER from "../../utils/backend/global-db/DB_HANDLER";
|
||||
import DSQL_USER_DB_HANDLER from "../../utils/backend/global-db/DSQL_USER_DB_HANDLER";
|
||||
import LOCAL_DB_HANDLER from "../../utils/backend/global-db/LOCAL_DB_HANDLER";
|
||||
import grabDSQLConnection from "../../utils/grab-dsql-connection";
|
||||
import connDbHandler from "../../utils/db/conn-db-handler";
|
||||
|
||||
type Param = {
|
||||
queryString: string;
|
||||
@@ -10,6 +9,7 @@ type Param = {
|
||||
database?: string;
|
||||
tableSchema?: import("../../types").DSQL_TableSchemaType;
|
||||
useLocal?: boolean;
|
||||
debug?: boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -21,66 +21,27 @@ export default async function varDatabaseDbHandler({
|
||||
database,
|
||||
tableSchema,
|
||||
useLocal,
|
||||
debug,
|
||||
}: Param): Promise<any> {
|
||||
/**
|
||||
* Declare variables
|
||||
*
|
||||
* @description Declare "results" variable
|
||||
*/
|
||||
const isMaster = useLocal
|
||||
? true
|
||||
: database?.match(/^datasquirel$/)
|
||||
? true
|
||||
: false;
|
||||
let CONNECTION = grabDSQLConnection({ fa: true });
|
||||
if (useLocal) CONNECTION = grabDSQLConnection({ local: true });
|
||||
if (database?.match(/^datasquirel$/)) CONNECTION = grabDSQLConnection();
|
||||
|
||||
const FINAL_DB_HANDLER: any = useLocal
|
||||
? LOCAL_DB_HANDLER
|
||||
: isMaster
|
||||
? DB_HANDLER
|
||||
: DSQL_USER_DB_HANDLER;
|
||||
if (debug) {
|
||||
console.log(`varDatabaseDbHandler:query:`, queryString);
|
||||
console.log(`varDatabaseDbHandler:values:`, queryValuesArray);
|
||||
}
|
||||
|
||||
let results;
|
||||
let results = await connDbHandler(
|
||||
CONNECTION,
|
||||
queryString,
|
||||
queryValuesArray
|
||||
);
|
||||
|
||||
/**
|
||||
* Fetch from db
|
||||
*
|
||||
* @description Fetch data from db if no cache
|
||||
*/
|
||||
try {
|
||||
if (
|
||||
queryString &&
|
||||
queryValuesArray &&
|
||||
Array.isArray(queryValuesArray) &&
|
||||
queryValuesArray[0]
|
||||
) {
|
||||
results = isMaster
|
||||
? await FINAL_DB_HANDLER(queryString, queryValuesArray)
|
||||
: await FINAL_DB_HANDLER({
|
||||
paradigm: "Full Access",
|
||||
queryString,
|
||||
queryValues: queryValuesArray,
|
||||
});
|
||||
} else {
|
||||
results = isMaster
|
||||
? await FINAL_DB_HANDLER(queryString)
|
||||
: await FINAL_DB_HANDLER({
|
||||
paradigm: "Full Access",
|
||||
queryString,
|
||||
});
|
||||
}
|
||||
} catch (error: any) {
|
||||
console.log(`varDatabaseDbHandler Error: ${error.message}`);
|
||||
serverError({
|
||||
component: "varDatabaseDbHandler/lines-29-32",
|
||||
message: error.message,
|
||||
});
|
||||
if (debug) {
|
||||
console.log(`varDatabaseDbHandler:results:`, results);
|
||||
}
|
||||
|
||||
/**
|
||||
* Return results
|
||||
*
|
||||
* @description Return results add to cache if "req" param is passed
|
||||
*/
|
||||
if (results && tableSchema) {
|
||||
try {
|
||||
const unparsedResults = results;
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
import { scryptSync, createDecipheriv } from "crypto";
|
||||
import { Buffer } from "buffer";
|
||||
import grabKeys from "../../utils/grab-keys";
|
||||
|
||||
type Param = {
|
||||
encryptedString: string;
|
||||
@@ -22,28 +23,26 @@ export default function decrypt({
|
||||
return encryptedString;
|
||||
}
|
||||
|
||||
const finalEncryptionKey =
|
||||
encryptionKey || process.env.DSQL_ENCRYPTION_PASSWORD;
|
||||
const finalEncryptionSalt =
|
||||
encryptionSalt || process.env.DSQL_ENCRYPTION_SALT;
|
||||
const finalKeyLen = process.env.DSQL_ENCRYPTION_KEY_LENGTH
|
||||
? Number(process.env.DSQL_ENCRYPTION_KEY_LENGTH)
|
||||
: 24;
|
||||
const {
|
||||
key: encrptKey,
|
||||
salt,
|
||||
keyLen,
|
||||
algorithm,
|
||||
bufferAllocSize,
|
||||
} = grabKeys({ encryptionKey });
|
||||
|
||||
if (!finalEncryptionKey?.match(/.{8,}/)) {
|
||||
if (!encrptKey?.match(/.{8,}/)) {
|
||||
console.log("Decrption key is invalid");
|
||||
return encryptedString;
|
||||
}
|
||||
|
||||
if (!finalEncryptionSalt?.match(/.{8,}/)) {
|
||||
if (!salt?.match(/.{8,}/)) {
|
||||
console.log("Decrption salt is invalid");
|
||||
return encryptedString;
|
||||
}
|
||||
|
||||
const algorithm = "aes-192-cbc";
|
||||
|
||||
let key = scryptSync(finalEncryptionKey, finalEncryptionSalt, finalKeyLen);
|
||||
let iv = Buffer.alloc(16, 0);
|
||||
let key = scryptSync(encrptKey, salt, keyLen);
|
||||
let iv = Buffer.alloc(bufferAllocSize, 0);
|
||||
|
||||
const decipher = createDecipheriv(algorithm, key, iv);
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
import { scryptSync, createCipheriv } from "crypto";
|
||||
import { Buffer } from "buffer";
|
||||
import grabKeys from "../../utils/grab-keys";
|
||||
|
||||
type Param = {
|
||||
data: string;
|
||||
@@ -22,36 +23,35 @@ export default function encrypt({
|
||||
return data;
|
||||
}
|
||||
|
||||
const finalEncryptionKey =
|
||||
encryptionKey || process.env.DSQL_ENCRYPTION_PASSWORD;
|
||||
const finalEncryptionSalt =
|
||||
encryptionSalt || process.env.DSQL_ENCRYPTION_SALT;
|
||||
const finalKeyLen = process.env.DSQL_ENCRYPTION_KEY_LENGTH
|
||||
? Number(process.env.DSQL_ENCRYPTION_KEY_LENGTH)
|
||||
: 24;
|
||||
const {
|
||||
key: encrptKey,
|
||||
salt,
|
||||
keyLen,
|
||||
algorithm,
|
||||
bufferAllocSize,
|
||||
} = grabKeys({ encryptionKey });
|
||||
|
||||
if (!finalEncryptionKey?.match(/.{8,}/)) {
|
||||
if (!encrptKey?.match(/.{8,}/)) {
|
||||
console.log("Encryption key is invalid");
|
||||
return data;
|
||||
}
|
||||
if (!finalEncryptionSalt?.match(/.{8,}/)) {
|
||||
if (!salt?.match(/.{8,}/)) {
|
||||
console.log("Encryption salt is invalid");
|
||||
return data;
|
||||
}
|
||||
|
||||
const algorithm = "aes-192-cbc";
|
||||
const password = finalEncryptionKey;
|
||||
const password = encrptKey;
|
||||
|
||||
let key = scryptSync(password, salt, keyLen);
|
||||
let iv = Buffer.alloc(bufferAllocSize, 0);
|
||||
|
||||
let key = scryptSync(password, finalEncryptionSalt, finalKeyLen);
|
||||
let iv = Buffer.alloc(16, 0);
|
||||
// @ts-ignore
|
||||
const cipher = createCipheriv(algorithm, key, iv);
|
||||
|
||||
try {
|
||||
let encrypted = cipher.update(data, "utf8", "hex");
|
||||
encrypted += cipher.final("hex");
|
||||
return encrypted;
|
||||
} catch (/** @type {*} */ error: any) {
|
||||
} catch (error: any) {
|
||||
console.log("Error in encrypting =>", error.message);
|
||||
return data;
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { createHmac } from "crypto";
|
||||
import grabKeys from "../../utils/grab-keys";
|
||||
|
||||
type Param = {
|
||||
password: string;
|
||||
@@ -12,14 +13,13 @@ export default function hashPassword({
|
||||
password,
|
||||
encryptionKey,
|
||||
}: Param): string {
|
||||
const finalEncryptionKey =
|
||||
encryptionKey || process.env.DSQL_ENCRYPTION_PASSWORD;
|
||||
const { key } = grabKeys({ encryptionKey });
|
||||
|
||||
if (!finalEncryptionKey?.match(/.{8,}/)) {
|
||||
if (!key?.match(/.{8,}/)) {
|
||||
throw new Error("Encryption key is invalid");
|
||||
}
|
||||
|
||||
const hmac = createHmac("sha512", finalEncryptionKey);
|
||||
const hmac = createHmac("sha512", key);
|
||||
hmac.update(password);
|
||||
let hashed = hmac.digest("base64");
|
||||
return hashed;
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
require("dotenv").config({ path: "./../.env" });
|
||||
import mysql from "serverless-mysql";
|
||||
import grabDbSSL from "../utils/backend/grabDbSSL";
|
||||
import grabDSQLConnection from "../utils/grab-dsql-connection";
|
||||
|
||||
/**
|
||||
* # Main DB Handler Function
|
||||
@@ -14,17 +14,17 @@ import grabDbSSL from "../utils/backend/grabDbSSL";
|
||||
* @returns {Promise<object|null>}
|
||||
*/
|
||||
(async () => {
|
||||
const connection = global.DSQL_DB_CONN;
|
||||
const CONNECTION = grabDSQLConnection();
|
||||
|
||||
try {
|
||||
const result = await connection.query(
|
||||
const result = await CONNECTION.query(
|
||||
"SELECT id,first_name,last_name FROM users LIMIT 3"
|
||||
);
|
||||
console.log("Connection Query Success =>", result);
|
||||
} catch (error: any) {
|
||||
console.log("Connection query ERROR =>", error.message);
|
||||
} finally {
|
||||
connection.end();
|
||||
CONNECTION?.end();
|
||||
process.exit();
|
||||
}
|
||||
})();
|
||||
|
||||
@@ -1,17 +1,5 @@
|
||||
require("dotenv").config({ path: "./.env" });
|
||||
import grabDbSSL from "../utils/backend/grabDbSSL";
|
||||
import mysql from "serverless-mysql";
|
||||
|
||||
const connection = mysql({
|
||||
config: {
|
||||
host: process.env.DSQL_DB_HOST,
|
||||
user: process.env.DB_USER,
|
||||
password: process.env.DB_PASS,
|
||||
// database: process.env.DSQL_DB_NAME,
|
||||
charset: "utf8mb4",
|
||||
ssl: grabDbSSL(),
|
||||
},
|
||||
});
|
||||
import grabDSQLConnection from "../utils/grab-dsql-connection";
|
||||
|
||||
/**
|
||||
* # Main DB Handler Function
|
||||
@@ -25,13 +13,15 @@ const connection = mysql({
|
||||
* @returns {Promise<object|null>}
|
||||
*/
|
||||
(async () => {
|
||||
const CONNECTION = grabDSQLConnection({ noDb: true });
|
||||
|
||||
/**
|
||||
* Switch Database
|
||||
*
|
||||
* @description If a database is provided, switch to it
|
||||
*/
|
||||
try {
|
||||
const result = await connection.query("SHOW DATABASES");
|
||||
const result = await CONNECTION.query("SHOW DATABASES");
|
||||
|
||||
const parsedResults = JSON.parse(JSON.stringify(result));
|
||||
|
||||
@@ -39,7 +29,7 @@ const connection = mysql({
|
||||
} catch (error: any) {
|
||||
console.log("Connection query ERROR =>", error.message);
|
||||
} finally {
|
||||
connection.end();
|
||||
CONNECTION?.end();
|
||||
process.exit();
|
||||
}
|
||||
})();
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
require("dotenv").config({ path: "./../.env" });
|
||||
import grabDbSSL from "../utils/backend/grabDbSSL";
|
||||
import mysql from "serverless-mysql";
|
||||
import grabDSQLConnection from "../utils/grab-dsql-connection";
|
||||
|
||||
/**
|
||||
* # Main DB Handler Function
|
||||
@@ -14,10 +14,10 @@ import mysql from "serverless-mysql";
|
||||
* @returns {Promise<object|null>}
|
||||
*/
|
||||
(async () => {
|
||||
const connection = global.DSQL_DB_CONN;
|
||||
const CONNECTION = grabDSQLConnection();
|
||||
|
||||
try {
|
||||
const result = await connection.query(
|
||||
const result = await CONNECTION.query(
|
||||
"SELECT user,host,ssl_type FROM mysql.user"
|
||||
);
|
||||
const parsedResults = JSON.parse(JSON.stringify(result));
|
||||
@@ -39,7 +39,7 @@ import mysql from "serverless-mysql";
|
||||
continue;
|
||||
}
|
||||
|
||||
const addUserSSL = await connection.query(
|
||||
const addUserSSL = await CONNECTION.query(
|
||||
`ALTER USER '${User}'@'${Host}'`
|
||||
);
|
||||
|
||||
@@ -48,7 +48,7 @@ import mysql from "serverless-mysql";
|
||||
} catch (error: any) {
|
||||
console.log("Connection query ERROR =>", error.message);
|
||||
} finally {
|
||||
connection.end();
|
||||
CONNECTION.end();
|
||||
process.exit();
|
||||
}
|
||||
})();
|
||||
|
||||
@@ -3,6 +3,7 @@ import path from "path";
|
||||
|
||||
import mysql from "serverless-mysql";
|
||||
import grabDbSSL from "../../utils/backend/grabDbSSL";
|
||||
import grabDSQLConnection from "../../utils/grab-dsql-connection";
|
||||
|
||||
type Param = {
|
||||
query: string;
|
||||
@@ -17,15 +18,15 @@ export default async function dbHandler({
|
||||
query,
|
||||
values,
|
||||
}: Param): Promise<any[] | object | null> {
|
||||
let connection = global.DSQL_DB_CONN;
|
||||
const CONNECTION = grabDSQLConnection();
|
||||
|
||||
let results;
|
||||
|
||||
try {
|
||||
if (query && values) {
|
||||
results = await connection.query(query, values);
|
||||
results = await CONNECTION.query(query, values);
|
||||
} else {
|
||||
results = await connection.query(query);
|
||||
results = await CONNECTION.query(query);
|
||||
}
|
||||
} catch (/** @type {any} */ error: any) {
|
||||
if (process.env.FIRST_RUN) {
|
||||
@@ -34,7 +35,7 @@ export default async function dbHandler({
|
||||
|
||||
console.log("ERROR in dbHandler =>", error.message);
|
||||
console.log(error);
|
||||
console.log(connection.config());
|
||||
console.log(CONNECTION.config());
|
||||
|
||||
fs.appendFileSync(
|
||||
path.resolve(__dirname, "../.tmp/dbErrorLogs.txt"),
|
||||
@@ -43,7 +44,7 @@ export default async function dbHandler({
|
||||
);
|
||||
results = null;
|
||||
} finally {
|
||||
await connection?.end();
|
||||
await CONNECTION?.end();
|
||||
}
|
||||
|
||||
if (results) {
|
||||
|
||||
@@ -158,6 +158,7 @@ export interface PackageUserLoginRequestBody {
|
||||
social?: boolean;
|
||||
dbSchema?: DSQL_DatabaseSchemaType;
|
||||
skipPassword?: boolean;
|
||||
dbUserId: string | number;
|
||||
}
|
||||
|
||||
export interface PackageUserLoginLocalBody {
|
||||
@@ -1208,6 +1209,8 @@ export type APILoginFunctionParams = {
|
||||
skipPassword?: boolean;
|
||||
social?: boolean;
|
||||
useLocal?: boolean;
|
||||
dbUserId?: number | string;
|
||||
debug?: boolean;
|
||||
};
|
||||
export type APILoginFunctionReturn = {
|
||||
success: boolean;
|
||||
|
||||
@@ -1,9 +1,12 @@
|
||||
import mysql from "serverless-mysql";
|
||||
import grabDSQLConnection from "../../grab-dsql-connection";
|
||||
|
||||
/**
|
||||
* # DSQL user read-only DB handler
|
||||
* @requires DSQL_DB_CONN - Gobal Variable for Datasquirel Database
|
||||
*/
|
||||
export default async function DB_HANDLER(...args: any[]) {
|
||||
const CONNECTION = global.DSQL_DB_CONN;
|
||||
const CONNECTION = grabDSQLConnection();
|
||||
|
||||
try {
|
||||
if (!CONNECTION)
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import connDbHandler from "../../db/conn-db-handler";
|
||||
import grabDSQLConnection from "../../grab-dsql-connection";
|
||||
|
||||
type Param = {
|
||||
paradigm: "Full Access" | "FA" | "Read Only";
|
||||
@@ -14,122 +15,17 @@ export default async function DSQL_USER_DB_HANDLER({
|
||||
queryString,
|
||||
queryValues,
|
||||
}: Param) {
|
||||
const CONNECTION =
|
||||
paradigm == "Read Only"
|
||||
? grabDSQLConnection({ ro: true })
|
||||
: grabDSQLConnection({ fa: true });
|
||||
|
||||
try {
|
||||
switch (paradigm) {
|
||||
case "Read Only":
|
||||
return await connDbHandler(
|
||||
global.DSQL_READ_ONLY_DB_CONN,
|
||||
queryString,
|
||||
queryValues
|
||||
);
|
||||
|
||||
case "Full Access":
|
||||
return await connDbHandler(
|
||||
global.DSQL_FULL_ACCESS_DB_CONN,
|
||||
queryString,
|
||||
queryValues
|
||||
);
|
||||
|
||||
case "FA":
|
||||
return await connDbHandler(
|
||||
global.DSQL_FULL_ACCESS_DB_CONN,
|
||||
queryString,
|
||||
queryValues
|
||||
);
|
||||
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
return await connDbHandler(CONNECTION, queryString, queryValues);
|
||||
} catch (error: any) {
|
||||
console.log(`DSQL_USER_DB_HANDLER Error: ${error.message}`);
|
||||
return null;
|
||||
} finally {
|
||||
CONNECTION?.end();
|
||||
}
|
||||
|
||||
// try {
|
||||
// return new Promise((resolve, reject) => {
|
||||
// const fullAccess = paradigm?.match(/full.access|^fa$/i)
|
||||
// ? true
|
||||
// : false;
|
||||
|
||||
// try {
|
||||
// if (fullAccess) {
|
||||
// DSQL_USER = mysql({
|
||||
// config: {
|
||||
// host: process.env.DSQL_DB_HOST,
|
||||
// user: process.env.DSQL_DB_FULL_ACCESS_USERNAME,
|
||||
// password: process.env.DSQL_DB_FULL_ACCESS_PASSWORD,
|
||||
// database: database,
|
||||
// ssl: grabDbSSL(),
|
||||
// },
|
||||
// });
|
||||
// } else {
|
||||
// DSQL_USER = mysql({
|
||||
// config: {
|
||||
// host: process.env.DSQL_DB_HOST,
|
||||
// user: process.env.DSQL_DB_READ_ONLY_USERNAME,
|
||||
// password: process.env.DSQL_DB_READ_ONLY_PASSWORD,
|
||||
// database: database,
|
||||
// ssl: grabDbSSL(),
|
||||
// },
|
||||
// });
|
||||
// }
|
||||
|
||||
// /**
|
||||
// * ### Run query Function
|
||||
// * @param {any} results
|
||||
// */
|
||||
// function runQuery(results: any) {
|
||||
// DSQL_USER.end();
|
||||
// resolve(JSON.parse(JSON.stringify(results)));
|
||||
// }
|
||||
|
||||
// /**
|
||||
// * ### Query Error
|
||||
// * @param {any} err
|
||||
// */
|
||||
// function queryError(err: any) {
|
||||
// DSQL_USER.end();
|
||||
// resolve({
|
||||
// error: err.message,
|
||||
// queryStringGenerated: queryString,
|
||||
// queryValuesGenerated: queryValues,
|
||||
// sql: err.sql,
|
||||
// });
|
||||
// }
|
||||
|
||||
// if (
|
||||
// queryValues &&
|
||||
// Array.isArray(queryValues) &&
|
||||
// queryValues[0]
|
||||
// ) {
|
||||
// DSQL_USER.query(queryString, queryValues)
|
||||
// .then(runQuery)
|
||||
// .catch(queryError);
|
||||
// } else {
|
||||
// DSQL_USER.query(queryString)
|
||||
// .then(runQuery)
|
||||
// .catch(queryError);
|
||||
// }
|
||||
|
||||
// ////////////////////////////////////////
|
||||
// } catch (/** @type {any} */ error: any) {
|
||||
// ////////////////////////////////////////
|
||||
|
||||
// fs.appendFileSync(
|
||||
// "./.tmp/dbErrorLogs.txt",
|
||||
// error.message + "\n" + Date() + "\n\n\n",
|
||||
// "utf8"
|
||||
// );
|
||||
|
||||
// resolve({
|
||||
// error: error.message,
|
||||
// });
|
||||
// }
|
||||
// });
|
||||
// } catch (/** @type {any} */ error: any) {
|
||||
// return {
|
||||
// success: false,
|
||||
// error: error.message,
|
||||
// };
|
||||
// }
|
||||
}
|
||||
|
||||
@@ -1,45 +1,24 @@
|
||||
import mysql from "serverless-mysql";
|
||||
import grabDbSSL from "../grabDbSSL";
|
||||
import grabDSQLConnection from "../../grab-dsql-connection";
|
||||
|
||||
/**
|
||||
* # DSQL user read-only DB handler
|
||||
*/
|
||||
export default async function LOCAL_DB_HANDLER(...args: any[]) {
|
||||
const MASTER = mysql({
|
||||
config: {
|
||||
host: process.env.DSQL_DB_HOST,
|
||||
user: process.env.DSQL_DB_USERNAME,
|
||||
password: process.env.DSQL_DB_PASSWORD,
|
||||
database: process.env.DSQL_DB_NAME,
|
||||
port: process.env.DSQL_DB_PORT
|
||||
? Number(process.env.DSQL_DB_PORT)
|
||||
: undefined,
|
||||
charset: "utf8mb4",
|
||||
ssl: grabDbSSL(),
|
||||
},
|
||||
onConnect: () => {
|
||||
console.log("Connection Successful!");
|
||||
},
|
||||
onConnectError: (/** @type {any} */ err: any) => {
|
||||
console.log("Connection Error", err.message);
|
||||
},
|
||||
onError: (/** @type {any} */ err: any) => {
|
||||
console.log("Client Error", err.message);
|
||||
},
|
||||
});
|
||||
const MASTER = grabDSQLConnection();
|
||||
|
||||
console.log("Querying ...");
|
||||
|
||||
try {
|
||||
const results = await MASTER.query(...args);
|
||||
await MASTER.end();
|
||||
|
||||
return JSON.parse(JSON.stringify(results));
|
||||
} catch (/** @type {any} */ error: any) {
|
||||
} catch (error: any) {
|
||||
console.log("DB Error =>", error.message);
|
||||
return {
|
||||
success: false,
|
||||
error: error.message,
|
||||
};
|
||||
} finally {
|
||||
await MASTER?.end();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,21 +1,22 @@
|
||||
import mysql from "serverless-mysql";
|
||||
import grabDbSSL from "../grabDbSSL";
|
||||
import grabDSQLConnection from "../../grab-dsql-connection";
|
||||
|
||||
/**
|
||||
* # DSQL user read-only DB handler
|
||||
*/
|
||||
export default function NO_DB_HANDLER(...args: any[]) {
|
||||
const NO_DB = global.DSQL_DB_CONN;
|
||||
const CONNECTION = grabDSQLConnection();
|
||||
|
||||
try {
|
||||
return new Promise((resolve, reject) => {
|
||||
NO_DB.query(...args)
|
||||
CONNECTION.query(...args)
|
||||
.then((results) => {
|
||||
NO_DB.end();
|
||||
CONNECTION.end();
|
||||
resolve(JSON.parse(JSON.stringify(results)));
|
||||
})
|
||||
.catch((err) => {
|
||||
NO_DB.end();
|
||||
CONNECTION.end();
|
||||
resolve({
|
||||
error: err.message,
|
||||
sql: err.sql,
|
||||
@@ -27,5 +28,7 @@ export default function NO_DB_HANDLER(...args: any[]) {
|
||||
success: false,
|
||||
error: error.message,
|
||||
};
|
||||
} finally {
|
||||
CONNECTION?.end();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,18 +1,20 @@
|
||||
import grabDSQLConnection from "../../grab-dsql-connection";
|
||||
|
||||
/**
|
||||
* # Root DB handler
|
||||
*/
|
||||
export default function ROOT_DB_HANDLER(...args: any[]) {
|
||||
const NO_DB = global.DSQL_DB_CONN;
|
||||
const CONNECTION = grabDSQLConnection();
|
||||
|
||||
try {
|
||||
return new Promise((resolve, reject) => {
|
||||
NO_DB.query(...args)
|
||||
CONNECTION.query(...args)
|
||||
.then((results) => {
|
||||
NO_DB.end();
|
||||
CONNECTION.end();
|
||||
resolve(JSON.parse(JSON.stringify(results)));
|
||||
})
|
||||
.catch((err) => {
|
||||
NO_DB.end();
|
||||
CONNECTION.end();
|
||||
resolve({
|
||||
error: err.message,
|
||||
sql: err.sql,
|
||||
@@ -24,5 +26,7 @@ export default function ROOT_DB_HANDLER(...args: any[]) {
|
||||
success: false,
|
||||
error: error.message,
|
||||
};
|
||||
} finally {
|
||||
CONNECTION?.end();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
type Param = {
|
||||
dbName: string;
|
||||
userId?: string | number;
|
||||
};
|
||||
|
||||
/**
|
||||
* # Grab Database Full Name
|
||||
*/
|
||||
export default function grabDbFullName({ dbName, userId }: Param): string {
|
||||
const sanitizedName = dbName.replace(/[^a-z0-9\_]/g, "");
|
||||
const cleanedDbName = sanitizedName.replace(/datasquirel_user_\d+_/, "");
|
||||
|
||||
if (!userId) return cleanedDbName;
|
||||
|
||||
const dbNamePrefix = `datasquirel_user_${userId}_`;
|
||||
|
||||
return dbNamePrefix + cleanedDbName;
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
import mysql, { ServerlessMysql } from "serverless-mysql";
|
||||
|
||||
type Param = {
|
||||
/**
|
||||
* Read Only?
|
||||
*/
|
||||
ro?: boolean;
|
||||
/**
|
||||
* Full Access?
|
||||
*/
|
||||
fa?: boolean;
|
||||
/**
|
||||
* No Database Connection
|
||||
*/
|
||||
noDb?: boolean;
|
||||
/**
|
||||
* Is this a local connection?
|
||||
*/
|
||||
local?: boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
* # Grab General CONNECTION for DSQL
|
||||
*/
|
||||
export default function grabDSQLConnection(param?: Param): ServerlessMysql {
|
||||
if (param?.ro) {
|
||||
return (
|
||||
DSQL_READ_ONLY_DB_CONN ||
|
||||
mysql({
|
||||
config: {
|
||||
host: process.env.DSQL_DB_HOST,
|
||||
user: process.env.DSQL_DB_READ_ONLY_USERNAME,
|
||||
password: process.env.DSQL_DB_READ_ONLY_PASSWORD,
|
||||
port: process.env.DSQL_DB_PORT
|
||||
? Number(process.env.DSQL_DB_PORT)
|
||||
: undefined,
|
||||
charset: "utf8mb4",
|
||||
},
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
if (param?.fa) {
|
||||
return (
|
||||
global.DSQL_FULL_ACCESS_DB_CONN ||
|
||||
mysql({
|
||||
config: {
|
||||
host: process.env.DSQL_DB_HOST,
|
||||
user: process.env.DSQL_DB_FULL_ACCESS_USERNAME,
|
||||
password: process.env.DSQL_DB_FULL_ACCESS_PASSWORD,
|
||||
port: process.env.DSQL_DB_PORT
|
||||
? Number(process.env.DSQL_DB_PORT)
|
||||
: undefined,
|
||||
charset: "utf8mb4",
|
||||
},
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
global.DSQL_DB_CONN ||
|
||||
mysql({
|
||||
config: {
|
||||
host: process.env.DSQL_DB_HOST,
|
||||
user: process.env.DSQL_DB_USERNAME,
|
||||
password: process.env.DSQL_DB_PASSWORD,
|
||||
database: param?.noDb ? undefined : process.env.DSQL_DB_NAME,
|
||||
port: process.env.DSQL_DB_PORT
|
||||
? Number(process.env.DSQL_DB_PORT)
|
||||
: undefined,
|
||||
charset: "utf8mb4",
|
||||
},
|
||||
})
|
||||
);
|
||||
}
|
||||
@@ -10,10 +10,14 @@ type GrabHostNamesReturn = {
|
||||
user_id: string | number;
|
||||
};
|
||||
|
||||
type Param = {
|
||||
userId?: string | number;
|
||||
};
|
||||
|
||||
/**
|
||||
* # Grab Names For Query
|
||||
*/
|
||||
export default function grabHostNames(): GrabHostNamesReturn {
|
||||
export default function grabHostNames(param?: Param): GrabHostNamesReturn {
|
||||
const scheme = process.env.DSQL_HTTP_SCHEME;
|
||||
const localHost = process.env.DSQL_LOCAL_HOST;
|
||||
const localHostPort = process.env.DSQL_LOCAL_HOST_PORT;
|
||||
@@ -28,6 +32,6 @@ export default function grabHostNames(): GrabHostNamesReturn {
|
||||
host: remoteHost || localHost || "datasquirel.com",
|
||||
port: remoteHostPort || localHostPort || 443,
|
||||
scheme: scheme?.match(/^http$/i) ? http : https,
|
||||
user_id: String(process.env.DSQL_API_USER_ID || 0),
|
||||
user_id: param?.userId || String(process.env.DSQL_API_USER_ID || 0),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
import numberfy from "./numberfy";
|
||||
|
||||
export type GrabEncryptionKeysParam = {
|
||||
encryptionKey?: string;
|
||||
encryptionSalt?: string;
|
||||
apiKey?: string;
|
||||
algorithm?: string;
|
||||
bufferAllocSize?: number;
|
||||
};
|
||||
|
||||
/**
|
||||
* # Grab Encryption Keys
|
||||
* @description Grab Required Encryption Keys
|
||||
*/
|
||||
export default function grabKeys(param?: GrabEncryptionKeysParam) {
|
||||
return {
|
||||
key: param?.encryptionKey || process.env.DSQL_ENCRYPTION_PASSWORD,
|
||||
keyLen: process.env.DSQL_ENCRYPTION_KEY_LENGTH
|
||||
? Number(process.env.DSQL_ENCRYPTION_KEY_LENGTH)
|
||||
: 24,
|
||||
salt: param?.encryptionSalt || process.env.DSQL_ENCRYPTION_SALT,
|
||||
apiKey: param?.apiKey || process.env.DSQL_API_KEY,
|
||||
algorithm:
|
||||
param?.algorithm ||
|
||||
process.env.DSQL_ENCRYPTION_ALGORITHM ||
|
||||
"aes-192-cbc",
|
||||
bufferAllocSize:
|
||||
param?.bufferAllocSize ||
|
||||
(process.env.DSQL_ENCRYPTION_BUFFER_ALLOCATION_SIZE
|
||||
? numberfy(process.env.DSQL_ENCRYPTION_BUFFER_ALLOCATION_SIZE)
|
||||
: undefined) ||
|
||||
16,
|
||||
};
|
||||
}
|
||||
@@ -7,7 +7,7 @@
|
||||
* numberfy("123.456", 0) // 123
|
||||
* numberfy("123.456", 3) // 123.456
|
||||
*/
|
||||
export default function numberfy(num: any, decimals: number): number {
|
||||
export default function numberfy(num: any, decimals?: number): number {
|
||||
try {
|
||||
const numberfiedNum = Number(num);
|
||||
if (typeof numberfiedNum !== "number") return 0;
|
||||
|
||||
Reference in New Issue
Block a user