Updates
This commit is contained in:
+24
-27
@@ -1,30 +1,30 @@
|
||||
// @ts-check
|
||||
|
||||
const _ = require("lodash");
|
||||
const serverError = require("../../backend/serverError");
|
||||
const runQuery = require("../../backend/db/runQuery");
|
||||
import _ from "lodash";
|
||||
import serverError from "../../backend/serverError";
|
||||
import runQuery from "../../backend/db/runQuery";
|
||||
import { DSQL_TableSchemaType, GetReturn } from "../../../types";
|
||||
|
||||
type Param = {
|
||||
query: string;
|
||||
queryValues?: (string | number)[];
|
||||
dbFullName: string;
|
||||
tableName?: string;
|
||||
dbSchema?: import("../../../types").DSQL_DatabaseSchemaType;
|
||||
useLocal?: boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
* # Get Function FOr API
|
||||
*
|
||||
* @param {object} params
|
||||
* @param {string} params.query
|
||||
* @param {(string|number)[]} [params.queryValues]
|
||||
* @param {string} params.dbFullName
|
||||
* @param {string} [params.tableName]
|
||||
* @param {import("../../../types").DSQL_DatabaseSchemaType} [params.dbSchema]
|
||||
* @param {boolean} [params.useLocal]
|
||||
*
|
||||
* @returns {Promise<import("../../../types").GetReturn>}
|
||||
*/
|
||||
module.exports = async function apiGet({
|
||||
export default async function apiGet({
|
||||
query,
|
||||
dbFullName,
|
||||
queryValues,
|
||||
tableName,
|
||||
dbSchema,
|
||||
useLocal,
|
||||
}) {
|
||||
}: Param): Promise<import("../../../types").GetReturn> {
|
||||
if (
|
||||
typeof query == "string" &&
|
||||
query.match(/^alter|^delete|information_schema|databases|^create/i)
|
||||
@@ -32,11 +32,6 @@ module.exports = async function apiGet({
|
||||
return { success: false, msg: "Wrong Input." };
|
||||
}
|
||||
|
||||
/**
|
||||
* Create new user folder and file
|
||||
*
|
||||
* @description Create new user folder and file
|
||||
*/
|
||||
let results;
|
||||
|
||||
try {
|
||||
@@ -50,8 +45,7 @@ module.exports = async function apiGet({
|
||||
local: useLocal,
|
||||
});
|
||||
|
||||
/** @type {import("../../../types").DSQL_TableSchemaType | undefined} */
|
||||
let tableSchema;
|
||||
let tableSchema: DSQL_TableSchemaType | undefined;
|
||||
|
||||
if (dbSchema) {
|
||||
const targetTable = dbSchema.tables.find(
|
||||
@@ -76,20 +70,23 @@ module.exports = async function apiGet({
|
||||
|
||||
results = result;
|
||||
|
||||
/** @type {import("../../../types").GetReturn} */
|
||||
const resObject = {
|
||||
const resObject: GetReturn = {
|
||||
success: true,
|
||||
payload: results,
|
||||
schema: tableName && tableSchema ? tableSchema : undefined,
|
||||
};
|
||||
|
||||
return resObject;
|
||||
} catch (/** @type {any} */ error) {
|
||||
} catch (error: any) {
|
||||
serverError({
|
||||
component: "/api/query/get/lines-85-94",
|
||||
message: error.message,
|
||||
});
|
||||
|
||||
return { success: false, payload: null, error: error.message };
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
error: error.message,
|
||||
};
|
||||
}
|
||||
};
|
||||
}
|
||||
+21
-22
@@ -1,30 +1,28 @@
|
||||
// @ts-check
|
||||
import _ from "lodash";
|
||||
import serverError from "../../backend/serverError";
|
||||
import runQuery from "../../backend/db/runQuery";
|
||||
import { DSQL_DatabaseSchemaType, PostReturn } from "../../../types";
|
||||
|
||||
const _ = require("lodash");
|
||||
const serverError = require("../../backend/serverError");
|
||||
const runQuery = require("../../backend/db/runQuery");
|
||||
type Param = {
|
||||
query: any;
|
||||
queryValues?: (string | number)[];
|
||||
dbFullName: string;
|
||||
tableName?: string;
|
||||
dbSchema?: DSQL_DatabaseSchemaType;
|
||||
useLocal?: boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
* # Post Function For API
|
||||
*
|
||||
* @param {object} params
|
||||
* @param {any} params.query
|
||||
* @param {(string|number)[]} [params.queryValues]
|
||||
* @param {string} params.dbFullName
|
||||
* @param {string} [params.tableName]
|
||||
* @param {import("../../../types").DSQL_DatabaseSchemaType} [params.dbSchema]
|
||||
* @param {boolean} [params.useLocal]
|
||||
*
|
||||
* @returns {Promise<import("../../../types").PostReturn>}
|
||||
*/
|
||||
module.exports = async function apiPost({
|
||||
export default async function apiPost({
|
||||
query,
|
||||
dbFullName,
|
||||
queryValues,
|
||||
tableName,
|
||||
dbSchema,
|
||||
useLocal,
|
||||
}) {
|
||||
}: Param): Promise<PostReturn> {
|
||||
if (typeof query === "string" && query?.match(/^create |^alter |^drop /i)) {
|
||||
return { success: false, msg: "Wrong Input" };
|
||||
}
|
||||
@@ -37,7 +35,7 @@ module.exports = async function apiPost({
|
||||
}
|
||||
|
||||
/** @type {any} */
|
||||
let results;
|
||||
let results: any;
|
||||
|
||||
/**
|
||||
* Create new user folder and file
|
||||
@@ -59,7 +57,9 @@ module.exports = async function apiPost({
|
||||
if (error) throw error;
|
||||
|
||||
/** @type {import("../../../types").DSQL_TableSchemaType | undefined} */
|
||||
let tableSchema;
|
||||
let tableSchema:
|
||||
| import("../../../types").DSQL_TableSchemaType
|
||||
| undefined;
|
||||
|
||||
if (dbSchema) {
|
||||
const targetTable = dbSchema.tables.find(
|
||||
@@ -76,6 +76,7 @@ module.exports = async function apiPost({
|
||||
delete clonedTargetTable.updateData;
|
||||
delete clonedTargetTable.tableNameOld;
|
||||
delete clonedTargetTable.indexes;
|
||||
|
||||
tableSchema = clonedTargetTable;
|
||||
}
|
||||
}
|
||||
@@ -86,9 +87,7 @@ module.exports = async function apiPost({
|
||||
error: error,
|
||||
schema: tableName && tableSchema ? tableSchema : undefined,
|
||||
};
|
||||
|
||||
////////////////////////////////////////
|
||||
} catch (/** @type {any} */ error) {
|
||||
} catch (error: any) {
|
||||
serverError({
|
||||
component: "/api/query/post/lines-132-142",
|
||||
message: error.message,
|
||||
@@ -100,4 +99,4 @@ module.exports = async function apiPost({
|
||||
error: error.message,
|
||||
};
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -1,128 +0,0 @@
|
||||
// @ts-check
|
||||
|
||||
/**
|
||||
* ==============================================================================
|
||||
* Imports
|
||||
* ==============================================================================
|
||||
*/
|
||||
|
||||
const DB_HANDLER = require("../../../utils/backend/global-db/DB_HANDLER");
|
||||
const handleNodemailer = require("../../backend/handleNodemailer");
|
||||
const serverError = require("../../backend/serverError");
|
||||
const hashPassword = require("../../dsql/hashPassword");
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
/**
|
||||
* ==============================================================================
|
||||
* Main Function
|
||||
* ==============================================================================
|
||||
* @param {object} params - parameters object
|
||||
* @param {any} params.body
|
||||
* @param {import("../../../types").UserType} params.usertype
|
||||
*/
|
||||
module.exports = async function facebookLogin({ usertype, body }) {
|
||||
try {
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
|
||||
const foundUser = await DB_HANDLER(
|
||||
`SELECT * FROM users WHERE email='${body.facebookUserEmail}' AND social_login='1'`
|
||||
);
|
||||
|
||||
if (foundUser && foundUser[0]) {
|
||||
return foundUser[0];
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
|
||||
let socialHashedPassword = hashPassword({
|
||||
password: body.facebookUserId,
|
||||
});
|
||||
|
||||
let newUser = await DB_HANDLER(`INSERT INTO ${usertype} (
|
||||
first_name,
|
||||
last_name,
|
||||
social_platform,
|
||||
social_name,
|
||||
email,
|
||||
image,
|
||||
image_thumbnail,
|
||||
password,
|
||||
verification_status,
|
||||
social_login,
|
||||
social_id,
|
||||
terms_agreement,
|
||||
date_created,
|
||||
date_code
|
||||
) VALUES (
|
||||
'${body.facebookUserFirstName}',
|
||||
'${body.facebookUserLastName}',
|
||||
'facebook',
|
||||
'facebook_${
|
||||
body.facebookUserEmail
|
||||
? body.facebookUserEmail.replace(/@.*/, "")
|
||||
: body.facebookUserFirstName.toLowerCase()
|
||||
}',
|
||||
'${body.facebookUserEmail}',
|
||||
'${body.facebookUserImage}',
|
||||
'${body.facebookUserImage}',
|
||||
'${socialHashedPassword}',
|
||||
'1',
|
||||
'1',
|
||||
'${body.facebookUserId}',
|
||||
'1',
|
||||
'${Date()}',
|
||||
'${Date.now()}'
|
||||
)`);
|
||||
|
||||
const newFoundUser = await DB_HANDLER(
|
||||
`SELECT * FROM ${usertype} WHERE id='${newUser.insertId}'`
|
||||
);
|
||||
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
|
||||
/**
|
||||
* Send email notifications to admin
|
||||
*
|
||||
* @description Send verification email to newly created agent
|
||||
*/
|
||||
// handleNodemailer({
|
||||
// to: "",
|
||||
// subject: "New Registered Buyer",
|
||||
// text: "We have a new registered Buyer from facebook",
|
||||
// html: `
|
||||
// <h2>${newFoundUser[0].first_name} ${newFoundUser[0].last_name} just registered from facebook.</h2>
|
||||
// <p>We have a new buyer registration</p>
|
||||
// <div>Name: <b>${newFoundUser[0].first_name} ${newFoundUser[0].last_name}</b></div>
|
||||
// <div>Email: <b>${newFoundUser[0].email}</b></div>
|
||||
// <div>Site: <b>${process.env.DSQL_DB_HOST}</b></div>
|
||||
// `,
|
||||
// }).catch((error) => {
|
||||
// console.log(
|
||||
// "error in mail notification for new Facebook user =>",
|
||||
// error.message
|
||||
// );
|
||||
// });
|
||||
} catch (/** @type {any} */ error) {
|
||||
serverError({
|
||||
component: "functions/backend/facebookLogin",
|
||||
message: error.message,
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
isFacebookAuthValid: false,
|
||||
newFoundUser: null,
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,80 @@
|
||||
import { UserType } from "../../../types";
|
||||
import DB_HANDLER from "../../../utils/backend/global-db/DB_HANDLER";
|
||||
import handleNodemailer from "../../backend/handleNodemailer";
|
||||
import serverError from "../../backend/serverError";
|
||||
import hashPassword from "../../dsql/hashPassword";
|
||||
|
||||
/**
|
||||
* # Facebook Login
|
||||
*/
|
||||
export default async function facebookLogin({
|
||||
usertype,
|
||||
body,
|
||||
}: {
|
||||
body: any;
|
||||
usertype: UserType;
|
||||
}) {
|
||||
try {
|
||||
const foundUser = await DB_HANDLER(
|
||||
`SELECT * FROM users WHERE email='${body.facebookUserEmail}' AND social_login='1'`
|
||||
);
|
||||
|
||||
if (foundUser && foundUser[0]) {
|
||||
return foundUser[0];
|
||||
}
|
||||
|
||||
let socialHashedPassword = hashPassword({
|
||||
password: body.facebookUserId,
|
||||
});
|
||||
|
||||
let newUser = await DB_HANDLER(`INSERT INTO ${usertype} (
|
||||
first_name,
|
||||
last_name,
|
||||
social_platform,
|
||||
social_name,
|
||||
email,
|
||||
image,
|
||||
image_thumbnail,
|
||||
password,
|
||||
verification_status,
|
||||
social_login,
|
||||
social_id,
|
||||
terms_agreement,
|
||||
date_created,
|
||||
date_code
|
||||
) VALUES (
|
||||
'${body.facebookUserFirstName}',
|
||||
'${body.facebookUserLastName}',
|
||||
'facebook',
|
||||
'facebook_${
|
||||
body.facebookUserEmail
|
||||
? body.facebookUserEmail.replace(/@.*/, "")
|
||||
: body.facebookUserFirstName.toLowerCase()
|
||||
}',
|
||||
'${body.facebookUserEmail}',
|
||||
'${body.facebookUserImage}',
|
||||
'${body.facebookUserImage}',
|
||||
'${socialHashedPassword}',
|
||||
'1',
|
||||
'1',
|
||||
'${body.facebookUserId}',
|
||||
'1',
|
||||
'${Date()}',
|
||||
'${Date.now()}'
|
||||
)`);
|
||||
|
||||
const newFoundUser = await DB_HANDLER(
|
||||
`SELECT * FROM ${usertype} WHERE id='${newUser.insertId}'`
|
||||
);
|
||||
} catch (/** @type {any} */ error: any) {
|
||||
serverError({
|
||||
component: "functions/backend/facebookLogin",
|
||||
message: error.message,
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
isFacebookAuthValid: false,
|
||||
newFoundUser: null,
|
||||
};
|
||||
}
|
||||
@@ -1,160 +0,0 @@
|
||||
// @ts-check
|
||||
|
||||
const DB_HANDLER = require("../../../utils/backend/global-db/DB_HANDLER");
|
||||
const httpsRequest = require("../../backend/httpsRequest");
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
/**
|
||||
*
|
||||
* @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|undefined>}
|
||||
*/
|
||||
module.exports = async function githubLogin({ code, clientId, clientSecret }) {
|
||||
/** @type {GithubUserPayload | undefined} */
|
||||
let gitHubUser;
|
||||
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
|
||||
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.DSQL_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": "*",
|
||||
},
|
||||
scheme: "https",
|
||||
});
|
||||
|
||||
// `https://github.com/login/oauth/access_token?client_id=${process.env.DSQL_GITHUB_ID}&client_secret=${process.env.DSQL_GITHUB_SECRET}&code=${code}`,
|
||||
// body: JSON.stringify({
|
||||
// client_id: process.env.DSQL_GITHUB_ID,
|
||||
// client_secret: process.env.DSQL_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": "*",
|
||||
},
|
||||
scheme: "https",
|
||||
});
|
||||
|
||||
gitHubUser = JSON.parse(userDataResponse);
|
||||
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
|
||||
if (!gitHubUser?.email && gitHubUser) {
|
||||
const existingGithubUser = await DB_HANDLER(
|
||||
`SELECT email FROM users WHERE social_login='1' AND social_platform='github' AND social_id='${gitHubUser.id}'`
|
||||
);
|
||||
|
||||
if (existingGithubUser && existingGithubUser[0]) {
|
||||
gitHubUser.email = existingGithubUser[0].email;
|
||||
}
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
} catch (/** @type {any} */ 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;
|
||||
};
|
||||
@@ -0,0 +1,102 @@
|
||||
import DB_HANDLER from "../../../utils/backend/global-db/DB_HANDLER";
|
||||
import httpsRequest from "../../backend/httpsRequest";
|
||||
|
||||
export interface GithubUserPayload {
|
||||
login: string;
|
||||
id: number;
|
||||
node_id: string;
|
||||
avatar_url: string;
|
||||
gravatar_id: string;
|
||||
url: string;
|
||||
html_url: string;
|
||||
followers_url: string;
|
||||
following_url: string;
|
||||
gists_url: string;
|
||||
starred_url: string;
|
||||
subscriptions_url: string;
|
||||
organizations_url: string;
|
||||
repos_url: string;
|
||||
received_events_url: string;
|
||||
type: string;
|
||||
site_admin: boolean;
|
||||
name: string;
|
||||
company: string;
|
||||
blog: string;
|
||||
location: string;
|
||||
email: string;
|
||||
hireable: string;
|
||||
bio: string;
|
||||
twitter_username: string;
|
||||
public_repos: number;
|
||||
public_gists: number;
|
||||
followers: number;
|
||||
following: number;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
type Param = {
|
||||
code: string;
|
||||
clientId: string;
|
||||
clientSecret: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* # Login/signup a github user
|
||||
*/
|
||||
export default async function githubLogin({
|
||||
code,
|
||||
clientId,
|
||||
clientSecret,
|
||||
}: Param): Promise<GithubUserPayload | null | undefined> {
|
||||
let gitHubUser: GithubUserPayload | undefined;
|
||||
|
||||
try {
|
||||
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": "*",
|
||||
},
|
||||
scheme: "https",
|
||||
});
|
||||
|
||||
const accessTokenObject = JSON.parse(response as string);
|
||||
|
||||
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": "*",
|
||||
},
|
||||
scheme: "https",
|
||||
});
|
||||
|
||||
gitHubUser = JSON.parse(userDataResponse as string);
|
||||
|
||||
if (!gitHubUser?.email && gitHubUser) {
|
||||
const existingGithubUser = await DB_HANDLER(
|
||||
`SELECT email FROM users WHERE social_login='1' AND social_platform='github' AND social_id='${gitHubUser.id}'`
|
||||
);
|
||||
|
||||
if (existingGithubUser && existingGithubUser[0]) {
|
||||
gitHubUser.email = existingGithubUser[0].email;
|
||||
}
|
||||
}
|
||||
} catch (/** @type {any} */ error: any) {
|
||||
console.log(
|
||||
"ERROR in githubLogin.ts backend function =>",
|
||||
error.message
|
||||
);
|
||||
}
|
||||
|
||||
return gitHubUser;
|
||||
}
|
||||
+20
-49
@@ -1,44 +1,23 @@
|
||||
// @ts-check
|
||||
import fs from "fs";
|
||||
import { OAuth2Client } from "google-auth-library";
|
||||
import serverError from "../../backend/serverError";
|
||||
import DB_HANDLER from "../../../utils/backend/global-db/DB_HANDLER";
|
||||
import hashPassword from "../../dsql/hashPassword";
|
||||
|
||||
type Param = {
|
||||
usertype: string;
|
||||
foundUser: any;
|
||||
isSocialValidated: boolean;
|
||||
isUserValid: boolean;
|
||||
reqBody: any;
|
||||
serverRes: any;
|
||||
loginFailureReason: any;
|
||||
};
|
||||
|
||||
/**
|
||||
* ==============================================================================
|
||||
* Imports
|
||||
* ==============================================================================
|
||||
* # Google Login
|
||||
*/
|
||||
const fs = require("fs");
|
||||
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
|
||||
const { OAuth2Client } = require("google-auth-library");
|
||||
|
||||
const serverError = require("../../backend/serverError");
|
||||
const { ServerResponse } = require("http");
|
||||
const DB_HANDLER = require("../../../utils/backend/global-db/DB_HANDLER");
|
||||
const hashPassword = require("../../dsql/hashPassword");
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
/**
|
||||
* ==============================================================================
|
||||
* Main Function
|
||||
* ==============================================================================
|
||||
* @param {Object} params
|
||||
* @param {string} params.usertype
|
||||
* @param {any} params.foundUser
|
||||
* @param {boolean} params.isSocialValidated
|
||||
* @param {boolean} params.isUserValid
|
||||
* @param {any} params.reqBody
|
||||
* @param {any} params.serverRes
|
||||
* @param {any} params.loginFailureReason
|
||||
*/
|
||||
module.exports = async function googleLogin({
|
||||
export default async function googleLogin({
|
||||
usertype,
|
||||
foundUser,
|
||||
isSocialValidated,
|
||||
@@ -46,7 +25,7 @@ module.exports = async function googleLogin({
|
||||
reqBody,
|
||||
serverRes,
|
||||
loginFailureReason,
|
||||
}) {
|
||||
}: Param) {
|
||||
const client = new OAuth2Client(
|
||||
process.env.NEXT_PUBLIC_DSQL_GOOGLE_CLIENT_ID
|
||||
);
|
||||
@@ -156,11 +135,7 @@ module.exports = async function googleLogin({
|
||||
newFoundUser = await DB_HANDLER(
|
||||
`SELECT * FROM ${usertype} WHERE id='${newUser.insertId}'`
|
||||
);
|
||||
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
} catch (/** @type {any} */ error) {
|
||||
} catch (error: any) {
|
||||
serverError({
|
||||
component: "googleLogin",
|
||||
message: error.message,
|
||||
@@ -172,9 +147,5 @@ module.exports = async function googleLogin({
|
||||
isSocialValidated = false;
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
|
||||
return { isGoogleAuthValid: isGoogleAuthValid, newFoundUser: newFoundUser };
|
||||
};
|
||||
}
|
||||
+26
-25
@@ -1,18 +1,20 @@
|
||||
// @ts-check
|
||||
|
||||
const fs = require("fs");
|
||||
const handleNodemailer = require("../../backend/handleNodemailer");
|
||||
const path = require("path");
|
||||
const addMariadbUser = require("../../backend/addMariadbUser");
|
||||
const varDatabaseDbHandler = require("../../backend/varDatabaseDbHandler");
|
||||
const encrypt = require("../../dsql/encrypt");
|
||||
const addDbEntry = require("../../backend/db/addDbEntry");
|
||||
const loginSocialUser = require("./loginSocialUser");
|
||||
import fs from "fs";
|
||||
import handleNodemailer from "../../backend/handleNodemailer";
|
||||
import path from "path";
|
||||
import addMariadbUser from "../../backend/addMariadbUser";
|
||||
import varDatabaseDbHandler from "../../backend/varDatabaseDbHandler";
|
||||
import encrypt from "../../dsql/encrypt";
|
||||
import addDbEntry from "../../backend/db/addDbEntry";
|
||||
import loginSocialUser from "./loginSocialUser";
|
||||
import {
|
||||
APILoginFunctionReturn,
|
||||
HandleSocialDbFunctionParams,
|
||||
} from "../../../types";
|
||||
|
||||
/**
|
||||
* @type {import("../../../types").HandleSocialDbFunction}
|
||||
* # Handle Social DB
|
||||
*/
|
||||
module.exports = async function handleSocialDb({
|
||||
export default async function handleSocialDb({
|
||||
database,
|
||||
social_id,
|
||||
email,
|
||||
@@ -22,9 +24,9 @@ module.exports = async function handleSocialDb({
|
||||
supEmail,
|
||||
additionalFields,
|
||||
useLocal,
|
||||
}) {
|
||||
}: HandleSocialDbFunctionParams): Promise<APILoginFunctionReturn> {
|
||||
try {
|
||||
const existingSocialIdUserQuery = `SELECT * FROM users WHERE social_id = ? AND social_login='1' AND social_platform = ? `;
|
||||
const existingSocialIdUserQuery = `SELECT * FROM datasquirel.users WHERE social_id = ? AND social_login='1' AND social_platform = ? `;
|
||||
const existingSocialIdUserValues = [
|
||||
social_id.toString(),
|
||||
social_platform,
|
||||
@@ -58,7 +60,7 @@ module.exports = async function handleSocialDb({
|
||||
};
|
||||
}
|
||||
|
||||
const existingEmailOnlyQuery = `SELECT * FROM users WHERE email='${finalEmail}'`;
|
||||
const existingEmailOnlyQuery = `SELECT * FROM datasquirel.users WHERE email='${finalEmail}'`;
|
||||
|
||||
let existingEmailOnly = await varDatabaseDbHandler({
|
||||
database: database ? database : "datasquirel",
|
||||
@@ -74,7 +76,7 @@ module.exports = async function handleSocialDb({
|
||||
};
|
||||
}
|
||||
|
||||
const foundUserQuery = `SELECT * FROM users WHERE email=? AND social_login='1' AND social_platform=? AND social_id=?`;
|
||||
const foundUserQuery = `SELECT * FROM datasquirel.users WHERE email=? AND social_login='1' AND social_platform=? AND social_id=?`;
|
||||
const foundUserQueryValues = [finalEmail, social_platform, social_id];
|
||||
|
||||
const foundUser = await varDatabaseDbHandler({
|
||||
@@ -99,8 +101,7 @@ module.exports = async function handleSocialDb({
|
||||
data: social_id.toString(),
|
||||
});
|
||||
|
||||
/** @type {any} */
|
||||
const data = {
|
||||
const data: { [k: string]: any } = {
|
||||
social_login: "1",
|
||||
verification_status: supEmail ? "0" : "1",
|
||||
password: socialHashedPassword,
|
||||
@@ -133,7 +134,7 @@ module.exports = async function handleSocialDb({
|
||||
await addMariadbUser({ userId: newUser.insertId, useLocal });
|
||||
}
|
||||
|
||||
const newUserQueriedQuery = `SELECT * FROM users WHERE id='${newUser.insertId}'`;
|
||||
const newUserQueriedQuery = `SELECT * FROM datasquirel.users WHERE id='${newUser.insertId}'`;
|
||||
|
||||
const newUserQueried = await varDatabaseDbHandler({
|
||||
database: database ? database : "datasquirel",
|
||||
@@ -173,7 +174,7 @@ module.exports = async function handleSocialDb({
|
||||
)
|
||||
.replace(/{{host}}/, process.env.DSQL_HOST || "")
|
||||
.replace(/{{token}}/, generatedToken || ""),
|
||||
}).then((mail) => {});
|
||||
}).then(() => {});
|
||||
}
|
||||
|
||||
const STATIC_ROOT = process.env.DSQL_STATIC_SERVER_DIR;
|
||||
@@ -220,19 +221,19 @@ module.exports = async function handleSocialDb({
|
||||
});
|
||||
} else {
|
||||
console.log(
|
||||
"Social User Failed to insert in 'handleSocialDb.js' backend function =>",
|
||||
"Social User Failed to insert in 'handleSocialDb.ts' backend function =>",
|
||||
newUser
|
||||
);
|
||||
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: "Social User Failed to insert in 'handleSocialDb.js' backend function",
|
||||
msg: "Social User Failed to insert in 'handleSocialDb.ts' backend function",
|
||||
};
|
||||
}
|
||||
} catch (/** @type {any} */ error) {
|
||||
} catch (error: any) {
|
||||
console.log(
|
||||
"ERROR in 'handleSocialDb.js' backend function =>",
|
||||
"ERROR in 'handleSocialDb.ts' backend function =>",
|
||||
error.message
|
||||
);
|
||||
|
||||
@@ -242,4 +243,4 @@ module.exports = async function handleSocialDb({
|
||||
msg: error.message,
|
||||
};
|
||||
}
|
||||
};
|
||||
}
|
||||
+24
-31
@@ -1,47 +1,42 @@
|
||||
// @ts-check
|
||||
import addAdminUserOnLogin from "../../backend/addAdminUserOnLogin";
|
||||
import varDatabaseDbHandler from "../../backend/varDatabaseDbHandler";
|
||||
import { APILoginFunctionReturn } from "../../../types";
|
||||
|
||||
const addAdminUserOnLogin = require("../../backend/addAdminUserOnLogin");
|
||||
const { ServerResponse } = require("http");
|
||||
const varDatabaseDbHandler = require("../../backend/varDatabaseDbHandler");
|
||||
const encrypt = require("../../dsql/encrypt");
|
||||
const getAuthCookieNames = require("../../backend/cookies/get-auth-cookie-names");
|
||||
type Param = {
|
||||
user: {
|
||||
first_name: string;
|
||||
last_name: string;
|
||||
email: string;
|
||||
social_id: string | number;
|
||||
};
|
||||
social_platform: string;
|
||||
invitation?: any;
|
||||
database?: string;
|
||||
additionalFields?: string[];
|
||||
useLocal?: boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
* 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 {any} [params.invitation] - A query object if user was invited
|
||||
* @param {string} [params.database] - Target Database
|
||||
* @param {string[]} [params.additionalFields] - Additional fields to be added to the user payload
|
||||
* @param {boolean} [params.useLocal]
|
||||
*
|
||||
* @returns {Promise<import("../../../types").APILoginFunctionReturn>}
|
||||
*/
|
||||
async function loginSocialUser({
|
||||
export default async function loginSocialUser({
|
||||
user,
|
||||
social_platform,
|
||||
invitation,
|
||||
database,
|
||||
additionalFields,
|
||||
useLocal,
|
||||
}) {
|
||||
const foundUserQuery = `SELECT * FROM users WHERE email=? AND social_id=? AND social_platform=?`;
|
||||
}: Param): Promise<APILoginFunctionReturn> {
|
||||
const finalDbName = database ? database : "datasquirel";
|
||||
|
||||
const foundUserQuery = `SELECT * FROM \`${finalDbName}\`.\`users\` WHERE email=? AND social_id=? AND social_platform=?`;
|
||||
const foundUserValues = [user.email, user.social_id, social_platform];
|
||||
|
||||
const foundUser = await varDatabaseDbHandler({
|
||||
database: database ? database : "datasquirel",
|
||||
database: finalDbName,
|
||||
queryString: foundUserQuery,
|
||||
queryValuesArray: foundUserValues,
|
||||
useLocal,
|
||||
@@ -59,7 +54,7 @@ async function loginSocialUser({
|
||||
Math.random().toString(36).substring(2);
|
||||
|
||||
/** @type {import("../../../types").DATASQUIREL_LoggedInUser} */
|
||||
let userPayload = {
|
||||
let userPayload: import("../../../types").DATASQUIREL_LoggedInUser = {
|
||||
id: foundUser[0].id,
|
||||
first_name: foundUser[0].first_name,
|
||||
last_name: foundUser[0].last_name,
|
||||
@@ -92,7 +87,7 @@ async function loginSocialUser({
|
||||
}
|
||||
|
||||
/** @type {import("../../../types").APILoginFunctionReturn} */
|
||||
let result = {
|
||||
let result: import("../../../types").APILoginFunctionReturn = {
|
||||
success: true,
|
||||
payload: userPayload,
|
||||
csrf: csrfKey,
|
||||
@@ -100,5 +95,3 @@ async function loginSocialUser({
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
module.exports = loginSocialUser;
|
||||
+16
-15
@@ -1,19 +1,22 @@
|
||||
// @ts-check
|
||||
|
||||
const addUsersTableToDb = require("../../backend/addUsersTableToDb");
|
||||
const addDbEntry = require("../../backend/db/addDbEntry");
|
||||
const updateUsersTableSchema = require("../../backend/updateUsersTableSchema");
|
||||
const varDatabaseDbHandler = require("../../backend/varDatabaseDbHandler");
|
||||
const hashPassword = require("../../dsql/hashPassword");
|
||||
import { APICreateUserFunctionParams } from "../../../types";
|
||||
import addUsersTableToDb from "../../backend/addUsersTableToDb";
|
||||
import addDbEntry from "../../backend/db/addDbEntry";
|
||||
import updateUsersTableSchema from "../../backend/updateUsersTableSchema";
|
||||
import varDatabaseDbHandler from "../../backend/varDatabaseDbHandler";
|
||||
import hashPassword from "../../dsql/hashPassword";
|
||||
|
||||
/** @type {import("../../../types").APICreateUserFunction} */
|
||||
module.exports = async function apiCreateUser({
|
||||
/**
|
||||
* # API Create User
|
||||
*/
|
||||
export default async function apiCreateUser({
|
||||
encryptionKey,
|
||||
payload,
|
||||
database,
|
||||
userId,
|
||||
useLocal,
|
||||
}) {
|
||||
}: APICreateUserFunctionParams) {
|
||||
const dbFullName = database;
|
||||
const API_USER_ID = userId || process.env.DSQL_API_USER_ID;
|
||||
|
||||
@@ -43,7 +46,7 @@ module.exports = async function apiCreateUser({
|
||||
|
||||
payload.password = hashedPassword;
|
||||
|
||||
const fieldsQuery = `SHOW COLUMNS FROM users`;
|
||||
const fieldsQuery = `SHOW COLUMNS FROM ${dbFullName}.users`;
|
||||
|
||||
let fields = await varDatabaseDbHandler({
|
||||
queryString: fieldsQuery,
|
||||
@@ -73,9 +76,7 @@ module.exports = async function apiCreateUser({
|
||||
};
|
||||
}
|
||||
|
||||
const fieldsTitles = fields.map(
|
||||
(/** @type {any} */ fieldObject) => fieldObject.Field
|
||||
);
|
||||
const fieldsTitles = fields.map((fieldObject: any) => fieldObject.Field);
|
||||
|
||||
let invalidField = null;
|
||||
|
||||
@@ -99,7 +100,7 @@ module.exports = async function apiCreateUser({
|
||||
};
|
||||
}
|
||||
|
||||
const existingUserQuery = `SELECT * FROM users WHERE email = ?${
|
||||
const existingUserQuery = `SELECT * FROM ${dbFullName}.users WHERE email = ?${
|
||||
payload.username ? " OR username = ?" : ""
|
||||
}`;
|
||||
const existingUserValues = payload.username
|
||||
@@ -139,7 +140,7 @@ module.exports = async function apiCreateUser({
|
||||
});
|
||||
|
||||
if (addUser?.insertId) {
|
||||
const newlyAddedUserQuery = `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}'`;
|
||||
const newlyAddedUserQuery = `SELECT id,first_name,last_name,email,username,phone,image,image_thumbnail,city,state,country,zip_code,address,verification_status,more_user_data FROM ${dbFullName}.users WHERE id='${addUser.insertId}'`;
|
||||
|
||||
const newlyAddedUser = await varDatabaseDbHandler({
|
||||
queryString: newlyAddedUserQuery,
|
||||
@@ -159,4 +160,4 @@ module.exports = async function apiCreateUser({
|
||||
payload: null,
|
||||
};
|
||||
}
|
||||
};
|
||||
}
|
||||
+12
-14
@@ -1,24 +1,22 @@
|
||||
// @ts-check
|
||||
import deleteDbEntry from "../../backend/db/deleteDbEntry";
|
||||
import varDatabaseDbHandler from "../../backend/varDatabaseDbHandler";
|
||||
|
||||
const deleteDbEntry = require("../../backend/db/deleteDbEntry");
|
||||
const varDatabaseDbHandler = require("../../backend/varDatabaseDbHandler");
|
||||
type Param = {
|
||||
dbFullName: string;
|
||||
deletedUserId: string | number;
|
||||
useLocal?: boolean;
|
||||
};
|
||||
type Return = { success: boolean; result?: any; msg?: string };
|
||||
|
||||
/**
|
||||
* # Update API User Function
|
||||
*
|
||||
* @param {object} params
|
||||
* @param {string} params.dbFullName
|
||||
* @param {string | number} params.deletedUserId
|
||||
* @param {boolean} [params.useLocal]
|
||||
*
|
||||
* @returns {Promise<{ success: boolean, result?: any, msg?: string }>}
|
||||
*/
|
||||
module.exports = async function apiDeleteUser({
|
||||
export default async function apiDeleteUser({
|
||||
dbFullName,
|
||||
deletedUserId,
|
||||
useLocal,
|
||||
}) {
|
||||
const existingUserQuery = `SELECT * FROM users WHERE id = ?`;
|
||||
}: Param): Promise<Return> {
|
||||
const existingUserQuery = `SELECT * FROM ${dbFullName}.users WHERE id = ?`;
|
||||
const existingUserValues = [deletedUserId];
|
||||
|
||||
const existingUser = await varDatabaseDbHandler({
|
||||
@@ -49,4 +47,4 @@ module.exports = async function apiDeleteUser({
|
||||
success: true,
|
||||
result: deleteUser,
|
||||
};
|
||||
};
|
||||
}
|
||||
@@ -1,33 +0,0 @@
|
||||
// @ts-check
|
||||
|
||||
const varDatabaseDbHandler = require("../../backend/varDatabaseDbHandler");
|
||||
|
||||
/** @type {import("../../../types").APIGetUserFunction} */
|
||||
module.exports = async function apiGetUser({
|
||||
fields,
|
||||
dbFullName,
|
||||
userId,
|
||||
useLocal,
|
||||
}) {
|
||||
const query = `SELECT ${fields.join(",")} FROM users WHERE id=?`;
|
||||
const API_USER_ID = userId || process.env.DSQL_API_USER_ID;
|
||||
|
||||
let foundUser = await varDatabaseDbHandler({
|
||||
queryString: query,
|
||||
queryValuesArray: [API_USER_ID],
|
||||
database: dbFullName.replace(/[^a-z0-9_]/g, ""),
|
||||
useLocal,
|
||||
});
|
||||
|
||||
if (!foundUser || !foundUser[0]) {
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
payload: foundUser[0],
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,41 @@
|
||||
import {
|
||||
APIGetUserFunctionParams,
|
||||
GetUserFunctionReturn,
|
||||
} from "../../../types";
|
||||
import varDatabaseDbHandler from "../../backend/varDatabaseDbHandler";
|
||||
|
||||
/**
|
||||
* # API Get User
|
||||
*/
|
||||
export default async function apiGetUser({
|
||||
fields,
|
||||
dbFullName,
|
||||
userId,
|
||||
useLocal,
|
||||
}: APIGetUserFunctionParams): Promise<GetUserFunctionReturn> {
|
||||
const finalDbName = dbFullName.replace(/[^a-z0-9_]/g, "");
|
||||
|
||||
const query = `SELECT ${fields.join(
|
||||
","
|
||||
)} FROM ${finalDbName}.users WHERE id=?`;
|
||||
const API_USER_ID = userId || process.env.DSQL_API_USER_ID;
|
||||
|
||||
let foundUser = await varDatabaseDbHandler({
|
||||
queryString: query,
|
||||
queryValuesArray: [API_USER_ID],
|
||||
database: finalDbName,
|
||||
useLocal,
|
||||
});
|
||||
|
||||
if (!foundUser || !foundUser[0]) {
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
payload: foundUser[0],
|
||||
};
|
||||
}
|
||||
+21
-21
@@ -1,10 +1,15 @@
|
||||
// @ts-check
|
||||
import {
|
||||
APILoginFunctionParams,
|
||||
APILoginFunctionReturn,
|
||||
DATASQUIREL_LoggedInUser,
|
||||
} from "../../../types";
|
||||
import varDatabaseDbHandler from "../../backend/varDatabaseDbHandler";
|
||||
import hashPassword from "../../dsql/hashPassword";
|
||||
|
||||
const varDatabaseDbHandler = require("../../backend/varDatabaseDbHandler");
|
||||
const hashPassword = require("../../dsql/hashPassword");
|
||||
|
||||
/** @type {import("../../../types").APILoginFunction} */
|
||||
module.exports = async function apiLoginUser({
|
||||
/**
|
||||
* # API Login
|
||||
*/
|
||||
export default async function apiLoginUser({
|
||||
encryptionKey,
|
||||
email,
|
||||
username,
|
||||
@@ -18,8 +23,8 @@ module.exports = async function apiLoginUser({
|
||||
skipPassword,
|
||||
social,
|
||||
useLocal,
|
||||
}) {
|
||||
const dbFullName = database;
|
||||
}: APILoginFunctionParams): Promise<APILoginFunctionReturn> {
|
||||
const dbFullName = database.replace(/[^a-z0-9_]/g, "");
|
||||
|
||||
/**
|
||||
* Check input validity
|
||||
@@ -50,9 +55,9 @@ module.exports = async function apiLoginUser({
|
||||
: null;
|
||||
|
||||
let foundUser = await varDatabaseDbHandler({
|
||||
queryString: `SELECT * FROM users WHERE email = ? OR username = ?`,
|
||||
queryString: `SELECT * FROM ${dbFullName}.users WHERE email = ? OR username = ?`,
|
||||
queryValuesArray: [email, username],
|
||||
database: dbFullName.replace(/[^a-z0-9_]/g, ""),
|
||||
database: dbFullName,
|
||||
useLocal,
|
||||
});
|
||||
|
||||
@@ -103,9 +108,9 @@ module.exports = async function apiLoginUser({
|
||||
|
||||
if (isPasswordCorrect && email_login) {
|
||||
const resetTempCode = await varDatabaseDbHandler({
|
||||
queryString: `UPDATE users SET ${email_login_field} = '' WHERE email = ? OR username = ?`,
|
||||
queryString: `UPDATE ${dbFullName}.users SET ${email_login_field} = '' WHERE email = ? OR username = ?`,
|
||||
queryValuesArray: [email, username],
|
||||
database: dbFullName.replace(/[^a-z0-9_]/g, ""),
|
||||
database: dbFullName,
|
||||
useLocal,
|
||||
});
|
||||
}
|
||||
@@ -115,8 +120,7 @@ module.exports = async function apiLoginUser({
|
||||
"-" +
|
||||
Math.random().toString(36).substring(2);
|
||||
|
||||
/** @type {import("../../../types").DATASQUIREL_LoggedInUser} */
|
||||
let userPayload = {
|
||||
let userPayload: DATASQUIREL_LoggedInUser = {
|
||||
id: foundUser[0].id,
|
||||
first_name: foundUser[0].first_name,
|
||||
last_name: foundUser[0].last_name,
|
||||
@@ -135,14 +139,10 @@ module.exports = async function apiLoginUser({
|
||||
date: Date.now(),
|
||||
};
|
||||
|
||||
/** @type {import("../../../types").APILoginFunctionReturn} */
|
||||
const resposeObject = {
|
||||
const resposeObject: APILoginFunctionReturn = {
|
||||
success: true,
|
||||
msg: "Login Successful",
|
||||
payload:
|
||||
/** @type {import("../../../types").DATASQUIREL_LoggedInUser} */ (
|
||||
userPayload
|
||||
),
|
||||
payload: userPayload,
|
||||
userId: foundUser[0].id,
|
||||
csrf: csrfKey,
|
||||
};
|
||||
@@ -158,4 +158,4 @@ module.exports = async function apiLoginUser({
|
||||
}
|
||||
|
||||
return resposeObject;
|
||||
};
|
||||
}
|
||||
+13
-29
@@ -1,39 +1,32 @@
|
||||
// @ts-check
|
||||
import { APILoginFunctionReturn } from "../../../types";
|
||||
import varDatabaseDbHandler from "../../backend/varDatabaseDbHandler";
|
||||
|
||||
const LOCAL_DB_HANDLER = require("../../../utils/backend/global-db/LOCAL_DB_HANDLER");
|
||||
const varDatabaseDbHandler = require("../../backend/varDatabaseDbHandler");
|
||||
const nodemailer = require("nodemailer");
|
||||
type Param = {
|
||||
existingUser: { [s: string]: any };
|
||||
database?: string;
|
||||
additionalFields?: string[];
|
||||
useLocal?: boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
* # Re-authenticate API user
|
||||
* @param {object} param
|
||||
* @param {Object<string, any>} param.existingUser
|
||||
* @param {string} [param.database]
|
||||
* @param {string[]} [param.additionalFields]
|
||||
* @param {boolean} [param.useLocal]
|
||||
*
|
||||
* @returns {Promise<import("../../../types").APILoginFunctionReturn>}
|
||||
*/
|
||||
module.exports = async function apiReauthUser({
|
||||
export default async function apiReauthUser({
|
||||
existingUser,
|
||||
database,
|
||||
additionalFields,
|
||||
useLocal,
|
||||
}) {
|
||||
}: Param): Promise<APILoginFunctionReturn> {
|
||||
let foundUser =
|
||||
existingUser?.id && existingUser.id.toString().match(/./)
|
||||
? await varDatabaseDbHandler({
|
||||
queryString: `SELECT * FROM users WHERE id=?`,
|
||||
queryString: `SELECT * FROM ${database}.users WHERE id=?`,
|
||||
queryValuesArray: [existingUser.id.toString()],
|
||||
database,
|
||||
useLocal,
|
||||
})
|
||||
: null;
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
if (!foundUser || !foundUser[0])
|
||||
return {
|
||||
success: false,
|
||||
@@ -41,17 +34,13 @@ module.exports = async function apiReauthUser({
|
||||
msg: "No user found",
|
||||
};
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
let csrfKey =
|
||||
Math.random().toString(36).substring(2) +
|
||||
"-" +
|
||||
Math.random().toString(36).substring(2);
|
||||
|
||||
/** @type {import("../../../types").DATASQUIREL_LoggedInUser} */
|
||||
let userPayload = {
|
||||
let userPayload: import("../../../types").DATASQUIREL_LoggedInUser = {
|
||||
id: foundUser[0].id,
|
||||
first_name: foundUser[0].first_name,
|
||||
last_name: foundUser[0].last_name,
|
||||
@@ -80,15 +69,10 @@ module.exports = async function apiReauthUser({
|
||||
});
|
||||
}
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
/** ********************* Send Response */
|
||||
return {
|
||||
success: true,
|
||||
msg: "Login Successful",
|
||||
payload: userPayload,
|
||||
csrf: csrfKey,
|
||||
};
|
||||
};
|
||||
}
|
||||
+54
-49
@@ -1,32 +1,30 @@
|
||||
// @ts-check
|
||||
import varDatabaseDbHandler from "../../backend/varDatabaseDbHandler";
|
||||
import nodemailer, { SendMailOptions } from "nodemailer";
|
||||
import http from "http";
|
||||
import getAuthCookieNames from "../../backend/cookies/get-auth-cookie-names";
|
||||
import encrypt from "../../dsql/encrypt";
|
||||
import serializeCookies from "../../../utils/serialize-cookies";
|
||||
import { SendOneTimeCodeEmailResponse } from "../../../types";
|
||||
|
||||
const varDatabaseDbHandler = require("../../backend/varDatabaseDbHandler");
|
||||
const nodemailer = require("nodemailer");
|
||||
const http = require("http");
|
||||
const getAuthCookieNames = require("../../backend/cookies/get-auth-cookie-names");
|
||||
const encrypt = require("../../dsql/encrypt");
|
||||
const serializeCookies = require("../../../utils/serialize-cookies");
|
||||
type Param = {
|
||||
email: string;
|
||||
database: string;
|
||||
email_login_field?: string;
|
||||
mail_domain?: string;
|
||||
mail_port?: number;
|
||||
sender?: string;
|
||||
mail_username?: string;
|
||||
mail_password?: string;
|
||||
html: string;
|
||||
useLocal?: boolean;
|
||||
response?: http.ServerResponse & { [s: string]: any };
|
||||
extraCookies?: import("../../../../package-shared/types").CookieObject[];
|
||||
};
|
||||
|
||||
/**
|
||||
* # Send Email Login Code
|
||||
*
|
||||
* @param {object} param
|
||||
* @param {string} param.email
|
||||
* @param {string} param.database
|
||||
* @param {string} [param.email_login_field]
|
||||
* @param {string} [param.mail_domain]
|
||||
* @param {number} [param.mail_port]
|
||||
* @param {string} [param.sender]
|
||||
* @param {string} [param.mail_username]
|
||||
* @param {string} [param.mail_password]
|
||||
* @param {string} param.html
|
||||
* @param {boolean} [param.useLocal]
|
||||
* @param {http.ServerResponse & Object<string,any>} [param.response]
|
||||
* @param {import("../../../../package-shared/types").CookieObject[]} [param.extraCookies]
|
||||
*
|
||||
* @returns {Promise<import("../../../types").SendOneTimeCodeEmailResponse>}
|
||||
*/
|
||||
module.exports = async function apiSendEmailCode({
|
||||
export default async function apiSendEmailCode({
|
||||
email,
|
||||
database,
|
||||
email_login_field,
|
||||
@@ -39,7 +37,7 @@ module.exports = async function apiSendEmailCode({
|
||||
useLocal,
|
||||
response,
|
||||
extraCookies,
|
||||
}) {
|
||||
}: Param): Promise<SendOneTimeCodeEmailResponse> {
|
||||
if (email?.match(/ /)) {
|
||||
return {
|
||||
success: false,
|
||||
@@ -48,7 +46,7 @@ module.exports = async function apiSendEmailCode({
|
||||
}
|
||||
const createdAt = Date.now();
|
||||
|
||||
const foundUserQuery = `SELECT * FROM users WHERE email = ?`;
|
||||
const foundUserQuery = `SELECT * FROM ${database}.users WHERE email = ?`;
|
||||
const foundUserValues = [email];
|
||||
|
||||
let foundUser = await varDatabaseDbHandler({
|
||||
@@ -83,7 +81,11 @@ module.exports = async function apiSendEmailCode({
|
||||
|
||||
let transporter = nodemailer.createTransport({
|
||||
host: mail_domain || process.env.DSQL_MAIL_HOST,
|
||||
port: mail_port || process.env.DSQL_MAIL_PORT || 465,
|
||||
port: mail_port
|
||||
? mail_port
|
||||
: process.env.DSQL_MAIL_PORT
|
||||
? Number(process.env.DSQL_MAIL_PORT)
|
||||
: 465,
|
||||
secure: true,
|
||||
auth: {
|
||||
user: mail_username || process.env.DSQL_MAIL_EMAIL,
|
||||
@@ -91,7 +93,7 @@ module.exports = async function apiSendEmailCode({
|
||||
},
|
||||
});
|
||||
|
||||
let mailObject = {};
|
||||
let mailObject: SendMailOptions = {};
|
||||
|
||||
mailObject["from"] = `"Datasquirel SSO" <${
|
||||
sender || "support@datasquirel.com"
|
||||
@@ -105,24 +107,25 @@ module.exports = async function apiSendEmailCode({
|
||||
|
||||
if (!info?.accepted) throw new Error("Mail not Sent!");
|
||||
|
||||
const setTempCodeQuery = `UPDATE users SET ${email_login_field} = ? WHERE email = ?`;
|
||||
const setTempCodeQuery = `UPDATE ${database}.users SET ${email_login_field} = ? WHERE email = ?`;
|
||||
const setTempCodeValues = [tempCode + `-${createdAt}`, email];
|
||||
|
||||
let setTempCode = await varDatabaseDbHandler({
|
||||
queryString: setTempCodeQuery,
|
||||
queryValuesArray: setTempCodeValues,
|
||||
database: database,
|
||||
database,
|
||||
useLocal,
|
||||
});
|
||||
|
||||
/** @type {import("../../../types").SendOneTimeCodeEmailResponse} */
|
||||
const resObject = {
|
||||
success: true,
|
||||
code: tempCode,
|
||||
email: email,
|
||||
createdAt,
|
||||
msg: "Success",
|
||||
};
|
||||
const resObject: import("../../../types").SendOneTimeCodeEmailResponse =
|
||||
{
|
||||
success: true,
|
||||
code: tempCode,
|
||||
email: email,
|
||||
createdAt,
|
||||
msg: "Success",
|
||||
};
|
||||
|
||||
if (response) {
|
||||
const cookieKeyNames = getAuthCookieNames();
|
||||
@@ -139,19 +142,21 @@ module.exports = async function apiSendEmailCode({
|
||||
}
|
||||
|
||||
/** @type {import("../../../../package-shared/types").CookieObject} */
|
||||
const oneTimeCookieObject = {
|
||||
name: oneTimeCodeCookieName,
|
||||
value: encryptedPayload,
|
||||
sameSite: "Strict",
|
||||
path: "/",
|
||||
httpOnly: true,
|
||||
secure: true,
|
||||
};
|
||||
const oneTimeCookieObject: import("../../../../package-shared/types").CookieObject =
|
||||
{
|
||||
name: oneTimeCodeCookieName,
|
||||
value: encryptedPayload,
|
||||
sameSite: "Strict",
|
||||
path: "/",
|
||||
httpOnly: true,
|
||||
secure: true,
|
||||
};
|
||||
|
||||
/** @type {import("../../../../package-shared/types").CookieObject[]} */
|
||||
const cookiesObjectArray = extraCookies
|
||||
? [...extraCookies, oneTimeCookieObject]
|
||||
: [oneTimeCookieObject];
|
||||
const cookiesObjectArray: import("../../../../package-shared/types").CookieObject[] =
|
||||
extraCookies
|
||||
? [...extraCookies, oneTimeCookieObject]
|
||||
: [oneTimeCookieObject];
|
||||
|
||||
const serializedCookies = serializeCookies({
|
||||
cookies: cookiesObjectArray,
|
||||
@@ -167,4 +172,4 @@ module.exports = async function apiSendEmailCode({
|
||||
msg: "Invalid Email/Password format",
|
||||
};
|
||||
}
|
||||
};
|
||||
}
|
||||
+19
-18
@@ -1,30 +1,31 @@
|
||||
// @ts-check
|
||||
|
||||
const updateDbEntry = require("../../backend/db/updateDbEntry");
|
||||
const encrypt = require("../../dsql/encrypt");
|
||||
const hashPassword = require("../../dsql/hashPassword");
|
||||
const varDatabaseDbHandler = require("../../backend/varDatabaseDbHandler");
|
||||
import updateDbEntry from "../../backend/db/updateDbEntry";
|
||||
import encrypt from "../../dsql/encrypt";
|
||||
import hashPassword from "../../dsql/hashPassword";
|
||||
import varDatabaseDbHandler from "../../backend/varDatabaseDbHandler";
|
||||
|
||||
type Param = {
|
||||
payload: { [s: string]: any };
|
||||
dbFullName: string;
|
||||
updatedUserId: string | number;
|
||||
useLocal?: boolean;
|
||||
dbSchema?: import("../../../types").DSQL_DatabaseSchemaType;
|
||||
};
|
||||
|
||||
type Return = { success: boolean; payload?: any; msg?: string };
|
||||
|
||||
/**
|
||||
* # Update API User Function
|
||||
*
|
||||
* @param {object} params
|
||||
* @param {Object<string, any>} params.payload
|
||||
* @param {string} params.dbFullName
|
||||
* @param {string | number} params.updatedUserId
|
||||
* @param {boolean} [params.useLocal]
|
||||
* @param {import("../../../types").DSQL_DatabaseSchemaType} [params.dbSchema]
|
||||
*
|
||||
* @returns {Promise<{ success: boolean, payload?: any, msg?: string }>}
|
||||
*/
|
||||
module.exports = async function apiUpdateUser({
|
||||
export default async function apiUpdateUser({
|
||||
payload,
|
||||
dbFullName,
|
||||
updatedUserId,
|
||||
useLocal,
|
||||
dbSchema,
|
||||
}) {
|
||||
const existingUserQuery = `SELECT * FROM users WHERE id = ?`;
|
||||
}: Param): Promise<Return> {
|
||||
const existingUserQuery = `SELECT * FROM ${dbFullName}.users WHERE id = ?`;
|
||||
const existingUserValues = [updatedUserId];
|
||||
|
||||
const existingUser = await varDatabaseDbHandler({
|
||||
@@ -56,7 +57,7 @@ module.exports = async function apiUpdateUser({
|
||||
})();
|
||||
|
||||
/** @type {any} */
|
||||
const finalData = {};
|
||||
const finalData: any = {};
|
||||
|
||||
reqBodyKeys.forEach((key) => {
|
||||
const targetFieldSchema = targetTableSchema?.fields?.find(
|
||||
@@ -95,4 +96,4 @@ module.exports = async function apiUpdateUser({
|
||||
success: true,
|
||||
payload: updateUser,
|
||||
};
|
||||
};
|
||||
}
|
||||
+24
-23
@@ -1,33 +1,30 @@
|
||||
// @ts-check
|
||||
import handleSocialDb from "../../social-login/handleSocialDb";
|
||||
import githubLogin from "../../social-login/githubLogin";
|
||||
import camelJoinedtoCamelSpace from "../../../../utils/camelJoinedtoCamelSpace";
|
||||
import { APILoginFunctionReturn } from "../../../../types";
|
||||
|
||||
const handleSocialDb = require("../../social-login/handleSocialDb");
|
||||
const githubLogin = require("../../social-login/githubLogin");
|
||||
const camelJoinedtoCamelSpace = require("../../../../utils/camelJoinedtoCamelSpace");
|
||||
type Param = {
|
||||
code?: string;
|
||||
clientId?: string;
|
||||
clientSecret?: string;
|
||||
database?: string;
|
||||
additionalFields?: string[];
|
||||
additionalData?: { [s: string]: string | number };
|
||||
email?: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* # Login with Github
|
||||
* @param {object} param
|
||||
* @param {string} [param.code]
|
||||
* @param {string} [param.clientId]
|
||||
* @param {string} [param.clientSecret]
|
||||
* @param {string} [param.database]
|
||||
* @param {string[]} [param.additionalFields]
|
||||
* @param {any} [param.res]
|
||||
* @param {string} [param.email]
|
||||
* @param {string | number} [param.userId]
|
||||
*
|
||||
* @returns {Promise<import("../../../../types").APILoginFunctionReturn>}
|
||||
* # API Login with Github
|
||||
*/
|
||||
module.exports = async function apiGithubLogin({
|
||||
export default async function apiGithubLogin({
|
||||
code,
|
||||
clientId,
|
||||
clientSecret,
|
||||
database,
|
||||
additionalFields,
|
||||
res,
|
||||
email,
|
||||
userId,
|
||||
}) {
|
||||
additionalData,
|
||||
}: Param): Promise<APILoginFunctionReturn> {
|
||||
if (!code || !clientId || !clientSecret || !database) {
|
||||
return {
|
||||
success: false,
|
||||
@@ -73,7 +70,7 @@ module.exports = async function apiGithubLogin({
|
||||
? targetName?.split("-")
|
||||
: [targetName];
|
||||
|
||||
const payload = {
|
||||
let payload = {
|
||||
email: gitHubUser.email,
|
||||
first_name: camelJoinedtoCamelSpace(nameArray[0]),
|
||||
last_name: camelJoinedtoCamelSpace(nameArray[1]),
|
||||
@@ -84,10 +81,14 @@ module.exports = async function apiGithubLogin({
|
||||
username: "github-user-" + socialId,
|
||||
};
|
||||
|
||||
if (additionalData) {
|
||||
payload = { ...payload, ...additionalData };
|
||||
}
|
||||
|
||||
const loggedInGithubUser = await handleSocialDb({
|
||||
database,
|
||||
email: gitHubUser.email,
|
||||
payload: payload,
|
||||
payload,
|
||||
social_platform: "github",
|
||||
social_id: socialId,
|
||||
supEmail: email,
|
||||
@@ -99,4 +100,4 @@ module.exports = async function apiGithubLogin({
|
||||
////////////////////////////////////////////////
|
||||
|
||||
return { ...loggedInGithubUser };
|
||||
};
|
||||
}
|
||||
+46
-35
@@ -1,40 +1,47 @@
|
||||
// @ts-check
|
||||
import https from "https";
|
||||
import handleSocialDb from "../../social-login/handleSocialDb";
|
||||
import EJSON from "../../../../utils/ejson";
|
||||
import {
|
||||
APIGoogleLoginFunctionParams,
|
||||
APILoginFunctionReturn,
|
||||
GoogleOauth2User,
|
||||
} from "../../../../types";
|
||||
|
||||
const https = require("https");
|
||||
const handleSocialDb = require("../../social-login/handleSocialDb");
|
||||
const EJSON = require("../../../../utils/ejson");
|
||||
|
||||
/** @type {import("../../../../types").APIGoogleLoginFunction} */
|
||||
module.exports = async function apiGoogleLogin({
|
||||
/**
|
||||
* # API google login
|
||||
*/
|
||||
export default async function apiGoogleLogin({
|
||||
token,
|
||||
database,
|
||||
additionalFields,
|
||||
}) {
|
||||
additionalData,
|
||||
}: APIGoogleLoginFunctionParams): Promise<APILoginFunctionReturn> {
|
||||
try {
|
||||
/** @type {import("../../../../types").GoogleOauth2User | undefined} */
|
||||
const gUser = await new Promise((resolve, reject) => {
|
||||
https
|
||||
.request(
|
||||
{
|
||||
method: "GET",
|
||||
hostname: "www.googleapis.com",
|
||||
path: "/oauth2/v3/userinfo",
|
||||
headers: {
|
||||
Authorization: `Bearer ${token}`,
|
||||
const gUser: GoogleOauth2User | undefined = await new Promise(
|
||||
(resolve, reject) => {
|
||||
https
|
||||
.request(
|
||||
{
|
||||
method: "GET",
|
||||
hostname: "www.googleapis.com",
|
||||
path: "/oauth2/v3/userinfo",
|
||||
headers: {
|
||||
Authorization: `Bearer ${token}`,
|
||||
},
|
||||
},
|
||||
},
|
||||
(res) => {
|
||||
let data = "";
|
||||
res.on("data", (chunk) => {
|
||||
data += chunk;
|
||||
});
|
||||
res.on("end", () => {
|
||||
resolve(/** @type {any} */ (EJSON.parse(data)));
|
||||
});
|
||||
}
|
||||
)
|
||||
.end();
|
||||
});
|
||||
(res) => {
|
||||
let data = "";
|
||||
res.on("data", (chunk) => {
|
||||
data += chunk;
|
||||
});
|
||||
res.on("end", () => {
|
||||
resolve(EJSON.parse(data) as any);
|
||||
});
|
||||
}
|
||||
)
|
||||
.end();
|
||||
}
|
||||
);
|
||||
|
||||
if (!gUser?.email_verified) throw new Error("No Google User.");
|
||||
|
||||
@@ -59,7 +66,7 @@ module.exports = async function apiGoogleLogin({
|
||||
const { given_name, family_name, email, sub, picture } = gUser;
|
||||
|
||||
/** @type {Object<string, any>} */
|
||||
const payloadObject = {
|
||||
let payloadObject: { [s: string]: any } = {
|
||||
email: email,
|
||||
first_name: given_name,
|
||||
last_name: family_name,
|
||||
@@ -70,6 +77,10 @@ module.exports = async function apiGoogleLogin({
|
||||
username: `google-user-${sub}`,
|
||||
};
|
||||
|
||||
if (additionalData) {
|
||||
payloadObject = { ...payloadObject, ...additionalData };
|
||||
}
|
||||
|
||||
const loggedInGoogleUser = await handleSocialDb({
|
||||
database,
|
||||
email: email || "",
|
||||
@@ -84,8 +95,8 @@ module.exports = async function apiGoogleLogin({
|
||||
////////////////////////////////////////
|
||||
|
||||
return { ...loggedInGoogleUser };
|
||||
} catch (/** @type {any} */ error) {
|
||||
console.log(`apo-google-login.js ERROR: ${error.message}`);
|
||||
} catch (/** @type {any} */ error: any) {
|
||||
console.log(`api-google-login.ts ERROR: ${error.message}`);
|
||||
|
||||
return {
|
||||
success: false,
|
||||
@@ -93,4 +104,4 @@ module.exports = async function apiGoogleLogin({
|
||||
msg: error.message,
|
||||
};
|
||||
}
|
||||
};
|
||||
}
|
||||
+22
-33
@@ -1,9 +1,19 @@
|
||||
// @ts-check
|
||||
import serverError from "./serverError";
|
||||
import DB_HANDLER from "../../utils/backend/global-db/DB_HANDLER";
|
||||
import addDbEntry from "./db/addDbEntry";
|
||||
import LOCAL_DB_HANDLER from "../../utils/backend/global-db/LOCAL_DB_HANDLER";
|
||||
import { DATASQUIREL_LoggedInUser } from "../../types";
|
||||
|
||||
const serverError = require("./serverError");
|
||||
const DB_HANDLER = require("../../utils/backend/global-db/DB_HANDLER");
|
||||
const addDbEntry = require("./db/addDbEntry");
|
||||
const LOCAL_DB_HANDLER = require("../../utils/backend/global-db/LOCAL_DB_HANDLER");
|
||||
type Param = {
|
||||
query: {
|
||||
invite: number;
|
||||
database_access: string;
|
||||
priviledge: string;
|
||||
email: string;
|
||||
};
|
||||
useLocal?: boolean;
|
||||
user: DATASQUIREL_LoggedInUser;
|
||||
};
|
||||
|
||||
/**
|
||||
* Add Admin User on Login
|
||||
@@ -12,21 +22,12 @@ const LOCAL_DB_HANDLER = require("../../utils/backend/global-db/LOCAL_DB_HANDLER
|
||||
* @description this function handles admin users that have been invited by another
|
||||
* admin user. This fires when the invited user has been logged in or a new account
|
||||
* has been created for the invited user
|
||||
*
|
||||
* @param {object} params - parameters object
|
||||
*
|
||||
* @param {object} params.query - query object
|
||||
* @param {number} params.query.invite - Invitation user id
|
||||
* @param {string} params.query.database_access - String containing authorized databases
|
||||
* @param {string} params.query.priviledge - String containing databases priviledges
|
||||
* @param {string} params.query.email - Inviting user email address
|
||||
*
|
||||
* @param {boolean} [params.useLocal]
|
||||
* @param {import("../../types").DATASQUIREL_LoggedInUser} params.user - invited user object
|
||||
*
|
||||
* @returns {Promise<any>} new user auth object payload
|
||||
*/
|
||||
module.exports = async function addAdminUserOnLogin({ query, user, useLocal }) {
|
||||
export default async function addAdminUserOnLogin({
|
||||
query,
|
||||
user,
|
||||
useLocal,
|
||||
}: Param): Promise<any> {
|
||||
try {
|
||||
const finalDbHandler = useLocal ? LOCAL_DB_HANDLER : DB_HANDLER;
|
||||
const { invite, database_access, priviledge, email } = query;
|
||||
@@ -132,23 +133,11 @@ module.exports = async function addAdminUserOnLogin({ query, user, useLocal }) {
|
||||
[invite, email]
|
||||
);
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
} catch (/** @type {any} */ error) {
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
|
||||
} catch (error: any) {
|
||||
serverError({
|
||||
component: "addAdminUserOnLogin",
|
||||
message: error.message,
|
||||
user: user,
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
}
|
||||
+16
-18
@@ -1,24 +1,22 @@
|
||||
// @ts-check
|
||||
import generator from "generate-password";
|
||||
import DB_HANDLER from "../../utils/backend/global-db/DB_HANDLER";
|
||||
import NO_DB_HANDLER from "../../utils/backend/global-db/NO_DB_HANDLER";
|
||||
import addDbEntry from "./db/addDbEntry";
|
||||
import encrypt from "../dsql/encrypt";
|
||||
import LOCAL_DB_HANDLER from "../../utils/backend/global-db/LOCAL_DB_HANDLER";
|
||||
|
||||
const generator = require("generate-password");
|
||||
const DB_HANDLER = require("../../utils/backend/global-db/DB_HANDLER");
|
||||
const NO_DB_HANDLER = require("../../utils/backend/global-db/NO_DB_HANDLER");
|
||||
const addDbEntry = require("./db/addDbEntry");
|
||||
const encrypt = require("../dsql/encrypt");
|
||||
const LOCAL_DB_HANDLER = require("../../utils/backend/global-db/LOCAL_DB_HANDLER");
|
||||
type Param = {
|
||||
userId: number | string;
|
||||
useLocal?: boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
* # Add Mariadb User
|
||||
*
|
||||
* @description this function adds a Mariadb user to the database server
|
||||
*
|
||||
* @param {object} params - parameters object *
|
||||
* @param {number | string} params.userId - invited user object
|
||||
* @param {boolean} [params.useLocal]
|
||||
*
|
||||
* @returns {Promise<any>} new user auth object payload
|
||||
*/
|
||||
module.exports = async function addMariadbUser({ userId, useLocal }) {
|
||||
export default async function addMariadbUser({
|
||||
userId,
|
||||
useLocal,
|
||||
}: Param): Promise<any> {
|
||||
try {
|
||||
const defaultMariadbUserHost = process.env.DSQL_DB_HOST || "127.0.0.1";
|
||||
|
||||
@@ -62,13 +60,13 @@ module.exports = async function addMariadbUser({ userId, useLocal }) {
|
||||
});
|
||||
|
||||
console.log(`User ${userId} SQL credentials successfully added.`);
|
||||
} catch (/** @type {any} */ error) {
|
||||
} catch (/** @type {any} */ error: any) {
|
||||
console.log(
|
||||
`Error in adding SQL user in 'addMariadbUser' function =>`,
|
||||
error.message
|
||||
);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
+22
-28
@@ -1,34 +1,28 @@
|
||||
// @ts-check
|
||||
import serverError from "./serverError";
|
||||
import DB_HANDLER from "../../utils/backend/global-db/DB_HANDLER";
|
||||
import { default as grabUserSchemaData } from "./grabUserSchemaData";
|
||||
import { default as setUserSchemaData } from "./setUserSchemaData";
|
||||
import addDbEntry from "./db/addDbEntry";
|
||||
import createDbFromSchema from "../../shell/createDbFromSchema";
|
||||
import LOCAL_DB_HANDLER from "../../utils/backend/global-db/LOCAL_DB_HANDLER";
|
||||
import grabNewUsersTableSchema from "./grabNewUsersTableSchema";
|
||||
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
const { execSync } = require("child_process");
|
||||
const serverError = require("./serverError");
|
||||
const DB_HANDLER = require("../../utils/backend/global-db/DB_HANDLER");
|
||||
const { default: grabUserSchemaData } = require("./grabUserSchemaData");
|
||||
const { default: setUserSchemaData } = require("./setUserSchemaData");
|
||||
const addDbEntry = require("./db/addDbEntry");
|
||||
const createDbFromSchema = require("../../shell/createDbFromSchema");
|
||||
const LOCAL_DB_HANDLER = require("../../utils/backend/global-db/LOCAL_DB_HANDLER");
|
||||
const grabNewUsersTableSchema = require("./grabNewUsersTableSchema");
|
||||
type Param = {
|
||||
userId: number;
|
||||
database: string;
|
||||
useLocal?: boolean;
|
||||
payload?: { [s: string]: any };
|
||||
};
|
||||
|
||||
/**
|
||||
* # Add User Table to Database
|
||||
*
|
||||
* @param {object} params
|
||||
* @param {number} params.userId - user id
|
||||
* @param {string} params.database
|
||||
* @param {boolean} [params.useLocal]
|
||||
* @param {Object<string, any>} [params.payload] - payload object
|
||||
*
|
||||
* @returns {Promise<any>} new user auth object payload
|
||||
*/
|
||||
module.exports = async function addUsersTableToDb({
|
||||
export default async function addUsersTableToDb({
|
||||
userId,
|
||||
database,
|
||||
useLocal,
|
||||
payload,
|
||||
}) {
|
||||
}: Param): Promise<any> {
|
||||
try {
|
||||
const dbFullName = database;
|
||||
|
||||
@@ -39,7 +33,7 @@ module.exports = async function addUsersTableToDb({
|
||||
if (!userSchemaData) throw new Error("User schema data not found!");
|
||||
|
||||
let targetDatabase = userSchemaData.find(
|
||||
(db) => db.dbFullName === database
|
||||
(db: any) => db.dbFullName === database
|
||||
);
|
||||
|
||||
if (!targetDatabase) {
|
||||
@@ -47,7 +41,7 @@ module.exports = async function addUsersTableToDb({
|
||||
}
|
||||
|
||||
let existingTableIndex = targetDatabase?.tables.findIndex(
|
||||
(table) => table.tableName === "users"
|
||||
(table: any) => table.tableName === "users"
|
||||
);
|
||||
|
||||
if (typeof existingTableIndex == "number" && existingTableIndex > 0) {
|
||||
@@ -59,7 +53,7 @@ module.exports = async function addUsersTableToDb({
|
||||
setUserSchemaData({ schemaData: userSchemaData, userId });
|
||||
|
||||
/** @type {any[] | null} */
|
||||
const targetDb = useLocal
|
||||
const targetDb: any[] | null = useLocal
|
||||
? await LOCAL_DB_HANDLER(
|
||||
`SELECT id FROM user_databases WHERE user_id=? AND db_slug=?`,
|
||||
[userId, database]
|
||||
@@ -90,8 +84,8 @@ module.exports = async function addUsersTableToDb({
|
||||
});
|
||||
|
||||
return `Done!`;
|
||||
} catch (/** @type {any} */ error) {
|
||||
console.log(`addUsersTableToDb.js ERROR: ${error.message}`);
|
||||
} catch (/** @type {any} */ error: any) {
|
||||
console.log(`addUsersTableToDb.ts ERROR: ${error.message}`);
|
||||
|
||||
serverError({
|
||||
component: "addUsersTableToDb",
|
||||
@@ -100,4 +94,4 @@ module.exports = async function addUsersTableToDb({
|
||||
});
|
||||
return error.message;
|
||||
}
|
||||
};
|
||||
}
|
||||
+18
-9
@@ -1,10 +1,17 @@
|
||||
// @ts-check
|
||||
import fs from "fs";
|
||||
import decrypt from "../dsql/decrypt";
|
||||
import { CheckApiCredentialsFn } from "../../types";
|
||||
|
||||
const fs = require("fs");
|
||||
const decrypt = require("../dsql/decrypt");
|
||||
|
||||
/** @type {import("../../types").CheckApiCredentialsFn} */
|
||||
const grabApiCred = ({ key, database, table, user_id, media }) => {
|
||||
/**
|
||||
* # Grap API Credentials
|
||||
*/
|
||||
const grabApiCred: CheckApiCredentialsFn = ({
|
||||
key,
|
||||
database,
|
||||
table,
|
||||
user_id,
|
||||
media,
|
||||
}) => {
|
||||
if (!key) return null;
|
||||
if (!user_id) return null;
|
||||
|
||||
@@ -18,7 +25,9 @@ const grabApiCred = ({ key, database, table, user_id, media }) => {
|
||||
|
||||
const ApiJSON = decrypt({ encryptedString: key });
|
||||
/** @type {import("../../types").ApiKeyObject} */
|
||||
const ApiObject = JSON.parse(ApiJSON || "");
|
||||
const ApiObject: import("../../types").ApiKeyObject = JSON.parse(
|
||||
ApiJSON || ""
|
||||
);
|
||||
const isApiKeyValid = fs.existsSync(
|
||||
`${allowedKeysPath}/${ApiObject.sign}`
|
||||
);
|
||||
@@ -41,10 +50,10 @@ const grabApiCred = ({ key, database, table, user_id, media }) => {
|
||||
.includes(String(table));
|
||||
if (isTableAllowed) return ApiObject;
|
||||
return null;
|
||||
} catch (/** @type {any} */ error) {
|
||||
} catch (/** @type {any} */ error: any) {
|
||||
console.log(`api-cred ERROR: ${error.message}`);
|
||||
return { error: `api-cred ERROR: ${error.message}` };
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = grabApiCred;
|
||||
export default grabApiCred;
|
||||
+13
-25
@@ -1,9 +1,7 @@
|
||||
// @ts-check
|
||||
import fs from "fs";
|
||||
import path from "path";
|
||||
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
|
||||
const grabAuthDirs = () => {
|
||||
export const grabAuthDirs = () => {
|
||||
const DSQL_AUTH_DIR = process.env.DSQL_AUTH_DIR;
|
||||
const ROOT_DIR = DSQL_AUTH_DIR?.match(/./)
|
||||
? DSQL_AUTH_DIR
|
||||
@@ -13,7 +11,7 @@ const grabAuthDirs = () => {
|
||||
return { root: ROOT_DIR, auth: AUTH_DIR };
|
||||
};
|
||||
|
||||
const initAuthFiles = () => {
|
||||
export const initAuthFiles = () => {
|
||||
try {
|
||||
const authDirs = grabAuthDirs();
|
||||
|
||||
@@ -22,7 +20,7 @@ const initAuthFiles = () => {
|
||||
if (!fs.existsSync(authDirs.auth))
|
||||
fs.mkdirSync(authDirs.auth, { recursive: true });
|
||||
return true;
|
||||
} catch (/** @type {any} */ error) {
|
||||
} catch (error: any) {
|
||||
console.log(`Error initializing Auth Files: ${error.message}`);
|
||||
return false;
|
||||
}
|
||||
@@ -30,15 +28,13 @@ const initAuthFiles = () => {
|
||||
|
||||
/**
|
||||
* # Write Auth Files
|
||||
* @param {string} name
|
||||
* @param {string} data
|
||||
*/
|
||||
const writeAuthFile = (name, data) => {
|
||||
export const writeAuthFile = (name: string, data: string) => {
|
||||
initAuthFiles();
|
||||
try {
|
||||
fs.writeFileSync(path.join(grabAuthDirs().auth, name), data);
|
||||
return true;
|
||||
} catch (/** @type {any} */ error) {
|
||||
} catch (/** @type {any} */ error: any) {
|
||||
console.log(`Error writing Auth File: ${error.message}`);
|
||||
return false;
|
||||
}
|
||||
@@ -46,13 +42,12 @@ const writeAuthFile = (name, data) => {
|
||||
|
||||
/**
|
||||
* # Get Auth Files
|
||||
* @param {string} name
|
||||
*/
|
||||
const getAuthFile = (name) => {
|
||||
export const getAuthFile = (name: string) => {
|
||||
try {
|
||||
const authFilePath = path.join(grabAuthDirs().auth, name);
|
||||
return fs.readFileSync(authFilePath, "utf-8");
|
||||
} catch (/** @type {any} */ error) {
|
||||
} catch (/** @type {any} */ error: any) {
|
||||
console.log(`Error getting Auth File: ${error.message}`);
|
||||
return null;
|
||||
}
|
||||
@@ -62,10 +57,10 @@ const getAuthFile = (name) => {
|
||||
* # Delete Auth Files
|
||||
* @param {string} name
|
||||
*/
|
||||
const deleteAuthFile = (name) => {
|
||||
export const deleteAuthFile = (name: string) => {
|
||||
try {
|
||||
return fs.rmSync(path.join(grabAuthDirs().auth, name));
|
||||
} catch (/** @type {any} */ error) {
|
||||
} catch (/** @type {any} */ error: any) {
|
||||
console.log(`Error deleting Auth File: ${error.message}`);
|
||||
return null;
|
||||
}
|
||||
@@ -75,19 +70,12 @@ const deleteAuthFile = (name) => {
|
||||
* # Delete Auth Files
|
||||
* @param {string} name
|
||||
*/
|
||||
const checkAuthFile = (name) => {
|
||||
export const checkAuthFile = (name: string) => {
|
||||
try {
|
||||
return fs.existsSync(path.join(grabAuthDirs().auth, name));
|
||||
return true;
|
||||
} catch (/** @type {any} */ error) {
|
||||
} catch (/** @type {any} */ error: any) {
|
||||
console.log(`Error checking Auth File: ${error.message}`);
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
exports.grabAuthDirs = grabAuthDirs;
|
||||
exports.initAuthFiles = initAuthFiles;
|
||||
exports.writeAuthFile = writeAuthFile;
|
||||
exports.getAuthFile = getAuthFile;
|
||||
exports.deleteAuthFile = deleteAuthFile;
|
||||
exports.checkAuthFile = checkAuthFile;
|
||||
+12
-9
@@ -1,15 +1,18 @@
|
||||
// @ts-check
|
||||
type Param = {
|
||||
database?: string;
|
||||
userId?: string | number;
|
||||
};
|
||||
|
||||
type Return = {
|
||||
keyCookieName: string;
|
||||
csrfCookieName: string;
|
||||
oneTimeCodeName: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* # Grab Auth Cookie Names
|
||||
*
|
||||
* @param {object} [params]
|
||||
* @param {string} [params.database]
|
||||
* @param {string | number} [params.userId]
|
||||
*
|
||||
* @returns {{ keyCookieName: string, csrfCookieName: string, oneTimeCodeName: string }}
|
||||
*/
|
||||
module.exports = function getAuthCookieNames(params) {
|
||||
export default function getAuthCookieNames(params?: Param): Return {
|
||||
const cookiesPrefix = process.env.DSQL_COOKIES_PREFIX || "dsql_";
|
||||
const cookiesKeyName = process.env.DSQL_COOKIES_KEY_NAME || "key";
|
||||
const cookiesCSRFName = process.env.DSQL_COOKIES_CSRF_NAME || "csrf";
|
||||
@@ -40,4 +43,4 @@ module.exports = function getAuthCookieNames(params) {
|
||||
csrfCookieName,
|
||||
oneTimeCodeName,
|
||||
};
|
||||
};
|
||||
}
|
||||
+29
-26
@@ -1,13 +1,28 @@
|
||||
// @ts-check
|
||||
|
||||
const sanitizeHtml = require("sanitize-html");
|
||||
const sanitizeHtmlOptions = require("../html/sanitizeHtmlOptions");
|
||||
const updateDbEntry = require("./updateDbEntry");
|
||||
const _ = require("lodash");
|
||||
const DB_HANDLER = require("../../../utils/backend/global-db/DB_HANDLER");
|
||||
const DSQL_USER_DB_HANDLER = require("../../../utils/backend/global-db/DSQL_USER_DB_HANDLER");
|
||||
const encrypt = require("../../dsql/encrypt");
|
||||
const LOCAL_DB_HANDLER = require("../../../utils/backend/global-db/LOCAL_DB_HANDLER");
|
||||
import sanitizeHtml from "sanitize-html";
|
||||
import sanitizeHtmlOptions from "../html/sanitizeHtmlOptions";
|
||||
import updateDbEntry from "./updateDbEntry";
|
||||
import _ from "lodash";
|
||||
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 encrypt from "../../dsql/encrypt";
|
||||
import LOCAL_DB_HANDLER from "../../../utils/backend/global-db/LOCAL_DB_HANDLER";
|
||||
|
||||
type Param = {
|
||||
dbContext?: "Master" | "Dsql User";
|
||||
paradigm?: "Read Only" | "Full Access";
|
||||
dbFullName?: string;
|
||||
tableName: string;
|
||||
data: any;
|
||||
tableSchema?: import("../../../types").DSQL_TableSchemaType;
|
||||
duplicateColumnName?: string;
|
||||
duplicateColumnValue?: string;
|
||||
update?: boolean;
|
||||
encryptionKey?: string;
|
||||
encryptionSalt?: string;
|
||||
useLocal?: boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
* Add a db Entry Function
|
||||
@@ -33,7 +48,7 @@ const LOCAL_DB_HANDLER = require("../../../utils/backend/global-db/LOCAL_DB_HAND
|
||||
*
|
||||
* @returns {Promise<any>}
|
||||
*/
|
||||
async function addDbEntry({
|
||||
export default async function addDbEntry({
|
||||
dbContext,
|
||||
paradigm,
|
||||
dbFullName,
|
||||
@@ -46,7 +61,7 @@ async function addDbEntry({
|
||||
encryptionKey,
|
||||
encryptionSalt,
|
||||
useLocal,
|
||||
}) {
|
||||
}: Param): Promise<any> {
|
||||
/**
|
||||
* Initialize variables
|
||||
*/
|
||||
@@ -59,7 +74,7 @@ async function addDbEntry({
|
||||
: true;
|
||||
|
||||
/** @type { any } */
|
||||
const dbHandler = useLocal
|
||||
const dbHandler: any = useLocal
|
||||
? LOCAL_DB_HANDLER
|
||||
: isMaster
|
||||
? DB_HANDLER
|
||||
@@ -92,8 +107,7 @@ async function addDbEntry({
|
||||
)
|
||||
: await dbHandler({
|
||||
paradigm: "Read Only",
|
||||
database: dbFullName,
|
||||
queryString: `SELECT * FROM \`${tableName}\` WHERE \`${duplicateColumnName}\`=?`,
|
||||
queryString: `SELECT * FROM \`${dbFullName}\`.\`${tableName}\` WHERE \`${duplicateColumnName}\`=?`,
|
||||
queryValues: [duplicateColumnValue],
|
||||
});
|
||||
|
||||
@@ -187,7 +201,7 @@ async function addDbEntry({
|
||||
} else {
|
||||
insertValuesArray.push(value);
|
||||
}
|
||||
} catch (/** @type {any} */ error) {
|
||||
} catch (/** @type {any} */ error: any) {
|
||||
console.log("DSQL: Error in parsing data keys =>", error.message);
|
||||
continue;
|
||||
}
|
||||
@@ -219,7 +233,7 @@ async function addDbEntry({
|
||||
|
||||
////////////////////////////////////////
|
||||
|
||||
const query = `INSERT INTO \`${tableName}\` (${insertKeysArray.join(
|
||||
const query = `INSERT INTO \`${dbFullName}\`.\`${tableName}\` (${insertKeysArray.join(
|
||||
","
|
||||
)}) VALUES (${insertValuesArray.map(() => "?").join(",")})`;
|
||||
const queryValuesArray = insertValuesArray;
|
||||
@@ -228,23 +242,12 @@ async function addDbEntry({
|
||||
? await dbHandler(query, queryValuesArray)
|
||||
: await dbHandler({
|
||||
paradigm,
|
||||
database: dbFullName,
|
||||
queryString: query,
|
||||
queryValues: queryValuesArray,
|
||||
});
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
/**
|
||||
* Return statement
|
||||
*/
|
||||
return newInsert;
|
||||
}
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
module.exports = addDbEntry;
|
||||
@@ -1,104 +0,0 @@
|
||||
// @ts-check
|
||||
|
||||
const DB_HANDLER = require("../../../utils/backend/global-db/DB_HANDLER");
|
||||
const DSQL_USER_DB_HANDLER = require("../../../utils/backend/global-db/DSQL_USER_DB_HANDLER");
|
||||
const LOCAL_DB_HANDLER = require("../../../utils/backend/global-db/LOCAL_DB_HANDLER");
|
||||
|
||||
/**
|
||||
* Imports: Handle imports
|
||||
*/
|
||||
|
||||
/**
|
||||
* Delete DB Entry Function
|
||||
* ==============================================================================
|
||||
* @description Description
|
||||
* @async
|
||||
*
|
||||
* @param {object} params - An object containing the function parameters.
|
||||
* @param {string} [params.dbContext] - What is the database context? "Master"
|
||||
* or "Dsql User". Defaults to "Master"
|
||||
* @param {("Read Only" | "Full Access")} [params.paradigm] - What is the paradigm for "Dsql User"?
|
||||
* "Read only" or "Full Access"? Defaults to "Read Only"
|
||||
* @param {string} params.dbFullName - Database full name
|
||||
* @param {string} params.tableName - Table name
|
||||
* @param {import("../../../types").DSQL_TableSchemaType} [params.tableSchema] - Table schema
|
||||
* @param {string} params.identifierColumnName - Update row identifier column name
|
||||
* @param {string|number} params.identifierValue - Update row identifier column value
|
||||
* @param {boolean} [params.useLocal]
|
||||
*
|
||||
* @returns {Promise<object|null>}
|
||||
*/
|
||||
async function deleteDbEntry({
|
||||
dbContext,
|
||||
paradigm,
|
||||
dbFullName,
|
||||
tableName,
|
||||
identifierColumnName,
|
||||
identifierValue,
|
||||
useLocal,
|
||||
}) {
|
||||
try {
|
||||
/**
|
||||
* Check if data is valid
|
||||
*/
|
||||
const isMaster = useLocal
|
||||
? true
|
||||
: dbContext?.match(/dsql.user/i)
|
||||
? false
|
||||
: dbFullName && !dbFullName.match(/^datasquirel$/)
|
||||
? false
|
||||
: true;
|
||||
|
||||
/** @type { (a1:any, a2?:any) => any } */
|
||||
const dbHandler = useLocal
|
||||
? LOCAL_DB_HANDLER
|
||||
: isMaster
|
||||
? DB_HANDLER
|
||||
: DSQL_USER_DB_HANDLER;
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
/**
|
||||
* Execution
|
||||
*
|
||||
* @description
|
||||
*/
|
||||
const query = `DELETE FROM ${tableName} WHERE \`${identifierColumnName}\`=?`;
|
||||
|
||||
const deletedEntry = isMaster
|
||||
? await dbHandler(query, [identifierValue])
|
||||
: await dbHandler({
|
||||
paradigm,
|
||||
queryString: query,
|
||||
database: dbFullName,
|
||||
queryValues: [identifierValue],
|
||||
});
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
/**
|
||||
* Return statement
|
||||
*/
|
||||
return deletedEntry;
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
} catch (error) {
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
module.exports = deleteDbEntry;
|
||||
@@ -0,0 +1,67 @@
|
||||
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";
|
||||
|
||||
type Param = {
|
||||
dbContext?: string;
|
||||
paradigm?: "Read Only" | "Full Access";
|
||||
dbFullName: string;
|
||||
tableName: string;
|
||||
tableSchema?: import("../../../types").DSQL_TableSchemaType;
|
||||
identifierColumnName: string;
|
||||
identifierValue: string | number;
|
||||
useLocal?: boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
* # Delete DB Entry Function
|
||||
* @description
|
||||
*/
|
||||
export default async function deleteDbEntry({
|
||||
dbContext,
|
||||
paradigm,
|
||||
dbFullName,
|
||||
tableName,
|
||||
identifierColumnName,
|
||||
identifierValue,
|
||||
useLocal,
|
||||
}: Param): Promise<object | null> {
|
||||
try {
|
||||
const isMaster = useLocal
|
||||
? true
|
||||
: dbContext?.match(/dsql.user/i)
|
||||
? false
|
||||
: dbFullName && !dbFullName.match(/^datasquirel$/)
|
||||
? false
|
||||
: true;
|
||||
|
||||
/** @type { (a1:any, a2?:any) => any } */
|
||||
const dbHandler: (a1: any, a2?: any) => any = useLocal
|
||||
? LOCAL_DB_HANDLER
|
||||
: isMaster
|
||||
? DB_HANDLER
|
||||
: DSQL_USER_DB_HANDLER;
|
||||
|
||||
/**
|
||||
* Execution
|
||||
*
|
||||
* @description
|
||||
*/
|
||||
const query = `DELETE FROM \`${dbFullName}\`.\`${tableName}\` WHERE \`${identifierColumnName}\`=?`;
|
||||
|
||||
const deletedEntry = isMaster
|
||||
? await dbHandler(query, [identifierValue])
|
||||
: await dbHandler({
|
||||
paradigm,
|
||||
queryString: query,
|
||||
queryValues: [identifierValue],
|
||||
});
|
||||
|
||||
/**
|
||||
* Return statement
|
||||
*/
|
||||
return deletedEntry;
|
||||
} catch (error) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -1,14 +0,0 @@
|
||||
// @ts-check
|
||||
|
||||
/**
|
||||
* # Path Traversal Check
|
||||
*
|
||||
* @param {string|number} text - Text or number or object
|
||||
*
|
||||
* @returns {string}
|
||||
*/
|
||||
function pathTraversalCheck(text) {
|
||||
return text.toString().replace(/\//g, "");
|
||||
}
|
||||
|
||||
module.exports = pathTraversalCheck;
|
||||
@@ -0,0 +1,7 @@
|
||||
/**
|
||||
* # Path Traversal Check
|
||||
* @returns {string}
|
||||
*/
|
||||
export default function pathTraversalCheck(text: string | number): string {
|
||||
return text.toString().replace(/\//g, "");
|
||||
}
|
||||
+24
-49
@@ -1,32 +1,26 @@
|
||||
// @ts-check
|
||||
import fullAccessDbHandler from "../fullAccessDbHandler";
|
||||
import varReadOnlyDatabaseDbHandler from "../varReadOnlyDatabaseDbHandler";
|
||||
import serverError from "../serverError";
|
||||
import addDbEntry from "./addDbEntry";
|
||||
import updateDbEntry from "./updateDbEntry";
|
||||
import deleteDbEntry from "./deleteDbEntry";
|
||||
import trimSql from "../../../utils/trim-sql";
|
||||
import { DSQL_TableSchemaType } from "../../../types";
|
||||
|
||||
const fs = require("fs");
|
||||
|
||||
const LOCAL_DB_HANDLER = require("../../../utils/backend/global-db/LOCAL_DB_HANDLER");
|
||||
const fullAccessDbHandler = require("../fullAccessDbHandler");
|
||||
const varReadOnlyDatabaseDbHandler = require("../varReadOnlyDatabaseDbHandler");
|
||||
const serverError = require("../serverError");
|
||||
const addDbEntry = require("./addDbEntry");
|
||||
const updateDbEntry = require("./updateDbEntry");
|
||||
const deleteDbEntry = require("./deleteDbEntry");
|
||||
const parseDbResults = require("../parseDbResults");
|
||||
const trimSql = require("../../../utils/trim-sql");
|
||||
type Param = {
|
||||
dbFullName: string;
|
||||
query: string | any;
|
||||
readOnly?: boolean;
|
||||
local?: boolean;
|
||||
dbSchema?: import("../../../types").DSQL_DatabaseSchemaType;
|
||||
queryValuesArray?: (string | number)[];
|
||||
tableName?: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* Run DSQL users queries
|
||||
* ==============================================================================
|
||||
* @param {object} params - An object containing the function parameters.
|
||||
* @param {string} params.dbFullName - Database full name. Eg. "datasquire_user_2_test"
|
||||
* @param {string | any} params.query - Query string or object
|
||||
* @param {boolean} [params.readOnly] - Is this operation read only?
|
||||
* @param {boolean} [params.local] - Is this operation read only?
|
||||
* @param {import("../../../types").DSQL_DatabaseSchemaType} [params.dbSchema] - Database schema
|
||||
* @param {(string | number)[]} [params.queryValuesArray] - An optional array of query values if "?" is used in the query string
|
||||
* @param {string} [params.tableName] - Table Name
|
||||
*
|
||||
* @return {Promise<any>}
|
||||
* # Run DSQL users queries
|
||||
*/
|
||||
async function runQuery({
|
||||
export default async function runQuery({
|
||||
dbFullName,
|
||||
query,
|
||||
readOnly,
|
||||
@@ -34,19 +28,16 @@ async function runQuery({
|
||||
queryValuesArray,
|
||||
tableName,
|
||||
local,
|
||||
}) {
|
||||
}: Param): Promise<any> {
|
||||
/**
|
||||
* Declare variables
|
||||
*
|
||||
* @description Declare "results" variable
|
||||
*/
|
||||
|
||||
/** @type {any} */
|
||||
let result;
|
||||
/** @type {any} */
|
||||
let error;
|
||||
/** @type {import("../../../types").DSQL_TableSchemaType | undefined} */
|
||||
let tableSchema;
|
||||
let result: any;
|
||||
let error: any;
|
||||
let tableSchema: DSQL_TableSchemaType | undefined;
|
||||
|
||||
if (dbSchema) {
|
||||
try {
|
||||
@@ -93,7 +84,6 @@ async function runQuery({
|
||||
result = await varReadOnlyDatabaseDbHandler({
|
||||
queryString: formattedQuery,
|
||||
queryValuesArray: queryValuesArray?.map((vl) => String(vl)),
|
||||
database: dbFullName,
|
||||
tableSchema,
|
||||
useLocal: local,
|
||||
});
|
||||
@@ -101,7 +91,6 @@ async function runQuery({
|
||||
result = await fullAccessDbHandler({
|
||||
queryString: formattedQuery,
|
||||
queryValuesArray: queryValuesArray?.map((vl) => String(vl)),
|
||||
database: dbFullName,
|
||||
tableSchema,
|
||||
local,
|
||||
});
|
||||
@@ -178,11 +167,7 @@ async function runQuery({
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
} catch (/** @type {any} */ error) {
|
||||
} catch (/** @type {any} */ error: any) {
|
||||
serverError({
|
||||
component: "functions/backend/runQuery",
|
||||
message: error.message,
|
||||
@@ -191,15 +176,5 @@ async function runQuery({
|
||||
error = error.message;
|
||||
}
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
return { result, error };
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
}
|
||||
|
||||
module.exports = runQuery;
|
||||
+9
-14
@@ -1,20 +1,12 @@
|
||||
// @ts-check
|
||||
|
||||
const _ = require("lodash");
|
||||
import _ from "lodash";
|
||||
|
||||
/**
|
||||
* Sanitize SQL function
|
||||
* ==============================================================================
|
||||
* @description this function takes in a text(or number) and returns a sanitized
|
||||
* text, usually without spaces
|
||||
*
|
||||
* @param {any} text - Text or number or object
|
||||
* @param {boolean} [spaces] - Allow spaces
|
||||
* @param {RegExp?} [regex] - Regular expression, removes any match
|
||||
*
|
||||
* @returns {any}
|
||||
*/
|
||||
function sanitizeSql(text, spaces, regex) {
|
||||
function sanitizeSql(text: any, spaces?: boolean, regex?: RegExp | null): any {
|
||||
if (!text) return "";
|
||||
if (typeof text == "number" || typeof text == "boolean") return text;
|
||||
if (typeof text == "string" && !text?.toString()?.match(/./)) return "";
|
||||
@@ -63,9 +55,9 @@ function sanitizeSql(text, spaces, regex) {
|
||||
*
|
||||
* @returns {object}
|
||||
*/
|
||||
function sanitizeObjects(object, spaces) {
|
||||
function sanitizeObjects(object: any, spaces?: boolean): object {
|
||||
/** @type {any} */
|
||||
let objectUpdated = { ...object };
|
||||
let objectUpdated: any = { ...object };
|
||||
const keys = Object.keys(objectUpdated);
|
||||
|
||||
keys.forEach((key) => {
|
||||
@@ -98,7 +90,10 @@ function sanitizeObjects(object, spaces) {
|
||||
*
|
||||
* @returns {string[]|number[]|object[]}
|
||||
*/
|
||||
function sanitizeArrays(array, spaces) {
|
||||
function sanitizeArrays(
|
||||
array: any[],
|
||||
spaces?: boolean
|
||||
): string[] | number[] | object[] {
|
||||
let arrayUpdated = _.cloneDeep(array);
|
||||
|
||||
arrayUpdated.forEach((item, index) => {
|
||||
@@ -121,4 +116,4 @@ function sanitizeArrays(array, spaces) {
|
||||
return arrayUpdated;
|
||||
}
|
||||
|
||||
module.exports = sanitizeSql;
|
||||
export default sanitizeSql;
|
||||
+27
-48
@@ -1,39 +1,29 @@
|
||||
// @ts-check
|
||||
import sanitizeHtml from "sanitize-html";
|
||||
import sanitizeHtmlOptions from "../html/sanitizeHtmlOptions";
|
||||
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 encrypt from "../../dsql/encrypt";
|
||||
import LOCAL_DB_HANDLER from "../../../utils/backend/global-db/LOCAL_DB_HANDLER";
|
||||
|
||||
type Param = {
|
||||
dbContext?: "Master" | "Dsql User";
|
||||
paradigm?: "Read Only" | "Full Access";
|
||||
dbFullName?: string;
|
||||
tableName: string;
|
||||
encryptionKey?: string;
|
||||
encryptionSalt?: string;
|
||||
data: any;
|
||||
tableSchema?: import("../../../types").DSQL_TableSchemaType;
|
||||
identifierColumnName: string;
|
||||
identifierValue: string | number;
|
||||
useLocal?: boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
* Imports: Handle imports
|
||||
* # Update DB Function
|
||||
* @description
|
||||
*/
|
||||
const sanitizeHtml = require("sanitize-html");
|
||||
const sanitizeHtmlOptions = require("../html/sanitizeHtmlOptions");
|
||||
const DB_HANDLER = require("../../../utils/backend/global-db/DB_HANDLER");
|
||||
const DSQL_USER_DB_HANDLER = require("../../../utils/backend/global-db/DSQL_USER_DB_HANDLER");
|
||||
const encrypt = require("../../dsql/encrypt");
|
||||
const LOCAL_DB_HANDLER = require("../../../utils/backend/global-db/LOCAL_DB_HANDLER");
|
||||
|
||||
/**
|
||||
* Update DB Function
|
||||
* ==============================================================================
|
||||
* @description Description
|
||||
* @async
|
||||
*
|
||||
* @param {object} params - An object containing the function parameters.
|
||||
* @param {("Master" | "Dsql User")} [params.dbContext] - What is the database context? "Master"
|
||||
* or "Dsql User". Defaults to "Master"
|
||||
* @param {("Read Only" | "Full Access")} [params.paradigm] - What is the paradigm for "Dsql User"?
|
||||
* "Read only" or "Full Access"? Defaults to "Read Only"
|
||||
* @param {string} [params.dbFullName] - Database full name
|
||||
* @param {string} params.tableName - Table name
|
||||
* @param {string} [params.encryptionKey]
|
||||
* @param {string} [params.encryptionSalt]
|
||||
* @param {any} params.data - Data to add
|
||||
* @param {import("../../../types").DSQL_TableSchemaType} [params.tableSchema] - Table schema
|
||||
* @param {string} params.identifierColumnName - Update row identifier column name
|
||||
* @param {string | number} params.identifierValue - Update row identifier column value
|
||||
* @param {boolean} [params.useLocal]
|
||||
*
|
||||
* @returns {Promise<object|null>}
|
||||
*/
|
||||
async function updateDbEntry({
|
||||
export default async function updateDbEntry({
|
||||
dbContext,
|
||||
paradigm,
|
||||
dbFullName,
|
||||
@@ -45,7 +35,7 @@ async function updateDbEntry({
|
||||
encryptionKey,
|
||||
encryptionSalt,
|
||||
useLocal,
|
||||
}) {
|
||||
}: Param): Promise<object | null> {
|
||||
/**
|
||||
* Check if data is valid
|
||||
*/
|
||||
@@ -60,7 +50,7 @@ async function updateDbEntry({
|
||||
: true;
|
||||
|
||||
/** @type {(a1:any, a2?:any)=> any } */
|
||||
const dbHandler = useLocal
|
||||
const dbHandler: (a1: any, a2?: any) => any = useLocal
|
||||
? LOCAL_DB_HANDLER
|
||||
: isMaster
|
||||
? DB_HANDLER
|
||||
@@ -153,7 +143,7 @@ async function updateDbEntry({
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
} catch (/** @type {any} */ error) {
|
||||
} catch (/** @type {any} */ error: any) {
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
@@ -174,7 +164,7 @@ async function updateDbEntry({
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
const query = `UPDATE ${tableName} SET ${updateKeyValueArray.join(
|
||||
const query = `UPDATE \`${dbFullName}\`.\`${tableName}\` SET ${updateKeyValueArray.join(
|
||||
","
|
||||
)} WHERE \`${identifierColumnName}\`=?`;
|
||||
|
||||
@@ -184,23 +174,12 @@ async function updateDbEntry({
|
||||
? await dbHandler(query, updateValues)
|
||||
: await dbHandler({
|
||||
paradigm,
|
||||
database: dbFullName,
|
||||
queryString: query,
|
||||
queryValues: updateValues,
|
||||
});
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
/**
|
||||
* Return statement
|
||||
*/
|
||||
return updatedEntry;
|
||||
}
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
module.exports = updateDbEntry;
|
||||
@@ -1,86 +0,0 @@
|
||||
// @ts-check
|
||||
|
||||
const fs = require("fs");
|
||||
const serverError = require("./serverError");
|
||||
|
||||
const mysql = require("serverless-mysql");
|
||||
const grabDbSSL = require("../../utils/backend/grabDbSSL");
|
||||
|
||||
const connection = 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,
|
||||
charset: "utf8mb4",
|
||||
ssl: grabDbSSL(),
|
||||
},
|
||||
});
|
||||
|
||||
/**
|
||||
* Main DB Handler Function
|
||||
* ==============================================================================
|
||||
* @async
|
||||
*
|
||||
* @param {any} args
|
||||
* @returns {Promise<object|null>}
|
||||
*/
|
||||
module.exports = async function dbHandler(...args) {
|
||||
process.env.NODE_ENV?.match(/dev/) &&
|
||||
fs.appendFileSync(
|
||||
"./.tmp/sqlQuery.sql",
|
||||
args[0] + "\n" + Date() + "\n\n\n",
|
||||
"utf8"
|
||||
);
|
||||
|
||||
/**
|
||||
* 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) => {
|
||||
// @ts-ignore
|
||||
connection.query(...args, (error, result, fields) => {
|
||||
if (error) {
|
||||
resolve({ error: error.message });
|
||||
} else {
|
||||
resolve(result);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
await connection.end();
|
||||
} catch (/** @type {any} */ error) {
|
||||
fs.appendFileSync(
|
||||
"./.tmp/dbErrorLogs.txt",
|
||||
JSON.stringify(error, null, 4) + "\n" + Date() + "\n\n\n",
|
||||
"utf8"
|
||||
);
|
||||
|
||||
results = null;
|
||||
|
||||
serverError({
|
||||
component: "dbHandler",
|
||||
message: error.message,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Return results
|
||||
*
|
||||
* @description Return results add to cache if "req" param is passed
|
||||
*/
|
||||
if (results) {
|
||||
return JSON.parse(JSON.stringify(results));
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,64 @@
|
||||
import fs from "fs";
|
||||
import serverError from "./serverError";
|
||||
|
||||
/**
|
||||
* # Main DB Handler Function
|
||||
*/
|
||||
export default async function dbHandler(...args: any[]) {
|
||||
process.env.NODE_ENV?.match(/dev/) &&
|
||||
fs.appendFileSync(
|
||||
"./.tmp/sqlQuery.sql",
|
||||
args[0] + "\n" + Date() + "\n\n\n",
|
||||
"utf8"
|
||||
);
|
||||
|
||||
let results;
|
||||
|
||||
/**
|
||||
* Fetch from db
|
||||
*
|
||||
* @description Fetch data from db if no cache
|
||||
*/
|
||||
try {
|
||||
const connection = global.DSQL_DB_CONN;
|
||||
|
||||
results = await new Promise((resolve, reject) => {
|
||||
connection.query(
|
||||
...args,
|
||||
(error: any, result: any, fields: any) => {
|
||||
if (error) {
|
||||
resolve({ error: error.message });
|
||||
} else {
|
||||
resolve(result);
|
||||
}
|
||||
}
|
||||
);
|
||||
});
|
||||
|
||||
await connection.end();
|
||||
} catch (error: any) {
|
||||
fs.appendFileSync(
|
||||
"./.tmp/dbErrorLogs.txt",
|
||||
JSON.stringify(error, null, 4) + "\n" + Date() + "\n\n\n",
|
||||
"utf8"
|
||||
);
|
||||
|
||||
results = null;
|
||||
|
||||
serverError({
|
||||
component: "dbHandler",
|
||||
message: error.message,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Return results
|
||||
*
|
||||
* @description Return results add to cache if "req" param is passed
|
||||
*/
|
||||
if (results) {
|
||||
return JSON.parse(JSON.stringify(results));
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
+1
-3
@@ -1,5 +1,3 @@
|
||||
// @ts-check
|
||||
|
||||
/**
|
||||
* Regular expression to match default fields
|
||||
*
|
||||
@@ -8,4 +6,4 @@
|
||||
const defaultFieldsRegexp =
|
||||
/^id$|^uuid$|^date_created$|^date_created_code$|^date_created_timestamp$|^date_updated$|^date_updated_code$|^date_updated_timestamp$/;
|
||||
|
||||
module.exports = defaultFieldsRegexp;
|
||||
export default defaultFieldsRegexp;
|
||||
+16
-18
@@ -1,27 +1,26 @@
|
||||
// @ts-check
|
||||
|
||||
const DSQL_USER_DB_HANDLER = require("../../utils/backend/global-db/DSQL_USER_DB_HANDLER");
|
||||
const LOCAL_DB_HANDLER = require("../../utils/backend/global-db/LOCAL_DB_HANDLER");
|
||||
const parseDbResults = require("./parseDbResults");
|
||||
const serverError = require("./serverError");
|
||||
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 parseDbResults from "./parseDbResults";
|
||||
import serverError from "./serverError";
|
||||
|
||||
type Param = {
|
||||
queryString: string;
|
||||
local?: boolean;
|
||||
tableSchema?: import("../../types").DSQL_TableSchemaType | null;
|
||||
queryValuesArray?: string[];
|
||||
};
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {object} param0
|
||||
* @param {string} param0.queryString
|
||||
* @param {string} param0.database
|
||||
* @param {boolean} [param0.local]
|
||||
* @param {import("../../types").DSQL_TableSchemaType | null} [param0.tableSchema]
|
||||
* @param {string[]} [param0.queryValuesArray]
|
||||
* @returns
|
||||
* # Full Access Db Handler
|
||||
*/
|
||||
module.exports = async function fullAccessDbHandler({
|
||||
export default async function fullAccessDbHandler({
|
||||
queryString,
|
||||
database,
|
||||
tableSchema,
|
||||
queryValuesArray,
|
||||
local,
|
||||
}) {
|
||||
}: Param) {
|
||||
/**
|
||||
* Declare variables
|
||||
*
|
||||
@@ -41,13 +40,12 @@ module.exports = async function fullAccessDbHandler({
|
||||
? await LOCAL_DB_HANDLER(queryString, queryValuesArray)
|
||||
: await DSQL_USER_DB_HANDLER({
|
||||
paradigm: "Full Access",
|
||||
database,
|
||||
queryString,
|
||||
queryValues: queryValuesArray,
|
||||
});
|
||||
|
||||
////////////////////////////////////////
|
||||
} catch (/** @type {any} */ error) {
|
||||
} catch (/** @type {any} */ error: any) {
|
||||
////////////////////////////////////////
|
||||
|
||||
serverError({
|
||||
@@ -78,4 +76,4 @@ module.exports = async function fullAccessDbHandler({
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
}
|
||||
+11
-17
@@ -1,22 +1,16 @@
|
||||
// @ts-check
|
||||
|
||||
const grabSchemaFieldsFromData = require("./grabSchemaFieldsFromData");
|
||||
const serverError = require("./serverError");
|
||||
import { DSQL_FieldSchemaType, DSQL_TableSchemaType } from "../../types";
|
||||
import grabSchemaFieldsFromData from "./grabSchemaFieldsFromData";
|
||||
import serverError from "./serverError";
|
||||
|
||||
/**
|
||||
* # Add User Table to Database
|
||||
*
|
||||
* @param {object} [params]
|
||||
* @param {Object<string,any>} [params.payload] - fields to add to the table
|
||||
*
|
||||
* @returns {import("../../types").DSQL_TableSchemaType | null} new user auth object payload
|
||||
*/
|
||||
module.exports = function grabNewUsersTableSchema(params) {
|
||||
export default function grabNewUsersTableSchema(params: {
|
||||
payload?: { [s: string]: any };
|
||||
}): DSQL_TableSchemaType | null {
|
||||
try {
|
||||
/** @type {import("../../types").DSQL_TableSchemaType} */
|
||||
const userPreset = require("../../data/presets/users.json");
|
||||
/** @type {import("../../types").DSQL_FieldSchemaType[]} */
|
||||
const defaultFields = require("../../data/defaultFields.json");
|
||||
const userPreset: DSQL_TableSchemaType = require("../../data/presets/users.json");
|
||||
const defaultFields: DSQL_FieldSchemaType[] = require("../../data/defaultFields.json");
|
||||
|
||||
const supplementalFields = params?.payload
|
||||
? grabSchemaFieldsFromData({
|
||||
@@ -41,8 +35,8 @@ module.exports = function grabNewUsersTableSchema(params) {
|
||||
userPreset.fields = [...finalFields];
|
||||
|
||||
return userPreset;
|
||||
} catch (/** @type {any} */ error) {
|
||||
console.log(`grabNewUsersTableSchema.js ERROR: ${error.message}`);
|
||||
} catch (/** @type {any} */ error: any) {
|
||||
console.log(`grabNewUsersTableSchema.ts ERROR: ${error.message}`);
|
||||
|
||||
serverError({
|
||||
component: "grabNewUsersTableSchema",
|
||||
@@ -51,4 +45,4 @@ module.exports = function grabNewUsersTableSchema(params) {
|
||||
|
||||
return null;
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -1,94 +0,0 @@
|
||||
// @ts-check
|
||||
|
||||
const serverError = require("./serverError");
|
||||
|
||||
/**
|
||||
* # Add User Table to Database
|
||||
*
|
||||
* @param {object} params
|
||||
* @param {Object<string,any>} [params.data]
|
||||
* @param {string[]} [params.fields]
|
||||
* @param {Object<string,any>} [params.excludeData]
|
||||
* @param {import("../../types").DSQL_FieldSchemaType[]} [params.excludeFields]
|
||||
*
|
||||
* @returns {import("../../types").DSQL_FieldSchemaType[]} new user auth object payload
|
||||
*/
|
||||
module.exports = function grabSchemaFieldsFromData({
|
||||
data,
|
||||
fields,
|
||||
excludeData,
|
||||
excludeFields,
|
||||
}) {
|
||||
try {
|
||||
const possibleFields = require("../../data/possibleFields.json");
|
||||
const dataTypes = require("../../data/dataTypes.json");
|
||||
|
||||
/** @type {import("../../types").DSQL_FieldSchemaType[]} */
|
||||
const finalFields = [];
|
||||
|
||||
/** @type {string[]} */
|
||||
let filteredFields = [];
|
||||
|
||||
if (data && Object.keys(data)?.[0]) {
|
||||
filteredFields = Object.keys(data);
|
||||
}
|
||||
|
||||
if (fields) {
|
||||
filteredFields = [...filteredFields, ...fields];
|
||||
filteredFields = [...new Set(filteredFields)];
|
||||
}
|
||||
|
||||
filteredFields = filteredFields
|
||||
.filter(
|
||||
(fld) => !excludeData || !Object.keys(excludeData).includes(fld)
|
||||
)
|
||||
.filter(
|
||||
(fld) =>
|
||||
!excludeFields ||
|
||||
!excludeFields.find((exlFld) => exlFld.fieldName == fld)
|
||||
);
|
||||
|
||||
filteredFields.forEach((fld) => {
|
||||
const value = data ? data[fld] : null;
|
||||
|
||||
if (typeof value == "string") {
|
||||
const newField =
|
||||
/** @type {import("../../types").DSQL_FieldSchemaType} */ ({
|
||||
fieldName: fld,
|
||||
dataType: value.length > 255 ? "TEXT" : "VARCHAR(255)",
|
||||
});
|
||||
|
||||
if (Boolean(value.match(/<[^>]+>/g))) {
|
||||
newField.richText = true;
|
||||
}
|
||||
|
||||
finalFields.push(newField);
|
||||
} else if (typeof value == "number") {
|
||||
finalFields.push(
|
||||
/** @type {import("../../types").DSQL_FieldSchemaType} */ ({
|
||||
fieldName: fld,
|
||||
dataType: "INT",
|
||||
})
|
||||
);
|
||||
} else {
|
||||
finalFields.push(
|
||||
/** @type {import("../../types").DSQL_FieldSchemaType} */ ({
|
||||
fieldName: fld,
|
||||
dataType: "VARCHAR(255)",
|
||||
})
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
return finalFields;
|
||||
} catch (/** @type {any} */ error) {
|
||||
console.log(`grabSchemaFieldsFromData.js ERROR: ${error.message}`);
|
||||
|
||||
serverError({
|
||||
component: "grabSchemaFieldsFromData.js",
|
||||
message: error.message,
|
||||
});
|
||||
|
||||
return [];
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,87 @@
|
||||
import { DSQL_FieldSchemaType } from "../../types";
|
||||
import serverError from "./serverError";
|
||||
|
||||
type Param = {
|
||||
data?: { [s: string]: any };
|
||||
fields?: string[];
|
||||
excludeData?: { [s: string]: any };
|
||||
excludeFields?: DSQL_FieldSchemaType[];
|
||||
};
|
||||
|
||||
/**
|
||||
* # Add User Table to Database
|
||||
*/
|
||||
export default function grabSchemaFieldsFromData({
|
||||
data,
|
||||
fields,
|
||||
excludeData,
|
||||
excludeFields,
|
||||
}: Param): DSQL_FieldSchemaType[] {
|
||||
try {
|
||||
const possibleFields = require("../../data/possibleFields.json");
|
||||
const dataTypes = require("../../data/dataTypes.json");
|
||||
|
||||
/** @type {DSQL_FieldSchemaType[]} */
|
||||
const finalFields: DSQL_FieldSchemaType[] = [];
|
||||
|
||||
/** @type {string[]} */
|
||||
let filteredFields: string[] = [];
|
||||
|
||||
if (data && Object.keys(data)?.[0]) {
|
||||
filteredFields = Object.keys(data);
|
||||
}
|
||||
|
||||
if (fields) {
|
||||
filteredFields = [...filteredFields, ...fields];
|
||||
filteredFields = [...new Set(filteredFields)];
|
||||
}
|
||||
|
||||
filteredFields = filteredFields
|
||||
.filter(
|
||||
(fld) => !excludeData || !Object.keys(excludeData).includes(fld)
|
||||
)
|
||||
.filter(
|
||||
(fld) =>
|
||||
!excludeFields ||
|
||||
!excludeFields.find((exlFld) => exlFld.fieldName == fld)
|
||||
);
|
||||
|
||||
filteredFields.forEach((fld) => {
|
||||
const value = data ? data[fld] : null;
|
||||
|
||||
if (typeof value == "string") {
|
||||
const newField: DSQL_FieldSchemaType = {
|
||||
fieldName: fld,
|
||||
dataType: value.length > 255 ? "TEXT" : "VARCHAR(255)",
|
||||
};
|
||||
|
||||
if (Boolean(value.match(/<[^>]+>/g))) {
|
||||
newField.richText = true;
|
||||
}
|
||||
|
||||
finalFields.push(newField);
|
||||
} else if (typeof value == "number") {
|
||||
finalFields.push({
|
||||
fieldName: fld,
|
||||
dataType: "INT",
|
||||
});
|
||||
} else {
|
||||
finalFields.push({
|
||||
fieldName: fld,
|
||||
dataType: "VARCHAR(255)",
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
return finalFields;
|
||||
} catch (/** @type {any} */ error: any) {
|
||||
console.log(`grabSchemaFieldsFromData.ts ERROR: ${error.message}`);
|
||||
|
||||
serverError({
|
||||
component: "grabSchemaFieldsFromData.ts",
|
||||
message: error.message,
|
||||
});
|
||||
|
||||
return [];
|
||||
}
|
||||
}
|
||||
@@ -1,46 +0,0 @@
|
||||
// @ts-check
|
||||
|
||||
const serverError = require("./serverError");
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
|
||||
/**
|
||||
* ==============================================================================
|
||||
* @param {Object} params
|
||||
* @param {string | number} params.userId
|
||||
* @returns {import("../../types").DSQL_DatabaseSchemaType[] | null}
|
||||
*/
|
||||
module.exports = function grabUserSchemaData({ userId }) {
|
||||
try {
|
||||
const userSchemaFilePath = path.resolve(
|
||||
process.cwd(),
|
||||
`${process.env.DSQL_USER_DB_SCHEMA_PATH}/user-${userId}/main.json`
|
||||
);
|
||||
const userSchemaData = JSON.parse(
|
||||
fs.readFileSync(userSchemaFilePath, "utf-8")
|
||||
);
|
||||
|
||||
return userSchemaData;
|
||||
} catch (/** @type {any} */ error) {
|
||||
serverError({
|
||||
component: "grabUserSchemaData",
|
||||
message: error.message,
|
||||
});
|
||||
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
@@ -0,0 +1,31 @@
|
||||
import serverError from "./serverError";
|
||||
import fs from "fs";
|
||||
import path from "path";
|
||||
|
||||
/**
|
||||
* # Grab User Schema Data
|
||||
*/
|
||||
export default function grabUserSchemaData({
|
||||
userId,
|
||||
}: {
|
||||
userId: string | number;
|
||||
}): import("../../types").DSQL_DatabaseSchemaType[] | null {
|
||||
try {
|
||||
const userSchemaFilePath = path.resolve(
|
||||
process.cwd(),
|
||||
`${process.env.DSQL_USER_DB_SCHEMA_PATH}/user-${userId}/main.json`
|
||||
);
|
||||
const userSchemaData = JSON.parse(
|
||||
fs.readFileSync(userSchemaFilePath, "utf-8")
|
||||
);
|
||||
|
||||
return userSchemaData;
|
||||
} catch (error: any) {
|
||||
serverError({
|
||||
component: "grabUserSchemaData",
|
||||
message: error.message,
|
||||
});
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
+19
-45
@@ -1,21 +1,5 @@
|
||||
// @ts-check
|
||||
|
||||
/**
|
||||
* Imports
|
||||
* ==============================================================================
|
||||
*/
|
||||
|
||||
const fs = require("fs");
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
const nodemailer = require("nodemailer");
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
import fs from "fs";
|
||||
import nodemailer from "nodemailer";
|
||||
|
||||
let transporter = nodemailer.createTransport({
|
||||
host: process.env.DSQL_MAIL_HOST,
|
||||
@@ -27,31 +11,26 @@ let transporter = nodemailer.createTransport({
|
||||
},
|
||||
});
|
||||
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
type Param = {
|
||||
to?: string;
|
||||
subject?: string;
|
||||
text?: string;
|
||||
html?: string;
|
||||
senderName?: string;
|
||||
alias?: string | null;
|
||||
};
|
||||
|
||||
/**
|
||||
* # Handle mails
|
||||
* @param {object} mailObject - Mail Object with params
|
||||
* @param {string} [mailObject.to] - who is recieving this email? Comma separated for multiple recipients
|
||||
* @param {string} [mailObject.subject] - Mail Subject
|
||||
* @param {string} [mailObject.text] - Mail text
|
||||
* @param {string} [mailObject.html] - Mail HTML
|
||||
* @param {string | null} [mailObject.alias] - Sender alias: "support" or null
|
||||
*
|
||||
* @returns {Promise<any>} mail object
|
||||
* # Handle mails With Nodemailer
|
||||
*/
|
||||
module.exports = async function handleNodemailer({
|
||||
export default async function handleNodemailer({
|
||||
to,
|
||||
subject,
|
||||
text,
|
||||
html,
|
||||
alias,
|
||||
}) {
|
||||
senderName,
|
||||
}: Param): Promise<any> {
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
@@ -89,12 +68,11 @@ module.exports = async function handleNodemailer({
|
||||
////////////////////////////////////////
|
||||
|
||||
try {
|
||||
let mailObject = {};
|
||||
let mailObject: any = {};
|
||||
|
||||
mailObject["from"] = `"Datasquirel" <${sender}>`;
|
||||
mailObject["from"] = `"${senderName || "Datasquirel"}" <${sender}>`;
|
||||
mailObject["sender"] = sender;
|
||||
if (alias) mailObject["replyTo "] = sender;
|
||||
// mailObject["priority"] = "high";
|
||||
if (alias) mailObject["replyTo"] = sender;
|
||||
mailObject["to"] = to;
|
||||
mailObject["subject"] = subject;
|
||||
mailObject["text"] = text;
|
||||
@@ -108,7 +86,7 @@ module.exports = async function handleNodemailer({
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
} catch (/** @type {any} */ error) {
|
||||
} catch (/** @type {any} */ error: any) {
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
@@ -122,8 +100,4 @@ module.exports = async function handleNodemailer({
|
||||
}
|
||||
|
||||
return sentMessage;
|
||||
};
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
// @ts-check
|
||||
|
||||
const sanitizeHtmlOptions = {
|
||||
allowedTags: ["b", "i", "em", "strong", "a", "p", "span", "ul", "ol", "li", "h1", "h2", "h3", "h4", "h5", "h6", "img", "div", "button", "pre", "code", "br"],
|
||||
allowedAttributes: {
|
||||
a: ["href"],
|
||||
img: ["src", "alt", "width", "height", "class", "style"],
|
||||
"*": ["style", "class"],
|
||||
},
|
||||
};
|
||||
|
||||
module.exports = sanitizeHtmlOptions;
|
||||
@@ -0,0 +1,35 @@
|
||||
// @ts-check
|
||||
|
||||
const sanitizeHtmlOptions = {
|
||||
allowedTags: [
|
||||
"b",
|
||||
"i",
|
||||
"em",
|
||||
"strong",
|
||||
"a",
|
||||
"p",
|
||||
"span",
|
||||
"ul",
|
||||
"ol",
|
||||
"li",
|
||||
"h1",
|
||||
"h2",
|
||||
"h3",
|
||||
"h4",
|
||||
"h5",
|
||||
"h6",
|
||||
"img",
|
||||
"div",
|
||||
"button",
|
||||
"pre",
|
||||
"code",
|
||||
"br",
|
||||
],
|
||||
allowedAttributes: {
|
||||
a: ["href"],
|
||||
img: ["src", "alt", "width", "height", "class", "style"],
|
||||
"*": ["style", "class"],
|
||||
},
|
||||
};
|
||||
|
||||
export default sanitizeHtmlOptions;
|
||||
@@ -0,0 +1,110 @@
|
||||
import http from "node:http";
|
||||
import https from "node:https";
|
||||
import querystring from "querystring";
|
||||
import serializeQuery from "../../utils/serialize-query";
|
||||
import _ from "lodash";
|
||||
import { HttpFunctionResponse, HttpRequestParams } from "../../types";
|
||||
|
||||
/**
|
||||
* # Generate a http Request
|
||||
*/
|
||||
export default function httpRequest<
|
||||
ReqObj extends { [k: string]: any } = { [k: string]: any },
|
||||
ResObj extends { [k: string]: any } = { [k: string]: any }
|
||||
>(params: HttpRequestParams<ReqObj>): Promise<HttpFunctionResponse<ResObj>> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const isUrlEncodedFormBody = params.urlEncodedFormBody;
|
||||
|
||||
const reqPayloadString = params.body
|
||||
? isUrlEncodedFormBody
|
||||
? querystring.stringify(params.body)
|
||||
: JSON.stringify(params.body).replace(/\n|\r|\n\r/gm, "")
|
||||
: undefined;
|
||||
|
||||
const reqQueryString = params.query
|
||||
? serializeQuery(params.query)
|
||||
: undefined;
|
||||
|
||||
const paramScheme = params.scheme;
|
||||
const finalScheme = paramScheme == "http" ? http : https;
|
||||
|
||||
const finalPath = params.path
|
||||
? params.path + (reqQueryString ? reqQueryString : "")
|
||||
: undefined;
|
||||
|
||||
delete params.body;
|
||||
delete params.scheme;
|
||||
delete params.query;
|
||||
delete params.urlEncodedFormBody;
|
||||
|
||||
/** @type {import("node:https").RequestOptions} */
|
||||
const requestOptions: import("node:https").RequestOptions = {
|
||||
...params,
|
||||
headers: {
|
||||
"Content-Type": isUrlEncodedFormBody
|
||||
? "application/x-www-form-urlencoded"
|
||||
: "application/json",
|
||||
"Content-Length": reqPayloadString
|
||||
? Buffer.from(reqPayloadString).length
|
||||
: undefined,
|
||||
...params.headers,
|
||||
},
|
||||
port: paramScheme == "https" ? 443 : params.port,
|
||||
path: finalPath,
|
||||
};
|
||||
|
||||
const httpsRequest = finalScheme.request(
|
||||
requestOptions,
|
||||
/**
|
||||
* Callback Function
|
||||
*
|
||||
* @description https request callback
|
||||
*/
|
||||
(response) => {
|
||||
var str = "";
|
||||
|
||||
response.on("data", function (chunk) {
|
||||
str += chunk;
|
||||
});
|
||||
|
||||
response.on("end", function () {
|
||||
const data = (() => {
|
||||
try {
|
||||
const jsonObj: { [k: string]: any } =
|
||||
JSON.parse(str);
|
||||
return jsonObj;
|
||||
} catch (error) {
|
||||
return undefined;
|
||||
}
|
||||
})() as any;
|
||||
|
||||
resolve({
|
||||
status: response.statusCode || 404,
|
||||
data,
|
||||
str,
|
||||
requestedPath: finalPath,
|
||||
});
|
||||
});
|
||||
|
||||
response.on("error", (err) => {
|
||||
resolve({
|
||||
status: response.statusCode || 404,
|
||||
str,
|
||||
error: err.message,
|
||||
requestedPath: finalPath,
|
||||
});
|
||||
});
|
||||
}
|
||||
);
|
||||
|
||||
if (reqPayloadString) {
|
||||
httpsRequest.write(reqPayloadString);
|
||||
}
|
||||
|
||||
httpsRequest.on("error", (error) => {
|
||||
console.log("HTTPS request ERROR =>", error);
|
||||
});
|
||||
|
||||
httpsRequest.end();
|
||||
});
|
||||
}
|
||||
+19
-43
@@ -1,35 +1,22 @@
|
||||
// @ts-check
|
||||
import https from "https";
|
||||
import http from "http";
|
||||
import { URL } from "url";
|
||||
|
||||
type Param = {
|
||||
scheme?: string;
|
||||
url?: string;
|
||||
method?: string;
|
||||
hostname?: string;
|
||||
path?: string;
|
||||
port?: number | string;
|
||||
headers?: object;
|
||||
body?: object;
|
||||
};
|
||||
|
||||
/**
|
||||
* Imports
|
||||
* ==============================================================================
|
||||
* # Make Https Request
|
||||
*/
|
||||
const https = require("https");
|
||||
const http = require("http");
|
||||
const { URL } = require("url");
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
/**
|
||||
* Main Function
|
||||
* ==============================================================================
|
||||
* @param {{
|
||||
* scheme?: string,
|
||||
* url?: string,
|
||||
* method?: string,
|
||||
* hostname?: string,
|
||||
* path?: string,
|
||||
* port?: number | string,
|
||||
* headers?: object,
|
||||
* body?: object,
|
||||
* }} params - params
|
||||
*/
|
||||
module.exports = function httpsRequest({
|
||||
export default function httpsRequest({
|
||||
url,
|
||||
method,
|
||||
hostname,
|
||||
@@ -38,7 +25,7 @@ module.exports = function httpsRequest({
|
||||
body,
|
||||
port,
|
||||
scheme,
|
||||
}) {
|
||||
}: Param) {
|
||||
const reqPayloadString = body ? JSON.stringify(body) : null;
|
||||
|
||||
const PARSED_URL = url ? new URL(url) : null;
|
||||
@@ -48,7 +35,7 @@ module.exports = function httpsRequest({
|
||||
////////////////////////////////////////////////
|
||||
|
||||
/** @type {any} */
|
||||
let requestOptions = {
|
||||
let requestOptions: any = {
|
||||
method: method || "GET",
|
||||
hostname: PARSED_URL ? PARSED_URL.hostname : hostname,
|
||||
port: scheme?.match(/https/i)
|
||||
@@ -126,16 +113,5 @@ module.exports = function httpsRequest({
|
||||
});
|
||||
|
||||
httpsRequest.end();
|
||||
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
});
|
||||
};
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
}
|
||||
+9
-12
@@ -1,16 +1,13 @@
|
||||
// @ts-check
|
||||
|
||||
const fs = require("fs");
|
||||
const serverError = require("./serverError");
|
||||
const NO_DB_HANDLER = require("../../../package-shared/utils/backend/global-db/NO_DB_HANDLER");
|
||||
import fs from "fs";
|
||||
import serverError from "./serverError";
|
||||
import NO_DB_HANDLER from "@/package-shared/utils/backend/global-db/NO_DB_HANDLER";
|
||||
|
||||
/**
|
||||
* Create database from Schema Function
|
||||
* ==============================================================================
|
||||
* @param {string} queryString - Query String
|
||||
* @returns {Promise<any>}
|
||||
* # No Database DB Handler
|
||||
*/
|
||||
module.exports = async function noDatabaseDbHandler(queryString) {
|
||||
export default async function noDatabaseDbHandler(
|
||||
queryString: string
|
||||
): Promise<any> {
|
||||
process.env.NODE_ENV?.match(/dev/) &&
|
||||
fs.appendFileSync(
|
||||
"./.tmp/sqlQuery.sql",
|
||||
@@ -37,7 +34,7 @@ module.exports = async function noDatabaseDbHandler(queryString) {
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
} catch (/** @type {any} */ error) {
|
||||
} catch (/** @type {any} */ error: any) {
|
||||
serverError({
|
||||
component: "noDatabaseDbHandler",
|
||||
message: error.message,
|
||||
@@ -56,4 +53,4 @@ module.exports = async function noDatabaseDbHandler(queryString) {
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
}
|
||||
+11
-12
@@ -1,7 +1,12 @@
|
||||
// @ts-check
|
||||
|
||||
const decrypt = require("../dsql/decrypt");
|
||||
const defaultFieldsRegexp = require("./defaultFieldsRegexp");
|
||||
import decrypt from "../dsql/decrypt";
|
||||
import defaultFieldsRegexp from "./defaultFieldsRegexp";
|
||||
|
||||
type Param = {
|
||||
unparsedResults: any[];
|
||||
tableSchema?: import("../../types").DSQL_TableSchemaType;
|
||||
};
|
||||
|
||||
/**
|
||||
* Parse Database results
|
||||
@@ -9,17 +14,11 @@ const defaultFieldsRegexp = require("./defaultFieldsRegexp");
|
||||
* @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 {any[]} params.unparsedResults - Array of data objects containing Fields(keys)
|
||||
* and corresponding values of the fields(values)
|
||||
* @param {import("../../types").DSQL_TableSchemaType} [params.tableSchema] - Table schema
|
||||
* @returns {Promise<object[]|null>}
|
||||
*/
|
||||
module.exports = async function parseDbResults({
|
||||
export default async function parseDbResults({
|
||||
unparsedResults,
|
||||
tableSchema,
|
||||
}) {
|
||||
}: Param): Promise<any[] | null> {
|
||||
/**
|
||||
* Declare variables
|
||||
*
|
||||
@@ -71,8 +70,8 @@ module.exports = async function parseDbResults({
|
||||
* @description Declare "results" variable
|
||||
*/
|
||||
return parsedResults;
|
||||
} catch (/** @type {any} */ error) {
|
||||
} catch (/** @type {any} */ error: any) {
|
||||
console.log("ERROR in parseDbResults Function =>", error.message);
|
||||
return unparsedResults;
|
||||
}
|
||||
};
|
||||
}
|
||||
+19
-16
@@ -1,28 +1,31 @@
|
||||
// @ts-check
|
||||
|
||||
const fs = require("fs");
|
||||
const { IncomingMessage } = require("http");
|
||||
import fs from "fs";
|
||||
import { IncomingMessage } from "http";
|
||||
|
||||
type Param = {
|
||||
user?: {
|
||||
id?: number | string;
|
||||
first_name?: string;
|
||||
last_name?: string;
|
||||
email?: string;
|
||||
} & any;
|
||||
message: string;
|
||||
component?: string;
|
||||
noMail?: boolean;
|
||||
req?: import("next").NextApiRequest & IncomingMessage;
|
||||
};
|
||||
|
||||
/**
|
||||
* # Server Error
|
||||
*
|
||||
* @param {{
|
||||
* user?: { id?: number | string, first_name?: string, last_name?: string, email?: string } & *,
|
||||
* message: string,
|
||||
* component?: string,
|
||||
* noMail?: boolean,
|
||||
* req?: import("next").NextApiRequest & IncomingMessage,
|
||||
* }} params - user id
|
||||
*
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
module.exports = async function serverError({
|
||||
export default async function serverError({
|
||||
user,
|
||||
message,
|
||||
component,
|
||||
noMail,
|
||||
req,
|
||||
}) {
|
||||
}: Param): Promise<void> {
|
||||
const date = new Date();
|
||||
|
||||
const reqIp = (() => {
|
||||
@@ -80,10 +83,10 @@ module.exports = async function serverError({
|
||||
|
||||
fs.writeFileSync(`./.tmp/error.log`, log);
|
||||
fs.appendFileSync(`./.tmp/error.log`, `\n\n\n\n\n${initialText}`);
|
||||
} catch (/** @type {any} */ error) {
|
||||
} catch (/** @type {any} */ error: any) {
|
||||
console.log("Server Error Reporting Error:", error.message);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
@@ -1,49 +0,0 @@
|
||||
// @ts-check
|
||||
|
||||
const serverError = require("./serverError");
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
|
||||
/**
|
||||
* ==============================================================================
|
||||
* @param {Object} params
|
||||
* @param {string | number} params.userId
|
||||
* @param {import("../../types").DSQL_DatabaseSchemaType[]} params.schemaData
|
||||
* @returns {boolean}
|
||||
*/
|
||||
module.exports = function setUserSchemaData({ userId, schemaData }) {
|
||||
try {
|
||||
const userSchemaFilePath = path.resolve(
|
||||
process.cwd(),
|
||||
`${process.env.DSQL_USER_DB_SCHEMA_PATH}/user-${userId}/main.json`
|
||||
);
|
||||
fs.writeFileSync(
|
||||
userSchemaFilePath,
|
||||
JSON.stringify(schemaData),
|
||||
"utf8"
|
||||
);
|
||||
|
||||
return true;
|
||||
} catch (/** @type {any} */ error) {
|
||||
serverError({
|
||||
component: "/functions/backend/setUserSchemaData",
|
||||
message: error.message,
|
||||
});
|
||||
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
@@ -0,0 +1,45 @@
|
||||
import serverError from "./serverError";
|
||||
import fs from "fs";
|
||||
import path from "path";
|
||||
import { DSQL_DatabaseSchemaType } from "../../types";
|
||||
|
||||
type Param = {
|
||||
userId: string | number;
|
||||
schemaData: DSQL_DatabaseSchemaType[];
|
||||
};
|
||||
|
||||
/**
|
||||
* # Set User Schema Data
|
||||
*/
|
||||
export default function setUserSchemaData({
|
||||
userId,
|
||||
schemaData,
|
||||
}: Param): boolean {
|
||||
try {
|
||||
const userSchemaFilePath = path.resolve(
|
||||
process.cwd(),
|
||||
`${process.env.DSQL_USER_DB_SCHEMA_PATH}/user-${userId}/main.json`
|
||||
);
|
||||
fs.writeFileSync(
|
||||
userSchemaFilePath,
|
||||
JSON.stringify(schemaData),
|
||||
"utf8"
|
||||
);
|
||||
|
||||
return true;
|
||||
} catch (error: any) {
|
||||
serverError({
|
||||
component: "/functions/backend/setUserSchemaData",
|
||||
message: error.message,
|
||||
});
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
+12
-12
@@ -1,17 +1,17 @@
|
||||
// @ts-check
|
||||
|
||||
const { IncomingMessage } = require("http");
|
||||
const parseCookies = require("../../utils/backend/parseCookies");
|
||||
const decrypt = require("../dsql/decrypt");
|
||||
const getAuthCookieNames = require("./cookies/get-auth-cookie-names");
|
||||
import { IncomingMessage } from "http";
|
||||
import parseCookies from "../../utils/backend/parseCookies";
|
||||
import decrypt from "../dsql/decrypt";
|
||||
import getAuthCookieNames from "./cookies/get-auth-cookie-names";
|
||||
|
||||
/**
|
||||
* @async
|
||||
* @param {IncomingMessage} req - https request object
|
||||
*
|
||||
* @returns {Promise<({ email: string, password: string, authKey: string, logged_in_status: boolean, date: number } | null)>}
|
||||
*/
|
||||
module.exports = async function (req) {
|
||||
export default async function (req: IncomingMessage): Promise<{
|
||||
email: string;
|
||||
password: string;
|
||||
authKey: string;
|
||||
logged_in_status: boolean;
|
||||
date: number;
|
||||
} | null> {
|
||||
const { keyCookieName, csrfCookieName } = getAuthCookieNames();
|
||||
const suKeyName = `${keyCookieName}_su`;
|
||||
|
||||
@@ -40,4 +40,4 @@ module.exports = async function (req) {
|
||||
|
||||
/** ********************* return user object */
|
||||
return userObject;
|
||||
};
|
||||
}
|
||||
+16
-19
@@ -1,28 +1,25 @@
|
||||
// @ts-check
|
||||
import serverError from "./serverError";
|
||||
import grabUserSchemaData from "./grabUserSchemaData";
|
||||
import setUserSchemaData from "./setUserSchemaData";
|
||||
import createDbFromSchema from "../../shell/createDbFromSchema";
|
||||
import grabSchemaFieldsFromData from "./grabSchemaFieldsFromData";
|
||||
|
||||
const serverError = require("./serverError");
|
||||
const { default: grabUserSchemaData } = require("./grabUserSchemaData");
|
||||
const { default: setUserSchemaData } = require("./setUserSchemaData");
|
||||
const createDbFromSchema = require("../../shell/createDbFromSchema");
|
||||
const grabSchemaFieldsFromData = require("./grabSchemaFieldsFromData");
|
||||
type Param = {
|
||||
userId: number | string;
|
||||
database: string;
|
||||
newFields?: string[];
|
||||
newPayload?: { [s: string]: any };
|
||||
};
|
||||
|
||||
/**
|
||||
* # Add User Table to Database
|
||||
*
|
||||
* @param {object} params
|
||||
* @param {number | string} params.userId - user id
|
||||
* @param {string} params.database
|
||||
* @param {string[]} [params.newFields] - new fields to add to the users table
|
||||
* @param {Object<string, any>} [params.newPayload]
|
||||
*
|
||||
* @returns {Promise<any>} new user auth object payload
|
||||
*/
|
||||
module.exports = async function updateUsersTableSchema({
|
||||
export default async function updateUsersTableSchema({
|
||||
userId,
|
||||
database,
|
||||
newFields,
|
||||
newPayload,
|
||||
}) {
|
||||
}: Param): Promise<any> {
|
||||
try {
|
||||
const dbFullName = database;
|
||||
|
||||
@@ -67,8 +64,8 @@ module.exports = async function updateUsersTableSchema({
|
||||
});
|
||||
|
||||
return `Done!`;
|
||||
} catch (/** @type {any} */ error) {
|
||||
console.log(`addUsersTableToDb.js ERROR: ${error.message}`);
|
||||
} catch (error: any) {
|
||||
console.log(`addUsersTableToDb.ts ERROR: ${error.message}`);
|
||||
|
||||
serverError({
|
||||
component: "addUsersTableToDb",
|
||||
@@ -77,4 +74,4 @@ module.exports = async function updateUsersTableSchema({
|
||||
});
|
||||
return error.message;
|
||||
}
|
||||
};
|
||||
}
|
||||
+20
-38
@@ -1,31 +1,27 @@
|
||||
// @ts-check
|
||||
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";
|
||||
|
||||
const fs = require("fs");
|
||||
const parseDbResults = require("./parseDbResults");
|
||||
const serverError = require("./serverError");
|
||||
const DB_HANDLER = require("../../utils/backend/global-db/DB_HANDLER");
|
||||
const DSQL_USER_DB_HANDLER = require("../../utils/backend/global-db/DSQL_USER_DB_HANDLER");
|
||||
const LOCAL_DB_HANDLER = require("../../utils/backend/global-db/LOCAL_DB_HANDLER");
|
||||
type Param = {
|
||||
queryString: string;
|
||||
queryValuesArray?: any[];
|
||||
database?: string;
|
||||
tableSchema?: import("../../types").DSQL_TableSchemaType;
|
||||
useLocal?: boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
* DB handler for specific database
|
||||
* ==============================================================================
|
||||
* @async
|
||||
* @param {object} params - Single object params
|
||||
* @param {string} params.queryString - SQL string
|
||||
* @param {*[]} [params.queryValuesArray] - Values Array
|
||||
* @param {string} [params.database] - Database name
|
||||
* @param {import("../../types").DSQL_TableSchemaType} [params.tableSchema] - Table schema
|
||||
* @param {boolean} [params.useLocal]
|
||||
* @returns {Promise<any>}
|
||||
* # DB handler for specific database
|
||||
*/
|
||||
module.exports = async function varDatabaseDbHandler({
|
||||
export default async function varDatabaseDbHandler({
|
||||
queryString,
|
||||
queryValuesArray,
|
||||
database,
|
||||
tableSchema,
|
||||
useLocal,
|
||||
}) {
|
||||
}: Param): Promise<any> {
|
||||
/**
|
||||
* Declare variables
|
||||
*
|
||||
@@ -37,8 +33,7 @@ module.exports = async function varDatabaseDbHandler({
|
||||
? true
|
||||
: false;
|
||||
|
||||
/** @type {any} */
|
||||
const FINAL_DB_HANDLER = useLocal
|
||||
const FINAL_DB_HANDLER: any = useLocal
|
||||
? LOCAL_DB_HANDLER
|
||||
: isMaster
|
||||
? DB_HANDLER
|
||||
@@ -62,7 +57,6 @@ module.exports = async function varDatabaseDbHandler({
|
||||
? await FINAL_DB_HANDLER(queryString, queryValuesArray)
|
||||
: await FINAL_DB_HANDLER({
|
||||
paradigm: "Full Access",
|
||||
database,
|
||||
queryString,
|
||||
queryValues: queryValuesArray,
|
||||
});
|
||||
@@ -71,15 +65,11 @@ module.exports = async function varDatabaseDbHandler({
|
||||
? await FINAL_DB_HANDLER(queryString)
|
||||
: await FINAL_DB_HANDLER({
|
||||
paradigm: "Full Access",
|
||||
database,
|
||||
queryString,
|
||||
});
|
||||
}
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
} catch (/** @type {any} */ error) {
|
||||
} catch (error: any) {
|
||||
console.log(`varDatabaseDbHandler Error: ${error.message}`);
|
||||
serverError({
|
||||
component: "varDatabaseDbHandler/lines-29-32",
|
||||
message: error.message,
|
||||
@@ -99,7 +89,7 @@ module.exports = async function varDatabaseDbHandler({
|
||||
tableSchema: tableSchema,
|
||||
});
|
||||
return parsedResults;
|
||||
} catch (/** @type {any} */ error) {
|
||||
} catch (error: any) {
|
||||
console.log(
|
||||
"\x1b[31mvarDatabaseDbHandler ERROR\x1b[0m =>",
|
||||
database,
|
||||
@@ -111,17 +101,9 @@ module.exports = async function varDatabaseDbHandler({
|
||||
});
|
||||
return null;
|
||||
}
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
} else if (results) {
|
||||
return results;
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
}
|
||||
+17
-18
@@ -1,28 +1,28 @@
|
||||
// @ts-check
|
||||
|
||||
const fs = require("fs");
|
||||
const serverError = require("./serverError");
|
||||
const parseDbResults = require("./parseDbResults");
|
||||
const DSQL_USER_DB_HANDLER = require("../../utils/backend/global-db/DSQL_USER_DB_HANDLER");
|
||||
const LOCAL_DB_HANDLER = require("../../utils/backend/global-db/LOCAL_DB_HANDLER");
|
||||
import fs from "fs";
|
||||
import serverError from "./serverError";
|
||||
import parseDbResults from "./parseDbResults";
|
||||
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";
|
||||
|
||||
type Param = {
|
||||
queryString: string;
|
||||
queryValuesArray?: string[];
|
||||
tableSchema?: import("../../types").DSQL_TableSchemaType;
|
||||
useLocal?: boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {object} param0
|
||||
* @param {string} param0.queryString
|
||||
* @param {string} param0.database
|
||||
* @param {string[]} [param0.queryValuesArray]
|
||||
* @param {import("../../types").DSQL_TableSchemaType} [param0.tableSchema]
|
||||
* @param {boolean} [param0.useLocal]
|
||||
* # Read Only Db Handler with Varaibles
|
||||
* @returns
|
||||
*/
|
||||
module.exports = async function varReadOnlyDatabaseDbHandler({
|
||||
export default async function varReadOnlyDatabaseDbHandler({
|
||||
queryString,
|
||||
database,
|
||||
queryValuesArray,
|
||||
tableSchema,
|
||||
useLocal,
|
||||
}) {
|
||||
}: Param) {
|
||||
/**
|
||||
* Declare variables
|
||||
*
|
||||
@@ -40,13 +40,12 @@ module.exports = async function varReadOnlyDatabaseDbHandler({
|
||||
? await LOCAL_DB_HANDLER(queryString, queryValuesArray)
|
||||
: await DSQL_USER_DB_HANDLER({
|
||||
paradigm: "Read Only",
|
||||
database,
|
||||
queryString,
|
||||
queryValues: queryValuesArray,
|
||||
});
|
||||
|
||||
////////////////////////////////////////
|
||||
} catch (/** @type {any} */ error) {
|
||||
} catch (/** @type {any} */ error: any) {
|
||||
////////////////////////////////////////
|
||||
|
||||
serverError({
|
||||
@@ -76,4 +75,4 @@ module.exports = async function varReadOnlyDatabaseDbHandler({
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
}
|
||||
+17
-13
@@ -1,16 +1,22 @@
|
||||
// @ts-check
|
||||
|
||||
const { scryptSync, createDecipheriv } = require("crypto");
|
||||
const { Buffer } = require("buffer");
|
||||
import { scryptSync, createDecipheriv } from "crypto";
|
||||
import { Buffer } from "buffer";
|
||||
|
||||
type Param = {
|
||||
encryptedString: string;
|
||||
encryptionKey?: string;
|
||||
encryptionSalt?: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* @param {object} param0
|
||||
* @param {string} param0.encryptedString
|
||||
* @param {string} [param0.encryptionKey]
|
||||
* @param {string} [param0.encryptionSalt]
|
||||
* @returns
|
||||
* # Decrypt Function
|
||||
*/
|
||||
const decrypt = ({ encryptedString, encryptionKey, encryptionSalt }) => {
|
||||
export default function decrypt({
|
||||
encryptedString,
|
||||
encryptionKey,
|
||||
encryptionSalt,
|
||||
}: Param) {
|
||||
if (!encryptedString?.match(/./)) {
|
||||
console.log("Encrypted string is invalid");
|
||||
return encryptedString;
|
||||
@@ -38,17 +44,15 @@ const decrypt = ({ encryptedString, encryptionKey, encryptionSalt }) => {
|
||||
|
||||
let key = scryptSync(finalEncryptionKey, finalEncryptionSalt, finalKeyLen);
|
||||
let iv = Buffer.alloc(16, 0);
|
||||
// @ts-ignore
|
||||
|
||||
const decipher = createDecipheriv(algorithm, key, iv);
|
||||
|
||||
try {
|
||||
let decrypted = decipher.update(encryptedString, "hex", "utf8");
|
||||
decrypted += decipher.final("utf8");
|
||||
return decrypted;
|
||||
} catch (/** @type {*} */ error) {
|
||||
} catch (error: any) {
|
||||
console.log("Error in decrypting =>", error.message);
|
||||
return encryptedString;
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = decrypt;
|
||||
}
|
||||
+16
-13
@@ -1,17 +1,22 @@
|
||||
// @ts-check
|
||||
|
||||
const { scryptSync, createCipheriv } = require("crypto");
|
||||
const { Buffer } = require("buffer");
|
||||
import { scryptSync, createCipheriv } from "crypto";
|
||||
import { Buffer } from "buffer";
|
||||
|
||||
type Param = {
|
||||
data: string;
|
||||
encryptionKey?: string;
|
||||
encryptionSalt?: string;
|
||||
};
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {object} param0
|
||||
* @param {string} param0.data
|
||||
* @param {string} [param0.encryptionKey]
|
||||
* @param {string} [param0.encryptionSalt]
|
||||
* @returns {string | null}
|
||||
* # Encrypt String
|
||||
*/
|
||||
const encrypt = ({ data, encryptionKey, encryptionSalt }) => {
|
||||
export default function encrypt({
|
||||
data,
|
||||
encryptionKey,
|
||||
encryptionSalt,
|
||||
}: Param): string | null {
|
||||
if (!data?.match(/./)) {
|
||||
console.log("Encryption string is invalid");
|
||||
return data;
|
||||
@@ -46,10 +51,8 @@ const encrypt = ({ data, encryptionKey, encryptionSalt }) => {
|
||||
let encrypted = cipher.update(data, "utf8", "hex");
|
||||
encrypted += cipher.final("hex");
|
||||
return encrypted;
|
||||
} catch (/** @type {*} */ error) {
|
||||
} catch (/** @type {*} */ error: any) {
|
||||
console.log("Error in encrypting =>", error.message);
|
||||
return data;
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = encrypt;
|
||||
}
|
||||
+10
-8
@@ -1,15 +1,17 @@
|
||||
// @ts-check
|
||||
import { createHmac } from "crypto";
|
||||
|
||||
const { createHmac } = require("crypto");
|
||||
type Param = {
|
||||
password: string;
|
||||
encryptionKey?: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* # Hash password Function
|
||||
* @param {object} param0
|
||||
* @param {string} param0.password - Password to hash
|
||||
* @param {string} [param0.encryptionKey] - Encryption key
|
||||
* @returns {string}
|
||||
*/
|
||||
module.exports = function hashPassword({ password, encryptionKey }) {
|
||||
export default function hashPassword({
|
||||
password,
|
||||
encryptionKey,
|
||||
}: Param): string {
|
||||
const finalEncryptionKey =
|
||||
encryptionKey || process.env.DSQL_ENCRYPTION_PASSWORD;
|
||||
|
||||
@@ -21,4 +23,4 @@ module.exports = function hashPassword({ password, encryptionKey }) {
|
||||
hmac.update(password);
|
||||
let hashed = hmac.digest("base64");
|
||||
return hashed;
|
||||
};
|
||||
}
|
||||
@@ -1,41 +0,0 @@
|
||||
// @ts-check
|
||||
|
||||
/**
|
||||
* @typedef {object} SQLDeleteGenReturn
|
||||
* @property {string} query
|
||||
* @property {string[]} values
|
||||
*/
|
||||
|
||||
/**
|
||||
* @param {object} param0
|
||||
* @param {any} param0.data
|
||||
* @param {string} param0.tableName
|
||||
*
|
||||
* @return {SQLDeleteGenReturn | undefined}
|
||||
*/
|
||||
function sqlDeleteGenerator({ tableName, data }) {
|
||||
try {
|
||||
let queryStr = `DELETE FROM ${tableName}`;
|
||||
|
||||
/** @type {string[]} */
|
||||
let deleteBatch = [];
|
||||
/** @type {string[]} */
|
||||
let queryArr = [];
|
||||
|
||||
Object.keys(data).forEach((ky) => {
|
||||
deleteBatch.push(`${ky}=?`);
|
||||
queryArr.push(data[ky]);
|
||||
});
|
||||
queryStr += ` WHERE ${deleteBatch.join(" AND ")}`;
|
||||
|
||||
return {
|
||||
query: queryStr,
|
||||
values: queryArr,
|
||||
};
|
||||
} catch (/** @type {any} */ error) {
|
||||
console.log(`SQL delete gen ERROR: ${error.message}`);
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = sqlDeleteGenerator;
|
||||
@@ -0,0 +1,36 @@
|
||||
interface SQLDeleteGenReturn {
|
||||
query: string;
|
||||
values: string[];
|
||||
}
|
||||
|
||||
/**
|
||||
* # SQL Delete Generator
|
||||
*/
|
||||
export default function sqlDeleteGenerator({
|
||||
tableName,
|
||||
data,
|
||||
}: {
|
||||
data: any;
|
||||
tableName: string;
|
||||
}): SQLDeleteGenReturn | undefined {
|
||||
try {
|
||||
let queryStr = `DELETE FROM ${tableName}`;
|
||||
|
||||
let deleteBatch: string[] = [];
|
||||
let queryArr: string[] = [];
|
||||
|
||||
Object.keys(data).forEach((ky) => {
|
||||
deleteBatch.push(`${ky}=?`);
|
||||
queryArr.push(data[ky]);
|
||||
});
|
||||
queryStr += ` WHERE ${deleteBatch.join(" AND ")}`;
|
||||
|
||||
return {
|
||||
query: queryStr,
|
||||
values: queryArr,
|
||||
};
|
||||
} catch (/** @type {any} */ error: any) {
|
||||
console.log(`SQL delete gen ERROR: ${error.message}`);
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
+116
-29
@@ -1,28 +1,51 @@
|
||||
// @ts-check
|
||||
import {
|
||||
ServerQueryParam,
|
||||
ServerQueryParamsJoin,
|
||||
ServerQueryQueryObject,
|
||||
} from "../../../types";
|
||||
|
||||
type Param = {
|
||||
genObject?: ServerQueryParam;
|
||||
tableName: string;
|
||||
};
|
||||
|
||||
type Return =
|
||||
| {
|
||||
string: string;
|
||||
values: string[];
|
||||
}
|
||||
| undefined;
|
||||
|
||||
/**
|
||||
* # SQL Query Generator
|
||||
* @description Generates an SQL Query for node module `mysql` or `serverless-mysql`
|
||||
* @type {import("../../../types").SqlGeneratorFn}
|
||||
*/
|
||||
function sqlGenerator({ tableName, genObject }) {
|
||||
export default function sqlGenerator({ tableName, genObject }: Param): Return {
|
||||
if (!genObject) return undefined;
|
||||
|
||||
const finalQuery = genObject.query ? genObject.query : undefined;
|
||||
|
||||
const queryKeys = finalQuery ? Object.keys(finalQuery) : undefined;
|
||||
|
||||
/** @type {string[]} */
|
||||
const sqlSearhValues = [];
|
||||
const sqlSearhString = queryKeys?.map((field) => {
|
||||
const queryObj = finalQuery?.[field];
|
||||
if (!queryObj) return;
|
||||
const sqlSearhValues: string[] = [];
|
||||
|
||||
/**
|
||||
* # Generate Query
|
||||
*/
|
||||
function genSqlSrchStr({
|
||||
queryObj,
|
||||
join,
|
||||
field,
|
||||
}: {
|
||||
queryObj: ServerQueryQueryObject[string];
|
||||
join?: ServerQueryParamsJoin[];
|
||||
field?: string;
|
||||
}) {
|
||||
const finalFieldName = (() => {
|
||||
if (queryObj?.tableName) {
|
||||
return `${queryObj.tableName}.${field}`;
|
||||
}
|
||||
if (genObject.join) {
|
||||
if (join) {
|
||||
return `${tableName}.${field}`;
|
||||
}
|
||||
return field;
|
||||
@@ -35,20 +58,27 @@ function sqlGenerator({ tableName, genObject }) {
|
||||
typeof queryObj.value == "number"
|
||||
) {
|
||||
const valueParsed = String(queryObj.value);
|
||||
|
||||
if (queryObj.equality == "LIKE") {
|
||||
str = `LOWER(${finalFieldName}) LIKE LOWER('%${valueParsed}%')`;
|
||||
} else if (queryObj.equality == "NOT EQUAL") {
|
||||
str = `${finalFieldName} != ?`;
|
||||
sqlSearhValues.push(valueParsed);
|
||||
} else {
|
||||
sqlSearhValues.push(valueParsed);
|
||||
}
|
||||
} else if (Array.isArray(queryObj.value)) {
|
||||
/** @type {string[]} */
|
||||
const strArray = [];
|
||||
const strArray: string[] = [];
|
||||
queryObj.value.forEach((val) => {
|
||||
const valueParsed = val;
|
||||
if (queryObj.equality == "LIKE") {
|
||||
strArray.push(
|
||||
`LOWER(${finalFieldName}) LIKE LOWER('%${valueParsed}%')`
|
||||
);
|
||||
} else if (queryObj.equality == "NOT EQUAL") {
|
||||
strArray.push(`${finalFieldName} != ?`);
|
||||
sqlSearhValues.push(valueParsed);
|
||||
} else {
|
||||
strArray.push(`${finalFieldName} = ?`);
|
||||
sqlSearhValues.push(valueParsed);
|
||||
@@ -59,11 +89,44 @@ function sqlGenerator({ tableName, genObject }) {
|
||||
}
|
||||
|
||||
return str;
|
||||
}
|
||||
|
||||
const sqlSearhString = queryKeys?.map((field) => {
|
||||
const queryObj =
|
||||
/** @type {import("../../../types").ServerQueryQueryObject} */ finalQuery?.[
|
||||
field
|
||||
];
|
||||
if (!queryObj) return;
|
||||
|
||||
if (queryObj.__query) {
|
||||
const subQueryGroup =
|
||||
/** @type {import("../../../types").ServerQueryQueryObject}} */ queryObj.__query;
|
||||
|
||||
const subSearchKeys = Object.keys(subQueryGroup);
|
||||
const subSearchString = subSearchKeys.map((_field) => {
|
||||
const newSubQueryObj = subQueryGroup?.[_field];
|
||||
|
||||
return genSqlSrchStr({
|
||||
queryObj: newSubQueryObj,
|
||||
field: _field,
|
||||
join: genObject.join,
|
||||
});
|
||||
});
|
||||
console.log("queryObj.operator", queryObj.operator);
|
||||
|
||||
return (
|
||||
"(" +
|
||||
subSearchString.join(` ${queryObj.operator || "AND"} `) +
|
||||
")"
|
||||
);
|
||||
}
|
||||
|
||||
return genSqlSrchStr({ queryObj, field, join: genObject.join });
|
||||
});
|
||||
|
||||
function generateJoinStr(
|
||||
/** @type {import("../../../types").ServerQueryParamsJoinMatchObject} */ mtch,
|
||||
/** @type {import("../../../types").ServerQueryParamsJoin} */ join
|
||||
/** @type {import("../../../types").ServerQueryParamsJoinMatchObject} */ mtch: import("../../../types").ServerQueryParamsJoinMatchObject,
|
||||
/** @type {import("../../../types").ServerQueryParamsJoin} */ join: import("../../../types").ServerQueryParamsJoin
|
||||
) {
|
||||
return `${
|
||||
typeof mtch.source == "object" ? mtch.source.tableName : tableName
|
||||
@@ -74,6 +137,18 @@ function sqlGenerator({ tableName, genObject }) {
|
||||
return `'${mtch.targetLiteral}'`;
|
||||
}
|
||||
|
||||
if (join.alias) {
|
||||
return `${
|
||||
typeof mtch.target == "object"
|
||||
? mtch.target.tableName
|
||||
: join.alias
|
||||
}.${
|
||||
typeof mtch.target == "object"
|
||||
? mtch.target.fieldName
|
||||
: mtch.target
|
||||
}`;
|
||||
}
|
||||
|
||||
return `${
|
||||
typeof mtch.target == "object"
|
||||
? mtch.target.tableName
|
||||
@@ -106,31 +181,37 @@ function sqlGenerator({ tableName, genObject }) {
|
||||
|
||||
if (genObject.join) {
|
||||
/** @type {string[]} */
|
||||
const existingJoinTableNames = [tableName];
|
||||
const existingJoinTableNames: string[] = [tableName];
|
||||
|
||||
str +=
|
||||
"," +
|
||||
genObject.join
|
||||
.map((joinObj) => {
|
||||
if (existingJoinTableNames.includes(joinObj.tableName))
|
||||
const joinTableName = joinObj.alias
|
||||
? joinObj.alias
|
||||
: joinObj.tableName;
|
||||
|
||||
if (existingJoinTableNames.includes(joinTableName))
|
||||
return null;
|
||||
existingJoinTableNames.push(joinObj.tableName);
|
||||
existingJoinTableNames.push(joinTableName);
|
||||
|
||||
if (joinObj.selectFields) {
|
||||
return joinObj.selectFields
|
||||
.map((slFld) => {
|
||||
if (typeof slFld == "string") {
|
||||
return `${joinObj.tableName}.${slFld}`;
|
||||
} else if (typeof slFld == "object") {
|
||||
let aliasSlctFld = `${joinObj.tableName}.${slFld.field}`;
|
||||
if (slFld.alias)
|
||||
aliasSlctFld += ` as ${slFld.alias}`;
|
||||
return aliasSlctFld;
|
||||
.map((selectField) => {
|
||||
if (typeof selectField == "string") {
|
||||
return `${joinTableName}.${selectField}`;
|
||||
} else if (typeof selectField == "object") {
|
||||
let aliasSelectField = selectField.count
|
||||
? `COUNT(${joinTableName}.${selectField.field})`
|
||||
: `${joinTableName}.${selectField.field}`;
|
||||
if (selectField.alias)
|
||||
aliasSelectField += ` AS ${selectField.alias}`;
|
||||
return aliasSelectField;
|
||||
}
|
||||
})
|
||||
.join(",");
|
||||
} else {
|
||||
return `${joinObj.tableName}.*`;
|
||||
return `${joinTableName}.*`;
|
||||
}
|
||||
})
|
||||
.filter((_) => Boolean(_))
|
||||
@@ -147,7 +228,9 @@ function sqlGenerator({ tableName, genObject }) {
|
||||
return (
|
||||
join.joinType +
|
||||
" " +
|
||||
join.tableName +
|
||||
(join.alias
|
||||
? join.tableName + " " + join.alias
|
||||
: join.tableName) +
|
||||
" ON " +
|
||||
(() => {
|
||||
if (Array.isArray(join.match)) {
|
||||
@@ -157,7 +240,11 @@ function sqlGenerator({ tableName, genObject }) {
|
||||
.map((mtch) =>
|
||||
generateJoinStr(mtch, join)
|
||||
)
|
||||
.join(" AND ") +
|
||||
.join(
|
||||
join.operator
|
||||
? ` ${join.operator} `
|
||||
: " AND "
|
||||
) +
|
||||
")"
|
||||
);
|
||||
} else if (typeof join.match == "object") {
|
||||
@@ -172,7 +259,7 @@ function sqlGenerator({ tableName, genObject }) {
|
||||
return str;
|
||||
})();
|
||||
|
||||
if (sqlSearhString) {
|
||||
if (sqlSearhString?.[0] && sqlSearhString.find((str) => str)) {
|
||||
const stringOperator = genObject?.searchOperator || "AND";
|
||||
queryString += ` WHERE ${sqlSearhString.join(` ${stringOperator} `)} `;
|
||||
}
|
||||
@@ -183,12 +270,12 @@ function sqlGenerator({ tableName, genObject }) {
|
||||
? `${tableName}.${genObject.order.field}`
|
||||
: genObject.order.field
|
||||
} ${genObject.order.strategy}`;
|
||||
|
||||
if (genObject.limit) queryString += ` LIMIT ${genObject.limit}`;
|
||||
if (genObject.offset) queryString += ` OFFSET ${genObject.offset}`;
|
||||
|
||||
return {
|
||||
string: queryString,
|
||||
values: sqlSearhValues,
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = sqlGenerator;
|
||||
+16
-17
@@ -1,23 +1,24 @@
|
||||
// @ts-check
|
||||
|
||||
/**
|
||||
* @typedef {object} SQLInsertGenReturn
|
||||
* @property {string} query
|
||||
* @property {string[]} values
|
||||
*/
|
||||
interface SQLInsertGenReturn {
|
||||
query: string;
|
||||
values: string[];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {object} param0
|
||||
* @param {any[]} param0.data
|
||||
* @param {string} param0.tableName
|
||||
*
|
||||
* @return {SQLInsertGenReturn | undefined}
|
||||
* # SQL Insert Generator
|
||||
*/
|
||||
function sqlInsertGenerator({ tableName, data }) {
|
||||
export default function sqlInsertGenerator({
|
||||
tableName,
|
||||
data,
|
||||
}: {
|
||||
data: any[];
|
||||
tableName: string;
|
||||
}): SQLInsertGenReturn | undefined {
|
||||
try {
|
||||
if (Array.isArray(data) && data?.[0]) {
|
||||
/** @type {string[]} */
|
||||
let insertKeys = [];
|
||||
let insertKeys: string[] = [];
|
||||
|
||||
data.forEach((dt) => {
|
||||
const kys = Object.keys(dt);
|
||||
@@ -29,9 +30,9 @@ function sqlInsertGenerator({ tableName, data }) {
|
||||
});
|
||||
|
||||
/** @type {string[]} */
|
||||
let queryBatches = [];
|
||||
let queryBatches: string[] = [];
|
||||
/** @type {string[]} */
|
||||
let queryValues = [];
|
||||
let queryValues: string[] = [];
|
||||
|
||||
data.forEach((item) => {
|
||||
queryBatches.push(
|
||||
@@ -58,10 +59,8 @@ function sqlInsertGenerator({ tableName, data }) {
|
||||
} else {
|
||||
return undefined;
|
||||
}
|
||||
} catch (/** @type {any} */ error) {
|
||||
} catch (/** @type {any} */ error: any) {
|
||||
console.log(`SQL insert gen ERROR: ${error.message}`);
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = sqlInsertGenerator;
|
||||
@@ -1,57 +0,0 @@
|
||||
// @ts-check
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
require("dotenv").config({ path: "./../.env" });
|
||||
const mysql = require("serverless-mysql");
|
||||
const grabDbSSL = require("../utils/backend/grabDbSSL");
|
||||
|
||||
const connection = 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,
|
||||
charset: "utf8mb4",
|
||||
ssl: grabDbSSL(),
|
||||
},
|
||||
});
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
/**
|
||||
* # Main DB Handler Function
|
||||
* @async
|
||||
*
|
||||
* @param {object} params
|
||||
* @param {string} params.query
|
||||
* @param {string[] | object} [params.values]
|
||||
* @param {string} [params.database]
|
||||
*
|
||||
* @returns {Promise<object|null>}
|
||||
*/
|
||||
(async () => {
|
||||
/**
|
||||
* Switch Database
|
||||
*
|
||||
* @description If a database is provided, switch to it
|
||||
*/
|
||||
try {
|
||||
const result = await connection.query(
|
||||
"SELECT id,first_name,last_name FROM users LIMIT 3"
|
||||
);
|
||||
console.log("Connection Query Success =>", result);
|
||||
} catch (/** @type {any} */ error) {
|
||||
console.log("Connection query ERROR =>", error.message);
|
||||
} finally {
|
||||
connection.end();
|
||||
process.exit();
|
||||
}
|
||||
})();
|
||||
Executable
+30
@@ -0,0 +1,30 @@
|
||||
require("dotenv").config({ path: "./../.env" });
|
||||
import mysql from "serverless-mysql";
|
||||
import grabDbSSL from "../utils/backend/grabDbSSL";
|
||||
|
||||
/**
|
||||
* # Main DB Handler Function
|
||||
* @async
|
||||
*
|
||||
* @param {object} params
|
||||
* @param {string} params.query
|
||||
* @param {string[] | object} [params.values]
|
||||
* @param {string} [params.database]
|
||||
*
|
||||
* @returns {Promise<object|null>}
|
||||
*/
|
||||
(async () => {
|
||||
const connection = global.DSQL_DB_CONN;
|
||||
|
||||
try {
|
||||
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();
|
||||
process.exit();
|
||||
}
|
||||
})();
|
||||
+49
-53
@@ -1,28 +1,37 @@
|
||||
// @ts-check
|
||||
import path from "path";
|
||||
import fs from "fs";
|
||||
|
||||
const path = require("path");
|
||||
const fs = require("fs");
|
||||
import noDatabaseDbHandler from "./utils/noDatabaseDbHandler";
|
||||
import varDatabaseDbHandler from "./utils/varDatabaseDbHandler";
|
||||
import createTable from "./utils/createTable";
|
||||
import updateTable from "./utils/updateTable";
|
||||
import dbHandler from "./utils/dbHandler";
|
||||
import EJSON from "../utils/ejson";
|
||||
import { DSQL_DatabaseSchemaType } from "../types";
|
||||
|
||||
require("dotenv").config({ path: "./../.env" });
|
||||
|
||||
const noDatabaseDbHandler = require("./utils/noDatabaseDbHandler");
|
||||
const varDatabaseDbHandler = require("./utils/varDatabaseDbHandler");
|
||||
const createTable = require("./utils/createTable");
|
||||
const updateTable = require("./utils/updateTable");
|
||||
const dbHandler = require("./utils/dbHandler");
|
||||
const EJSON = require("../utils/ejson");
|
||||
|
||||
const execFlag = process.argv.find((arg) => arg === "--exec");
|
||||
type Param = {
|
||||
userId?: number | string | null;
|
||||
targetDatabase?: string;
|
||||
dbSchemaData?: import("../types").DSQL_DatabaseSchemaType[];
|
||||
};
|
||||
|
||||
/**
|
||||
* Create database from Schema Function
|
||||
* =============================================
|
||||
* @param {object} params - Single object params
|
||||
* @param {number|string|null} [params.userId] - User ID or null
|
||||
* @param {string} [params.targetDatabase] - User Database full name
|
||||
* @param {import("../types").DSQL_DatabaseSchemaType[]} [params.dbSchemaData]
|
||||
* # Create database from Schema Function
|
||||
* @requires DSQL_DB_CONN - Gobal Variable for Datasquirel Database
|
||||
*/
|
||||
async function createDbFromSchema({ userId, targetDatabase, dbSchemaData }) {
|
||||
export default async function createDbFromSchema({
|
||||
userId,
|
||||
targetDatabase,
|
||||
dbSchemaData,
|
||||
}: Param) {
|
||||
console.log("///////////////////////////////");
|
||||
console.log("///////////////////////////////");
|
||||
console.log("Rebuilding Database ...");
|
||||
console.log("process.env.DSQL_DB_HOST", process.env.DSQL_DB_HOST);
|
||||
console.log("process.env.DSQL_DB_USERNAME", process.env.DSQL_DB_USERNAME);
|
||||
console.log("process.env.DSQL_DB_PASSWORD", process.env.DSQL_DB_PASSWORD);
|
||||
console.log("process.env.DSQL_DB_NAME", process.env.DSQL_DB_NAME);
|
||||
|
||||
const schemaPath = userId
|
||||
? path.join(
|
||||
String(process.env.DSQL_USER_DB_SCHEMA_PATH),
|
||||
@@ -30,12 +39,11 @@ async function createDbFromSchema({ userId, targetDatabase, dbSchemaData }) {
|
||||
)
|
||||
: path.resolve(__dirname, "../../jsonData/dbSchemas/main.json");
|
||||
|
||||
/** @type {import("../types").DSQL_DatabaseSchemaType[] | undefined} */
|
||||
const dbSchema =
|
||||
const dbSchema: DSQL_DatabaseSchemaType[] | undefined =
|
||||
dbSchemaData ||
|
||||
/** @type {import("../types").DSQL_DatabaseSchemaType[] | undefined} */ (
|
||||
EJSON.parse(fs.readFileSync(schemaPath, "utf8"))
|
||||
);
|
||||
(EJSON.parse(fs.readFileSync(schemaPath, "utf8")) as
|
||||
| DSQL_DatabaseSchemaType[]
|
||||
| undefined);
|
||||
|
||||
if (!dbSchema) {
|
||||
console.log("Schema Not Found!");
|
||||
@@ -45,8 +53,8 @@ async function createDbFromSchema({ userId, targetDatabase, dbSchemaData }) {
|
||||
// await createDatabasesFromSchema(dbSchema);
|
||||
|
||||
for (let i = 0; i < dbSchema.length; i++) {
|
||||
/** @type {import("../types").DSQL_DatabaseSchemaType} */
|
||||
const database = dbSchema[i];
|
||||
const database: DSQL_DatabaseSchemaType = dbSchema[i];
|
||||
|
||||
const { dbFullName, tables, dbName, dbSlug, childrenDatabases } =
|
||||
database;
|
||||
|
||||
@@ -55,13 +63,11 @@ async function createDbFromSchema({ userId, targetDatabase, dbSchemaData }) {
|
||||
}
|
||||
|
||||
/** @type {any} */
|
||||
const dbCheck = await noDatabaseDbHandler(
|
||||
const dbCheck: any = await noDatabaseDbHandler(
|
||||
`SELECT SCHEMA_NAME AS dbFullName FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = '${dbFullName}'`
|
||||
);
|
||||
|
||||
if (dbCheck && dbCheck[0]?.dbFullName) {
|
||||
// Database Exists
|
||||
} else {
|
||||
if (!dbCheck?.[0]?.dbFullName) {
|
||||
const newDatabase = await noDatabaseDbHandler(
|
||||
`CREATE DATABASE IF NOT EXISTS \`${dbFullName}\` CHARACTER SET utf8mb4 COLLATE utf8mb4_bin`
|
||||
);
|
||||
@@ -72,7 +78,7 @@ async function createDbFromSchema({ userId, targetDatabase, dbSchemaData }) {
|
||||
* @type {any}
|
||||
* @description Select All tables in target database
|
||||
*/
|
||||
const allTables = await noDatabaseDbHandler(
|
||||
const allTables: any = await noDatabaseDbHandler(
|
||||
`SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA='${dbFullName}'`
|
||||
);
|
||||
|
||||
@@ -102,20 +108,17 @@ async function createDbFromSchema({ userId, targetDatabase, dbSchemaData }) {
|
||||
if (oldTableFilteredArray && oldTableFilteredArray[0]) {
|
||||
console.log("Renaming Table");
|
||||
await varDatabaseDbHandler({
|
||||
queryString: `RENAME TABLE \`${oldTableFilteredArray[0].tableNameOld}\` TO \`${oldTableFilteredArray[0].tableName}\``,
|
||||
database: dbFullName,
|
||||
queryString: `RENAME TABLE \`${dbFullName}\`.\`${oldTableFilteredArray[0].tableNameOld}\` TO \`${oldTableFilteredArray[0].tableName}\``,
|
||||
});
|
||||
} else {
|
||||
console.log(`Dropping Table from ${dbFullName}`);
|
||||
await varDatabaseDbHandler({
|
||||
queryString: `DROP TABLE \`${TABLE_NAME}\``,
|
||||
database: dbFullName,
|
||||
queryString: `DROP TABLE \`${dbFullName}\`.\`${TABLE_NAME}\``,
|
||||
});
|
||||
|
||||
const deleteTableEntry = await dbHandler({
|
||||
query: `DELETE FROM user_database_tables WHERE user_id = ? AND db_slug = ? AND table_slug = ?`,
|
||||
query: `DELETE FROM datasquirel.user_database_tables WHERE user_id = ? AND db_slug = ? AND table_slug = ?`,
|
||||
values: [userId, dbSlug, TABLE_NAME],
|
||||
database: "datasquirel",
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -123,8 +126,7 @@ async function createDbFromSchema({ userId, targetDatabase, dbSchemaData }) {
|
||||
|
||||
const recordedDbEntryArray = userId
|
||||
? await varDatabaseDbHandler({
|
||||
database: "datasquirel",
|
||||
queryString: `SELECT * FROM user_databases WHERE db_full_name = ?`,
|
||||
queryString: `SELECT * FROM datasquirel.user_databases WHERE db_full_name = ?`,
|
||||
queryValuesArray: [dbFullName],
|
||||
})
|
||||
: undefined;
|
||||
@@ -143,7 +145,7 @@ async function createDbFromSchema({ userId, targetDatabase, dbSchemaData }) {
|
||||
* @description Check if table exists
|
||||
* @type {any}
|
||||
*/
|
||||
const tableCheck = await varDatabaseDbHandler({
|
||||
const tableCheck: any = await varDatabaseDbHandler({
|
||||
queryString: `
|
||||
SELECT EXISTS (
|
||||
SELECT
|
||||
@@ -155,7 +157,6 @@ async function createDbFromSchema({ userId, targetDatabase, dbSchemaData }) {
|
||||
TABLE_NAME = ?
|
||||
) AS tableExists`,
|
||||
queryValuesArray: [dbFullName, table.tableName],
|
||||
database: dbFullName,
|
||||
});
|
||||
|
||||
////////////////////////////////////////
|
||||
@@ -209,7 +210,6 @@ async function createDbFromSchema({ userId, targetDatabase, dbSchemaData }) {
|
||||
tableName: tableName,
|
||||
tableInfoArray: fields,
|
||||
dbFullName: dbFullName,
|
||||
dbSchema,
|
||||
tableSchema: table,
|
||||
recordedDbEntry,
|
||||
});
|
||||
@@ -240,10 +240,9 @@ async function createDbFromSchema({ userId, targetDatabase, dbSchemaData }) {
|
||||
* @type {import("../types").DSQL_MYSQL_SHOW_INDEXES_Type[]}
|
||||
* @description All indexes from MYSQL db
|
||||
*/ // @ts-ignore
|
||||
const allExistingIndexes =
|
||||
const allExistingIndexes: import("../types").DSQL_MYSQL_SHOW_INDEXES_Type[] =
|
||||
await varDatabaseDbHandler({
|
||||
queryString: `SHOW INDEXES FROM \`${tableName}\``,
|
||||
database: dbFullName,
|
||||
queryString: `SHOW INDEXES FROM \`${dbFullName}\`.\`${tableName}\``,
|
||||
});
|
||||
|
||||
const existingKeyInDb =
|
||||
@@ -265,11 +264,10 @@ async function createDbFromSchema({ userId, targetDatabase, dbSchemaData }) {
|
||||
indexType?.match(/fullText/i)
|
||||
? " FULLTEXT"
|
||||
: ""
|
||||
} INDEX \`${alias}\` ON ${tableName}(${indexTableFields
|
||||
} INDEX \`${alias}\` ON \`${dbFullName}\`.\`${tableName}\`(${indexTableFields
|
||||
?.map((nm) => nm.value)
|
||||
.map((nm) => `\`${nm}\``)
|
||||
.join(",")}) COMMENT 'schema_index'`,
|
||||
database: dbFullName,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -293,10 +291,8 @@ async function createDbFromSchema({ userId, targetDatabase, dbSchemaData }) {
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = createDbFromSchema;
|
||||
|
||||
if (execFlag) {
|
||||
createDbFromSchema({});
|
||||
console.log("Database Successfully Rebuilt!");
|
||||
console.log("///////////////////////////////");
|
||||
console.log("///////////////////////////////");
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
// @ts-check
|
||||
|
||||
const fs = require("fs");
|
||||
|
||||
async function deploy() {}
|
||||
|
||||
deploy();
|
||||
Executable
+5
@@ -0,0 +1,5 @@
|
||||
import fs from "fs";
|
||||
|
||||
async function deploy() {}
|
||||
|
||||
deploy();
|
||||
+2
-13
@@ -1,10 +1,6 @@
|
||||
// @ts-check
|
||||
|
||||
require("dotenv").config({ path: "./../.env" });
|
||||
|
||||
////////////////////////////////////////
|
||||
|
||||
const varDatabaseDbHandler = require("../functions/backend/varDatabaseDbHandler");
|
||||
import varDatabaseDbHandler from "../functions/backend/varDatabaseDbHandler";
|
||||
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
@@ -36,23 +32,16 @@ varDatabaseDbHandler({
|
||||
|
||||
const tableInfo = await varDatabaseDbHandler({
|
||||
queryString: `SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA='${db_full_name}' AND TABLE_NAME='${table_slug}'`,
|
||||
database: db_full_name,
|
||||
});
|
||||
|
||||
const updateDbCharset = await varDatabaseDbHandler({
|
||||
queryString: `ALTER DATABASE ${db_full_name} CHARACTER SET = utf8mb4 COLLATE = utf8mb4_bin;`,
|
||||
database: db_full_name,
|
||||
});
|
||||
|
||||
const updateEncoding = await varDatabaseDbHandler({
|
||||
queryString: `ALTER TABLE \`${table_slug}\` CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_bin`,
|
||||
database: db_full_name,
|
||||
queryString: `ALTER TABLE \`${db_full_name}\`.\`${table_slug}\` CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_bin`,
|
||||
});
|
||||
}
|
||||
|
||||
process.exit();
|
||||
});
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
+2
-4
@@ -1,7 +1,5 @@
|
||||
// @ts-check
|
||||
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
import fs from "fs";
|
||||
import path from "path";
|
||||
|
||||
const jsonFile = path.resolve(__dirname, "../../jsonData/userPriviledges.json");
|
||||
const base64File = Buffer.from(fs.readFileSync(jsonFile, "utf8")).toString(
|
||||
@@ -1,79 +0,0 @@
|
||||
// @ts-check
|
||||
|
||||
require("dotenv").config({ path: "./../.env" });
|
||||
|
||||
const serverError = require("../functions/backend/serverError");
|
||||
const noDatabaseDbHandler = require("./utils/noDatabaseDbHandler");
|
||||
////////////////////////////////////////
|
||||
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
|
||||
/**
|
||||
* # Create Database From Schema
|
||||
* @param {object} param0
|
||||
* @param {string | null} param0.userId
|
||||
*/
|
||||
async function createDbFromSchema({ userId }) {
|
||||
/**
|
||||
* Grab Schema
|
||||
*
|
||||
* @description Grab Schema
|
||||
*/
|
||||
try {
|
||||
const defaultMariadbUserHost = process.env.DSQL_DB_HOST || "127.0.0.1";
|
||||
|
||||
const allDatabases = await noDatabaseDbHandler(`SHOW DATABASES`);
|
||||
|
||||
const datasquirelUserDatabases = allDatabases.filter(
|
||||
(/** @type {any} */ database) =>
|
||||
database.Database.match(/datasquirel_user_/)
|
||||
);
|
||||
|
||||
for (let i = 0; i < datasquirelUserDatabases.length; i++) {
|
||||
const datasquirelUserDatabase = datasquirelUserDatabases[i];
|
||||
const { Database } = datasquirelUserDatabase;
|
||||
|
||||
const grantDbPriviledges = await noDatabaseDbHandler(
|
||||
`GRANT ALL PRIVILEGES ON ${Database}.* TO '${process.env.DSQL_DB_FULL_ACCESS_USERNAME}'@'%' WITH GRANT OPTION`
|
||||
);
|
||||
|
||||
const grantRead = await noDatabaseDbHandler(
|
||||
`GRANT SELECT ON ${Database}.* TO '${process.env.DSQL_DB_READ_ONLY_USERNAME}'@'%'`
|
||||
);
|
||||
}
|
||||
|
||||
const flushPriviledged = await noDatabaseDbHandler(`FLUSH PRIVILEGES`);
|
||||
} catch (/** @type {any} */ error) {
|
||||
serverError({
|
||||
component: "shell/grantDbPriviledges/main-catch-error",
|
||||
message: error.message,
|
||||
user: { id: userId },
|
||||
});
|
||||
}
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
process.exit();
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
}
|
||||
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
|
||||
const userArg = process.argv[process.argv.indexOf("--user")];
|
||||
const externalUser = process.argv[process.argv.indexOf("--user") + 1];
|
||||
|
||||
createDbFromSchema({ userId: userArg ? externalUser : null });
|
||||
+52
@@ -0,0 +1,52 @@
|
||||
require("dotenv").config({ path: "./../.env" });
|
||||
import serverError from "../functions/backend/serverError";
|
||||
import noDatabaseDbHandler from "./utils/noDatabaseDbHandler";
|
||||
|
||||
/**
|
||||
* # Create Database From Schema
|
||||
*/
|
||||
async function grantFullPrivileges({ userId }: { userId: string | null }) {
|
||||
/**
|
||||
* Grab Schema
|
||||
*
|
||||
* @description Grab Schema
|
||||
*/
|
||||
try {
|
||||
const defaultMariadbUserHost = process.env.DSQL_DB_HOST || "127.0.0.1";
|
||||
|
||||
const allDatabases = await noDatabaseDbHandler(`SHOW DATABASES`);
|
||||
|
||||
const datasquirelUserDatabases = allDatabases.filter(
|
||||
(/** @type {any} */ database: any) =>
|
||||
database.Database.match(/datasquirel_user_/)
|
||||
);
|
||||
|
||||
for (let i = 0; i < datasquirelUserDatabases.length; i++) {
|
||||
const datasquirelUserDatabase = datasquirelUserDatabases[i];
|
||||
const { Database } = datasquirelUserDatabase;
|
||||
|
||||
const grantDbPriviledges = await noDatabaseDbHandler(
|
||||
`GRANT ALL PRIVILEGES ON ${Database}.* TO '${process.env.DSQL_DB_FULL_ACCESS_USERNAME}'@'%' WITH GRANT OPTION`
|
||||
);
|
||||
|
||||
const grantRead = await noDatabaseDbHandler(
|
||||
`GRANT SELECT ON ${Database}.* TO '${process.env.DSQL_DB_READ_ONLY_USERNAME}'@'%'`
|
||||
);
|
||||
}
|
||||
|
||||
const flushPriviledged = await noDatabaseDbHandler(`FLUSH PRIVILEGES`);
|
||||
} catch (/** @type {any} */ error: any) {
|
||||
serverError({
|
||||
component: "shell/grantDbPriviledges/main-catch-error",
|
||||
message: error.message,
|
||||
user: { id: userId },
|
||||
});
|
||||
}
|
||||
|
||||
process.exit();
|
||||
}
|
||||
|
||||
const userArg = process.argv[process.argv.indexOf("--user")];
|
||||
const externalUser = process.argv[process.argv.indexOf("--user") + 1];
|
||||
|
||||
grantFullPrivileges({ userId: userArg ? externalUser : null });
|
||||
+10
-14
@@ -1,5 +1,5 @@
|
||||
const fs = require("fs");
|
||||
const { exec } = require("child_process");
|
||||
import fs from "fs";
|
||||
import { exec } from "child_process";
|
||||
|
||||
require("dotenv").config({ path: "./../.env" });
|
||||
|
||||
@@ -12,24 +12,21 @@ const destinationFile =
|
||||
? process.argv[process.argv.indexOf("--dst") + 1]
|
||||
: null;
|
||||
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
|
||||
console.log("Running Less compiler ...");
|
||||
|
||||
const sourceFiles = sourceFile.split(",");
|
||||
const dstFiles = destinationFile.split(",");
|
||||
const sourceFiles = sourceFile?.split(",");
|
||||
const dstFiles = destinationFile?.split(",");
|
||||
|
||||
if (!sourceFiles || !dstFiles) {
|
||||
throw new Error("No Source or Destination Files!");
|
||||
}
|
||||
|
||||
for (let i = 0; i < sourceFiles.length; i++) {
|
||||
const srcFolder = sourceFiles[i];
|
||||
const dstFile = dstFiles[i];
|
||||
|
||||
fs.watch(srcFolder, { recursive: true }, (evtType, prev) => {
|
||||
if (prev?.match(/\(/) || prev?.match(/\.js$/i)) {
|
||||
if (prev?.match(/\(/) || prev?.match(/\.(j|t)s$/i)) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -61,11 +58,10 @@ for (let i = 0; i < sourceFiles.length; i++) {
|
||||
: finalDstPath.replace(/\/$/, "") + "/_main.css"
|
||||
}`,
|
||||
(error, stdout, stderr) => {
|
||||
/** @type {Error} */
|
||||
if (error) {
|
||||
console.log("ERROR =>", error.message);
|
||||
|
||||
if (!evtType?.match(/change/i) && prev.match(/\[/)) {
|
||||
if (!evtType?.match(/change/i) && prev?.match(/\[/)) {
|
||||
fs.unlinkSync(finalDstPath);
|
||||
}
|
||||
|
||||
+22
-23
@@ -1,26 +1,27 @@
|
||||
// @ts-check
|
||||
import noDatabaseDbHandler from "../utils/noDatabaseDbHandler";
|
||||
|
||||
const noDatabaseDbHandler = require("../utils/noDatabaseDbHandler");
|
||||
export interface GrantType {
|
||||
database: string;
|
||||
table: string;
|
||||
privileges: string[];
|
||||
}
|
||||
|
||||
type Param = {
|
||||
username?: string;
|
||||
host?: string;
|
||||
grants?: GrantType[];
|
||||
userId: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* @typedef {object} GrantType
|
||||
* @property {string} database - Database Name
|
||||
* @property {string} table - Table Name
|
||||
* @property {string[]} privileges - Privileges
|
||||
* # Handle Grants for Users
|
||||
*/
|
||||
|
||||
/**
|
||||
* Handle Grants for Users
|
||||
* ================================================
|
||||
* @param {object} params - Single object params
|
||||
* @param {string} params.username - Username
|
||||
* @param {string} params.host - Host
|
||||
* @param {GrantType[]} params.grants - Grants
|
||||
* @param {string} params.userId
|
||||
*
|
||||
* @returns {Promise<boolean>} success
|
||||
*/
|
||||
async function handleGrants({ username, host, grants, userId }) {
|
||||
export default async function handleGrants({
|
||||
username,
|
||||
host,
|
||||
grants,
|
||||
userId,
|
||||
}: Param): Promise<boolean> {
|
||||
let success = false;
|
||||
|
||||
console.log(`Handling Grants for User =>`, username, host);
|
||||
@@ -72,7 +73,7 @@ async function handleGrants({ username, host, grants, userId }) {
|
||||
/**
|
||||
* @type {GrantType[]}
|
||||
*/
|
||||
const grantsArray = grants;
|
||||
const grantsArray: GrantType[] = grants;
|
||||
|
||||
for (let i = 0; i < grantsArray.length; i++) {
|
||||
const grantObject = grantsArray[i];
|
||||
@@ -95,11 +96,9 @@ async function handleGrants({ username, host, grants, userId }) {
|
||||
}
|
||||
|
||||
success = true;
|
||||
} catch (/** @type {any} */ error) {
|
||||
} catch (/** @type {any} */ error: any) {
|
||||
console.log(`Error in adding SQL user =>`, error.message);
|
||||
}
|
||||
|
||||
return success;
|
||||
}
|
||||
|
||||
module.exports = handleGrants;
|
||||
+74
-87
@@ -1,52 +1,53 @@
|
||||
// @ts-check
|
||||
|
||||
const path = require("path");
|
||||
import path from "path";
|
||||
require("dotenv").config({ path: path.resolve(__dirname, "../../../.env") });
|
||||
|
||||
const generator = require("generate-password");
|
||||
const noDatabaseDbHandler = require("../utils/noDatabaseDbHandler");
|
||||
const dbHandler = require("../utils/dbHandler");
|
||||
const handleGrants = require("./handleGrants");
|
||||
const encrypt = require("../../functions/dsql/encrypt");
|
||||
const decrypt = require("../../functions/dsql/decrypt");
|
||||
import generator from "generate-password";
|
||||
import noDatabaseDbHandler from "../utils/noDatabaseDbHandler";
|
||||
import dbHandler from "../utils/dbHandler";
|
||||
import handleGrants, { GrantType } from "./handleGrants";
|
||||
import encrypt from "../../functions/dsql/encrypt";
|
||||
import decrypt from "../../functions/dsql/decrypt";
|
||||
import { MYSQL_mariadb_users_table_def } from "../../types";
|
||||
|
||||
const defaultMariadbUserHost = process.env.DSQL_DB_HOST || "127.0.0.1";
|
||||
|
||||
type Param = {
|
||||
userId?: number | string;
|
||||
mariadbUserHost?: string;
|
||||
mariadbUsername?: string;
|
||||
sqlUserID?: string | number;
|
||||
};
|
||||
|
||||
/**
|
||||
* Refresh Mariadb User Grants
|
||||
* ===================================================
|
||||
* @param {object} params
|
||||
* @param {number | string} [params.userId]
|
||||
* @param {string} [params.mariadbUserHost]
|
||||
* @param {string} [params.mariadbUser]
|
||||
* @param {string | number} [params.sqlUserID]
|
||||
* # Refresh Mariadb User Grants
|
||||
*/
|
||||
async function refreshUsersAndGrants({
|
||||
export default async function refreshUsersAndGrants({
|
||||
userId,
|
||||
mariadbUserHost,
|
||||
mariadbUser,
|
||||
mariadbUsername,
|
||||
sqlUserID,
|
||||
}) {
|
||||
/**
|
||||
* @description Users
|
||||
* @type {*[] | null}
|
||||
*/ // @ts-ignore
|
||||
const users = await dbHandler({
|
||||
query: `SELECT * FROM users`,
|
||||
});
|
||||
}: Param) {
|
||||
const mariadbUsers = (await dbHandler({
|
||||
query: `SELECT * FROM mariadb_users`,
|
||||
})) as any[] | null;
|
||||
|
||||
if (!users?.[0]) {
|
||||
process.exit();
|
||||
if (!mariadbUsers?.[0]) {
|
||||
return;
|
||||
}
|
||||
|
||||
for (let i = 0; i < users.length; i++) {
|
||||
const user = users[i];
|
||||
const isRootUser = userId
|
||||
? userId == Number(process.env.DSQL_SU_USER_ID)
|
||||
: false;
|
||||
|
||||
if (!user) continue;
|
||||
if (userId && user.id != userId) continue;
|
||||
for (let i = 0; i < mariadbUsers.length; i++) {
|
||||
const mariadbUser = mariadbUsers[i];
|
||||
|
||||
if (!mariadbUser) continue;
|
||||
if (userId && mariadbUser.user_id != userId) continue;
|
||||
|
||||
try {
|
||||
const { mariadb_user, mariadb_host, mariadb_pass, id } = user;
|
||||
const { mariadb_user, mariadb_host, mariadb_pass, user_id } =
|
||||
mariadbUser;
|
||||
const existingUser = await noDatabaseDbHandler(
|
||||
`SELECT * FROM mysql.user WHERE User = '${mariadb_user}' AND Host = '${mariadb_host}'`
|
||||
);
|
||||
@@ -59,12 +60,9 @@ async function refreshUsersAndGrants({
|
||||
})
|
||||
: null;
|
||||
|
||||
/**
|
||||
* @type {import("../../types").MYSQL_mariadb_users_table_def | undefined}
|
||||
*/
|
||||
const activeMariadbUserObject = Array.isArray(
|
||||
existingMariaDBUserArray
|
||||
)
|
||||
const activeMariadbUserObject:
|
||||
| import("../../types").MYSQL_mariadb_users_table_def
|
||||
| undefined = Array.isArray(existingMariaDBUserArray)
|
||||
? existingMariaDBUserArray?.[0]
|
||||
: undefined;
|
||||
|
||||
@@ -80,7 +78,10 @@ async function refreshUsersAndGrants({
|
||||
mariadbUserHost == defaultMariadbUserHost
|
||||
);
|
||||
|
||||
const dslUsername = `dsql_user_${id}`;
|
||||
const dslUsername = isRootUser
|
||||
? mariadbUsername
|
||||
: `dsql_user_${user_id}`;
|
||||
|
||||
const dsqlPassword = activeMariadbUserObject?.password
|
||||
? activeMariadbUserObject.password
|
||||
: isUserExisting
|
||||
@@ -102,12 +103,13 @@ async function refreshUsersAndGrants({
|
||||
encryptionKey: process.env.DSQL_ENCRYPTION_PASSWORD,
|
||||
encryptionSalt: process.env.DSQL_ENCRYPTION_SALT,
|
||||
});
|
||||
|
||||
if (
|
||||
!isUserExisting &&
|
||||
!sqlUserID &&
|
||||
!isPrimary &&
|
||||
!mariadbUserHost &&
|
||||
!mariadbUser
|
||||
!mariadbUsername
|
||||
) {
|
||||
const createNewUser = await noDatabaseDbHandler(
|
||||
`CREATE USER IF NOT EXISTS '${dslUsername}'@'${defaultMariadbUserHost}' IDENTIFIED BY '${dsqlPassword}'`
|
||||
@@ -116,7 +118,7 @@ async function refreshUsersAndGrants({
|
||||
console.log("createNewUser", createNewUser);
|
||||
|
||||
console.log(
|
||||
`User ${user.id}: ${user.first_name} ${user.last_name} SQL credentials successfully updated.`
|
||||
`User ${mariadbUser.id}: ${mariadbUser.first_name} ${mariadbUser.last_name} SQL credentials successfully updated.`
|
||||
);
|
||||
|
||||
const updateUser = await dbHandler({
|
||||
@@ -125,9 +127,13 @@ async function refreshUsersAndGrants({
|
||||
dslUsername,
|
||||
defaultMariadbUserHost,
|
||||
encryptedPassword,
|
||||
user.id,
|
||||
mariadbUser.id,
|
||||
],
|
||||
});
|
||||
} else if (!isUserExisting && mariadbUserHost) {
|
||||
const createNewUser = await noDatabaseDbHandler(
|
||||
`CREATE USER IF NOT EXISTS '${dslUsername}'@'${mariadbUserHost}' IDENTIFIED BY '${dsqlPassword}'`
|
||||
);
|
||||
}
|
||||
|
||||
if (isPrimary) {
|
||||
@@ -141,7 +147,7 @@ async function refreshUsersAndGrants({
|
||||
dslUsername,
|
||||
finalHost,
|
||||
encryptedPassword,
|
||||
user.id,
|
||||
mariadbUser.id,
|
||||
],
|
||||
});
|
||||
}
|
||||
@@ -155,7 +161,7 @@ async function refreshUsersAndGrants({
|
||||
*/
|
||||
const existingMariadbPrimaryUser = await dbHandler({
|
||||
query: `SELECT * FROM mariadb_users WHERE user_id = ? AND \`primary\` = 1`,
|
||||
values: [id],
|
||||
values: [user_id],
|
||||
});
|
||||
|
||||
const isPrimaryUserExisting = Boolean(
|
||||
@@ -163,8 +169,7 @@ async function refreshUsersAndGrants({
|
||||
existingMariadbPrimaryUser?.[0]?.user_id
|
||||
);
|
||||
|
||||
/** @type {import("./handleGrants").GrantType[]} */
|
||||
const primaryUserGrants = [
|
||||
const primaryUserGrants: GrantType[] = [
|
||||
{
|
||||
database: "*",
|
||||
table: "*",
|
||||
@@ -176,7 +181,7 @@ async function refreshUsersAndGrants({
|
||||
const insertPrimaryMariadbUser = await dbHandler({
|
||||
query: `INSERT INTO mariadb_users (user_id, username, password, \`primary\`, grants) VALUES (?, ?, ?, ?, ?)`,
|
||||
values: [
|
||||
id,
|
||||
user_id,
|
||||
dslUsername,
|
||||
encryptedPassword,
|
||||
"1",
|
||||
@@ -189,32 +194,31 @@ async function refreshUsersAndGrants({
|
||||
|
||||
const existingExtraMariadbUsers = await dbHandler({
|
||||
query: `SELECT * FROM mariadb_users WHERE user_id = ? AND \`primary\` != '1'`,
|
||||
values: [id],
|
||||
values: [user_id],
|
||||
});
|
||||
|
||||
if (Array.isArray(existingExtraMariadbUsers)) {
|
||||
for (let i = 0; i < existingExtraMariadbUsers.length; i++) {
|
||||
const mariadbUser = existingExtraMariadbUsers[i];
|
||||
const {
|
||||
user_id,
|
||||
username,
|
||||
host,
|
||||
password,
|
||||
primary,
|
||||
grants,
|
||||
} = mariadbUser;
|
||||
const _mariadbUser = existingExtraMariadbUsers[
|
||||
i
|
||||
] as MYSQL_mariadb_users_table_def;
|
||||
|
||||
if (mariadbUser && username != mariadbUser) continue;
|
||||
if (mariadbUserHost && host != mariadbUserHost) continue;
|
||||
if (
|
||||
_mariadbUser &&
|
||||
_mariadbUser.username != mariadbUsername
|
||||
)
|
||||
continue;
|
||||
if (mariadbUserHost && _mariadbUser.host != mariadbUserHost)
|
||||
continue;
|
||||
|
||||
const decrptedPassword = decrypt({
|
||||
encryptedString: password,
|
||||
encryptedString: _mariadbUser.password || "",
|
||||
encryptionKey: process.env.DSQL_ENCRYPTION_PASSWORD,
|
||||
encryptionSalt: process.env.DSQL_ENCRYPTION_SALT,
|
||||
});
|
||||
|
||||
const existingExtraMariadbUser = await noDatabaseDbHandler(
|
||||
`SELECT * FROM mysql.user WHERE User = '${username}' AND Host = '${host}'`
|
||||
`SELECT * FROM mysql.user WHERE User='${_mariadbUser.username}' AND Host='${_mariadbUser.host}'`
|
||||
);
|
||||
|
||||
const isExtraMariadbUserExisting = Boolean(
|
||||
@@ -223,47 +227,30 @@ async function refreshUsersAndGrants({
|
||||
|
||||
if (!isExtraMariadbUserExisting) {
|
||||
await noDatabaseDbHandler(
|
||||
`CREATE USER IF NOT EXISTS '${username}'@'${host}' IDENTIFIED BY '${decrptedPassword}'`
|
||||
`CREATE USER IF NOT EXISTS '${_mariadbUser.username}'@'${_mariadbUser.host}' IDENTIFIED BY '${decrptedPassword}'`
|
||||
);
|
||||
}
|
||||
|
||||
const isGrantHandled = await handleGrants({
|
||||
username,
|
||||
host,
|
||||
username: _mariadbUser.username,
|
||||
host: _mariadbUser.host,
|
||||
grants:
|
||||
grants && typeof grants == "string"
|
||||
? JSON.parse(grants)
|
||||
_mariadbUser.grants &&
|
||||
typeof _mariadbUser.grants == "string"
|
||||
? JSON.parse(_mariadbUser.grants)
|
||||
: [],
|
||||
userId: String(userId),
|
||||
});
|
||||
|
||||
if (!isGrantHandled) {
|
||||
console.log(
|
||||
`Error in handling grants for user ${username}@${host}`
|
||||
`Error in handling grants for user ${_mariadbUser.username}@${_mariadbUser.host}`
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////
|
||||
//////////////////////////////////////////////
|
||||
//////////////////////////////////////////////
|
||||
} catch (/** @type {any} */ error) {
|
||||
} catch (error: any) {
|
||||
console.log(`Error in adding SQL user =>`, error.message);
|
||||
}
|
||||
}
|
||||
|
||||
process.exit();
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
}
|
||||
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
|
||||
module.exports = refreshUsersAndGrants;
|
||||
@@ -1,105 +0,0 @@
|
||||
// @ts-check
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
require("dotenv").config({ path: "../../.env" });
|
||||
const generator = require("generate-password");
|
||||
const noDatabaseDbHandler = require("../utils/noDatabaseDbHandler");
|
||||
const dbHandler = require("../utils/dbHandler");
|
||||
const encrypt = require("../../functions/dsql/encrypt");
|
||||
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
|
||||
/**
|
||||
* Create database from Schema Function
|
||||
* ==============================================================================
|
||||
* @param {object} params - Single object params
|
||||
* @param {number|string|null} params.userId - User ID or null
|
||||
*/
|
||||
async function resetSQLCredentialsPasswords() {
|
||||
/**
|
||||
* @description Users
|
||||
* @type {*[] | null}
|
||||
*/ // @ts-ignore
|
||||
const users = await dbHandler({
|
||||
query: `SELECT * FROM users`,
|
||||
});
|
||||
|
||||
if (!users) {
|
||||
process.exit();
|
||||
}
|
||||
|
||||
for (let i = 0; i < users.length; i++) {
|
||||
const user = users[i];
|
||||
|
||||
if (!user) continue;
|
||||
|
||||
try {
|
||||
/**
|
||||
* @type {any[]}
|
||||
*/ // @ts-ignore
|
||||
const maridbUsers = await dbHandler({
|
||||
query: `SELECT * FROM mysql.user WHERE User = 'dsql_user_${user.id}'`,
|
||||
});
|
||||
|
||||
for (let j = 0; j < maridbUsers.length; j++) {
|
||||
const { User, Host } = maridbUsers[j];
|
||||
|
||||
const password = generator.generate({
|
||||
length: 16,
|
||||
numbers: true,
|
||||
symbols: true,
|
||||
uppercase: true,
|
||||
exclude: "*#.'`\"",
|
||||
});
|
||||
|
||||
const encryptedPassword = encrypt({
|
||||
data: password,
|
||||
encryptionKey: process.env.DSQL_ENCRYPTION_PASSWORD,
|
||||
encryptionSalt: process.env.DSQL_ENCRYPTION_SALT,
|
||||
});
|
||||
|
||||
await noDatabaseDbHandler(
|
||||
`SET PASSWORD FOR '${User}'@'${Host}' = PASSWORD('${password}')`
|
||||
);
|
||||
|
||||
if (user.mariadb_user == User && user.mariadb_host == Host) {
|
||||
const updateUser = await dbHandler({
|
||||
query: `UPDATE users SET mariadb_pass = ? WHERE id = ?`,
|
||||
values: [encryptedPassword, user.id],
|
||||
});
|
||||
}
|
||||
|
||||
console.log(
|
||||
`User ${user.id}: ${user.first_name} ${user.last_name} Password Updated successfully added.`
|
||||
);
|
||||
}
|
||||
} catch (/** @type {any} */ error) {
|
||||
console.log(
|
||||
`Error Updating User ${user.id} Password =>`,
|
||||
error.message
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
process.exit();
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
}
|
||||
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
|
||||
resetSQLCredentialsPasswords();
|
||||
@@ -0,0 +1,72 @@
|
||||
require("dotenv").config({ path: "../../.env" });
|
||||
import generator from "generate-password";
|
||||
import noDatabaseDbHandler from "../utils/noDatabaseDbHandler";
|
||||
import dbHandler from "../utils/dbHandler";
|
||||
import encrypt from "../../functions/dsql/encrypt";
|
||||
|
||||
/**
|
||||
* # Reset SQL Passwords
|
||||
*/
|
||||
async function resetSQLCredentialsPasswords() {
|
||||
const users = (await dbHandler({
|
||||
query: `SELECT * FROM users`,
|
||||
})) as any[];
|
||||
|
||||
if (!users) {
|
||||
process.exit();
|
||||
}
|
||||
|
||||
for (let i = 0; i < users.length; i++) {
|
||||
const user = users[i];
|
||||
|
||||
if (!user) continue;
|
||||
|
||||
try {
|
||||
const maridbUsers = (await dbHandler({
|
||||
query: `SELECT * FROM mysql.user WHERE User = 'dsql_user_${user.id}'`,
|
||||
})) as any[];
|
||||
|
||||
for (let j = 0; j < maridbUsers.length; j++) {
|
||||
const { User, Host } = maridbUsers[j];
|
||||
|
||||
const password = generator.generate({
|
||||
length: 16,
|
||||
numbers: true,
|
||||
symbols: true,
|
||||
uppercase: true,
|
||||
exclude: "*#.'`\"",
|
||||
});
|
||||
|
||||
const encryptedPassword = encrypt({
|
||||
data: password,
|
||||
encryptionKey: process.env.DSQL_ENCRYPTION_PASSWORD,
|
||||
encryptionSalt: process.env.DSQL_ENCRYPTION_SALT,
|
||||
});
|
||||
|
||||
await noDatabaseDbHandler(
|
||||
`SET PASSWORD FOR '${User}'@'${Host}' = PASSWORD('${password}')`
|
||||
);
|
||||
|
||||
if (user.mariadb_user == User && user.mariadb_host == Host) {
|
||||
const updateUser = await dbHandler({
|
||||
query: `UPDATE users SET mariadb_pass = ? WHERE id = ?`,
|
||||
values: [encryptedPassword, user.id],
|
||||
});
|
||||
}
|
||||
|
||||
console.log(
|
||||
`User ${user.id}: ${user.first_name} ${user.last_name} Password Updated successfully added.`
|
||||
);
|
||||
}
|
||||
} catch (error: any) {
|
||||
console.log(
|
||||
`Error Updating User ${user.id} Password =>`,
|
||||
error.message
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
process.exit();
|
||||
}
|
||||
|
||||
resetSQLCredentialsPasswords();
|
||||
+10
-12
@@ -1,15 +1,13 @@
|
||||
// @ts-check
|
||||
|
||||
const path = require("path");
|
||||
import path from "path";
|
||||
require("dotenv").config({ path: "../../../.env" });
|
||||
const fs = require("fs");
|
||||
const { execSync } = require("child_process");
|
||||
const EJSON = require("../../../utils/ejson");
|
||||
const DB_HANDLER = require("../../../utils/backend/global-db/DB_HANDLER");
|
||||
const addDbEntry = require("../../../functions/backend/db/addDbEntry");
|
||||
const addMariadbUser = require("../../../functions/backend/addMariadbUser");
|
||||
const updateDbEntry = require("../../../functions/backend/db/updateDbEntry");
|
||||
const hashPassword = require("../../../functions/dsql/hashPassword");
|
||||
import fs from "fs";
|
||||
import { execSync } from "child_process";
|
||||
import EJSON from "../../../utils/ejson";
|
||||
import DB_HANDLER from "../../../utils/backend/global-db/DB_HANDLER";
|
||||
import addDbEntry from "../../../functions/backend/db/addDbEntry";
|
||||
import addMariadbUser from "../../../functions/backend/addMariadbUser";
|
||||
import updateDbEntry from "../../../functions/backend/db/updateDbEntry";
|
||||
import hashPassword from "../../../functions/dsql/hashPassword";
|
||||
|
||||
const tmpDir = process.argv[process.argv.length - 1];
|
||||
|
||||
@@ -169,7 +167,7 @@ async function createUser() {
|
||||
}
|
||||
|
||||
return true;
|
||||
} catch (/** @type {any} */ error) {
|
||||
} catch (error: any) {
|
||||
console.log(`Error in creating user => ${error.message}`);
|
||||
return false;
|
||||
}
|
||||
+7
-10
@@ -1,11 +1,9 @@
|
||||
// @ts-check
|
||||
|
||||
const path = require("path");
|
||||
import path from "path";
|
||||
require("dotenv").config({ path: "../../../.env" });
|
||||
const fs = require("fs");
|
||||
const EJSON = require("../../../utils/ejson");
|
||||
const hashPassword = require("../../../functions/dsql/hashPassword");
|
||||
const updateDbEntry = require("../../../functions/backend/db/updateDbEntry");
|
||||
import fs from "fs";
|
||||
import EJSON from "../../../utils/ejson";
|
||||
import hashPassword from "../../../functions/dsql/hashPassword";
|
||||
import updateDbEntry from "../../../functions/backend/db/updateDbEntry";
|
||||
|
||||
const tmpDir = process.argv[process.argv.length - 1];
|
||||
|
||||
@@ -40,8 +38,7 @@ async function createUser() {
|
||||
updatePayload["password"] = hashedPassword;
|
||||
}
|
||||
|
||||
/** @type {any} */
|
||||
const newUser = await updateDbEntry({
|
||||
const newUser: any = await updateDbEntry({
|
||||
dbFullName: "datasquirel",
|
||||
tableName: "users",
|
||||
data: { ...updatePayload, id: undefined },
|
||||
@@ -58,7 +55,7 @@ async function createUser() {
|
||||
}
|
||||
|
||||
return true;
|
||||
} catch (/** @type {any} */ error) {
|
||||
} catch (error: any) {
|
||||
console.log(`Error in creating user => ${error.message}`);
|
||||
return false;
|
||||
}
|
||||
@@ -1,24 +0,0 @@
|
||||
// @ts-check
|
||||
|
||||
const fs = require("fs");
|
||||
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
|
||||
/**
|
||||
* Grab Schema
|
||||
*
|
||||
* @description Grab Schema
|
||||
*/
|
||||
const imageBase64 = fs.readFileSync(
|
||||
"./../public/images/unique-tokens-icon.png",
|
||||
"base64"
|
||||
);
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
Executable
+6
@@ -0,0 +1,6 @@
|
||||
import fs from "fs";
|
||||
|
||||
const imageBase64 = fs.readFileSync(
|
||||
"./../public/images/unique-tokens-icon.png",
|
||||
"base64"
|
||||
);
|
||||
+7
-28
@@ -1,27 +1,13 @@
|
||||
// @ts-check
|
||||
|
||||
const fs = require("fs");
|
||||
import fs from "fs";
|
||||
require("dotenv").config({ path: "./../.env" });
|
||||
|
||||
////////////////////////////////////////
|
||||
|
||||
const varDatabaseDbHandler = require("../functions/backend/varDatabaseDbHandler");
|
||||
const DB_HANDLER = require("../utils/backend/global-db/DB_HANDLER");
|
||||
|
||||
/** ****************************************************************************** */
|
||||
import varDatabaseDbHandler from "../functions/backend/varDatabaseDbHandler";
|
||||
import DB_HANDLER from "../utils/backend/global-db/DB_HANDLER";
|
||||
|
||||
const userId =
|
||||
process.argv.indexOf("--userId") >= 0
|
||||
? process.argv[process.argv.indexOf("--userId") + 1]
|
||||
: null;
|
||||
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
|
||||
/**
|
||||
* Grab Schema
|
||||
*
|
||||
@@ -43,8 +29,7 @@ async function recoverMainJsonFromDb() {
|
||||
const { id, db_name, db_slug, db_full_name, db_image, db_description } =
|
||||
databases[i];
|
||||
|
||||
/** @type {any} */
|
||||
const dbObject = {
|
||||
const dbObject: any = {
|
||||
dbName: db_name,
|
||||
dbSlug: db_slug,
|
||||
dbFullName: db_full_name,
|
||||
@@ -60,8 +45,7 @@ async function recoverMainJsonFromDb() {
|
||||
for (let j = 0; j < tables.length; j++) {
|
||||
const { table_name, table_slug, table_description } = tables[j];
|
||||
|
||||
/** @type {any} */
|
||||
const tableObject = {
|
||||
const tableObject: any = {
|
||||
tableName: table_slug,
|
||||
tableFullName: table_name,
|
||||
fields: [],
|
||||
@@ -70,14 +54,13 @@ async function recoverMainJsonFromDb() {
|
||||
|
||||
const tableFields = await varDatabaseDbHandler({
|
||||
database: db_full_name,
|
||||
queryString: `SHOW COLUMNS FROM ${table_slug}`,
|
||||
queryString: `SHOW COLUMNS FROM ${db_full_name}.${table_slug}`,
|
||||
});
|
||||
|
||||
for (let k = 0; k < tableFields.length; k++) {
|
||||
const { Field, Type, Null, Default, Key } = tableFields[k];
|
||||
|
||||
/** @type {any} */
|
||||
const fieldObject = {
|
||||
const fieldObject: any = {
|
||||
fieldName: Field,
|
||||
dataType: Type.toUpperCase(),
|
||||
};
|
||||
@@ -113,8 +96,4 @@ async function recoverMainJsonFromDb() {
|
||||
process.exit();
|
||||
}
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
recoverMainJsonFromDb();
|
||||
+7
-34
@@ -1,21 +1,8 @@
|
||||
// @ts-check
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
require("dotenv").config({ path: "./../.env" });
|
||||
const generator = require("generate-password");
|
||||
const noDatabaseDbHandler = require("./utils/noDatabaseDbHandler");
|
||||
const dbHandler = require("./utils/dbHandler");
|
||||
const encrypt = require("../functions/dsql/encrypt");
|
||||
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
import generator from "generate-password";
|
||||
import noDatabaseDbHandler from "./utils/noDatabaseDbHandler";
|
||||
import dbHandler from "./utils/dbHandler";
|
||||
import encrypt from "../functions/dsql/encrypt";
|
||||
|
||||
/**
|
||||
* Create database from Schema Function
|
||||
@@ -24,13 +11,9 @@ const encrypt = require("../functions/dsql/encrypt");
|
||||
* @param {number|string|null} params.userId - User ID or null
|
||||
*/
|
||||
async function resetSQLCredentials() {
|
||||
/**
|
||||
* @description Users
|
||||
* @type {*[] | null}
|
||||
*/ // @ts-ignore
|
||||
const users = await dbHandler({
|
||||
const users = (await dbHandler({
|
||||
query: `SELECT * FROM users`,
|
||||
});
|
||||
})) as any[];
|
||||
|
||||
if (!users) {
|
||||
process.exit();
|
||||
@@ -82,22 +65,12 @@ async function resetSQLCredentials() {
|
||||
console.log(
|
||||
`User ${user.id}: ${user.first_name} ${user.last_name} SQL credentials successfully added.`
|
||||
);
|
||||
} catch (/** @type {any} */ error) {
|
||||
} catch (error: any) {
|
||||
console.log(`Error in adding SQL user =>`, error.message);
|
||||
}
|
||||
}
|
||||
|
||||
process.exit();
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
}
|
||||
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
|
||||
resetSQLCredentials();
|
||||
@@ -1,90 +0,0 @@
|
||||
// @ts-check
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
require("dotenv").config({ path: "./../.env" });
|
||||
const generator = require("generate-password");
|
||||
const noDatabaseDbHandler = require("./utils/noDatabaseDbHandler");
|
||||
const dbHandler = require("./utils/dbHandler");
|
||||
const encrypt = require("../functions/dsql/encrypt");
|
||||
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
|
||||
/**
|
||||
* Create database from Schema Function
|
||||
* ==============================================================================
|
||||
* @param {object} params - Single object params
|
||||
* @param {number|string|null} params.userId - User ID or null
|
||||
*/
|
||||
async function resetSQLCredentialsPasswords() {
|
||||
/**
|
||||
* @description Users
|
||||
* @type {*[] | null}
|
||||
*/ // @ts-ignore
|
||||
const users = await dbHandler({
|
||||
query: `SELECT * FROM users`,
|
||||
});
|
||||
|
||||
if (!users) {
|
||||
process.exit();
|
||||
}
|
||||
|
||||
for (let i = 0; i < users.length; i++) {
|
||||
const user = users[i];
|
||||
|
||||
if (!user) continue;
|
||||
|
||||
const defaultMariadbUserHost = process.env.DSQL_DB_HOST || "127.0.0.1";
|
||||
|
||||
try {
|
||||
const username = `dsql_user_${user.id}`;
|
||||
const password = generator.generate({
|
||||
length: 16,
|
||||
numbers: true,
|
||||
symbols: true,
|
||||
uppercase: true,
|
||||
exclude: "*#.'`\"",
|
||||
});
|
||||
const encryptedPassword = encrypt({ data: password });
|
||||
|
||||
await noDatabaseDbHandler(
|
||||
`SET PASSWORD FOR '${username}'@'${defaultMariadbUserHost}' = PASSWORD('${password}')`
|
||||
);
|
||||
|
||||
const updateUser = await dbHandler({
|
||||
query: `UPDATE users SET mariadb_pass = ? WHERE id = ?`,
|
||||
values: [encryptedPassword, user.id],
|
||||
});
|
||||
|
||||
console.log(
|
||||
`User ${user.id}: ${user.first_name} ${user.last_name} Password Updated successfully added.`
|
||||
);
|
||||
} catch (/** @type {any} */ error) {
|
||||
console.log(
|
||||
`Error Updating User ${user.id} Password =>`,
|
||||
error.message
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
process.exit();
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
}
|
||||
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
|
||||
resetSQLCredentialsPasswords();
|
||||
@@ -0,0 +1,60 @@
|
||||
require("dotenv").config({ path: "./../.env" });
|
||||
import generator from "generate-password";
|
||||
import noDatabaseDbHandler from "./utils/noDatabaseDbHandler";
|
||||
import dbHandler from "./utils/dbHandler";
|
||||
import encrypt from "../functions/dsql/encrypt";
|
||||
|
||||
/**
|
||||
* # Create database from Schema Function
|
||||
*/
|
||||
async function resetSQLCredentialsPasswords() {
|
||||
const users = (await dbHandler({
|
||||
query: `SELECT * FROM users`,
|
||||
})) as any[];
|
||||
|
||||
if (!users) {
|
||||
process.exit();
|
||||
}
|
||||
|
||||
for (let i = 0; i < users.length; i++) {
|
||||
const user = users[i];
|
||||
|
||||
if (!user) continue;
|
||||
|
||||
const defaultMariadbUserHost = process.env.DSQL_DB_HOST || "127.0.0.1";
|
||||
|
||||
try {
|
||||
const username = `dsql_user_${user.id}`;
|
||||
const password = generator.generate({
|
||||
length: 16,
|
||||
numbers: true,
|
||||
symbols: true,
|
||||
uppercase: true,
|
||||
exclude: "*#.'`\"",
|
||||
});
|
||||
const encryptedPassword = encrypt({ data: password });
|
||||
|
||||
await noDatabaseDbHandler(
|
||||
`SET PASSWORD FOR '${username}'@'${defaultMariadbUserHost}' = PASSWORD('${password}')`
|
||||
);
|
||||
|
||||
const updateUser = await dbHandler({
|
||||
query: `UPDATE users SET mariadb_pass = ? WHERE id = ?`,
|
||||
values: [encryptedPassword, user.id],
|
||||
});
|
||||
|
||||
console.log(
|
||||
`User ${user.id}: ${user.first_name} ${user.last_name} Password Updated successfully added.`
|
||||
);
|
||||
} catch (error: any) {
|
||||
console.log(
|
||||
`Error Updating User ${user.id} Password =>`,
|
||||
error.message
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
process.exit();
|
||||
}
|
||||
|
||||
resetSQLCredentialsPasswords();
|
||||
@@ -0,0 +1,46 @@
|
||||
import path from "path";
|
||||
import fs from "fs";
|
||||
|
||||
const rootDir = path.resolve(__dirname, "../../../");
|
||||
const ignorePattern =
|
||||
/\/\.git\/|\/\.next\/|\/\.dist\/|node_modules|\/\.local_dist\/|\/\.tmp\/|\/types\/|\.config\.js|\/public\//;
|
||||
|
||||
function transformJsToTs(dir: string) {
|
||||
const dirContent = fs.readdirSync(dir);
|
||||
|
||||
for (let i = 0; i < dirContent.length; i++) {
|
||||
const fileFolder = dirContent[i];
|
||||
const fullFileFolderPath = path.join(dir, fileFolder);
|
||||
const stat = fs.statSync(fullFileFolderPath);
|
||||
|
||||
if (stat.isDirectory()) {
|
||||
transformJsToTs(fullFileFolderPath);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (ignorePattern.test(fullFileFolderPath)) continue;
|
||||
|
||||
if (fullFileFolderPath.match(/\.jsx?$/)) {
|
||||
const extension = fullFileFolderPath.match(/\.jsx?$/)?.[0];
|
||||
if (!extension) continue;
|
||||
const newExtension = extension.replace("js", "ts");
|
||||
const newFilePath = fullFileFolderPath.replace(
|
||||
/\.jsx?$/,
|
||||
newExtension
|
||||
);
|
||||
|
||||
console.log(fullFileFolderPath);
|
||||
console.log(extension, "=>", newExtension);
|
||||
console.log(newFilePath);
|
||||
console.log("\n/////////////////////////////////////////");
|
||||
console.log("/////////////////////////////////////////\n");
|
||||
|
||||
fs.copyFileSync(fullFileFolderPath, newFilePath);
|
||||
fs.unlinkSync(fullFileFolderPath);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
console.log("rootDir", rootDir);
|
||||
|
||||
transformJsToTs(rootDir);
|
||||
+8
-33
@@ -1,14 +1,8 @@
|
||||
// @ts-check
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
require("dotenv").config({ path: "./../.env" });
|
||||
const generator = require("generate-password");
|
||||
const noDatabaseDbHandler = require("./utils/noDatabaseDbHandler");
|
||||
const dbHandler = require("./utils/dbHandler");
|
||||
const encrypt = require("../functions/dsql/encrypt");
|
||||
import generator from "generate-password";
|
||||
import noDatabaseDbHandler from "./utils/noDatabaseDbHandler";
|
||||
import dbHandler from "./utils/dbHandler";
|
||||
import encrypt from "../functions/dsql/encrypt";
|
||||
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
@@ -18,19 +12,12 @@ const encrypt = require("../functions/dsql/encrypt");
|
||||
/** ****************************************************************************** */
|
||||
|
||||
/**
|
||||
* Create database from Schema Function
|
||||
* ==============================================================================
|
||||
* @param {object} params - Single object params
|
||||
* @param {number|string|null} params.userId - User ID or null
|
||||
* # Set SQL Credentials
|
||||
*/
|
||||
async function setSQLCredentials() {
|
||||
/**
|
||||
* @description Users
|
||||
* @type {*[] | null}
|
||||
*/ // @ts-ignore
|
||||
const users = await dbHandler({
|
||||
const users = (await dbHandler({
|
||||
query: `SELECT * FROM users`,
|
||||
});
|
||||
})) as any[] | null;
|
||||
|
||||
if (!users) {
|
||||
process.exit();
|
||||
@@ -72,22 +59,10 @@ async function setSQLCredentials() {
|
||||
console.log(
|
||||
`User ${user.id}: ${user.first_name} ${user.last_name} SQL credentials successfully added.`
|
||||
);
|
||||
} catch (/** @type {any} */ error) {
|
||||
} catch (error: any) {
|
||||
console.log(`Error in adding SQL user =>`, error.message);
|
||||
}
|
||||
}
|
||||
|
||||
process.exit();
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
}
|
||||
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
|
||||
setSQLCredentials();
|
||||
@@ -1,29 +0,0 @@
|
||||
// @ts-check
|
||||
|
||||
const fs = require("fs");
|
||||
const { exec } = require("child_process");
|
||||
|
||||
require("dotenv").config({ path: "./../.env" });
|
||||
|
||||
const sourceFile = process.argv.indexOf("--src") >= 0 ? process.argv[process.argv.indexOf("--src") + 1] : null;
|
||||
const destinationFile = process.argv.indexOf("--dst") >= 0 ? process.argv[process.argv.indexOf("--dst") + 1] : null;
|
||||
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
|
||||
console.log("Running Tailwind CSS compiler ...");
|
||||
|
||||
fs.watch("./../", (curr, prev) => {
|
||||
exec(`npx tailwindcss -i ./tailwind/main.css -o ./styles/tailwind.css`, (error, stdout, stderr) => {
|
||||
if (error) {
|
||||
console.log("ERROR =>", error.message);
|
||||
return;
|
||||
}
|
||||
|
||||
console.log("Tailwind CSS Compilation \x1b[32msuccessful\x1b[0m!");
|
||||
});
|
||||
});
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
import fs from "fs";
|
||||
import { exec } from "child_process";
|
||||
|
||||
require("dotenv").config({ path: "./../.env" });
|
||||
|
||||
const sourceFile =
|
||||
process.argv.indexOf("--src") >= 0
|
||||
? process.argv[process.argv.indexOf("--src") + 1]
|
||||
: null;
|
||||
const destinationFile =
|
||||
process.argv.indexOf("--dst") >= 0
|
||||
? process.argv[process.argv.indexOf("--dst") + 1]
|
||||
: null;
|
||||
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
|
||||
console.log("Running Tailwind CSS compiler ...");
|
||||
|
||||
fs.watch("./../", (curr, prev) => {
|
||||
exec(
|
||||
`bunx tailwindcss -i ./tailwind/main.css -o ./styles/tailwind.css`,
|
||||
(error, stdout, stderr) => {
|
||||
if (error) {
|
||||
console.log("ERROR =>", error.message);
|
||||
return;
|
||||
}
|
||||
|
||||
console.log("Tailwind CSS Compilation \x1b[32msuccessful\x1b[0m!");
|
||||
}
|
||||
);
|
||||
});
|
||||
+3
-16
@@ -1,12 +1,6 @@
|
||||
// @ts-check
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
require("dotenv").config({ path: "./.env" });
|
||||
const grabDbSSL = require("../utils/backend/grabDbSSL");
|
||||
const mysql = require("serverless-mysql");
|
||||
import grabDbSSL from "../utils/backend/grabDbSSL";
|
||||
import mysql from "serverless-mysql";
|
||||
|
||||
const connection = mysql({
|
||||
config: {
|
||||
@@ -19,13 +13,6 @@ const connection = mysql({
|
||||
},
|
||||
});
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
/**
|
||||
* # Main DB Handler Function
|
||||
* @async
|
||||
@@ -49,7 +36,7 @@ const connection = mysql({
|
||||
const parsedResults = JSON.parse(JSON.stringify(result));
|
||||
|
||||
console.log("parsedResults =>", parsedResults);
|
||||
} catch (/** @type {any} */ error) {
|
||||
} catch (error: any) {
|
||||
console.log("Connection query ERROR =>", error.message);
|
||||
} finally {
|
||||
connection.end();
|
||||
@@ -1,221 +0,0 @@
|
||||
require("dotenv").config({ path: "./../.env" });
|
||||
|
||||
const dbEngine = require("@moduletrace/datasquirel/engine");
|
||||
const http = require("http");
|
||||
|
||||
const datasquirel = require("@moduletrace/datasquirel");
|
||||
|
||||
`curl http://www.dataden.tech`;
|
||||
|
||||
datasquirel
|
||||
.get({
|
||||
db: "test",
|
||||
key: process.env.DATASQUIREL_READ_ONLY_KEY,
|
||||
query: "SELECT title, slug, body FROM blog_posts",
|
||||
})
|
||||
.then((response) => {
|
||||
console.log(response);
|
||||
});
|
||||
|
||||
// dbEngine.db
|
||||
// .query({
|
||||
// dbFullName: "datasquirel",
|
||||
// dbHost: process.env.DSQL_DB_HOST,
|
||||
// dbPassword: process.env.DSQL_DB_PASSWORD,
|
||||
// dbUsername: process.env.DSQL_DB_USERNAME,
|
||||
// query: "SHOW TABLES",
|
||||
// })
|
||||
// .then((res) => {
|
||||
// console.log("res =>", res);
|
||||
// });
|
||||
|
||||
// run({
|
||||
// key: "bc057a2cd57922e085739c89b4985e5e676b655d7cc0ba7604659cad0a08c252040120c06597a5d22959a502a44bd816",
|
||||
// db: "showmerebates",
|
||||
// query: "SELECT * FROM test_table",
|
||||
// }).then((res) => {
|
||||
// console.log("res =>", res);
|
||||
// });
|
||||
|
||||
post({
|
||||
key: "3115fce7ea7772eda75f8f0e55a1414c5c018b4920f4bc99a2d4d7000bac203c15a7036fd3d7ef55ae67a002d4c757895b5c58ff82079a04ba6d42d23d4353256985090959a58a9af8e03cb277fc7895413e6f28ae11b1cc15329c7f94cdcf9a795f54d6e1d319adc287dc147143e62d",
|
||||
database: "showmerebates",
|
||||
query: {
|
||||
action: "delete",
|
||||
table: "test_table",
|
||||
identifierColumnName: "id",
|
||||
identifierValue: 6,
|
||||
},
|
||||
}).then((res) => {
|
||||
console.log("res =>", res);
|
||||
});
|
||||
|
||||
async function run({ key, db, query }) {
|
||||
const httpResponse = await new Promise((resolve, reject) => {
|
||||
http.request(
|
||||
{
|
||||
method: "GET",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: key,
|
||||
},
|
||||
hostname: "localhost",
|
||||
port: 7070,
|
||||
path: `/api/query/get?db=${db}&query=${query
|
||||
.replace(/\n|\r|\n\r/g, "")
|
||||
.replace(/ {2,}/g, " ")
|
||||
.replace(/ /g, "+")}`,
|
||||
},
|
||||
|
||||
/**
|
||||
* Callback Function
|
||||
*
|
||||
* @description https request callback
|
||||
*/
|
||||
(response) => {
|
||||
var str = "";
|
||||
|
||||
response.on("data", function (chunk) {
|
||||
str += chunk;
|
||||
});
|
||||
|
||||
response.on("end", function () {
|
||||
resolve(JSON.parse(str));
|
||||
});
|
||||
|
||||
response.on("error", (err) => {
|
||||
reject(err);
|
||||
});
|
||||
}
|
||||
).end();
|
||||
});
|
||||
|
||||
return httpResponse;
|
||||
}
|
||||
|
||||
/**
|
||||
* @typedef {Object} PostReturn
|
||||
* @property {boolean} success - Did the function run successfully?
|
||||
* @property {(Object[]|string)} [payload=[]] - The Y Coordinate
|
||||
*/
|
||||
|
||||
/**
|
||||
* @typedef {object} PostDataPayload
|
||||
* @property {string} action - "insert" | "update" | "delete"
|
||||
* @property {string} table - Table name(slug) eg "blog_posts"
|
||||
* @property {string} identifierColumnName - Table identifier field name => eg. "id" OR "email"
|
||||
* @property {string} identifierValue - Corresponding value of the selected field name => This
|
||||
* checks identifies a the target row for "update" or "delete". Not needed for "insert"
|
||||
* @property {object} data - Table insert payload object => This must have keys that match
|
||||
* table fields
|
||||
* @property {string?} duplicateColumnName - Duplicate column name to check for
|
||||
* @property {string?} duplicateColumnValue - Duplicate column value to match. If no "update" param
|
||||
* provided, function will return null
|
||||
* @property {boolean?} update - Should the "insert" action update the existing entry if indeed
|
||||
* the entry with "duplicateColumnValue" exists?
|
||||
*/
|
||||
|
||||
/**
|
||||
* Post request
|
||||
* ==============================================================================
|
||||
* @async
|
||||
*
|
||||
* @param {Object} params - Single object passed
|
||||
* @param {string} params.key - FULL ACCESS API Key
|
||||
* @param {string} params.database - Database Name
|
||||
* @param {PostDataPayload} params.query - SQL query String or Request Object
|
||||
*
|
||||
* @returns { Promise<PostReturn> } - Return Object
|
||||
*/
|
||||
async function post({ key, query, database }) {
|
||||
/**
|
||||
* Make https request
|
||||
*
|
||||
* @description make a request to datasquirel.com
|
||||
*/
|
||||
const httpResponse = await new Promise((resolve, reject) => {
|
||||
const reqPayloadString = JSON.stringify({
|
||||
query,
|
||||
database,
|
||||
}).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 = http.request(
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Content-Length": Buffer.from(reqPayload).length,
|
||||
Authorization: key,
|
||||
},
|
||||
hostname: "localhost",
|
||||
port: 7070,
|
||||
path: `/api/query/post`,
|
||||
},
|
||||
|
||||
/**
|
||||
* 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.message);
|
||||
console.log("Fetched Payload =>", str);
|
||||
|
||||
resolve({
|
||||
success: false,
|
||||
payload: null,
|
||||
error: error.message,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
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.message);
|
||||
});
|
||||
|
||||
httpsRequest.end();
|
||||
});
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
return httpResponse;
|
||||
}
|
||||
+9
-26
@@ -5,10 +5,10 @@
|
||||
////////////////////////////////////////
|
||||
|
||||
require("dotenv").config({ path: "./../.env" });
|
||||
const generator = require("generate-password");
|
||||
const noDatabaseDbHandler = require("./utils/noDatabaseDbHandler");
|
||||
const dbHandler = require("./utils/dbHandler");
|
||||
const encrypt = require("../functions/dsql/encrypt");
|
||||
import generator from "generate-password";
|
||||
import noDatabaseDbHandler from "./utils/noDatabaseDbHandler";
|
||||
import dbHandler from "./utils/dbHandler";
|
||||
import encrypt from "../functions/dsql/encrypt";
|
||||
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
@@ -18,19 +18,12 @@ const encrypt = require("../functions/dsql/encrypt");
|
||||
/** ****************************************************************************** */
|
||||
|
||||
/**
|
||||
* Create database from Schema Function
|
||||
* ==============================================================================
|
||||
* @param {object} params - Single object params
|
||||
* @param {number|string|null} params.userId - User ID or null
|
||||
* # Test SQL Escape
|
||||
*/
|
||||
async function testSQLEscape() {
|
||||
/**
|
||||
* @description Users
|
||||
* @type {*[] | null}
|
||||
*/ // @ts-ignore
|
||||
const users = await dbHandler({
|
||||
export default async function testSQLEscape() {
|
||||
const users = (await dbHandler({
|
||||
query: `SELECT * FROM users`,
|
||||
});
|
||||
})) as any[];
|
||||
|
||||
if (!users) {
|
||||
process.exit();
|
||||
@@ -81,22 +74,12 @@ async function testSQLEscape() {
|
||||
console.log(
|
||||
`User ${user.id}: ${user.first_name} ${user.last_name} SQL credentials successfully added.`
|
||||
);
|
||||
} catch (/** @type {any} */ error) {
|
||||
} catch (error: any) {
|
||||
console.log(`Error in adding SQL user =>`, error.message);
|
||||
}
|
||||
}
|
||||
|
||||
process.exit();
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
}
|
||||
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
|
||||
testSQLEscape();
|
||||
+2
-28
@@ -1,16 +1,7 @@
|
||||
// @ts-check
|
||||
|
||||
const DB_HANDLER = require("../utils/backend/global-db/DB_HANDLER");
|
||||
const fs = require("fs");
|
||||
import DB_HANDLER from "../utils/backend/global-db/DB_HANDLER";
|
||||
import fs from "fs";
|
||||
require("dotenv").config({ path: "./../.env" });
|
||||
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
|
||||
async function updateChildrenTablesOnDb() {
|
||||
/**
|
||||
* Grab Schema
|
||||
@@ -57,24 +48,7 @@ async function updateChildrenTablesOnDb() {
|
||||
console.log(error);
|
||||
}
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
process.exit();
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
}
|
||||
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
|
||||
// const userArg = process.argv[process.argv.indexOf("--user")];
|
||||
// const externalUser = process.argv[process.argv.indexOf("--user") + 1];
|
||||
|
||||
updateChildrenTablesOnDb();
|
||||
@@ -1,60 +0,0 @@
|
||||
// @ts-check
|
||||
|
||||
require("dotenv").config({ path: "./../.env" });
|
||||
|
||||
////////////////////////////////////////
|
||||
|
||||
const varDatabaseDbHandler = require("../functions/backend/varDatabaseDbHandler");
|
||||
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
|
||||
/**
|
||||
* Grab Schema
|
||||
*
|
||||
* @description Grab Schema
|
||||
*/
|
||||
varDatabaseDbHandler({
|
||||
queryString: `SELECT user_database_tables.*,user_databases.db_full_name FROM user_database_tables JOIN user_databases ON user_database_tables.db_id=user_databases.id`,
|
||||
database: "datasquirel",
|
||||
}).then(async (tables) => {
|
||||
for (let i = 0; i < tables.length; i++) {
|
||||
const table = tables[i];
|
||||
const {
|
||||
id,
|
||||
user_id,
|
||||
db_id,
|
||||
db_full_name,
|
||||
table_name,
|
||||
table_slug,
|
||||
table_description,
|
||||
} = table;
|
||||
|
||||
const tableInfo = await varDatabaseDbHandler({
|
||||
queryString: `SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA='${db_full_name}' AND TABLE_NAME='${table_slug}'`,
|
||||
database: db_full_name,
|
||||
});
|
||||
|
||||
const updateCreationDateTimestamp = await varDatabaseDbHandler({
|
||||
queryString: `ALTER TABLE \`${table_slug}\` MODIFY COLUMN date_created_timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP`,
|
||||
database: db_full_name,
|
||||
});
|
||||
|
||||
const updateDateTimestamp = await varDatabaseDbHandler({
|
||||
queryString: `ALTER TABLE \`${table_slug}\` MODIFY COLUMN date_updated_timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP`,
|
||||
database: db_full_name,
|
||||
});
|
||||
|
||||
console.log("Date Updated Column updated");
|
||||
}
|
||||
|
||||
process.exit();
|
||||
});
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
require("dotenv").config({ path: "./../.env" });
|
||||
import varDatabaseDbHandler from "../functions/backend/varDatabaseDbHandler";
|
||||
|
||||
/**
|
||||
* Grab Schema
|
||||
*
|
||||
* @description Grab Schema
|
||||
*/
|
||||
varDatabaseDbHandler({
|
||||
queryString: `SELECT user_database_tables.*,user_databases.db_full_name FROM user_database_tables JOIN user_databases ON user_database_tables.db_id=user_databases.id`,
|
||||
database: "datasquirel",
|
||||
}).then(async (tables) => {
|
||||
for (let i = 0; i < tables.length; i++) {
|
||||
const table = tables[i];
|
||||
const {
|
||||
id,
|
||||
user_id,
|
||||
db_id,
|
||||
db_full_name,
|
||||
table_name,
|
||||
table_slug,
|
||||
table_description,
|
||||
} = table;
|
||||
|
||||
const tableInfo = await varDatabaseDbHandler({
|
||||
queryString: `SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA='${db_full_name}' AND TABLE_NAME='${table_slug}'`,
|
||||
});
|
||||
|
||||
const updateCreationDateTimestamp = await varDatabaseDbHandler({
|
||||
queryString: `ALTER TABLE \`${db_full_name}\`.\`${table_slug}\` MODIFY COLUMN date_created_timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP`,
|
||||
});
|
||||
|
||||
const updateDateTimestamp = await varDatabaseDbHandler({
|
||||
queryString: `ALTER TABLE \`${db_full_name}\`.\`${table_slug}\` MODIFY COLUMN date_updated_timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP`,
|
||||
});
|
||||
|
||||
console.log("Date Updated Column updated");
|
||||
}
|
||||
|
||||
process.exit();
|
||||
});
|
||||
+5
-12
@@ -1,10 +1,8 @@
|
||||
// @ts-check
|
||||
|
||||
require("dotenv").config({ path: "./../.env" });
|
||||
|
||||
const serverError = require("../functions/backend/serverError");
|
||||
const varDatabaseDbHandler = require("./utils/varDatabaseDbHandler");
|
||||
const DB_HANDLER = require("../utils/backend/global-db/DB_HANDLER");
|
||||
import serverError from "../functions/backend/serverError";
|
||||
import varDatabaseDbHandler from "./utils/varDatabaseDbHandler";
|
||||
import DB_HANDLER from "../utils/backend/global-db/DB_HANDLER";
|
||||
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
@@ -19,8 +17,7 @@ const DB_HANDLER = require("../utils/backend/global-db/DB_HANDLER");
|
||||
* @description Grab Schema
|
||||
*/
|
||||
varDatabaseDbHandler({
|
||||
queryString: `SELECT DISTINCT db_id FROM user_database_tables`,
|
||||
database: "datasquirel",
|
||||
queryString: `SELECT DISTINCT db_id FROM datasquirel.user_database_tables`,
|
||||
}).then(async (tables) => {
|
||||
// console.log(tables);
|
||||
// process.exit();
|
||||
@@ -38,7 +35,7 @@ varDatabaseDbHandler({
|
||||
const updateTableSlug = await DB_HANDLER(
|
||||
`UPDATE user_database_tables SET db_slug='${dbSlug[0].db_slug}' WHERE db_id='${db_id}'`
|
||||
);
|
||||
} catch (/** @type {any} */ error) {
|
||||
} catch (error: any) {
|
||||
serverError({
|
||||
component:
|
||||
"shell/updateDbSlugsForTableRecords/main-catch-error",
|
||||
@@ -50,7 +47,3 @@ varDatabaseDbHandler({
|
||||
|
||||
process.exit();
|
||||
});
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
+5
-21
@@ -1,19 +1,6 @@
|
||||
// @ts-check
|
||||
|
||||
require("dotenv").config({ path: "./../.env" });
|
||||
const grabDbSSL = require("../utils/backend/grabDbSSL");
|
||||
const mysql = require("serverless-mysql");
|
||||
|
||||
const connection = 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,
|
||||
charset: "utf8mb4",
|
||||
ssl: grabDbSSL(),
|
||||
},
|
||||
});
|
||||
import grabDbSSL from "../utils/backend/grabDbSSL";
|
||||
import mysql from "serverless-mysql";
|
||||
|
||||
/**
|
||||
* # Main DB Handler Function
|
||||
@@ -27,11 +14,8 @@ const connection = mysql({
|
||||
* @returns {Promise<object|null>}
|
||||
*/
|
||||
(async () => {
|
||||
/**
|
||||
* Switch Database
|
||||
*
|
||||
* @description If a database is provided, switch to it
|
||||
*/
|
||||
const connection = global.DSQL_DB_CONN;
|
||||
|
||||
try {
|
||||
const result = await connection.query(
|
||||
"SELECT user,host,ssl_type FROM mysql.user"
|
||||
@@ -61,7 +45,7 @@ const connection = mysql({
|
||||
|
||||
console.log(`addUserSSL => ${User}@${Host}`, addUserSSL);
|
||||
}
|
||||
} catch (/** @type {any} */ error) {
|
||||
} catch (error: any) {
|
||||
console.log("Connection query ERROR =>", error.message);
|
||||
} finally {
|
||||
connection.end();
|
||||
+2
-8
@@ -1,16 +1,10 @@
|
||||
// @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}
|
||||
*/
|
||||
module.exports = function camelJoinedtoCamelSpace(text) {
|
||||
export default function camelJoinedtoCamelSpace(text: string): string | null {
|
||||
if (!text?.match(/./)) {
|
||||
return "";
|
||||
}
|
||||
@@ -56,4 +50,4 @@ module.exports = function camelJoinedtoCamelSpace(text) {
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
}
|
||||
+24
-49
@@ -1,38 +1,27 @@
|
||||
// @ts-check
|
||||
import varDatabaseDbHandler from "./varDatabaseDbHandler";
|
||||
import generateColumnDescription from "./generateColumnDescription";
|
||||
import supplementTable from "./supplementTable";
|
||||
import dbHandler from "./dbHandler";
|
||||
import { DSQL_DatabaseSchemaType, DSQL_TableSchemaType } from "../../types";
|
||||
|
||||
const varDatabaseDbHandler = require("./varDatabaseDbHandler");
|
||||
const generateColumnDescription = require("./generateColumnDescription");
|
||||
const supplementTable = require("./supplementTable");
|
||||
const dbHandler = require("./dbHandler");
|
||||
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
type Param = {
|
||||
dbFullName: string;
|
||||
tableName: string;
|
||||
tableInfoArray: any[];
|
||||
tableSchema?: DSQL_TableSchemaType;
|
||||
recordedDbEntry?: any;
|
||||
};
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {object} params
|
||||
* @param {string} params.dbFullName
|
||||
* @param {string} params.tableName
|
||||
* @param {any[]} params.tableInfoArray
|
||||
* @param {import("../../types").DSQL_DatabaseSchemaType[]} [params.dbSchema]
|
||||
* @param {import("../../types").DSQL_TableSchemaType} [params.tableSchema]
|
||||
* @param {any} [params.recordedDbEntry]
|
||||
* @param {boolean} [params.clone] - Is this a newly cloned table?
|
||||
* @returns
|
||||
* # Create Table Functions
|
||||
*/
|
||||
module.exports = async function createTable({
|
||||
export default async function createTable({
|
||||
dbFullName,
|
||||
tableName,
|
||||
tableInfoArray,
|
||||
dbSchema,
|
||||
clone,
|
||||
tableSchema,
|
||||
recordedDbEntry,
|
||||
}) {
|
||||
}: Param) {
|
||||
/**
|
||||
* Format tableInfoArray
|
||||
*
|
||||
@@ -47,7 +36,9 @@ module.exports = async function createTable({
|
||||
*/
|
||||
const createTableQueryArray = [];
|
||||
|
||||
createTableQueryArray.push(`CREATE TABLE IF NOT EXISTS \`${tableName}\` (`);
|
||||
createTableQueryArray.push(
|
||||
`CREATE TABLE IF NOT EXISTS \`${dbFullName}\`.\`${tableName}\` (`
|
||||
);
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
@@ -59,17 +50,17 @@ module.exports = async function createTable({
|
||||
}
|
||||
|
||||
const existingTable = await varDatabaseDbHandler({
|
||||
database: "datasquirel",
|
||||
queryString: `SELECT * FROM user_database_tables WHERE db_id = ? AND table_slug = ?`,
|
||||
queryString: `SELECT * FROM datasquirel.user_database_tables WHERE db_id = ? AND table_slug = ?`,
|
||||
queryValuesArray: [recordedDbEntry.id, tableSchema?.tableName],
|
||||
});
|
||||
|
||||
/** @type {import("../../types").MYSQL_user_database_tables_table_def} */
|
||||
const table = existingTable?.[0];
|
||||
const table: import("../../types").MYSQL_user_database_tables_table_def =
|
||||
existingTable?.[0];
|
||||
|
||||
if (!table?.id) {
|
||||
const newTableEntry = await dbHandler({
|
||||
query: `INSERT INTO user_database_tables SET ?`,
|
||||
query: `INSERT INTO datasquirel.user_database_tables SET ?`,
|
||||
values: {
|
||||
user_id: recordedDbEntry.user_id,
|
||||
db_id: recordedDbEntry.id,
|
||||
@@ -86,7 +77,6 @@ module.exports = async function createTable({
|
||||
date_updated: Date(),
|
||||
date_updated_code: Date.now(),
|
||||
},
|
||||
database: "datasquirel",
|
||||
});
|
||||
}
|
||||
} catch (error) {}
|
||||
@@ -98,7 +88,7 @@ module.exports = async function createTable({
|
||||
let primaryKeySet = false;
|
||||
|
||||
/** @type {import("../../types").DSQL_FieldSchemaType[]} */
|
||||
let foreignKeys = [];
|
||||
let foreignKeys: import("../../types").DSQL_FieldSchemaType[] = [];
|
||||
|
||||
////////////////////////////////////////
|
||||
|
||||
@@ -156,10 +146,6 @@ module.exports = async function createTable({
|
||||
////////////////////////////////////////
|
||||
}
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
if (foreignKeys[0]) {
|
||||
foreignKeys.forEach((foreighKey, index, array) => {
|
||||
const fieldName = foreighKey.fieldName;
|
||||
@@ -196,18 +182,7 @@ module.exports = async function createTable({
|
||||
|
||||
const newTable = await varDatabaseDbHandler({
|
||||
queryString: createTableQuery,
|
||||
database: dbFullName,
|
||||
});
|
||||
|
||||
return newTable;
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
};
|
||||
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
}
|
||||
@@ -1,118 +0,0 @@
|
||||
// @ts-check
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
|
||||
const mysql = require("serverless-mysql");
|
||||
const grabDbSSL = require("../../utils/backend/grabDbSSL");
|
||||
|
||||
let connection = 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,
|
||||
charset: "utf8mb4",
|
||||
ssl: grabDbSSL(),
|
||||
},
|
||||
});
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
/**
|
||||
* # Main DB Handler Function
|
||||
* @async
|
||||
*
|
||||
* @param {object} params
|
||||
* @param {string} params.query
|
||||
* @param {string[] | object} [params.values]
|
||||
* @param {string} [params.database]
|
||||
*
|
||||
* @returns {Promise<any[] | object | null>}
|
||||
*/
|
||||
module.exports = async function dbHandler({ query, values, database }) {
|
||||
/**
|
||||
* Switch Database
|
||||
*
|
||||
* @description If a database is provided, switch to it
|
||||
*/
|
||||
let isDbCorrect = true;
|
||||
|
||||
if (database) {
|
||||
connection = mysql({
|
||||
config: {
|
||||
host: process.env.DSQL_DB_HOST,
|
||||
user: process.env.DSQL_DB_USERNAME,
|
||||
password: process.env.DSQL_DB_PASSWORD,
|
||||
database: database,
|
||||
charset: "utf8mb4",
|
||||
ssl: grabDbSSL(),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
if (!isDbCorrect) {
|
||||
console.log(
|
||||
"Shell Db Handler ERROR in switching Database! Operation Failed!"
|
||||
);
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Declare variables
|
||||
*
|
||||
* @description Declare "results" variable
|
||||
*/
|
||||
let results;
|
||||
|
||||
/**
|
||||
* Fetch from db
|
||||
*
|
||||
* @description Fetch data from db if no cache
|
||||
*/
|
||||
try {
|
||||
if (query && values) {
|
||||
results = await connection.query(query, values);
|
||||
} else {
|
||||
results = await connection.query(query);
|
||||
}
|
||||
|
||||
/** ********************* Clean up */
|
||||
await connection.end();
|
||||
} catch (/** @type {any} */ error) {
|
||||
if (process.env.FIRST_RUN) {
|
||||
return null;
|
||||
}
|
||||
|
||||
console.log("ERROR in dbHandler =>", error.message);
|
||||
console.log(error);
|
||||
console.log(connection.config());
|
||||
|
||||
fs.appendFileSync(
|
||||
path.resolve(__dirname, "../.tmp/dbErrorLogs.txt"),
|
||||
JSON.stringify(error, null, 4) + "\n" + Date() + "\n\n\n",
|
||||
"utf8"
|
||||
);
|
||||
results = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return results
|
||||
*
|
||||
* @description Return results add to cache if "req" param is passed
|
||||
*/
|
||||
if (results) {
|
||||
return JSON.parse(JSON.stringify(results));
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user