Updates
This commit is contained in:
@@ -0,0 +1,13 @@
|
||||
type Param = {
|
||||
query: string;
|
||||
queryValues?: (string | number)[];
|
||||
dbFullName: string;
|
||||
tableName?: string;
|
||||
dbSchema?: import("../../../types").DSQL_DatabaseSchemaType;
|
||||
useLocal?: boolean;
|
||||
};
|
||||
/**
|
||||
* # Get Function FOr API
|
||||
*/
|
||||
export default function apiGet({ query, dbFullName, queryValues, tableName, dbSchema, useLocal, }: Param): Promise<import("../../../types").GetReturn>;
|
||||
export {};
|
||||
+82
@@ -0,0 +1,82 @@
|
||||
"use strict";
|
||||
// @ts-check
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = apiGet;
|
||||
const lodash_1 = __importDefault(require("lodash"));
|
||||
const serverError_1 = __importDefault(require("../../backend/serverError"));
|
||||
const runQuery_1 = __importDefault(require("../../backend/db/runQuery"));
|
||||
/**
|
||||
* # Get Function FOr API
|
||||
*/
|
||||
function apiGet(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ query, dbFullName, queryValues, tableName, dbSchema, useLocal, }) {
|
||||
if (typeof query == "string" &&
|
||||
query.match(/^alter|^delete|information_schema|databases|^create/i)) {
|
||||
return { success: false, msg: "Wrong Input." };
|
||||
}
|
||||
/**
|
||||
* Create new user folder and file
|
||||
*
|
||||
* @description Create new user folder and file
|
||||
*/
|
||||
let results;
|
||||
try {
|
||||
let { result, error } = yield (0, runQuery_1.default)({
|
||||
dbFullName: dbFullName,
|
||||
query: query,
|
||||
queryValuesArray: queryValues,
|
||||
readOnly: true,
|
||||
dbSchema,
|
||||
tableName,
|
||||
local: useLocal,
|
||||
});
|
||||
/** @type {import("../../../types").DSQL_TableSchemaType | undefined} */
|
||||
let tableSchema;
|
||||
if (dbSchema) {
|
||||
const targetTable = dbSchema.tables.find((table) => table.tableName === tableName);
|
||||
if (targetTable) {
|
||||
const clonedTargetTable = lodash_1.default.cloneDeep(targetTable);
|
||||
delete clonedTargetTable.childTable;
|
||||
delete clonedTargetTable.childTableDbFullName;
|
||||
delete clonedTargetTable.childTableName;
|
||||
delete clonedTargetTable.childrenTables;
|
||||
delete clonedTargetTable.updateData;
|
||||
delete clonedTargetTable.tableNameOld;
|
||||
delete clonedTargetTable.indexes;
|
||||
tableSchema = clonedTargetTable;
|
||||
}
|
||||
}
|
||||
if (error)
|
||||
throw error;
|
||||
if (result.error)
|
||||
throw new Error(result.error);
|
||||
results = result;
|
||||
/** @type {import("../../../types").GetReturn} */
|
||||
const resObject = {
|
||||
success: true,
|
||||
payload: results,
|
||||
schema: tableName && tableSchema ? tableSchema : undefined,
|
||||
};
|
||||
return resObject;
|
||||
}
|
||||
catch ( /** @type {any} */error) {
|
||||
(0, serverError_1.default)({
|
||||
component: "/api/query/get/lines-85-94",
|
||||
message: error.message,
|
||||
});
|
||||
return { success: false, payload: null, error: error.message };
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import { DSQL_DatabaseSchemaType, PostReturn } from "../../../types";
|
||||
type Param = {
|
||||
query: any;
|
||||
queryValues?: (string | number)[];
|
||||
dbFullName: string;
|
||||
tableName?: string;
|
||||
dbSchema?: DSQL_DatabaseSchemaType;
|
||||
useLocal?: boolean;
|
||||
};
|
||||
/**
|
||||
* # Post Function For API
|
||||
*/
|
||||
export default function apiPost({ query, dbFullName, queryValues, tableName, dbSchema, useLocal, }: Param): Promise<PostReturn>;
|
||||
export {};
|
||||
+86
@@ -0,0 +1,86 @@
|
||||
"use strict";
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = apiPost;
|
||||
const lodash_1 = __importDefault(require("lodash"));
|
||||
const serverError_1 = __importDefault(require("../../backend/serverError"));
|
||||
const runQuery_1 = __importDefault(require("../../backend/db/runQuery"));
|
||||
/**
|
||||
* # Post Function For API
|
||||
*/
|
||||
function apiPost(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ query, dbFullName, queryValues, tableName, dbSchema, useLocal, }) {
|
||||
var _b;
|
||||
if (typeof query === "string" && (query === null || query === void 0 ? void 0 : query.match(/^create |^alter |^drop /i))) {
|
||||
return { success: false, msg: "Wrong Input" };
|
||||
}
|
||||
if (typeof query === "object" &&
|
||||
((_b = query === null || query === void 0 ? void 0 : query.action) === null || _b === void 0 ? void 0 : _b.match(/^create |^alter |^drop /i))) {
|
||||
return { success: false, msg: "Wrong Input" };
|
||||
}
|
||||
/** @type {any} */
|
||||
let results;
|
||||
/**
|
||||
* Create new user folder and file
|
||||
*
|
||||
* @description Create new user folder and file
|
||||
*/
|
||||
try {
|
||||
let { result, error } = yield (0, runQuery_1.default)({
|
||||
dbFullName: dbFullName,
|
||||
query: query,
|
||||
dbSchema: dbSchema,
|
||||
queryValuesArray: queryValues,
|
||||
tableName,
|
||||
local: useLocal,
|
||||
});
|
||||
results = result;
|
||||
if (error)
|
||||
throw error;
|
||||
/** @type {import("../../../types").DSQL_TableSchemaType | undefined} */
|
||||
let tableSchema;
|
||||
if (dbSchema) {
|
||||
const targetTable = dbSchema.tables.find((table) => table.tableName === tableName);
|
||||
if (targetTable) {
|
||||
const clonedTargetTable = lodash_1.default.cloneDeep(targetTable);
|
||||
delete clonedTargetTable.childTable;
|
||||
delete clonedTargetTable.childTableDbFullName;
|
||||
delete clonedTargetTable.childTableName;
|
||||
delete clonedTargetTable.childrenTables;
|
||||
delete clonedTargetTable.updateData;
|
||||
delete clonedTargetTable.tableNameOld;
|
||||
delete clonedTargetTable.indexes;
|
||||
tableSchema = clonedTargetTable;
|
||||
}
|
||||
}
|
||||
return {
|
||||
success: true,
|
||||
payload: results,
|
||||
error: error,
|
||||
schema: tableName && tableSchema ? tableSchema : undefined,
|
||||
};
|
||||
}
|
||||
catch (error) {
|
||||
(0, serverError_1.default)({
|
||||
component: "/api/query/post/lines-132-142",
|
||||
message: error.message,
|
||||
});
|
||||
return {
|
||||
success: false,
|
||||
payload: results,
|
||||
error: error.message,
|
||||
};
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
import { UserType } from "../../../types";
|
||||
/**
|
||||
* # Facebook Login
|
||||
*/
|
||||
export default function facebookLogin({ usertype, body, }: {
|
||||
body: any;
|
||||
usertype: UserType;
|
||||
}): Promise<any>;
|
||||
@@ -0,0 +1,78 @@
|
||||
"use strict";
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = facebookLogin;
|
||||
const DB_HANDLER_1 = __importDefault(require("../../../utils/backend/global-db/DB_HANDLER"));
|
||||
const serverError_1 = __importDefault(require("../../backend/serverError"));
|
||||
const hashPassword_1 = __importDefault(require("../../dsql/hashPassword"));
|
||||
/**
|
||||
* # Facebook Login
|
||||
*/
|
||||
function facebookLogin(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ usertype, body, }) {
|
||||
try {
|
||||
const foundUser = yield (0, DB_HANDLER_1.default)(`SELECT * FROM users WHERE email='${body.facebookUserEmail}' AND social_login='1'`);
|
||||
if (foundUser && foundUser[0]) {
|
||||
return foundUser[0];
|
||||
}
|
||||
let socialHashedPassword = (0, hashPassword_1.default)({
|
||||
password: body.facebookUserId,
|
||||
});
|
||||
let newUser = yield (0, DB_HANDLER_1.default)(`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 = yield (0, DB_HANDLER_1.default)(`SELECT * FROM ${usertype} WHERE id='${newUser.insertId}'`);
|
||||
}
|
||||
catch ( /** @type {any} */error) {
|
||||
(0, serverError_1.default)({
|
||||
component: "functions/backend/facebookLogin",
|
||||
message: error.message,
|
||||
});
|
||||
}
|
||||
return {
|
||||
isFacebookAuthValid: false,
|
||||
newFoundUser: null,
|
||||
};
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
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 function githubLogin({ code, clientId, clientSecret, }: Param): Promise<GithubUserPayload | null | undefined>;
|
||||
export {};
|
||||
@@ -0,0 +1,62 @@
|
||||
"use strict";
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = githubLogin;
|
||||
const DB_HANDLER_1 = __importDefault(require("../../../utils/backend/global-db/DB_HANDLER"));
|
||||
const httpsRequest_1 = __importDefault(require("../../backend/httpsRequest"));
|
||||
/**
|
||||
* # Login/signup a github user
|
||||
*/
|
||||
function githubLogin(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ code, clientId, clientSecret, }) {
|
||||
let gitHubUser;
|
||||
try {
|
||||
const response = yield (0, httpsRequest_1.default)({
|
||||
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);
|
||||
if (!(accessTokenObject === null || accessTokenObject === void 0 ? void 0 : accessTokenObject.access_token)) {
|
||||
return gitHubUser;
|
||||
}
|
||||
const userDataResponse = yield (0, httpsRequest_1.default)({
|
||||
method: "GET",
|
||||
hostname: "api.github.com",
|
||||
path: "/user",
|
||||
headers: {
|
||||
Authorization: `Bearer ${accessTokenObject.access_token}`,
|
||||
"User-Agent": "*",
|
||||
},
|
||||
scheme: "https",
|
||||
});
|
||||
gitHubUser = JSON.parse(userDataResponse);
|
||||
if (!(gitHubUser === null || gitHubUser === void 0 ? void 0 : gitHubUser.email) && gitHubUser) {
|
||||
const existingGithubUser = yield (0, DB_HANDLER_1.default)(`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);
|
||||
}
|
||||
return gitHubUser;
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
type Param = {
|
||||
usertype: string;
|
||||
foundUser: any;
|
||||
isSocialValidated: boolean;
|
||||
isUserValid: boolean;
|
||||
reqBody: any;
|
||||
serverRes: any;
|
||||
loginFailureReason: any;
|
||||
};
|
||||
/**
|
||||
* # Google Login
|
||||
*/
|
||||
export default function googleLogin({ usertype, foundUser, isSocialValidated, isUserValid, reqBody, serverRes, loginFailureReason, }: Param): Promise<{
|
||||
isGoogleAuthValid: boolean;
|
||||
newFoundUser: null;
|
||||
loginFailureReason: any;
|
||||
} | {
|
||||
isGoogleAuthValid: boolean;
|
||||
newFoundUser: any;
|
||||
loginFailureReason?: undefined;
|
||||
} | undefined>;
|
||||
export {};
|
||||
@@ -0,0 +1,123 @@
|
||||
"use strict";
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = googleLogin;
|
||||
const google_auth_library_1 = require("google-auth-library");
|
||||
const serverError_1 = __importDefault(require("../../backend/serverError"));
|
||||
const DB_HANDLER_1 = __importDefault(require("../../../utils/backend/global-db/DB_HANDLER"));
|
||||
const hashPassword_1 = __importDefault(require("../../dsql/hashPassword"));
|
||||
/**
|
||||
* # Google Login
|
||||
*/
|
||||
function googleLogin(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ usertype, foundUser, isSocialValidated, isUserValid, reqBody, serverRes, loginFailureReason, }) {
|
||||
var _b;
|
||||
const client = new google_auth_library_1.OAuth2Client(process.env.NEXT_PUBLIC_DSQL_GOOGLE_CLIENT_ID);
|
||||
let isGoogleAuthValid = false;
|
||||
let newFoundUser = null;
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
try {
|
||||
const ticket = yield client.verifyIdToken({
|
||||
idToken: reqBody.token,
|
||||
audience: process.env.NEXT_PUBLIC_DSQL_GOOGLE_CLIENT_ID, // Specify the CLIENT_ID of the app that accesses the backend
|
||||
// Or, if multiple clients access the backend:
|
||||
//[CLIENT_ID_1, CLIENT_ID_2, CLIENT_ID_3]
|
||||
});
|
||||
const payload = ticket.getPayload();
|
||||
const userid = payload === null || payload === void 0 ? void 0 : payload["sub"];
|
||||
if (!payload)
|
||||
throw new Error("Google login failed. Credentials invalid");
|
||||
isUserValid = Boolean(payload.email_verified);
|
||||
if (!isUserValid || !payload || !payload.email_verified)
|
||||
return;
|
||||
serverRes.isUserValid = payload.email_verified;
|
||||
isSocialValidated = payload.email_verified;
|
||||
isGoogleAuthValid = payload.email_verified;
|
||||
////// If request specified a G Suite domain:
|
||||
////// const domain = payload['hd'];
|
||||
let socialHashedPassword = (0, hashPassword_1.default)({
|
||||
password: payload.at_hash || "",
|
||||
});
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
let existinEmail = yield (0, DB_HANDLER_1.default)(`SELECT * FROM ${usertype} WHERE email='${payload.email}' AND social_login!='1' AND social_platform!='google'`);
|
||||
if (existinEmail && existinEmail[0]) {
|
||||
loginFailureReason = "Email Exists Already";
|
||||
isGoogleAuthValid = false;
|
||||
return {
|
||||
isGoogleAuthValid: isGoogleAuthValid,
|
||||
newFoundUser: newFoundUser,
|
||||
loginFailureReason: loginFailureReason,
|
||||
};
|
||||
}
|
||||
////////////////////////////////////////
|
||||
foundUser = yield (0, DB_HANDLER_1.default)(`SELECT * FROM ${usertype} WHERE email='${payload.email}' AND social_login='1' AND social_platform='google'`);
|
||||
if (foundUser && foundUser[0]) {
|
||||
newFoundUser = foundUser;
|
||||
return {
|
||||
isGoogleAuthValid: isGoogleAuthValid,
|
||||
newFoundUser: newFoundUser,
|
||||
};
|
||||
}
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
let newUser = yield (0, DB_HANDLER_1.default)(`INSERT INTO ${usertype} (
|
||||
first_name,
|
||||
last_name,
|
||||
social_platform,
|
||||
social_name,
|
||||
social_id,
|
||||
email,
|
||||
image,
|
||||
image_thumbnail,
|
||||
password,
|
||||
verification_status,
|
||||
social_login,
|
||||
terms_agreement,
|
||||
date_created,
|
||||
date_code
|
||||
) VALUES (
|
||||
'${payload.given_name}',
|
||||
'${payload.family_name}',
|
||||
'google',
|
||||
'google_${(_b = payload.email) === null || _b === void 0 ? void 0 : _b.replace(/@.*/, "")}',
|
||||
'${payload.sub}',
|
||||
'${payload.email}',
|
||||
'${payload.picture}',
|
||||
'${payload.picture}',
|
||||
'${socialHashedPassword}',
|
||||
'1',
|
||||
'1',
|
||||
'1',
|
||||
'${Date()}',
|
||||
'${Date.now()}'
|
||||
)`);
|
||||
newFoundUser = yield (0, DB_HANDLER_1.default)(`SELECT * FROM ${usertype} WHERE id='${newUser.insertId}'`);
|
||||
}
|
||||
catch (error) {
|
||||
(0, serverError_1.default)({
|
||||
component: "googleLogin",
|
||||
message: error.message,
|
||||
});
|
||||
loginFailureReason = error;
|
||||
isUserValid = false;
|
||||
isSocialValidated = false;
|
||||
}
|
||||
return { isGoogleAuthValid: isGoogleAuthValid, newFoundUser: newFoundUser };
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
import { APILoginFunctionReturn, HandleSocialDbFunctionParams } from "../../../types";
|
||||
/**
|
||||
* # Handle Social DB
|
||||
*/
|
||||
export default function handleSocialDb({ database, social_id, email, social_platform, payload, invitation, supEmail, additionalFields, useLocal, }: HandleSocialDbFunctionParams): Promise<APILoginFunctionReturn>;
|
||||
@@ -0,0 +1,202 @@
|
||||
"use strict";
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = handleSocialDb;
|
||||
const fs_1 = __importDefault(require("fs"));
|
||||
const handleNodemailer_1 = __importDefault(require("../../backend/handleNodemailer"));
|
||||
const path_1 = __importDefault(require("path"));
|
||||
const addMariadbUser_1 = __importDefault(require("../../backend/addMariadbUser"));
|
||||
const varDatabaseDbHandler_1 = __importDefault(require("../../backend/varDatabaseDbHandler"));
|
||||
const encrypt_1 = __importDefault(require("../../dsql/encrypt"));
|
||||
const addDbEntry_1 = __importDefault(require("../../backend/db/addDbEntry"));
|
||||
const loginSocialUser_1 = __importDefault(require("./loginSocialUser"));
|
||||
/**
|
||||
* # Handle Social DB
|
||||
*/
|
||||
function handleSocialDb(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ database, social_id, email, social_platform, payload, invitation, supEmail, additionalFields, useLocal, }) {
|
||||
try {
|
||||
const existingSocialIdUserQuery = `SELECT * FROM users WHERE social_id = ? AND social_login='1' AND social_platform = ? `;
|
||||
const existingSocialIdUserValues = [
|
||||
social_id.toString(),
|
||||
social_platform,
|
||||
];
|
||||
let existingSocialIdUser = yield (0, varDatabaseDbHandler_1.default)({
|
||||
database: database ? database : "datasquirel",
|
||||
queryString: existingSocialIdUserQuery,
|
||||
queryValuesArray: existingSocialIdUserValues,
|
||||
useLocal,
|
||||
});
|
||||
if (existingSocialIdUser && existingSocialIdUser[0]) {
|
||||
return yield (0, loginSocialUser_1.default)({
|
||||
user: existingSocialIdUser[0],
|
||||
social_platform,
|
||||
invitation,
|
||||
database,
|
||||
additionalFields,
|
||||
useLocal,
|
||||
});
|
||||
}
|
||||
const finalEmail = email ? email : supEmail ? supEmail : null;
|
||||
if (!finalEmail) {
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: "No Email Present",
|
||||
};
|
||||
}
|
||||
const existingEmailOnlyQuery = `SELECT * FROM users WHERE email='${finalEmail}'`;
|
||||
let existingEmailOnly = yield (0, varDatabaseDbHandler_1.default)({
|
||||
database: database ? database : "datasquirel",
|
||||
queryString: existingEmailOnlyQuery,
|
||||
useLocal,
|
||||
});
|
||||
if (existingEmailOnly && existingEmailOnly[0]) {
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: "This Email is already taken",
|
||||
};
|
||||
}
|
||||
const foundUserQuery = `SELECT * FROM users WHERE email=? AND social_login='1' AND social_platform=? AND social_id=?`;
|
||||
const foundUserQueryValues = [finalEmail, social_platform, social_id];
|
||||
const foundUser = yield (0, varDatabaseDbHandler_1.default)({
|
||||
database: database ? database : "datasquirel",
|
||||
queryString: foundUserQuery,
|
||||
queryValuesArray: foundUserQueryValues,
|
||||
useLocal,
|
||||
});
|
||||
if (foundUser && foundUser[0]) {
|
||||
return yield (0, loginSocialUser_1.default)({
|
||||
user: payload,
|
||||
social_platform,
|
||||
invitation,
|
||||
database,
|
||||
additionalFields,
|
||||
useLocal,
|
||||
});
|
||||
}
|
||||
const socialHashedPassword = (0, encrypt_1.default)({
|
||||
data: social_id.toString(),
|
||||
});
|
||||
const data = {
|
||||
social_login: "1",
|
||||
verification_status: supEmail ? "0" : "1",
|
||||
password: socialHashedPassword,
|
||||
};
|
||||
Object.keys(payload).forEach((key) => {
|
||||
data[key] = payload[key];
|
||||
});
|
||||
/** @type {any} */
|
||||
const newUser = yield (0, addDbEntry_1.default)({
|
||||
dbContext: database ? "Dsql User" : undefined,
|
||||
paradigm: database ? "Full Access" : undefined,
|
||||
dbFullName: database ? database : "datasquirel",
|
||||
tableName: "users",
|
||||
duplicateColumnName: "email",
|
||||
duplicateColumnValue: finalEmail,
|
||||
data: Object.assign(Object.assign({}, data), { email: finalEmail }),
|
||||
useLocal,
|
||||
});
|
||||
if (newUser === null || newUser === void 0 ? void 0 : newUser.insertId) {
|
||||
if (!database) {
|
||||
/**
|
||||
* Add a Mariadb User for this User
|
||||
*/
|
||||
yield (0, addMariadbUser_1.default)({ userId: newUser.insertId, useLocal });
|
||||
}
|
||||
const newUserQueriedQuery = `SELECT * FROM users WHERE id='${newUser.insertId}'`;
|
||||
const newUserQueried = yield (0, varDatabaseDbHandler_1.default)({
|
||||
database: database ? database : "datasquirel",
|
||||
queryString: newUserQueriedQuery,
|
||||
useLocal,
|
||||
});
|
||||
if (!newUserQueried || !newUserQueried[0])
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: "User Insertion Failed!",
|
||||
};
|
||||
if (supEmail && (database === null || database === void 0 ? void 0 : database.match(/^datasquirel$/))) {
|
||||
/**
|
||||
* Send email Verification
|
||||
*
|
||||
* @description Send verification email to newly created agent
|
||||
*/
|
||||
let generatedToken = (0, encrypt_1.default)({
|
||||
data: JSON.stringify({
|
||||
id: newUser.insertId,
|
||||
email: supEmail,
|
||||
dateCode: Date.now(),
|
||||
}),
|
||||
});
|
||||
(0, handleNodemailer_1.default)({
|
||||
to: supEmail,
|
||||
subject: "Verify Email Address",
|
||||
text: "Please click the link to verify your email address",
|
||||
html: fs_1.default
|
||||
.readFileSync("./email/send-email-verification-link.html", "utf8")
|
||||
.replace(/{{host}}/, process.env.DSQL_HOST || "")
|
||||
.replace(/{{token}}/, generatedToken || ""),
|
||||
}).then(() => { });
|
||||
}
|
||||
const STATIC_ROOT = process.env.DSQL_STATIC_SERVER_DIR;
|
||||
if (!STATIC_ROOT) {
|
||||
console.log("Static File ENV not Found!");
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: "Static File ENV not Found!",
|
||||
};
|
||||
}
|
||||
/**
|
||||
* Create new user folder and file
|
||||
*
|
||||
* @description Create new user folder and file
|
||||
*/
|
||||
if (!database || (database === null || database === void 0 ? void 0 : database.match(/^datasquirel$/))) {
|
||||
let newUserSchemaFolderPath = `${process.env.DSQL_USER_DB_SCHEMA_PATH}/user-${newUser.insertId}`;
|
||||
let newUserMediaFolderPath = path_1.default.join(STATIC_ROOT, `images/user-images/user-${newUser.insertId}`);
|
||||
fs_1.default.mkdirSync(newUserSchemaFolderPath);
|
||||
fs_1.default.mkdirSync(newUserMediaFolderPath);
|
||||
fs_1.default.writeFileSync(`${newUserSchemaFolderPath}/main.json`, JSON.stringify([]), "utf8");
|
||||
}
|
||||
return yield (0, loginSocialUser_1.default)({
|
||||
user: newUserQueried[0],
|
||||
social_platform,
|
||||
invitation,
|
||||
database,
|
||||
additionalFields,
|
||||
useLocal,
|
||||
});
|
||||
}
|
||||
else {
|
||||
console.log("Social User Failed to insert in 'handleSocialDb.js' backend function =>", newUser);
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: "Social User Failed to insert in 'handleSocialDb.js' backend function",
|
||||
};
|
||||
}
|
||||
}
|
||||
catch (error) {
|
||||
console.log("ERROR in 'handleSocialDb.js' backend function =>", error.message);
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: error.message,
|
||||
};
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
import { APILoginFunctionReturn } from "../../../types";
|
||||
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
|
||||
*/
|
||||
export default function loginSocialUser({ user, social_platform, invitation, database, additionalFields, useLocal, }: Param): Promise<APILoginFunctionReturn>;
|
||||
export {};
|
||||
@@ -0,0 +1,80 @@
|
||||
"use strict";
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = loginSocialUser;
|
||||
const addAdminUserOnLogin_1 = __importDefault(require("../../backend/addAdminUserOnLogin"));
|
||||
const varDatabaseDbHandler_1 = __importDefault(require("../../backend/varDatabaseDbHandler"));
|
||||
/**
|
||||
* Function to login social user
|
||||
* ==============================================================================
|
||||
* @description This function logs in the user after 'handleSocialDb' function finishes
|
||||
* the user creation or confirmation process
|
||||
*/
|
||||
function loginSocialUser(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ user, social_platform, invitation, database, additionalFields, useLocal, }) {
|
||||
const foundUserQuery = `SELECT * FROM users WHERE email=? AND social_id=? AND social_platform=?`;
|
||||
const foundUserValues = [user.email, user.social_id, social_platform];
|
||||
const foundUser = yield (0, varDatabaseDbHandler_1.default)({
|
||||
database: database ? database : "datasquirel",
|
||||
queryString: foundUserQuery,
|
||||
queryValuesArray: foundUserValues,
|
||||
useLocal,
|
||||
});
|
||||
if (!(foundUser === null || foundUser === void 0 ? void 0 : foundUser[0]))
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
};
|
||||
let csrfKey = Math.random().toString(36).substring(2) +
|
||||
"-" +
|
||||
Math.random().toString(36).substring(2);
|
||||
/** @type {import("../../../types").DATASQUIREL_LoggedInUser} */
|
||||
let userPayload = {
|
||||
id: foundUser[0].id,
|
||||
first_name: foundUser[0].first_name,
|
||||
last_name: foundUser[0].last_name,
|
||||
username: foundUser[0].username,
|
||||
user_type: foundUser[0].user_type,
|
||||
email: foundUser[0].email,
|
||||
social_id: foundUser[0].social_id,
|
||||
image: foundUser[0].image,
|
||||
image_thumbnail: foundUser[0].image_thumbnail,
|
||||
verification_status: foundUser[0].verification_status,
|
||||
social_login: foundUser[0].social_login,
|
||||
social_platform: foundUser[0].social_platform,
|
||||
csrf_k: csrfKey,
|
||||
logged_in_status: true,
|
||||
date: Date.now(),
|
||||
};
|
||||
if (additionalFields === null || additionalFields === void 0 ? void 0 : additionalFields[0]) {
|
||||
additionalFields.forEach((key) => {
|
||||
userPayload[key] = foundUser[0][key];
|
||||
});
|
||||
}
|
||||
if (invitation && (!database || (database === null || database === void 0 ? void 0 : database.match(/^datasquirel$/)))) {
|
||||
(0, addAdminUserOnLogin_1.default)({
|
||||
query: invitation,
|
||||
user: userPayload,
|
||||
useLocal,
|
||||
});
|
||||
}
|
||||
/** @type {import("../../../types").APILoginFunctionReturn} */
|
||||
let result = {
|
||||
success: true,
|
||||
payload: userPayload,
|
||||
csrf: csrfKey,
|
||||
};
|
||||
return result;
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import { APICreateUserFunctionParams } from "../../../types";
|
||||
/**
|
||||
* # API Create User
|
||||
*/
|
||||
export default function apiCreateUser({ encryptionKey, payload, database, userId, useLocal, }: APICreateUserFunctionParams): Promise<{
|
||||
success: boolean;
|
||||
msg: string;
|
||||
payload: null;
|
||||
sqlResult?: undefined;
|
||||
} | {
|
||||
success: boolean;
|
||||
msg: string;
|
||||
payload?: undefined;
|
||||
sqlResult?: undefined;
|
||||
} | {
|
||||
success: boolean;
|
||||
payload: any;
|
||||
msg?: undefined;
|
||||
sqlResult?: undefined;
|
||||
} | {
|
||||
success: boolean;
|
||||
msg: string;
|
||||
sqlResult: any;
|
||||
payload: null;
|
||||
}>;
|
||||
@@ -0,0 +1,142 @@
|
||||
"use strict";
|
||||
// @ts-check
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = apiCreateUser;
|
||||
const addUsersTableToDb_1 = __importDefault(require("../../backend/addUsersTableToDb"));
|
||||
const addDbEntry_1 = __importDefault(require("../../backend/db/addDbEntry"));
|
||||
const updateUsersTableSchema_1 = __importDefault(require("../../backend/updateUsersTableSchema"));
|
||||
const varDatabaseDbHandler_1 = __importDefault(require("../../backend/varDatabaseDbHandler"));
|
||||
const hashPassword_1 = __importDefault(require("../../dsql/hashPassword"));
|
||||
/**
|
||||
* # API Create User
|
||||
*/
|
||||
function apiCreateUser(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ encryptionKey, payload, database, userId, useLocal, }) {
|
||||
const dbFullName = database;
|
||||
const API_USER_ID = userId || process.env.DSQL_API_USER_ID;
|
||||
const finalEncryptionKey = encryptionKey || process.env.DSQL_ENCRYPTION_PASSWORD;
|
||||
if (!finalEncryptionKey) {
|
||||
return {
|
||||
success: false,
|
||||
msg: "No encryption key provided",
|
||||
payload: null,
|
||||
};
|
||||
}
|
||||
if (!(finalEncryptionKey === null || finalEncryptionKey === void 0 ? void 0 : finalEncryptionKey.match(/.{8,}/))) {
|
||||
return {
|
||||
success: false,
|
||||
msg: "Encryption key must be at least 8 characters long",
|
||||
payload: null,
|
||||
};
|
||||
}
|
||||
const hashedPassword = (0, hashPassword_1.default)({
|
||||
encryptionKey: finalEncryptionKey,
|
||||
password: String(payload.password),
|
||||
});
|
||||
payload.password = hashedPassword;
|
||||
const fieldsQuery = `SHOW COLUMNS FROM users`;
|
||||
let fields = yield (0, varDatabaseDbHandler_1.default)({
|
||||
queryString: fieldsQuery,
|
||||
database: dbFullName,
|
||||
useLocal,
|
||||
});
|
||||
if (!(fields === null || fields === void 0 ? void 0 : fields[0])) {
|
||||
const newTable = yield (0, addUsersTableToDb_1.default)({
|
||||
userId: Number(API_USER_ID),
|
||||
database: dbFullName,
|
||||
useLocal,
|
||||
payload: payload,
|
||||
});
|
||||
fields = yield (0, varDatabaseDbHandler_1.default)({
|
||||
queryString: fieldsQuery,
|
||||
database: dbFullName,
|
||||
useLocal,
|
||||
});
|
||||
}
|
||||
if (!(fields === null || fields === void 0 ? void 0 : fields[0])) {
|
||||
return {
|
||||
success: false,
|
||||
msg: "Could not create users table",
|
||||
};
|
||||
}
|
||||
const fieldsTitles = fields.map((fieldObject) => fieldObject.Field);
|
||||
let invalidField = null;
|
||||
for (let i = 0; i < Object.keys(payload).length; i++) {
|
||||
const key = Object.keys(payload)[i];
|
||||
if (!fieldsTitles.includes(key)) {
|
||||
yield (0, updateUsersTableSchema_1.default)({
|
||||
userId: Number(API_USER_ID),
|
||||
database: dbFullName,
|
||||
newPayload: {
|
||||
[key]: payload[key],
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
if (invalidField) {
|
||||
return {
|
||||
success: false,
|
||||
msg: `${invalidField} is not a valid field!`,
|
||||
};
|
||||
}
|
||||
const existingUserQuery = `SELECT * FROM users WHERE email = ?${payload.username ? " OR username = ?" : ""}`;
|
||||
const existingUserValues = payload.username
|
||||
? [payload.email, payload.username]
|
||||
: [payload.email];
|
||||
const existingUser = yield (0, varDatabaseDbHandler_1.default)({
|
||||
queryString: existingUserQuery,
|
||||
queryValuesArray: existingUserValues,
|
||||
database: dbFullName,
|
||||
useLocal,
|
||||
});
|
||||
if (existingUser === null || existingUser === void 0 ? void 0 : existingUser[0]) {
|
||||
return {
|
||||
success: false,
|
||||
msg: "User Already Exists",
|
||||
payload: null,
|
||||
};
|
||||
}
|
||||
const addUser = yield (0, addDbEntry_1.default)({
|
||||
dbContext: "Dsql User",
|
||||
paradigm: "Full Access",
|
||||
dbFullName: dbFullName,
|
||||
tableName: "users",
|
||||
data: Object.assign(Object.assign({}, payload), { image: process.env.DSQL_DEFAULT_USER_IMAGE ||
|
||||
"/images/user-preset.png", image_thumbnail: process.env.DSQL_DEFAULT_USER_IMAGE ||
|
||||
"/images/user-preset-thumbnail.png" }),
|
||||
useLocal,
|
||||
});
|
||||
if (addUser === null || addUser === void 0 ? void 0 : 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 newlyAddedUser = yield (0, varDatabaseDbHandler_1.default)({
|
||||
queryString: newlyAddedUserQuery,
|
||||
database: dbFullName,
|
||||
useLocal,
|
||||
});
|
||||
return {
|
||||
success: true,
|
||||
payload: newlyAddedUser[0],
|
||||
};
|
||||
}
|
||||
else {
|
||||
return {
|
||||
success: false,
|
||||
msg: "Could not create user",
|
||||
sqlResult: addUser,
|
||||
payload: null,
|
||||
};
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
type Param = {
|
||||
dbFullName: string;
|
||||
deletedUserId: string | number;
|
||||
useLocal?: boolean;
|
||||
};
|
||||
type Return = {
|
||||
success: boolean;
|
||||
result?: any;
|
||||
msg?: string;
|
||||
};
|
||||
/**
|
||||
* # Update API User Function
|
||||
*/
|
||||
export default function apiDeleteUser({ dbFullName, deletedUserId, useLocal, }: Param): Promise<Return>;
|
||||
export {};
|
||||
@@ -0,0 +1,51 @@
|
||||
"use strict";
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = apiDeleteUser;
|
||||
const deleteDbEntry_1 = __importDefault(require("../../backend/db/deleteDbEntry"));
|
||||
const varDatabaseDbHandler_1 = __importDefault(require("../../backend/varDatabaseDbHandler"));
|
||||
/**
|
||||
* # Update API User Function
|
||||
*/
|
||||
function apiDeleteUser(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ dbFullName, deletedUserId, useLocal, }) {
|
||||
const existingUserQuery = `SELECT * FROM users WHERE id = ?`;
|
||||
const existingUserValues = [deletedUserId];
|
||||
const existingUser = yield (0, varDatabaseDbHandler_1.default)({
|
||||
queryString: existingUserQuery,
|
||||
queryValuesArray: existingUserValues,
|
||||
database: dbFullName,
|
||||
useLocal,
|
||||
});
|
||||
if (!(existingUser === null || existingUser === void 0 ? void 0 : existingUser[0])) {
|
||||
return {
|
||||
success: false,
|
||||
msg: "User not found",
|
||||
};
|
||||
}
|
||||
const deleteUser = yield (0, deleteDbEntry_1.default)({
|
||||
dbContext: "Dsql User",
|
||||
paradigm: "Full Access",
|
||||
dbFullName,
|
||||
tableName: "users",
|
||||
identifierColumnName: "id",
|
||||
identifierValue: deletedUserId,
|
||||
useLocal,
|
||||
});
|
||||
return {
|
||||
success: true,
|
||||
result: deleteUser,
|
||||
};
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
import { APIGetUserFunctionParams, GetUserFunctionReturn } from "../../../types";
|
||||
/**
|
||||
* # API Get User
|
||||
*/
|
||||
export default function apiGetUser({ fields, dbFullName, userId, useLocal, }: APIGetUserFunctionParams): Promise<GetUserFunctionReturn>;
|
||||
@@ -0,0 +1,41 @@
|
||||
"use strict";
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = apiGetUser;
|
||||
const varDatabaseDbHandler_1 = __importDefault(require("../../backend/varDatabaseDbHandler"));
|
||||
/**
|
||||
* # API Get User
|
||||
*/
|
||||
function apiGetUser(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ 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 = yield (0, varDatabaseDbHandler_1.default)({
|
||||
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,5 @@
|
||||
import { APILoginFunctionParams, APILoginFunctionReturn } from "../../../types";
|
||||
/**
|
||||
* # API Login
|
||||
*/
|
||||
export default function apiLoginUser({ encryptionKey, email, username, password, database, additionalFields, email_login, email_login_code, email_login_field, token, skipPassword, social, useLocal, }: APILoginFunctionParams): Promise<APILoginFunctionReturn>;
|
||||
@@ -0,0 +1,137 @@
|
||||
"use strict";
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = apiLoginUser;
|
||||
const varDatabaseDbHandler_1 = __importDefault(require("../../backend/varDatabaseDbHandler"));
|
||||
const hashPassword_1 = __importDefault(require("../../dsql/hashPassword"));
|
||||
/**
|
||||
* # API Login
|
||||
*/
|
||||
function apiLoginUser(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ encryptionKey, email, username, password, database, additionalFields, email_login, email_login_code, email_login_field, token, skipPassword, social, useLocal, }) {
|
||||
const dbFullName = database;
|
||||
/**
|
||||
* Check input validity
|
||||
*
|
||||
* @description Check input validity
|
||||
*/
|
||||
if ((email === null || email === void 0 ? void 0 : email.match(/ /)) ||
|
||||
(username && (username === null || username === void 0 ? void 0 : username.match(/ /))) ||
|
||||
(password && (password === null || password === void 0 ? void 0 : password.match(/ /)))) {
|
||||
return {
|
||||
success: false,
|
||||
msg: "Invalid Email/Password format",
|
||||
};
|
||||
}
|
||||
/**
|
||||
* Password hash
|
||||
*
|
||||
* @description Password hash
|
||||
*/
|
||||
let hashedPassword = password
|
||||
? (0, hashPassword_1.default)({
|
||||
encryptionKey: encryptionKey,
|
||||
password: password,
|
||||
})
|
||||
: null;
|
||||
let foundUser = yield (0, varDatabaseDbHandler_1.default)({
|
||||
queryString: `SELECT * FROM users WHERE email = ? OR username = ?`,
|
||||
queryValuesArray: [email, username],
|
||||
database: dbFullName.replace(/[^a-z0-9_]/g, ""),
|
||||
useLocal,
|
||||
});
|
||||
if ((!foundUser || !foundUser[0]) && !social)
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: "No user found",
|
||||
};
|
||||
let isPasswordCorrect = false;
|
||||
if ((foundUser === null || foundUser === void 0 ? void 0 : foundUser[0]) && !email_login && skipPassword) {
|
||||
isPasswordCorrect = true;
|
||||
}
|
||||
else if ((foundUser === null || foundUser === void 0 ? void 0 : foundUser[0]) && !email_login) {
|
||||
isPasswordCorrect = hashedPassword === foundUser[0].password;
|
||||
}
|
||||
else if (foundUser &&
|
||||
foundUser[0] &&
|
||||
email_login &&
|
||||
email_login_code &&
|
||||
email_login_field) {
|
||||
/** @type {string} */
|
||||
const tempCode = foundUser[0][email_login_field];
|
||||
if (!tempCode)
|
||||
throw new Error("No code Found!");
|
||||
const tempCodeArray = tempCode.split("-");
|
||||
const [code, codeDate] = tempCodeArray;
|
||||
const millisecond15mins = 1000 * 60 * 15;
|
||||
if (Date.now() - Number(codeDate) > millisecond15mins) {
|
||||
throw new Error("Code Expired");
|
||||
}
|
||||
isPasswordCorrect = code === email_login_code;
|
||||
}
|
||||
let socialUserValid = false;
|
||||
if (!isPasswordCorrect && !socialUserValid) {
|
||||
return {
|
||||
success: false,
|
||||
msg: "Wrong password, no social login validity",
|
||||
payload: null,
|
||||
};
|
||||
}
|
||||
if (isPasswordCorrect && email_login) {
|
||||
const resetTempCode = yield (0, varDatabaseDbHandler_1.default)({
|
||||
queryString: `UPDATE users SET ${email_login_field} = '' WHERE email = ? OR username = ?`,
|
||||
queryValuesArray: [email, username],
|
||||
database: dbFullName.replace(/[^a-z0-9_]/g, ""),
|
||||
useLocal,
|
||||
});
|
||||
}
|
||||
let csrfKey = Math.random().toString(36).substring(2) +
|
||||
"-" +
|
||||
Math.random().toString(36).substring(2);
|
||||
let userPayload = {
|
||||
id: foundUser[0].id,
|
||||
first_name: foundUser[0].first_name,
|
||||
last_name: foundUser[0].last_name,
|
||||
username: foundUser[0].username,
|
||||
email: foundUser[0].email,
|
||||
phone: foundUser[0].phone,
|
||||
social_id: foundUser[0].social_id,
|
||||
image: foundUser[0].image,
|
||||
image_thumbnail: foundUser[0].image_thumbnail,
|
||||
verification_status: foundUser[0].verification_status,
|
||||
social_login: foundUser[0].social_login,
|
||||
social_platform: foundUser[0].social_platform,
|
||||
csrf_k: csrfKey,
|
||||
more_data: foundUser[0].more_user_data,
|
||||
logged_in_status: true,
|
||||
date: Date.now(),
|
||||
};
|
||||
const resposeObject = {
|
||||
success: true,
|
||||
msg: "Login Successful",
|
||||
payload: userPayload,
|
||||
userId: foundUser[0].id,
|
||||
csrf: csrfKey,
|
||||
};
|
||||
if (additionalFields &&
|
||||
Array.isArray(additionalFields) &&
|
||||
additionalFields.length > 0) {
|
||||
additionalFields.forEach((key) => {
|
||||
userPayload[key] = foundUser[0][key];
|
||||
});
|
||||
}
|
||||
return resposeObject;
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import { APILoginFunctionReturn } from "../../../types";
|
||||
type Param = {
|
||||
existingUser: {
|
||||
[s: string]: any;
|
||||
};
|
||||
database?: string;
|
||||
additionalFields?: string[];
|
||||
useLocal?: boolean;
|
||||
};
|
||||
/**
|
||||
* # Re-authenticate API user
|
||||
*/
|
||||
export default function apiReauthUser({ existingUser, database, additionalFields, useLocal, }: Param): Promise<APILoginFunctionReturn>;
|
||||
export {};
|
||||
@@ -0,0 +1,72 @@
|
||||
"use strict";
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = apiReauthUser;
|
||||
const varDatabaseDbHandler_1 = __importDefault(require("../../backend/varDatabaseDbHandler"));
|
||||
/**
|
||||
* # Re-authenticate API user
|
||||
*/
|
||||
function apiReauthUser(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ existingUser, database, additionalFields, useLocal, }) {
|
||||
let foundUser = (existingUser === null || existingUser === void 0 ? void 0 : existingUser.id) && existingUser.id.toString().match(/./)
|
||||
? yield (0, varDatabaseDbHandler_1.default)({
|
||||
queryString: `SELECT * FROM users WHERE id=?`,
|
||||
queryValuesArray: [existingUser.id.toString()],
|
||||
database,
|
||||
useLocal,
|
||||
})
|
||||
: null;
|
||||
if (!foundUser || !foundUser[0])
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: "No user found",
|
||||
};
|
||||
let csrfKey = Math.random().toString(36).substring(2) +
|
||||
"-" +
|
||||
Math.random().toString(36).substring(2);
|
||||
/** @type {import("../../../types").DATASQUIREL_LoggedInUser} */
|
||||
let userPayload = {
|
||||
id: foundUser[0].id,
|
||||
first_name: foundUser[0].first_name,
|
||||
last_name: foundUser[0].last_name,
|
||||
username: foundUser[0].username,
|
||||
email: foundUser[0].email,
|
||||
phone: foundUser[0].phone,
|
||||
social_id: foundUser[0].social_id,
|
||||
image: foundUser[0].image,
|
||||
image_thumbnail: foundUser[0].image_thumbnail,
|
||||
verification_status: foundUser[0].verification_status,
|
||||
social_login: foundUser[0].social_login,
|
||||
social_platform: foundUser[0].social_platform,
|
||||
csrf_k: csrfKey,
|
||||
more_data: foundUser[0].more_user_data,
|
||||
logged_in_status: true,
|
||||
date: Date.now(),
|
||||
};
|
||||
if (additionalFields &&
|
||||
Array.isArray(additionalFields) &&
|
||||
additionalFields.length > 0) {
|
||||
additionalFields.forEach((key) => {
|
||||
userPayload[key] = foundUser[0][key];
|
||||
});
|
||||
}
|
||||
return {
|
||||
success: true,
|
||||
msg: "Login Successful",
|
||||
payload: userPayload,
|
||||
csrf: csrfKey,
|
||||
};
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import http from "http";
|
||||
import { SendOneTimeCodeEmailResponse } from "../../../types";
|
||||
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
|
||||
*/
|
||||
export default function apiSendEmailCode({ email, database, email_login_field, mail_domain, mail_port, sender, mail_username, mail_password, html, useLocal, response, extraCookies, }: Param): Promise<SendOneTimeCodeEmailResponse>;
|
||||
export {};
|
||||
@@ -0,0 +1,134 @@
|
||||
"use strict";
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = apiSendEmailCode;
|
||||
const varDatabaseDbHandler_1 = __importDefault(require("../../backend/varDatabaseDbHandler"));
|
||||
const nodemailer_1 = __importDefault(require("nodemailer"));
|
||||
const get_auth_cookie_names_1 = __importDefault(require("../../backend/cookies/get-auth-cookie-names"));
|
||||
const encrypt_1 = __importDefault(require("../../dsql/encrypt"));
|
||||
const serialize_cookies_1 = __importDefault(require("../../../utils/serialize-cookies"));
|
||||
/**
|
||||
* # Send Email Login Code
|
||||
*/
|
||||
function apiSendEmailCode(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ email, database, email_login_field, mail_domain, mail_port, sender, mail_username, mail_password, html, useLocal, response, extraCookies, }) {
|
||||
if (email === null || email === void 0 ? void 0 : email.match(/ /)) {
|
||||
return {
|
||||
success: false,
|
||||
msg: "Invalid Email/Password format",
|
||||
};
|
||||
}
|
||||
const createdAt = Date.now();
|
||||
const foundUserQuery = `SELECT * FROM users WHERE email = ?`;
|
||||
const foundUserValues = [email];
|
||||
let foundUser = yield (0, varDatabaseDbHandler_1.default)({
|
||||
queryString: foundUserQuery,
|
||||
queryValuesArray: foundUserValues,
|
||||
database,
|
||||
useLocal,
|
||||
});
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
if (!foundUser || !foundUser[0]) {
|
||||
return {
|
||||
success: false,
|
||||
msg: "No user found",
|
||||
};
|
||||
}
|
||||
function generateCode() {
|
||||
const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
|
||||
let code = "";
|
||||
for (let i = 0; i < 8; i++) {
|
||||
code += chars[Math.floor(Math.random() * chars.length)];
|
||||
}
|
||||
return code;
|
||||
}
|
||||
if ((foundUser === null || foundUser === void 0 ? void 0 : foundUser[0]) && email_login_field) {
|
||||
const tempCode = generateCode();
|
||||
let transporter = nodemailer_1.default.createTransport({
|
||||
host: mail_domain || process.env.DSQL_MAIL_HOST,
|
||||
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,
|
||||
pass: mail_password || process.env.DSQL_MAIL_PASSWORD,
|
||||
},
|
||||
});
|
||||
let mailObject = {};
|
||||
mailObject["from"] = `"Datasquirel SSO" <${sender || "support@datasquirel.com"}>`;
|
||||
mailObject["sender"] = sender || "support@datasquirel.com";
|
||||
mailObject["to"] = email;
|
||||
mailObject["subject"] = "One Time Login Code";
|
||||
mailObject["html"] = html.replace(/{{code}}/, tempCode);
|
||||
const info = yield transporter.sendMail(mailObject);
|
||||
if (!(info === null || info === void 0 ? void 0 : info.accepted))
|
||||
throw new Error("Mail not Sent!");
|
||||
const setTempCodeQuery = `UPDATE users SET ${email_login_field} = ? WHERE email = ?`;
|
||||
const setTempCodeValues = [tempCode + `-${createdAt}`, email];
|
||||
let setTempCode = yield (0, varDatabaseDbHandler_1.default)({
|
||||
queryString: setTempCodeQuery,
|
||||
queryValuesArray: setTempCodeValues,
|
||||
database: database,
|
||||
useLocal,
|
||||
});
|
||||
/** @type {import("../../../types").SendOneTimeCodeEmailResponse} */
|
||||
const resObject = {
|
||||
success: true,
|
||||
code: tempCode,
|
||||
email: email,
|
||||
createdAt,
|
||||
msg: "Success",
|
||||
};
|
||||
if (response) {
|
||||
const cookieKeyNames = (0, get_auth_cookie_names_1.default)();
|
||||
const oneTimeCodeCookieName = cookieKeyNames.oneTimeCodeName;
|
||||
const encryptedPayload = (0, encrypt_1.default)({
|
||||
data: JSON.stringify(resObject),
|
||||
});
|
||||
if (!encryptedPayload) {
|
||||
throw new Error("apiSendEmailCode Error: Failed to encrypt payload");
|
||||
}
|
||||
/** @type {import("../../../../package-shared/types").CookieObject} */
|
||||
const oneTimeCookieObject = {
|
||||
name: oneTimeCodeCookieName,
|
||||
value: encryptedPayload,
|
||||
sameSite: "Strict",
|
||||
path: "/",
|
||||
httpOnly: true,
|
||||
secure: true,
|
||||
};
|
||||
/** @type {import("../../../../package-shared/types").CookieObject[]} */
|
||||
const cookiesObjectArray = extraCookies
|
||||
? [...extraCookies, oneTimeCookieObject]
|
||||
: [oneTimeCookieObject];
|
||||
const serializedCookies = (0, serialize_cookies_1.default)({
|
||||
cookies: cookiesObjectArray,
|
||||
});
|
||||
response.setHeader("Set-Cookie", serializedCookies);
|
||||
}
|
||||
return resObject;
|
||||
}
|
||||
else {
|
||||
return {
|
||||
success: false,
|
||||
msg: "Invalid Email/Password format",
|
||||
};
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
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
|
||||
*/
|
||||
export default function apiUpdateUser({ payload, dbFullName, updatedUserId, useLocal, dbSchema, }: Param): Promise<Return>;
|
||||
export {};
|
||||
@@ -0,0 +1,85 @@
|
||||
"use strict";
|
||||
// @ts-check
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = apiUpdateUser;
|
||||
const updateDbEntry_1 = __importDefault(require("../../backend/db/updateDbEntry"));
|
||||
const encrypt_1 = __importDefault(require("../../dsql/encrypt"));
|
||||
const hashPassword_1 = __importDefault(require("../../dsql/hashPassword"));
|
||||
const varDatabaseDbHandler_1 = __importDefault(require("../../backend/varDatabaseDbHandler"));
|
||||
/**
|
||||
* # Update API User Function
|
||||
*/
|
||||
function apiUpdateUser(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ payload, dbFullName, updatedUserId, useLocal, dbSchema, }) {
|
||||
const existingUserQuery = `SELECT * FROM users WHERE id = ?`;
|
||||
const existingUserValues = [updatedUserId];
|
||||
const existingUser = yield (0, varDatabaseDbHandler_1.default)({
|
||||
queryString: existingUserQuery,
|
||||
queryValuesArray: existingUserValues,
|
||||
database: dbFullName,
|
||||
useLocal,
|
||||
});
|
||||
if (!(existingUser === null || existingUser === void 0 ? void 0 : existingUser[0])) {
|
||||
return {
|
||||
success: false,
|
||||
msg: "User not found",
|
||||
};
|
||||
}
|
||||
const data = (() => {
|
||||
const reqBodyKeys = Object.keys(payload);
|
||||
const targetTableSchema = (() => {
|
||||
var _a;
|
||||
try {
|
||||
const targetDatabaseSchema = (_a = dbSchema === null || dbSchema === void 0 ? void 0 : dbSchema.tables) === null || _a === void 0 ? void 0 : _a.find((tbl) => tbl.tableName == "users");
|
||||
return targetDatabaseSchema;
|
||||
}
|
||||
catch (error) {
|
||||
return undefined;
|
||||
}
|
||||
})();
|
||||
/** @type {any} */
|
||||
const finalData = {};
|
||||
reqBodyKeys.forEach((key) => {
|
||||
var _a;
|
||||
const targetFieldSchema = (_a = targetTableSchema === null || targetTableSchema === void 0 ? void 0 : targetTableSchema.fields) === null || _a === void 0 ? void 0 : _a.find((field) => field.fieldName == key);
|
||||
if (key === null || key === void 0 ? void 0 : key.match(/^date_|^id$|^uuid$/))
|
||||
return;
|
||||
let value = payload[key];
|
||||
if (targetFieldSchema === null || targetFieldSchema === void 0 ? void 0 : targetFieldSchema.encrypted) {
|
||||
value = (0, encrypt_1.default)({ data: value });
|
||||
}
|
||||
finalData[key] = value;
|
||||
});
|
||||
if (finalData.password && typeof finalData.password == "string") {
|
||||
finalData.password = (0, hashPassword_1.default)({ password: finalData.password });
|
||||
}
|
||||
return finalData;
|
||||
})();
|
||||
const updateUser = yield (0, updateDbEntry_1.default)({
|
||||
dbContext: "Dsql User",
|
||||
paradigm: "Full Access",
|
||||
dbFullName,
|
||||
tableName: "users",
|
||||
identifierColumnName: "id",
|
||||
identifierValue: updatedUserId,
|
||||
data: data,
|
||||
useLocal,
|
||||
});
|
||||
return {
|
||||
success: true,
|
||||
payload: updateUser,
|
||||
};
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import { APILoginFunctionReturn } from "../../../../types";
|
||||
type Param = {
|
||||
code?: string;
|
||||
clientId?: string;
|
||||
clientSecret?: string;
|
||||
database?: string;
|
||||
additionalFields?: string[];
|
||||
additionalData?: {
|
||||
[s: string]: string | number;
|
||||
};
|
||||
email?: string;
|
||||
};
|
||||
/**
|
||||
* # API Login with Github
|
||||
*/
|
||||
export default function apiGithubLogin({ code, clientId, clientSecret, database, additionalFields, email, additionalData, }: Param): Promise<APILoginFunctionReturn>;
|
||||
export {};
|
||||
@@ -0,0 +1,89 @@
|
||||
"use strict";
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = apiGithubLogin;
|
||||
const handleSocialDb_1 = __importDefault(require("../../social-login/handleSocialDb"));
|
||||
const githubLogin_1 = __importDefault(require("../../social-login/githubLogin"));
|
||||
const camelJoinedtoCamelSpace_1 = __importDefault(require("../../../../utils/camelJoinedtoCamelSpace"));
|
||||
/**
|
||||
* # API Login with Github
|
||||
*/
|
||||
function apiGithubLogin(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ code, clientId, clientSecret, database, additionalFields, email, additionalData, }) {
|
||||
if (!code || !clientId || !clientSecret || !database) {
|
||||
return {
|
||||
success: false,
|
||||
msg: "Missing query params",
|
||||
};
|
||||
}
|
||||
if (typeof code !== "string" ||
|
||||
typeof clientId !== "string" ||
|
||||
typeof clientSecret !== "string" ||
|
||||
typeof database !== "string") {
|
||||
return {
|
||||
success: false,
|
||||
msg: "Wrong Parameters",
|
||||
};
|
||||
}
|
||||
/**
|
||||
* Create new user folder and file
|
||||
*
|
||||
* @description Create new user folder and file
|
||||
*/
|
||||
const gitHubUser = yield (0, githubLogin_1.default)({
|
||||
code: code,
|
||||
clientId: clientId,
|
||||
clientSecret: clientSecret,
|
||||
});
|
||||
if (!gitHubUser) {
|
||||
return {
|
||||
success: false,
|
||||
msg: "No github user returned",
|
||||
};
|
||||
}
|
||||
const socialId = gitHubUser.name || gitHubUser.id || gitHubUser.login;
|
||||
const targetName = gitHubUser.name || gitHubUser.login;
|
||||
const nameArray = (targetName === null || targetName === void 0 ? void 0 : targetName.match(/ /))
|
||||
? targetName === null || targetName === void 0 ? void 0 : targetName.split(" ")
|
||||
: (targetName === null || targetName === void 0 ? void 0 : targetName.match(/\-/))
|
||||
? targetName === null || targetName === void 0 ? void 0 : targetName.split("-")
|
||||
: [targetName];
|
||||
let payload = {
|
||||
email: gitHubUser.email,
|
||||
first_name: (0, camelJoinedtoCamelSpace_1.default)(nameArray[0]),
|
||||
last_name: (0, camelJoinedtoCamelSpace_1.default)(nameArray[1]),
|
||||
social_id: socialId,
|
||||
social_platform: "github",
|
||||
image: gitHubUser.avatar_url,
|
||||
image_thumbnail: gitHubUser.avatar_url,
|
||||
username: "github-user-" + socialId,
|
||||
};
|
||||
if (additionalData) {
|
||||
payload = Object.assign(Object.assign({}, payload), additionalData);
|
||||
}
|
||||
const loggedInGithubUser = yield (0, handleSocialDb_1.default)({
|
||||
database,
|
||||
email: gitHubUser.email,
|
||||
payload,
|
||||
social_platform: "github",
|
||||
social_id: socialId,
|
||||
supEmail: email,
|
||||
additionalFields,
|
||||
});
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
return Object.assign({}, loggedInGithubUser);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
import { APIGoogleLoginFunctionParams, APILoginFunctionReturn } from "../../../../types";
|
||||
/**
|
||||
* # API google login
|
||||
*/
|
||||
export default function apiGoogleLogin({ token, database, additionalFields, additionalData, }: APIGoogleLoginFunctionParams): Promise<APILoginFunctionReturn>;
|
||||
@@ -0,0 +1,99 @@
|
||||
"use strict";
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = apiGoogleLogin;
|
||||
const https_1 = __importDefault(require("https"));
|
||||
const handleSocialDb_1 = __importDefault(require("../../social-login/handleSocialDb"));
|
||||
const ejson_1 = __importDefault(require("../../../../utils/ejson"));
|
||||
/**
|
||||
* # API google login
|
||||
*/
|
||||
function apiGoogleLogin(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ token, database, additionalFields, additionalData, }) {
|
||||
try {
|
||||
const gUser = yield new Promise((resolve, reject) => {
|
||||
https_1.default
|
||||
.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(ejson_1.default.parse(data));
|
||||
});
|
||||
})
|
||||
.end();
|
||||
});
|
||||
if (!(gUser === null || gUser === void 0 ? void 0 : gUser.email_verified))
|
||||
throw new Error("No Google User.");
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
if (!database || typeof database != "string" || (database === null || database === void 0 ? void 0 : database.match(/ /))) {
|
||||
return {
|
||||
success: false,
|
||||
payload: undefined,
|
||||
msg: "Please provide a database slug(database name in lowercase with no spaces)",
|
||||
};
|
||||
}
|
||||
/**
|
||||
* Create new user folder and file
|
||||
*
|
||||
* @description Create new user folder and file
|
||||
*/
|
||||
const { given_name, family_name, email, sub, picture } = gUser;
|
||||
/** @type {Object<string, any>} */
|
||||
let payloadObject = {
|
||||
email: email,
|
||||
first_name: given_name,
|
||||
last_name: family_name,
|
||||
social_id: sub,
|
||||
social_platform: "google",
|
||||
image: picture,
|
||||
image_thumbnail: picture,
|
||||
username: `google-user-${sub}`,
|
||||
};
|
||||
if (additionalData) {
|
||||
payloadObject = Object.assign(Object.assign({}, payloadObject), additionalData);
|
||||
}
|
||||
const loggedInGoogleUser = yield (0, handleSocialDb_1.default)({
|
||||
database,
|
||||
email: email || "",
|
||||
payload: payloadObject,
|
||||
social_platform: "google",
|
||||
social_id: sub,
|
||||
additionalFields,
|
||||
});
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
return Object.assign({}, loggedInGoogleUser);
|
||||
}
|
||||
catch ( /** @type {any} */error) {
|
||||
console.log(`apo-google-login.js ERROR: ${error.message}`);
|
||||
return {
|
||||
success: false,
|
||||
payload: undefined,
|
||||
msg: error.message,
|
||||
};
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import { DATASQUIREL_LoggedInUser } from "../../types";
|
||||
type Param = {
|
||||
query: {
|
||||
invite: number;
|
||||
database_access: string;
|
||||
priviledge: string;
|
||||
email: string;
|
||||
};
|
||||
useLocal?: boolean;
|
||||
user: DATASQUIREL_LoggedInUser;
|
||||
};
|
||||
/**
|
||||
* Add Admin User on Login
|
||||
* ==============================================================================
|
||||
*
|
||||
* @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
|
||||
*/
|
||||
export default function addAdminUserOnLogin({ query, user, useLocal, }: Param): Promise<any>;
|
||||
export {};
|
||||
@@ -0,0 +1,110 @@
|
||||
"use strict";
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = addAdminUserOnLogin;
|
||||
const serverError_1 = __importDefault(require("./serverError"));
|
||||
const DB_HANDLER_1 = __importDefault(require("../../utils/backend/global-db/DB_HANDLER"));
|
||||
const addDbEntry_1 = __importDefault(require("./db/addDbEntry"));
|
||||
const LOCAL_DB_HANDLER_1 = __importDefault(require("../../utils/backend/global-db/LOCAL_DB_HANDLER"));
|
||||
/**
|
||||
* Add Admin User on Login
|
||||
* ==============================================================================
|
||||
*
|
||||
* @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
|
||||
*/
|
||||
function addAdminUserOnLogin(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ query, user, useLocal, }) {
|
||||
try {
|
||||
const finalDbHandler = useLocal ? LOCAL_DB_HANDLER_1.default : DB_HANDLER_1.default;
|
||||
const { invite, database_access, priviledge, email } = query;
|
||||
const lastInviteTimeQuery = `SELECT date_created_code FROM invitations WHERE inviting_user_id=? AND invited_user_email=?`;
|
||||
const lastInviteTimeValues = [invite, email];
|
||||
const lastInviteTimeArray = yield finalDbHandler(lastInviteTimeQuery, lastInviteTimeValues);
|
||||
if (!lastInviteTimeArray || !lastInviteTimeArray[0]) {
|
||||
throw new Error("No Invitation Found");
|
||||
}
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
const invitingUserDbQuery = `SELECT first_name,last_name,email FROM users WHERE id=?`;
|
||||
const invitingUserDbValues = [invite];
|
||||
const invitingUserDb = yield finalDbHandler(invitingUserDbQuery, invitingUserDbValues);
|
||||
if (invitingUserDb === null || invitingUserDb === void 0 ? void 0 : invitingUserDb[0]) {
|
||||
const existingUserUser = yield finalDbHandler(`SELECT email FROM user_users WHERE user_id=? AND invited_user_id=? AND user_type='admin' AND email=?`, [invite, user.id, email]);
|
||||
if (existingUserUser === null || existingUserUser === void 0 ? void 0 : existingUserUser[0]) {
|
||||
console.log("User already added");
|
||||
}
|
||||
else {
|
||||
(0, addDbEntry_1.default)({
|
||||
dbFullName: "datasquirel",
|
||||
tableName: "user_users",
|
||||
data: {
|
||||
user_id: invite,
|
||||
invited_user_id: user.id,
|
||||
database_access: database_access,
|
||||
first_name: user.first_name,
|
||||
last_name: user.last_name,
|
||||
phone: user.phone,
|
||||
email: user.email,
|
||||
username: user.username,
|
||||
user_type: "admin",
|
||||
user_priviledge: priviledge,
|
||||
image: user.image,
|
||||
image_thumbnail: user.image_thumbnail,
|
||||
},
|
||||
useLocal,
|
||||
});
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
const dbTableData = yield finalDbHandler(`SELECT db_tables_data FROM invitations WHERE inviting_user_id=? AND invited_user_email=?`, [invite, email]);
|
||||
const clearEntries = yield finalDbHandler(`DELETE FROM delegated_user_tables WHERE root_user_id=? AND delegated_user_id=?`, [invite, user.id]);
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
if (dbTableData && dbTableData[0]) {
|
||||
const dbTableEntries = dbTableData[0].db_tables_data.split("|");
|
||||
for (let i = 0; i < dbTableEntries.length; i++) {
|
||||
const dbTableEntry = dbTableEntries[i];
|
||||
const dbTableEntryArray = dbTableEntry.split("-");
|
||||
const [db_slug, table_slug] = dbTableEntryArray;
|
||||
const newEntry = yield (0, addDbEntry_1.default)({
|
||||
dbFullName: "datasquirel",
|
||||
tableName: "delegated_user_tables",
|
||||
data: {
|
||||
delegated_user_id: user.id,
|
||||
root_user_id: invite,
|
||||
database: db_slug,
|
||||
table: table_slug,
|
||||
priviledge: priviledge,
|
||||
},
|
||||
useLocal,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
const inviteAccepted = yield finalDbHandler(`UPDATE invitations SET invitation_status='Accepted' WHERE inviting_user_id=? AND invited_user_email=?`, [invite, email]);
|
||||
}
|
||||
}
|
||||
catch (error) {
|
||||
(0, serverError_1.default)({
|
||||
component: "addAdminUserOnLogin",
|
||||
message: error.message,
|
||||
user: user,
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
type Param = {
|
||||
userId: number | string;
|
||||
useLocal?: boolean;
|
||||
};
|
||||
/**
|
||||
* # Add Mariadb User
|
||||
*/
|
||||
export default function addMariadbUser({ userId, useLocal, }: Param): Promise<any>;
|
||||
export {};
|
||||
@@ -0,0 +1,72 @@
|
||||
"use strict";
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = addMariadbUser;
|
||||
const generate_password_1 = __importDefault(require("generate-password"));
|
||||
const DB_HANDLER_1 = __importDefault(require("../../utils/backend/global-db/DB_HANDLER"));
|
||||
const NO_DB_HANDLER_1 = __importDefault(require("../../utils/backend/global-db/NO_DB_HANDLER"));
|
||||
const addDbEntry_1 = __importDefault(require("./db/addDbEntry"));
|
||||
const encrypt_1 = __importDefault(require("../dsql/encrypt"));
|
||||
const LOCAL_DB_HANDLER_1 = __importDefault(require("../../utils/backend/global-db/LOCAL_DB_HANDLER"));
|
||||
/**
|
||||
* # Add Mariadb User
|
||||
*/
|
||||
function addMariadbUser(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ userId, useLocal, }) {
|
||||
try {
|
||||
const defaultMariadbUserHost = process.env.DSQL_DB_HOST || "127.0.0.1";
|
||||
const username = `dsql_user_${userId}`;
|
||||
const password = generate_password_1.default.generate({
|
||||
length: 16,
|
||||
numbers: true,
|
||||
symbols: true,
|
||||
uppercase: true,
|
||||
exclude: "*#.'`\"",
|
||||
});
|
||||
const encryptedPassword = (0, encrypt_1.default)({ data: password });
|
||||
const createMariadbUsersQuery = `CREATE USER IF NOT EXISTS '${username}'@'127.0.0.1' IDENTIFIED BY '${password}'`;
|
||||
if (useLocal) {
|
||||
yield (0, LOCAL_DB_HANDLER_1.default)(createMariadbUsersQuery);
|
||||
}
|
||||
else {
|
||||
yield (0, NO_DB_HANDLER_1.default)(createMariadbUsersQuery);
|
||||
}
|
||||
const updateUserQuery = `UPDATE users SET mariadb_user = ?, mariadb_host = '127.0.0.1', mariadb_pass = ? WHERE id = ?`;
|
||||
const updateUserValues = [username, encryptedPassword, userId];
|
||||
const updateUser = useLocal
|
||||
? yield (0, LOCAL_DB_HANDLER_1.default)(updateUserQuery, updateUserValues)
|
||||
: yield (0, DB_HANDLER_1.default)(updateUserQuery, updateUserValues);
|
||||
const addMariadbUser = yield (0, addDbEntry_1.default)({
|
||||
tableName: "mariadb_users",
|
||||
data: {
|
||||
user_id: userId,
|
||||
username,
|
||||
host: defaultMariadbUserHost,
|
||||
password: encryptedPassword,
|
||||
primary: "1",
|
||||
grants: '[{"database":"*","table":"*","privileges":["ALL"]}]',
|
||||
},
|
||||
dbContext: "Master",
|
||||
useLocal,
|
||||
});
|
||||
console.log(`User ${userId} SQL credentials successfully added.`);
|
||||
}
|
||||
catch ( /** @type {any} */error) {
|
||||
console.log(`Error in adding SQL user in 'addMariadbUser' function =>`, error.message);
|
||||
}
|
||||
});
|
||||
}
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
@@ -0,0 +1,13 @@
|
||||
type Param = {
|
||||
userId: number;
|
||||
database: string;
|
||||
useLocal?: boolean;
|
||||
payload?: {
|
||||
[s: string]: any;
|
||||
};
|
||||
};
|
||||
/**
|
||||
* # Add User Table to Database
|
||||
*/
|
||||
export default function addUsersTableToDb({ userId, database, useLocal, payload, }: Param): Promise<any>;
|
||||
export {};
|
||||
@@ -0,0 +1,83 @@
|
||||
"use strict";
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = addUsersTableToDb;
|
||||
const serverError_1 = __importDefault(require("./serverError"));
|
||||
const DB_HANDLER_1 = __importDefault(require("../../utils/backend/global-db/DB_HANDLER"));
|
||||
const grabUserSchemaData_1 = __importDefault(require("./grabUserSchemaData"));
|
||||
const setUserSchemaData_1 = __importDefault(require("./setUserSchemaData"));
|
||||
const addDbEntry_1 = __importDefault(require("./db/addDbEntry"));
|
||||
const createDbFromSchema_1 = __importDefault(require("../../shell/createDbFromSchema"));
|
||||
const LOCAL_DB_HANDLER_1 = __importDefault(require("../../utils/backend/global-db/LOCAL_DB_HANDLER"));
|
||||
const grabNewUsersTableSchema_1 = __importDefault(require("./grabNewUsersTableSchema"));
|
||||
/**
|
||||
* # Add User Table to Database
|
||||
*/
|
||||
function addUsersTableToDb(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ userId, database, useLocal, payload, }) {
|
||||
try {
|
||||
const dbFullName = database;
|
||||
const userPreset = (0, grabNewUsersTableSchema_1.default)({ payload });
|
||||
if (!userPreset)
|
||||
throw new Error("Couldn't Get User Preset!");
|
||||
const userSchemaData = (0, grabUserSchemaData_1.default)({ userId });
|
||||
if (!userSchemaData)
|
||||
throw new Error("User schema data not found!");
|
||||
let targetDatabase = userSchemaData.find((db) => db.dbFullName === database);
|
||||
if (!targetDatabase) {
|
||||
throw new Error("Couldn't Find Target Database!");
|
||||
}
|
||||
let existingTableIndex = targetDatabase === null || targetDatabase === void 0 ? void 0 : targetDatabase.tables.findIndex((table) => table.tableName === "users");
|
||||
if (typeof existingTableIndex == "number" && existingTableIndex > 0) {
|
||||
targetDatabase.tables[existingTableIndex] = userPreset;
|
||||
}
|
||||
else {
|
||||
targetDatabase.tables.push(userPreset);
|
||||
}
|
||||
(0, setUserSchemaData_1.default)({ schemaData: userSchemaData, userId });
|
||||
/** @type {any[] | null} */
|
||||
const targetDb = useLocal
|
||||
? yield (0, LOCAL_DB_HANDLER_1.default)(`SELECT id FROM user_databases WHERE user_id=? AND db_slug=?`, [userId, database])
|
||||
: yield (0, DB_HANDLER_1.default)(`SELECT id FROM user_databases WHERE user_id=? AND db_slug=?`, [userId, database]);
|
||||
if (targetDb === null || targetDb === void 0 ? void 0 : targetDb[0]) {
|
||||
const newTableEntry = yield (0, addDbEntry_1.default)({
|
||||
dbFullName: "datasquirel",
|
||||
tableName: "user_database_tables",
|
||||
data: {
|
||||
user_id: userId,
|
||||
db_id: targetDb[0].id,
|
||||
db_slug: targetDatabase.dbSlug,
|
||||
table_name: "Users",
|
||||
table_slug: "users",
|
||||
},
|
||||
useLocal,
|
||||
});
|
||||
}
|
||||
const dbShellUpdate = yield (0, createDbFromSchema_1.default)({
|
||||
userId,
|
||||
targetDatabase: dbFullName,
|
||||
});
|
||||
return `Done!`;
|
||||
}
|
||||
catch ( /** @type {any} */error) {
|
||||
console.log(`addUsersTableToDb.js ERROR: ${error.message}`);
|
||||
(0, serverError_1.default)({
|
||||
component: "addUsersTableToDb",
|
||||
message: error.message,
|
||||
user: { id: userId },
|
||||
});
|
||||
return error.message;
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
import { CheckApiCredentialsFn } from "../../types";
|
||||
/**
|
||||
* # Grap API Credentials
|
||||
*/
|
||||
declare const grabApiCred: CheckApiCredentialsFn;
|
||||
export default grabApiCred;
|
||||
@@ -0,0 +1,50 @@
|
||||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const fs_1 = __importDefault(require("fs"));
|
||||
const decrypt_1 = __importDefault(require("../dsql/decrypt"));
|
||||
/**
|
||||
* # Grap API Credentials
|
||||
*/
|
||||
const grabApiCred = ({ key, database, table, user_id, media, }) => {
|
||||
var _a, _b;
|
||||
if (!key)
|
||||
return null;
|
||||
if (!user_id)
|
||||
return null;
|
||||
try {
|
||||
const allowedKeysPath = process.env.DSQL_API_KEYS_PATH;
|
||||
if (!allowedKeysPath)
|
||||
throw new Error("process.env.DSQL_API_KEYS_PATH variable not found");
|
||||
const ApiJSON = (0, decrypt_1.default)({ encryptedString: key });
|
||||
/** @type {import("../../types").ApiKeyObject} */
|
||||
const ApiObject = JSON.parse(ApiJSON || "");
|
||||
const isApiKeyValid = fs_1.default.existsSync(`${allowedKeysPath}/${ApiObject.sign}`);
|
||||
if (String(ApiObject.user_id) !== String(user_id))
|
||||
return null;
|
||||
if (!isApiKeyValid)
|
||||
return null;
|
||||
if (!ApiObject.target_database)
|
||||
return ApiObject;
|
||||
if (media)
|
||||
return ApiObject;
|
||||
if (!database && ApiObject.target_database)
|
||||
return null;
|
||||
const isDatabaseAllowed = (_a = ApiObject.target_database) === null || _a === void 0 ? void 0 : _a.split(",").includes(String(database));
|
||||
if (isDatabaseAllowed && !ApiObject.target_table)
|
||||
return ApiObject;
|
||||
if (isDatabaseAllowed && !table && ApiObject.target_table)
|
||||
return null;
|
||||
const isTableAllowed = (_b = ApiObject.target_table) === null || _b === void 0 ? void 0 : _b.split(",").includes(String(table));
|
||||
if (isTableAllowed)
|
||||
return ApiObject;
|
||||
return null;
|
||||
}
|
||||
catch ( /** @type {any} */error) {
|
||||
console.log(`api-cred ERROR: ${error.message}`);
|
||||
return { error: `api-cred ERROR: ${error.message}` };
|
||||
}
|
||||
};
|
||||
exports.default = grabApiCred;
|
||||
@@ -0,0 +1,23 @@
|
||||
export declare const grabAuthDirs: () => {
|
||||
root: string;
|
||||
auth: string;
|
||||
};
|
||||
export declare const initAuthFiles: () => boolean;
|
||||
/**
|
||||
* # Write Auth Files
|
||||
*/
|
||||
export declare const writeAuthFile: (name: string, data: string) => boolean;
|
||||
/**
|
||||
* # Get Auth Files
|
||||
*/
|
||||
export declare const getAuthFile: (name: string) => string | null;
|
||||
/**
|
||||
* # Delete Auth Files
|
||||
* @param {string} name
|
||||
*/
|
||||
export declare const deleteAuthFile: (name: string) => void | null;
|
||||
/**
|
||||
* # Delete Auth Files
|
||||
* @param {string} name
|
||||
*/
|
||||
export declare const checkAuthFile: (name: string) => boolean;
|
||||
@@ -0,0 +1,90 @@
|
||||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.checkAuthFile = exports.deleteAuthFile = exports.getAuthFile = exports.writeAuthFile = exports.initAuthFiles = exports.grabAuthDirs = void 0;
|
||||
const fs_1 = __importDefault(require("fs"));
|
||||
const path_1 = __importDefault(require("path"));
|
||||
const grabAuthDirs = () => {
|
||||
const DSQL_AUTH_DIR = process.env.DSQL_AUTH_DIR;
|
||||
const ROOT_DIR = (DSQL_AUTH_DIR === null || DSQL_AUTH_DIR === void 0 ? void 0 : DSQL_AUTH_DIR.match(/./))
|
||||
? DSQL_AUTH_DIR
|
||||
: path_1.default.resolve(process.cwd(), "./.tmp");
|
||||
const AUTH_DIR = path_1.default.join(ROOT_DIR, "logins");
|
||||
return { root: ROOT_DIR, auth: AUTH_DIR };
|
||||
};
|
||||
exports.grabAuthDirs = grabAuthDirs;
|
||||
const initAuthFiles = () => {
|
||||
try {
|
||||
const authDirs = (0, exports.grabAuthDirs)();
|
||||
if (!fs_1.default.existsSync(authDirs.root))
|
||||
fs_1.default.mkdirSync(authDirs.root, { recursive: true });
|
||||
if (!fs_1.default.existsSync(authDirs.auth))
|
||||
fs_1.default.mkdirSync(authDirs.auth, { recursive: true });
|
||||
return true;
|
||||
}
|
||||
catch (error) {
|
||||
console.log(`Error initializing Auth Files: ${error.message}`);
|
||||
return false;
|
||||
}
|
||||
};
|
||||
exports.initAuthFiles = initAuthFiles;
|
||||
/**
|
||||
* # Write Auth Files
|
||||
*/
|
||||
const writeAuthFile = (name, data) => {
|
||||
(0, exports.initAuthFiles)();
|
||||
try {
|
||||
fs_1.default.writeFileSync(path_1.default.join((0, exports.grabAuthDirs)().auth, name), data);
|
||||
return true;
|
||||
}
|
||||
catch ( /** @type {any} */error) {
|
||||
console.log(`Error writing Auth File: ${error.message}`);
|
||||
return false;
|
||||
}
|
||||
};
|
||||
exports.writeAuthFile = writeAuthFile;
|
||||
/**
|
||||
* # Get Auth Files
|
||||
*/
|
||||
const getAuthFile = (name) => {
|
||||
try {
|
||||
const authFilePath = path_1.default.join((0, exports.grabAuthDirs)().auth, name);
|
||||
return fs_1.default.readFileSync(authFilePath, "utf-8");
|
||||
}
|
||||
catch ( /** @type {any} */error) {
|
||||
console.log(`Error getting Auth File: ${error.message}`);
|
||||
return null;
|
||||
}
|
||||
};
|
||||
exports.getAuthFile = getAuthFile;
|
||||
/**
|
||||
* # Delete Auth Files
|
||||
* @param {string} name
|
||||
*/
|
||||
const deleteAuthFile = (name) => {
|
||||
try {
|
||||
return fs_1.default.rmSync(path_1.default.join((0, exports.grabAuthDirs)().auth, name));
|
||||
}
|
||||
catch ( /** @type {any} */error) {
|
||||
console.log(`Error deleting Auth File: ${error.message}`);
|
||||
return null;
|
||||
}
|
||||
};
|
||||
exports.deleteAuthFile = deleteAuthFile;
|
||||
/**
|
||||
* # Delete Auth Files
|
||||
* @param {string} name
|
||||
*/
|
||||
const checkAuthFile = (name) => {
|
||||
try {
|
||||
return fs_1.default.existsSync(path_1.default.join((0, exports.grabAuthDirs)().auth, name));
|
||||
return true;
|
||||
}
|
||||
catch ( /** @type {any} */error) {
|
||||
console.log(`Error checking Auth File: ${error.message}`);
|
||||
return false;
|
||||
}
|
||||
};
|
||||
exports.checkAuthFile = checkAuthFile;
|
||||
@@ -0,0 +1,14 @@
|
||||
type Param = {
|
||||
database?: string;
|
||||
userId?: string | number;
|
||||
};
|
||||
type Return = {
|
||||
keyCookieName: string;
|
||||
csrfCookieName: string;
|
||||
oneTimeCodeName: string;
|
||||
};
|
||||
/**
|
||||
* # Grab Auth Cookie Names
|
||||
*/
|
||||
export default function getAuthCookieNames(params?: Param): Return;
|
||||
export {};
|
||||
@@ -0,0 +1,38 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = getAuthCookieNames;
|
||||
/**
|
||||
* # Grab Auth Cookie Names
|
||||
*/
|
||||
function getAuthCookieNames(params) {
|
||||
var _a, _b;
|
||||
const cookiesPrefix = process.env.DSQL_COOKIES_PREFIX || "dsql_";
|
||||
const cookiesKeyName = process.env.DSQL_COOKIES_KEY_NAME || "key";
|
||||
const cookiesCSRFName = process.env.DSQL_COOKIES_CSRF_NAME || "csrf";
|
||||
const cookieOneTimeCodeName = process.env.DSQL_COOKIES_ONE_TIME_CODE_NAME || "one-time-code";
|
||||
const targetDatabase = ((_a = params === null || params === void 0 ? void 0 : params.database) === null || _a === void 0 ? void 0 : _a.replace(/^datasquirel_user_\d+_/, "")) ||
|
||||
((_b = process.env.DSQL_DB_NAME) === null || _b === void 0 ? void 0 : _b.replace(/^datasquirel_user_\d+_/, ""));
|
||||
let keyCookieName = cookiesPrefix;
|
||||
if (params === null || params === void 0 ? void 0 : params.userId)
|
||||
keyCookieName += `user_${params.userId}_`;
|
||||
if (targetDatabase)
|
||||
keyCookieName += `${targetDatabase}_`;
|
||||
keyCookieName += cookiesKeyName;
|
||||
let csrfCookieName = cookiesPrefix;
|
||||
if (params === null || params === void 0 ? void 0 : params.userId)
|
||||
csrfCookieName += `user_${params.userId}_`;
|
||||
if (targetDatabase)
|
||||
csrfCookieName += `${targetDatabase}_`;
|
||||
csrfCookieName += cookiesCSRFName;
|
||||
let oneTimeCodeName = cookiesPrefix;
|
||||
if (params === null || params === void 0 ? void 0 : params.userId)
|
||||
oneTimeCodeName += `user_${params.userId}_`;
|
||||
if (targetDatabase)
|
||||
oneTimeCodeName += `${targetDatabase}_`;
|
||||
oneTimeCodeName += cookieOneTimeCodeName;
|
||||
return {
|
||||
keyCookieName,
|
||||
csrfCookieName,
|
||||
oneTimeCodeName,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
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
|
||||
* ==============================================================================
|
||||
* @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 {any} params.data - Data to add
|
||||
* @param {import("../../../types").DSQL_TableSchemaType} [params.tableSchema] - Table schema
|
||||
* @param {string} [params.duplicateColumnName] - Duplicate column name
|
||||
* @param {string} [params.duplicateColumnValue] - Duplicate column value
|
||||
* @param {boolean} [params.update] - Update this row if it exists
|
||||
* @param {string} [params.encryptionKey] - Update this row if it exists
|
||||
* @param {string} [params.encryptionSalt] - Update this row if it exists
|
||||
* @param {boolean} [params.useLocal]
|
||||
*
|
||||
* @returns {Promise<any>}
|
||||
*/
|
||||
export default function addDbEntry({ dbContext, paradigm, dbFullName, tableName, data, tableSchema, duplicateColumnName, duplicateColumnValue, update, encryptionKey, encryptionSalt, useLocal, }: Param): Promise<any>;
|
||||
export {};
|
||||
@@ -0,0 +1,209 @@
|
||||
"use strict";
|
||||
// @ts-check
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = addDbEntry;
|
||||
const sanitize_html_1 = __importDefault(require("sanitize-html"));
|
||||
const sanitizeHtmlOptions_1 = __importDefault(require("../html/sanitizeHtmlOptions"));
|
||||
const updateDbEntry_1 = __importDefault(require("./updateDbEntry"));
|
||||
const DB_HANDLER_1 = __importDefault(require("../../../utils/backend/global-db/DB_HANDLER"));
|
||||
const DSQL_USER_DB_HANDLER_1 = __importDefault(require("../../../utils/backend/global-db/DSQL_USER_DB_HANDLER"));
|
||||
const encrypt_1 = __importDefault(require("../../dsql/encrypt"));
|
||||
const LOCAL_DB_HANDLER_1 = __importDefault(require("../../../utils/backend/global-db/LOCAL_DB_HANDLER"));
|
||||
/**
|
||||
* Add a db Entry 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 {any} params.data - Data to add
|
||||
* @param {import("../../../types").DSQL_TableSchemaType} [params.tableSchema] - Table schema
|
||||
* @param {string} [params.duplicateColumnName] - Duplicate column name
|
||||
* @param {string} [params.duplicateColumnValue] - Duplicate column value
|
||||
* @param {boolean} [params.update] - Update this row if it exists
|
||||
* @param {string} [params.encryptionKey] - Update this row if it exists
|
||||
* @param {string} [params.encryptionSalt] - Update this row if it exists
|
||||
* @param {boolean} [params.useLocal]
|
||||
*
|
||||
* @returns {Promise<any>}
|
||||
*/
|
||||
function addDbEntry(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ dbContext, paradigm, dbFullName, tableName, data, tableSchema, duplicateColumnName, duplicateColumnValue, update, encryptionKey, encryptionSalt, useLocal, }) {
|
||||
var _b, _c;
|
||||
/**
|
||||
* Initialize variables
|
||||
*/
|
||||
const isMaster = useLocal
|
||||
? true
|
||||
: (dbContext === null || dbContext === void 0 ? void 0 : dbContext.match(/dsql.user/i))
|
||||
? false
|
||||
: dbFullName && !dbFullName.match(/^datasquirel$/)
|
||||
? false
|
||||
: true;
|
||||
/** @type { any } */
|
||||
const dbHandler = useLocal
|
||||
? LOCAL_DB_HANDLER_1.default
|
||||
: isMaster
|
||||
? DB_HANDLER_1.default
|
||||
: DSQL_USER_DB_HANDLER_1.default;
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
if (data === null || data === void 0 ? void 0 : data["date_created_timestamp"])
|
||||
delete data["date_created_timestamp"];
|
||||
if (data === null || data === void 0 ? void 0 : data["date_updated_timestamp"])
|
||||
delete data["date_updated_timestamp"];
|
||||
if (data === null || data === void 0 ? void 0 : data["date_updated"])
|
||||
delete data["date_updated"];
|
||||
if (data === null || data === void 0 ? void 0 : data["date_updated_code"])
|
||||
delete data["date_updated_code"];
|
||||
if (data === null || data === void 0 ? void 0 : data["date_created"])
|
||||
delete data["date_created"];
|
||||
if (data === null || data === void 0 ? void 0 : data["date_created_code"])
|
||||
delete data["date_created_code"];
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
/**
|
||||
* Handle function logic
|
||||
*/
|
||||
if (duplicateColumnName && typeof duplicateColumnName === "string") {
|
||||
const duplicateValue = isMaster
|
||||
? yield dbHandler(`SELECT * FROM \`${tableName}\` WHERE \`${duplicateColumnName}\`=?`, [duplicateColumnValue])
|
||||
: yield dbHandler({
|
||||
paradigm: "Read Only",
|
||||
database: dbFullName,
|
||||
queryString: `SELECT * FROM \`${tableName}\` WHERE \`${duplicateColumnName}\`=?`,
|
||||
queryValues: [duplicateColumnValue],
|
||||
});
|
||||
if ((duplicateValue === null || duplicateValue === void 0 ? void 0 : duplicateValue[0]) && !update) {
|
||||
return null;
|
||||
}
|
||||
else if (duplicateValue && duplicateValue[0] && update) {
|
||||
return yield (0, updateDbEntry_1.default)({
|
||||
dbContext,
|
||||
paradigm,
|
||||
dbFullName,
|
||||
tableName,
|
||||
data,
|
||||
tableSchema,
|
||||
encryptionKey,
|
||||
encryptionSalt,
|
||||
identifierColumnName: duplicateColumnName,
|
||||
identifierValue: duplicateColumnValue || "",
|
||||
});
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Declare variables
|
||||
*
|
||||
* @description Declare "results" variable
|
||||
*/
|
||||
const dataKeys = Object.keys(data);
|
||||
let insertKeysArray = [];
|
||||
let insertValuesArray = [];
|
||||
for (let i = 0; i < dataKeys.length; i++) {
|
||||
try {
|
||||
const dataKey = dataKeys[i];
|
||||
// @ts-ignore
|
||||
let value = data === null || data === void 0 ? void 0 : data[dataKey];
|
||||
const targetFieldSchemaArray = tableSchema
|
||||
? (_b = tableSchema === null || tableSchema === void 0 ? void 0 : tableSchema.fields) === null || _b === void 0 ? void 0 : _b.filter((field) => field.fieldName == dataKey)
|
||||
: null;
|
||||
const targetFieldSchema = targetFieldSchemaArray && targetFieldSchemaArray[0]
|
||||
? targetFieldSchemaArray[0]
|
||||
: null;
|
||||
if (value == null || value == undefined)
|
||||
continue;
|
||||
if (((_c = targetFieldSchema === null || targetFieldSchema === void 0 ? void 0 : targetFieldSchema.dataType) === null || _c === void 0 ? void 0 : _c.match(/int$/i)) &&
|
||||
typeof value == "string" &&
|
||||
!(value === null || value === void 0 ? void 0 : value.match(/./)))
|
||||
continue;
|
||||
if (targetFieldSchema === null || targetFieldSchema === void 0 ? void 0 : targetFieldSchema.encrypted) {
|
||||
value = (0, encrypt_1.default)({
|
||||
data: value,
|
||||
encryptionKey,
|
||||
encryptionSalt,
|
||||
});
|
||||
console.log("DSQL: Encrypted value =>", value);
|
||||
}
|
||||
const htmlRegex = /<[^>]+>/g;
|
||||
if ((targetFieldSchema === null || targetFieldSchema === void 0 ? void 0 : targetFieldSchema.richText) || String(value).match(htmlRegex)) {
|
||||
value = (0, sanitize_html_1.default)(value, sanitizeHtmlOptions_1.default);
|
||||
}
|
||||
if (targetFieldSchema === null || targetFieldSchema === void 0 ? void 0 : targetFieldSchema.pattern) {
|
||||
const pattern = new RegExp(targetFieldSchema.pattern, targetFieldSchema.patternFlags || "");
|
||||
if (!pattern.test(value)) {
|
||||
console.log("DSQL: Pattern not matched =>", value);
|
||||
value = "";
|
||||
}
|
||||
}
|
||||
insertKeysArray.push("`" + dataKey + "`");
|
||||
if (typeof value === "object") {
|
||||
value = JSON.stringify(value);
|
||||
}
|
||||
if (typeof value == "number") {
|
||||
insertValuesArray.push(String(value));
|
||||
}
|
||||
else {
|
||||
insertValuesArray.push(value);
|
||||
}
|
||||
}
|
||||
catch ( /** @type {any} */error) {
|
||||
console.log("DSQL: Error in parsing data keys =>", error.message);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
////////////////////////////////////////
|
||||
if (!(data === null || data === void 0 ? void 0 : data["date_created"])) {
|
||||
insertKeysArray.push("`date_created`");
|
||||
insertValuesArray.push(Date());
|
||||
}
|
||||
if (!(data === null || data === void 0 ? void 0 : data["date_created_code"])) {
|
||||
insertKeysArray.push("`date_created_code`");
|
||||
insertValuesArray.push(Date.now());
|
||||
}
|
||||
////////////////////////////////////////
|
||||
if (!(data === null || data === void 0 ? void 0 : data["date_updated"])) {
|
||||
insertKeysArray.push("`date_updated`");
|
||||
insertValuesArray.push(Date());
|
||||
}
|
||||
if (!(data === null || data === void 0 ? void 0 : data["date_updated_code"])) {
|
||||
insertKeysArray.push("`date_updated_code`");
|
||||
insertValuesArray.push(Date.now());
|
||||
}
|
||||
////////////////////////////////////////
|
||||
const query = `INSERT INTO \`${tableName}\` (${insertKeysArray.join(",")}) VALUES (${insertValuesArray.map(() => "?").join(",")})`;
|
||||
const queryValuesArray = insertValuesArray;
|
||||
const newInsert = isMaster
|
||||
? yield dbHandler(query, queryValuesArray)
|
||||
: yield dbHandler({
|
||||
paradigm,
|
||||
database: dbFullName,
|
||||
queryString: query,
|
||||
queryValues: queryValuesArray,
|
||||
});
|
||||
/**
|
||||
* Return statement
|
||||
*/
|
||||
return newInsert;
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
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 function deleteDbEntry({ dbContext, paradigm, dbFullName, tableName, identifierColumnName, identifierValue, useLocal, }: Param): Promise<object | null>;
|
||||
export {};
|
||||
@@ -0,0 +1,62 @@
|
||||
"use strict";
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = deleteDbEntry;
|
||||
const DB_HANDLER_1 = __importDefault(require("../../../utils/backend/global-db/DB_HANDLER"));
|
||||
const DSQL_USER_DB_HANDLER_1 = __importDefault(require("../../../utils/backend/global-db/DSQL_USER_DB_HANDLER"));
|
||||
const LOCAL_DB_HANDLER_1 = __importDefault(require("../../../utils/backend/global-db/LOCAL_DB_HANDLER"));
|
||||
/**
|
||||
* # Delete DB Entry Function
|
||||
* @description
|
||||
*/
|
||||
function deleteDbEntry(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ dbContext, paradigm, dbFullName, tableName, identifierColumnName, identifierValue, useLocal, }) {
|
||||
try {
|
||||
const isMaster = useLocal
|
||||
? true
|
||||
: (dbContext === null || dbContext === void 0 ? void 0 : dbContext.match(/dsql.user/i))
|
||||
? false
|
||||
: dbFullName && !dbFullName.match(/^datasquirel$/)
|
||||
? false
|
||||
: true;
|
||||
/** @type { (a1:any, a2?:any) => any } */
|
||||
const dbHandler = useLocal
|
||||
? LOCAL_DB_HANDLER_1.default
|
||||
: isMaster
|
||||
? DB_HANDLER_1.default
|
||||
: DSQL_USER_DB_HANDLER_1.default;
|
||||
/**
|
||||
* Execution
|
||||
*
|
||||
* @description
|
||||
*/
|
||||
const query = `DELETE FROM ${tableName} WHERE \`${identifierColumnName}\`=?`;
|
||||
const deletedEntry = isMaster
|
||||
? yield dbHandler(query, [identifierValue])
|
||||
: yield dbHandler({
|
||||
paradigm,
|
||||
queryString: query,
|
||||
database: dbFullName,
|
||||
queryValues: [identifierValue],
|
||||
});
|
||||
/**
|
||||
* Return statement
|
||||
*/
|
||||
return deletedEntry;
|
||||
}
|
||||
catch (error) {
|
||||
return null;
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
/**
|
||||
* # Path Traversal Check
|
||||
* @returns {string}
|
||||
*/
|
||||
export default function pathTraversalCheck(text: string | number): string;
|
||||
@@ -0,0 +1,10 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = pathTraversalCheck;
|
||||
/**
|
||||
* # Path Traversal Check
|
||||
* @returns {string}
|
||||
*/
|
||||
function pathTraversalCheck(text) {
|
||||
return text.toString().replace(/\//g, "");
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
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
|
||||
*/
|
||||
export default function runQuery({ dbFullName, query, readOnly, dbSchema, queryValuesArray, tableName, local, }: Param): Promise<any>;
|
||||
export {};
|
||||
@@ -0,0 +1,155 @@
|
||||
"use strict";
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = runQuery;
|
||||
const fullAccessDbHandler_1 = __importDefault(require("../fullAccessDbHandler"));
|
||||
const varReadOnlyDatabaseDbHandler_1 = __importDefault(require("../varReadOnlyDatabaseDbHandler"));
|
||||
const serverError_1 = __importDefault(require("../serverError"));
|
||||
const addDbEntry_1 = __importDefault(require("./addDbEntry"));
|
||||
const updateDbEntry_1 = __importDefault(require("./updateDbEntry"));
|
||||
const deleteDbEntry_1 = __importDefault(require("./deleteDbEntry"));
|
||||
const trim_sql_1 = __importDefault(require("../../../utils/trim-sql"));
|
||||
/**
|
||||
* # Run DSQL users queries
|
||||
*/
|
||||
function runQuery(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ dbFullName, query, readOnly, dbSchema, queryValuesArray, tableName, local, }) {
|
||||
/**
|
||||
* Declare variables
|
||||
*
|
||||
* @description Declare "results" variable
|
||||
*/
|
||||
let result;
|
||||
let error;
|
||||
let tableSchema;
|
||||
if (dbSchema) {
|
||||
try {
|
||||
const table = tableName
|
||||
? tableName
|
||||
: typeof query == "string"
|
||||
? null
|
||||
: query
|
||||
? query === null || query === void 0 ? void 0 : query.table
|
||||
: null;
|
||||
if (!table)
|
||||
throw new Error("No table name provided");
|
||||
tableSchema = dbSchema.tables.filter((tb) => (tb === null || tb === void 0 ? void 0 : tb.tableName) === table)[0];
|
||||
}
|
||||
catch (_err) {
|
||||
// console.log("ERROR getting tableSchema: ", _err.message);
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Declare variables
|
||||
*
|
||||
* @description Declare "results" variable
|
||||
*/
|
||||
try {
|
||||
if (typeof query === "string") {
|
||||
const formattedQuery = (0, trim_sql_1.default)(query);
|
||||
/**
|
||||
* Input Validation
|
||||
*
|
||||
* @description Input Validation
|
||||
*/
|
||||
if (readOnly &&
|
||||
formattedQuery.match(/^alter|^delete|information_schema|^create/i)) {
|
||||
throw new Error("Wrong Input!");
|
||||
}
|
||||
if (readOnly) {
|
||||
result = yield (0, varReadOnlyDatabaseDbHandler_1.default)({
|
||||
queryString: formattedQuery,
|
||||
queryValuesArray: queryValuesArray === null || queryValuesArray === void 0 ? void 0 : queryValuesArray.map((vl) => String(vl)),
|
||||
database: dbFullName,
|
||||
tableSchema,
|
||||
useLocal: local,
|
||||
});
|
||||
}
|
||||
else {
|
||||
result = yield (0, fullAccessDbHandler_1.default)({
|
||||
queryString: formattedQuery,
|
||||
queryValuesArray: queryValuesArray === null || queryValuesArray === void 0 ? void 0 : queryValuesArray.map((vl) => String(vl)),
|
||||
database: dbFullName,
|
||||
tableSchema,
|
||||
local,
|
||||
});
|
||||
}
|
||||
}
|
||||
else if (typeof query === "object") {
|
||||
/**
|
||||
* Declare variables
|
||||
*
|
||||
* @description Declare "results" variable
|
||||
*/
|
||||
const { data, action, table, identifierColumnName, identifierValue, update, duplicateColumnName, duplicateColumnValue, } = query;
|
||||
switch (action.toLowerCase()) {
|
||||
case "insert":
|
||||
result = yield (0, addDbEntry_1.default)({
|
||||
dbContext: local ? "Master" : "Dsql User",
|
||||
paradigm: "Full Access",
|
||||
dbFullName: dbFullName,
|
||||
tableName: table,
|
||||
data: data,
|
||||
update,
|
||||
duplicateColumnName,
|
||||
duplicateColumnValue,
|
||||
tableSchema,
|
||||
useLocal: local,
|
||||
});
|
||||
if (!(result === null || result === void 0 ? void 0 : result.insertId)) {
|
||||
error = new Error("Couldn't insert data");
|
||||
}
|
||||
break;
|
||||
case "update":
|
||||
result = yield (0, updateDbEntry_1.default)({
|
||||
dbContext: local ? "Master" : "Dsql User",
|
||||
paradigm: "Full Access",
|
||||
dbFullName: dbFullName,
|
||||
tableName: table,
|
||||
data: data,
|
||||
identifierColumnName,
|
||||
identifierValue,
|
||||
tableSchema,
|
||||
useLocal: local,
|
||||
});
|
||||
break;
|
||||
case "delete":
|
||||
result = yield (0, deleteDbEntry_1.default)({
|
||||
dbContext: local ? "Master" : "Dsql User",
|
||||
paradigm: "Full Access",
|
||||
dbFullName: dbFullName,
|
||||
tableName: table,
|
||||
identifierColumnName,
|
||||
identifierValue,
|
||||
tableSchema,
|
||||
useLocal: local,
|
||||
});
|
||||
break;
|
||||
default:
|
||||
result = null;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
catch ( /** @type {any} */error) {
|
||||
(0, serverError_1.default)({
|
||||
component: "functions/backend/runQuery",
|
||||
message: error.message,
|
||||
});
|
||||
result = null;
|
||||
error = error.message;
|
||||
}
|
||||
return { result, error };
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
/**
|
||||
* Sanitize SQL function
|
||||
* ==============================================================================
|
||||
* @description this function takes in a text(or number) and returns a sanitized
|
||||
* text, usually without spaces
|
||||
*/
|
||||
declare function sanitizeSql(text: any, spaces: boolean, regex?: RegExp | null): any;
|
||||
export default sanitizeSql;
|
||||
@@ -0,0 +1,111 @@
|
||||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const lodash_1 = __importDefault(require("lodash"));
|
||||
/**
|
||||
* Sanitize SQL function
|
||||
* ==============================================================================
|
||||
* @description this function takes in a text(or number) and returns a sanitized
|
||||
* text, usually without spaces
|
||||
*/
|
||||
function sanitizeSql(text, spaces, regex) {
|
||||
var _a;
|
||||
if (!text)
|
||||
return "";
|
||||
if (typeof text == "number" || typeof text == "boolean")
|
||||
return text;
|
||||
if (typeof text == "string" && !((_a = text === null || text === void 0 ? void 0 : text.toString()) === null || _a === void 0 ? void 0 : _a.match(/./)))
|
||||
return "";
|
||||
if (typeof text == "object" && !Array.isArray(text)) {
|
||||
const newObject = sanitizeObjects(text, spaces);
|
||||
return newObject;
|
||||
}
|
||||
else if (typeof text == "object" && Array.isArray(text)) {
|
||||
const newArray = sanitizeArrays(text, spaces);
|
||||
return newArray;
|
||||
}
|
||||
let finalText = text;
|
||||
if (regex) {
|
||||
finalText = text.toString().replace(regex, "");
|
||||
}
|
||||
if (spaces) {
|
||||
}
|
||||
else {
|
||||
finalText = text
|
||||
.toString()
|
||||
.replace(/\n|\r|\n\r|\r\n/g, "")
|
||||
.replace(/ /g, "");
|
||||
}
|
||||
const escapeRegex = /select |insert |drop |delete |alter |create |exec | union | or | like | concat|LOAD_FILE|ASCII| COLLATE | HAVING | information_schema|DECLARE |\#|WAITFOR |delay |BENCHMARK |\/\*.*\*\//gi;
|
||||
finalText = finalText
|
||||
.replace(/(?<!\\)\'/g, "\\'")
|
||||
.replace(/(?<!\\)\`/g, "\\`")
|
||||
.replace(/\/\*\*\//g, "")
|
||||
.replace(escapeRegex, "\\$&");
|
||||
return finalText;
|
||||
}
|
||||
/**
|
||||
* Sanitize Objects Function
|
||||
* ==============================================================================
|
||||
* @description Sanitize objects in the form { key: "value" }
|
||||
*
|
||||
* @param {any} object - Database Full Name
|
||||
* @param {boolean} [spaces] - Allow spaces
|
||||
*
|
||||
* @returns {object}
|
||||
*/
|
||||
function sanitizeObjects(object, spaces) {
|
||||
/** @type {any} */
|
||||
let objectUpdated = Object.assign({}, object);
|
||||
const keys = Object.keys(objectUpdated);
|
||||
keys.forEach((key) => {
|
||||
const value = objectUpdated[key];
|
||||
if (!value) {
|
||||
delete objectUpdated[key];
|
||||
return;
|
||||
}
|
||||
if (typeof value == "string" || typeof value == "number") {
|
||||
objectUpdated[key] = sanitizeSql(value, spaces);
|
||||
}
|
||||
else if (typeof value == "object" && !Array.isArray(value)) {
|
||||
objectUpdated[key] = sanitizeObjects(value, spaces);
|
||||
}
|
||||
else if (typeof value == "object" && Array.isArray(value)) {
|
||||
objectUpdated[key] = sanitizeArrays(value, spaces);
|
||||
}
|
||||
});
|
||||
return objectUpdated;
|
||||
}
|
||||
/**
|
||||
* Sanitize Objects Function
|
||||
* ==============================================================================
|
||||
* @description Sanitize objects in the form { key: "value" }
|
||||
*
|
||||
* @param {any[]} array - Database Full Name
|
||||
* @param {boolean} [spaces] - Allow spaces
|
||||
*
|
||||
* @returns {string[]|number[]|object[]}
|
||||
*/
|
||||
function sanitizeArrays(array, spaces) {
|
||||
let arrayUpdated = lodash_1.default.cloneDeep(array);
|
||||
arrayUpdated.forEach((item, index) => {
|
||||
const value = item;
|
||||
if (!value) {
|
||||
arrayUpdated.splice(index, 1);
|
||||
return;
|
||||
}
|
||||
if (typeof item == "string" || typeof item == "number") {
|
||||
arrayUpdated[index] = sanitizeSql(value, spaces);
|
||||
}
|
||||
else if (typeof item == "object" && !Array.isArray(value)) {
|
||||
arrayUpdated[index] = sanitizeObjects(value, spaces);
|
||||
}
|
||||
else if (typeof item == "object" && Array.isArray(value)) {
|
||||
arrayUpdated[index] = sanitizeArrays(item, spaces);
|
||||
}
|
||||
});
|
||||
return arrayUpdated;
|
||||
}
|
||||
exports.default = sanitizeSql;
|
||||
@@ -0,0 +1,19 @@
|
||||
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;
|
||||
};
|
||||
/**
|
||||
* # Update DB Function
|
||||
* @description
|
||||
*/
|
||||
export default function updateDbEntry({ dbContext, paradigm, dbFullName, tableName, data, tableSchema, identifierColumnName, identifierValue, encryptionKey, encryptionSalt, useLocal, }: Param): Promise<object | null>;
|
||||
export {};
|
||||
@@ -0,0 +1,144 @@
|
||||
"use strict";
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = updateDbEntry;
|
||||
const sanitize_html_1 = __importDefault(require("sanitize-html"));
|
||||
const sanitizeHtmlOptions_1 = __importDefault(require("../html/sanitizeHtmlOptions"));
|
||||
const DB_HANDLER_1 = __importDefault(require("../../../utils/backend/global-db/DB_HANDLER"));
|
||||
const DSQL_USER_DB_HANDLER_1 = __importDefault(require("../../../utils/backend/global-db/DSQL_USER_DB_HANDLER"));
|
||||
const encrypt_1 = __importDefault(require("../../dsql/encrypt"));
|
||||
const LOCAL_DB_HANDLER_1 = __importDefault(require("../../../utils/backend/global-db/LOCAL_DB_HANDLER"));
|
||||
/**
|
||||
* # Update DB Function
|
||||
* @description
|
||||
*/
|
||||
function updateDbEntry(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ dbContext, paradigm, dbFullName, tableName, data, tableSchema, identifierColumnName, identifierValue, encryptionKey, encryptionSalt, useLocal, }) {
|
||||
var _b;
|
||||
/**
|
||||
* Check if data is valid
|
||||
*/
|
||||
if (!data || !Object.keys(data).length)
|
||||
return null;
|
||||
const isMaster = useLocal
|
||||
? true
|
||||
: (dbContext === null || dbContext === void 0 ? void 0 : dbContext.match(/dsql.user/i))
|
||||
? false
|
||||
: dbFullName && !dbFullName.match(/^datasquirel$/)
|
||||
? false
|
||||
: true;
|
||||
/** @type {(a1:any, a2?:any)=> any } */
|
||||
const dbHandler = useLocal
|
||||
? LOCAL_DB_HANDLER_1.default
|
||||
: isMaster
|
||||
? DB_HANDLER_1.default
|
||||
: DSQL_USER_DB_HANDLER_1.default;
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
/**
|
||||
* Declare variables
|
||||
*
|
||||
* @description Declare "results" variable
|
||||
*/
|
||||
const dataKeys = Object.keys(data);
|
||||
let updateKeyValueArray = [];
|
||||
let updateValues = [];
|
||||
for (let i = 0; i < dataKeys.length; i++) {
|
||||
try {
|
||||
const dataKey = dataKeys[i];
|
||||
// @ts-ignore
|
||||
let value = data[dataKey];
|
||||
const targetFieldSchemaArray = tableSchema
|
||||
? (_b = tableSchema === null || tableSchema === void 0 ? void 0 : tableSchema.fields) === null || _b === void 0 ? void 0 : _b.filter((field) => field.fieldName === dataKey)
|
||||
: null;
|
||||
const targetFieldSchema = targetFieldSchemaArray && targetFieldSchemaArray[0]
|
||||
? targetFieldSchemaArray[0]
|
||||
: null;
|
||||
if (value == null || value == undefined)
|
||||
continue;
|
||||
const htmlRegex = /<[^>]+>/g;
|
||||
if ((targetFieldSchema === null || targetFieldSchema === void 0 ? void 0 : targetFieldSchema.richText) || String(value).match(htmlRegex)) {
|
||||
value = (0, sanitize_html_1.default)(value, sanitizeHtmlOptions_1.default);
|
||||
}
|
||||
if (targetFieldSchema === null || targetFieldSchema === void 0 ? void 0 : targetFieldSchema.encrypted) {
|
||||
value = (0, encrypt_1.default)({
|
||||
data: value,
|
||||
encryptionKey,
|
||||
encryptionSalt,
|
||||
});
|
||||
}
|
||||
if (typeof value === "object") {
|
||||
value = JSON.stringify(value);
|
||||
}
|
||||
if (targetFieldSchema === null || targetFieldSchema === void 0 ? void 0 : targetFieldSchema.pattern) {
|
||||
const pattern = new RegExp(targetFieldSchema.pattern, targetFieldSchema.patternFlags || "");
|
||||
if (!pattern.test(value)) {
|
||||
console.log("DSQL: Pattern not matched =>", value);
|
||||
value = "";
|
||||
}
|
||||
}
|
||||
if (typeof value === "string" && value.match(/^null$/i)) {
|
||||
value = {
|
||||
toSqlString: function () {
|
||||
return "NULL";
|
||||
},
|
||||
};
|
||||
}
|
||||
if (typeof value === "string" && !value.match(/./i)) {
|
||||
value = {
|
||||
toSqlString: function () {
|
||||
return "NULL";
|
||||
},
|
||||
};
|
||||
}
|
||||
updateKeyValueArray.push(`\`${dataKey}\`=?`);
|
||||
if (typeof value == "number") {
|
||||
updateValues.push(String(value));
|
||||
}
|
||||
else {
|
||||
updateValues.push(value);
|
||||
}
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
}
|
||||
catch ( /** @type {any} */error) {
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
console.log("DSQL: Error in parsing data keys in update function =>", error.message);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
updateKeyValueArray.push(`date_updated='${Date()}'`);
|
||||
updateKeyValueArray.push(`date_updated_code='${Date.now()}'`);
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
const query = `UPDATE ${tableName} SET ${updateKeyValueArray.join(",")} WHERE \`${identifierColumnName}\`=?`;
|
||||
updateValues.push(identifierValue);
|
||||
const updatedEntry = isMaster
|
||||
? yield dbHandler(query, updateValues)
|
||||
: yield dbHandler({
|
||||
paradigm,
|
||||
database: dbFullName,
|
||||
queryString: query,
|
||||
queryValues: updateValues,
|
||||
});
|
||||
/**
|
||||
* Return statement
|
||||
*/
|
||||
return updatedEntry;
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
/**
|
||||
* # Main DB Handler Function
|
||||
*/
|
||||
export default function dbHandler(...args: any[]): Promise<any>;
|
||||
@@ -0,0 +1,82 @@
|
||||
"use strict";
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = dbHandler;
|
||||
const fs_1 = __importDefault(require("fs"));
|
||||
const serverError_1 = __importDefault(require("./serverError"));
|
||||
const serverless_mysql_1 = __importDefault(require("serverless-mysql"));
|
||||
const grabDbSSL_1 = __importDefault(require("../../utils/backend/grabDbSSL"));
|
||||
const connection = (0, serverless_mysql_1.default)({
|
||||
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: (0, grabDbSSL_1.default)(),
|
||||
},
|
||||
});
|
||||
/**
|
||||
* # Main DB Handler Function
|
||||
*/
|
||||
function dbHandler(...args) {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
var _a;
|
||||
((_a = process.env.NODE_ENV) === null || _a === void 0 ? void 0 : _a.match(/dev/)) &&
|
||||
fs_1.default.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 = yield new Promise((resolve, reject) => {
|
||||
connection.query(...args, (error, result, fields) => {
|
||||
if (error) {
|
||||
resolve({ error: error.message });
|
||||
}
|
||||
else {
|
||||
resolve(result);
|
||||
}
|
||||
});
|
||||
});
|
||||
yield connection.end();
|
||||
}
|
||||
catch (error) {
|
||||
fs_1.default.appendFileSync("./.tmp/dbErrorLogs.txt", JSON.stringify(error, null, 4) + "\n" + Date() + "\n\n\n", "utf8");
|
||||
results = null;
|
||||
(0, serverError_1.default)({
|
||||
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,7 @@
|
||||
/**
|
||||
* Regular expression to match default fields
|
||||
*
|
||||
* @description Regular expression to match default fields
|
||||
*/
|
||||
declare const defaultFieldsRegexp: RegExp;
|
||||
export default defaultFieldsRegexp;
|
||||
@@ -0,0 +1,9 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
/**
|
||||
* Regular expression to match default fields
|
||||
*
|
||||
* @description Regular expression to match default fields
|
||||
*/
|
||||
const defaultFieldsRegexp = /^id$|^uuid$|^date_created$|^date_created_code$|^date_created_timestamp$|^date_updated$|^date_updated_code$|^date_updated_timestamp$/;
|
||||
exports.default = defaultFieldsRegexp;
|
||||
@@ -0,0 +1,12 @@
|
||||
type Param = {
|
||||
queryString: string;
|
||||
database: string;
|
||||
local?: boolean;
|
||||
tableSchema?: import("../../types").DSQL_TableSchemaType | null;
|
||||
queryValuesArray?: string[];
|
||||
};
|
||||
/**
|
||||
* # Full Access Db Handler
|
||||
*/
|
||||
export default function fullAccessDbHandler({ queryString, database, tableSchema, queryValuesArray, local, }: Param): Promise<any>;
|
||||
export {};
|
||||
@@ -0,0 +1,80 @@
|
||||
"use strict";
|
||||
// @ts-check
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = fullAccessDbHandler;
|
||||
const DSQL_USER_DB_HANDLER_1 = __importDefault(require("../../utils/backend/global-db/DSQL_USER_DB_HANDLER"));
|
||||
const LOCAL_DB_HANDLER_1 = __importDefault(require("../../utils/backend/global-db/LOCAL_DB_HANDLER"));
|
||||
const parseDbResults_1 = __importDefault(require("./parseDbResults"));
|
||||
const serverError_1 = __importDefault(require("./serverError"));
|
||||
/**
|
||||
* # Full Access Db Handler
|
||||
*/
|
||||
function fullAccessDbHandler(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ queryString, database, tableSchema, queryValuesArray, local, }) {
|
||||
/**
|
||||
* Declare variables
|
||||
*
|
||||
* @description Declare "results" variable
|
||||
*/
|
||||
let results;
|
||||
/**
|
||||
* Fetch from db
|
||||
*
|
||||
* @description Fetch data from db if no cache
|
||||
*/
|
||||
try {
|
||||
/** ********************* Run Query */
|
||||
results = local
|
||||
? yield (0, LOCAL_DB_HANDLER_1.default)(queryString, queryValuesArray)
|
||||
: yield (0, DSQL_USER_DB_HANDLER_1.default)({
|
||||
paradigm: "Full Access",
|
||||
database,
|
||||
queryString,
|
||||
queryValues: queryValuesArray,
|
||||
});
|
||||
////////////////////////////////////////
|
||||
}
|
||||
catch ( /** @type {any} */error) {
|
||||
////////////////////////////////////////
|
||||
(0, serverError_1.default)({
|
||||
component: "fullAccessDbHandler",
|
||||
message: error.message,
|
||||
});
|
||||
/**
|
||||
* Return error
|
||||
*/
|
||||
return error.message;
|
||||
}
|
||||
/**
|
||||
* Return results
|
||||
*
|
||||
* @description Return results add to cache if "req" param is passed
|
||||
*/
|
||||
if (results && tableSchema) {
|
||||
const unparsedResults = results;
|
||||
const parsedResults = yield (0, parseDbResults_1.default)({
|
||||
unparsedResults: unparsedResults,
|
||||
tableSchema: tableSchema,
|
||||
});
|
||||
return parsedResults;
|
||||
}
|
||||
else if (results) {
|
||||
return results;
|
||||
}
|
||||
else {
|
||||
return null;
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
import { DSQL_TableSchemaType } from "../../types";
|
||||
/**
|
||||
* # Add User Table to Database
|
||||
*/
|
||||
export default function grabNewUsersTableSchema(params: {
|
||||
payload?: {
|
||||
[s: string]: any;
|
||||
};
|
||||
}): DSQL_TableSchemaType | null;
|
||||
@@ -0,0 +1,42 @@
|
||||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = grabNewUsersTableSchema;
|
||||
const grabSchemaFieldsFromData_1 = __importDefault(require("./grabSchemaFieldsFromData"));
|
||||
const serverError_1 = __importDefault(require("./serverError"));
|
||||
/**
|
||||
* # Add User Table to Database
|
||||
*/
|
||||
function grabNewUsersTableSchema(params) {
|
||||
try {
|
||||
const userPreset = require("../../data/presets/users.json");
|
||||
const defaultFields = require("../../data/defaultFields.json");
|
||||
const supplementalFields = (params === null || params === void 0 ? void 0 : params.payload)
|
||||
? (0, grabSchemaFieldsFromData_1.default)({
|
||||
data: params === null || params === void 0 ? void 0 : params.payload,
|
||||
excludeData: defaultFields,
|
||||
excludeFields: userPreset.fields,
|
||||
})
|
||||
: [];
|
||||
console.log("supplementalFields", supplementalFields);
|
||||
const allFields = [...userPreset.fields, ...supplementalFields];
|
||||
console.log("allFields", allFields);
|
||||
const finalFields = [
|
||||
...defaultFields.slice(0, 2),
|
||||
...allFields,
|
||||
...defaultFields.slice(2),
|
||||
];
|
||||
userPreset.fields = [...finalFields];
|
||||
return userPreset;
|
||||
}
|
||||
catch ( /** @type {any} */error) {
|
||||
console.log(`grabNewUsersTableSchema.js ERROR: ${error.message}`);
|
||||
(0, serverError_1.default)({
|
||||
component: "grabNewUsersTableSchema",
|
||||
message: error.message,
|
||||
});
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import { DSQL_FieldSchemaType } from "../../types";
|
||||
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[];
|
||||
export {};
|
||||
@@ -0,0 +1,66 @@
|
||||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = grabSchemaFieldsFromData;
|
||||
const serverError_1 = __importDefault(require("./serverError"));
|
||||
/**
|
||||
* # Add User Table to Database
|
||||
*/
|
||||
function grabSchemaFieldsFromData({ data, fields, excludeData, excludeFields, }) {
|
||||
var _a;
|
||||
try {
|
||||
const possibleFields = require("../../data/possibleFields.json");
|
||||
const dataTypes = require("../../data/dataTypes.json");
|
||||
/** @type {DSQL_FieldSchemaType[]} */
|
||||
const finalFields = [];
|
||||
/** @type {string[]} */
|
||||
let filteredFields = [];
|
||||
if (data && ((_a = Object.keys(data)) === null || _a === void 0 ? void 0 : _a[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 = {
|
||||
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) {
|
||||
console.log(`grabSchemaFieldsFromData.js ERROR: ${error.message}`);
|
||||
(0, serverError_1.default)({
|
||||
component: "grabSchemaFieldsFromData.js",
|
||||
message: error.message,
|
||||
});
|
||||
return [];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
/**
|
||||
* # Grab User Schema Data
|
||||
*/
|
||||
export default function grabUserSchemaData({ userId, }: {
|
||||
userId: string | number;
|
||||
}): import("../../types").DSQL_DatabaseSchemaType[] | null;
|
||||
@@ -0,0 +1,26 @@
|
||||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = grabUserSchemaData;
|
||||
const serverError_1 = __importDefault(require("./serverError"));
|
||||
const fs_1 = __importDefault(require("fs"));
|
||||
const path_1 = __importDefault(require("path"));
|
||||
/**
|
||||
* # Grab User Schema Data
|
||||
*/
|
||||
function grabUserSchemaData({ userId, }) {
|
||||
try {
|
||||
const userSchemaFilePath = path_1.default.resolve(process.cwd(), `${process.env.DSQL_USER_DB_SCHEMA_PATH}/user-${userId}/main.json`);
|
||||
const userSchemaData = JSON.parse(fs_1.default.readFileSync(userSchemaFilePath, "utf-8"));
|
||||
return userSchemaData;
|
||||
}
|
||||
catch (error) {
|
||||
(0, serverError_1.default)({
|
||||
component: "grabUserSchemaData",
|
||||
message: error.message,
|
||||
});
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
type Param = {
|
||||
to?: string;
|
||||
subject?: string;
|
||||
text?: string;
|
||||
html?: string;
|
||||
senderName?: string;
|
||||
alias?: string | null;
|
||||
};
|
||||
/**
|
||||
* # Handle mails With Nodemailer
|
||||
*/
|
||||
export default function handleNodemailer({ to, subject, text, html, alias, senderName, }: Param): Promise<any>;
|
||||
export {};
|
||||
@@ -0,0 +1,89 @@
|
||||
"use strict";
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = handleNodemailer;
|
||||
const fs_1 = __importDefault(require("fs"));
|
||||
const nodemailer_1 = __importDefault(require("nodemailer"));
|
||||
let transporter = nodemailer_1.default.createTransport({
|
||||
host: process.env.DSQL_MAIL_HOST,
|
||||
port: 465,
|
||||
secure: true,
|
||||
auth: {
|
||||
user: process.env.DSQL_MAIL_EMAIL,
|
||||
pass: process.env.DSQL_MAIL_PASSWORD,
|
||||
},
|
||||
});
|
||||
/**
|
||||
* # Handle mails With Nodemailer
|
||||
*/
|
||||
function handleNodemailer(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ to, subject, text, html, alias, senderName, }) {
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
if (!process.env.DSQL_MAIL_HOST ||
|
||||
!process.env.DSQL_MAIL_EMAIL ||
|
||||
!process.env.DSQL_MAIL_PASSWORD) {
|
||||
return null;
|
||||
}
|
||||
const sender = (() => {
|
||||
if (alias === null || alias === void 0 ? void 0 : alias.match(/support/i))
|
||||
return process.env.DSQL_MAIL_EMAIL;
|
||||
return process.env.DSQL_MAIL_EMAIL;
|
||||
})();
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
let sentMessage;
|
||||
if (!fs_1.default.existsSync("./email/index.html")) {
|
||||
return;
|
||||
}
|
||||
let mailRoot = fs_1.default.readFileSync("./email/index.html", "utf8");
|
||||
let finalHtml = mailRoot
|
||||
.replace(/{{email_body}}/, html ? html : "")
|
||||
.replace(/{{issue_date}}/, Date().substring(0, 24));
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
try {
|
||||
let mailObject = {};
|
||||
mailObject["from"] = `"${senderName || "Datasquirel"}" <${sender}>`;
|
||||
mailObject["sender"] = sender;
|
||||
if (alias)
|
||||
mailObject["replyTo"] = sender;
|
||||
mailObject["to"] = to;
|
||||
mailObject["subject"] = subject;
|
||||
mailObject["text"] = text;
|
||||
mailObject["html"] = finalHtml;
|
||||
// send mail with defined transport object
|
||||
let info = yield transporter.sendMail(mailObject);
|
||||
sentMessage = info;
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
}
|
||||
catch ( /** @type {any} */error) {
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
console.log("ERROR in handleNodemailer Function =>", error.message);
|
||||
// serverError({
|
||||
// component: "handleNodemailer",
|
||||
// message: error.message,
|
||||
// user: { email: to },
|
||||
// });
|
||||
}
|
||||
return sentMessage;
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
declare const sanitizeHtmlOptions: {
|
||||
allowedTags: string[];
|
||||
allowedAttributes: {
|
||||
a: string[];
|
||||
img: string[];
|
||||
"*": string[];
|
||||
};
|
||||
};
|
||||
export default sanitizeHtmlOptions;
|
||||
@@ -0,0 +1,35 @@
|
||||
"use strict";
|
||||
// @ts-check
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
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"],
|
||||
},
|
||||
};
|
||||
exports.default = sanitizeHtmlOptions;
|
||||
@@ -0,0 +1,13 @@
|
||||
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>>;
|
||||
@@ -0,0 +1,85 @@
|
||||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = httpRequest;
|
||||
const node_http_1 = __importDefault(require("node:http"));
|
||||
const node_https_1 = __importDefault(require("node:https"));
|
||||
const querystring_1 = __importDefault(require("querystring"));
|
||||
const serialize_query_1 = __importDefault(require("../../utils/serialize-query"));
|
||||
/**
|
||||
* # Generate a http Request
|
||||
*/
|
||||
function httpRequest(params) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const isUrlEncodedFormBody = params.urlEncodedFormBody;
|
||||
const reqPayloadString = params.body
|
||||
? isUrlEncodedFormBody
|
||||
? querystring_1.default.stringify(params.body)
|
||||
: JSON.stringify(params.body).replace(/\n|\r|\n\r/gm, "")
|
||||
: undefined;
|
||||
const reqQueryString = params.query
|
||||
? (0, serialize_query_1.default)(params.query)
|
||||
: undefined;
|
||||
const paramScheme = params.scheme;
|
||||
const finalScheme = paramScheme == "http" ? node_http_1.default : node_https_1.default;
|
||||
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 = Object.assign(Object.assign({}, params), { headers: Object.assign({ "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 = JSON.parse(str);
|
||||
return jsonObj;
|
||||
}
|
||||
catch (error) {
|
||||
return undefined;
|
||||
}
|
||||
})();
|
||||
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();
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
type Param = {
|
||||
scheme?: string;
|
||||
url?: string;
|
||||
method?: string;
|
||||
hostname?: string;
|
||||
path?: string;
|
||||
port?: number | string;
|
||||
headers?: object;
|
||||
body?: object;
|
||||
};
|
||||
/**
|
||||
* # Make Https Request
|
||||
*/
|
||||
export default function httpsRequest({ url, method, hostname, path, headers, body, port, scheme, }: Param): Promise<unknown>;
|
||||
export {};
|
||||
@@ -0,0 +1,88 @@
|
||||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = httpsRequest;
|
||||
const https_1 = __importDefault(require("https"));
|
||||
const http_1 = __importDefault(require("http"));
|
||||
const url_1 = require("url");
|
||||
/**
|
||||
* # Make Https Request
|
||||
*/
|
||||
function httpsRequest({ url, method, hostname, path, headers, body, port, scheme, }) {
|
||||
var _a;
|
||||
const reqPayloadString = body ? JSON.stringify(body) : null;
|
||||
const PARSED_URL = url ? new url_1.URL(url) : null;
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
/** @type {any} */
|
||||
let requestOptions = {
|
||||
method: method || "GET",
|
||||
hostname: PARSED_URL ? PARSED_URL.hostname : hostname,
|
||||
port: (scheme === null || scheme === void 0 ? void 0 : scheme.match(/https/i))
|
||||
? 443
|
||||
: PARSED_URL
|
||||
? ((_a = PARSED_URL.protocol) === null || _a === void 0 ? void 0 : _a.match(/https/i))
|
||||
? 443
|
||||
: PARSED_URL.port
|
||||
: port
|
||||
? Number(port)
|
||||
: 80,
|
||||
headers: {},
|
||||
};
|
||||
if (path)
|
||||
requestOptions.path = path;
|
||||
// if (href) requestOptions.href = href;
|
||||
if (headers)
|
||||
requestOptions.headers = headers;
|
||||
if (body) {
|
||||
requestOptions.headers["Content-Type"] = "application/json";
|
||||
requestOptions.headers["Content-Length"] = reqPayloadString
|
||||
? Buffer.from(reqPayloadString).length
|
||||
: undefined;
|
||||
}
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
return new Promise((res, rej) => {
|
||||
var _a;
|
||||
const httpsRequest = ((scheme === null || scheme === void 0 ? void 0 : scheme.match(/https/i))
|
||||
? https_1.default
|
||||
: ((_a = PARSED_URL === null || PARSED_URL === void 0 ? void 0 : PARSED_URL.protocol) === null || _a === void 0 ? void 0 : _a.match(/https/i))
|
||||
? https_1.default
|
||||
: http_1.default).request(
|
||||
/* ====== Request Options object ====== */
|
||||
requestOptions,
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
/* ====== Callback function ====== */
|
||||
(response) => {
|
||||
var str = "";
|
||||
// ## another chunk of data has been received, so append it to `str`
|
||||
response.on("data", function (chunk) {
|
||||
str += chunk;
|
||||
});
|
||||
// ## the whole response has been received, so we just print it out here
|
||||
response.on("end", function () {
|
||||
res(str);
|
||||
});
|
||||
response.on("error", (error) => {
|
||||
console.log("HTTP response error =>", error.message);
|
||||
rej(`HTTP response error =>, ${error.message}`);
|
||||
});
|
||||
response.on("close", () => {
|
||||
console.log("HTTP(S) Response Closed Successfully");
|
||||
});
|
||||
});
|
||||
if (body)
|
||||
httpsRequest.write(reqPayloadString);
|
||||
httpsRequest.on("error", (error) => {
|
||||
console.log("HTTPS request ERROR =>", error.message);
|
||||
rej(`HTTP request error =>, ${error.message}`);
|
||||
});
|
||||
httpsRequest.end();
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
/**
|
||||
* # No Database DB Handler
|
||||
*/
|
||||
export default function noDatabaseDbHandler(queryString: string): Promise<any>;
|
||||
@@ -0,0 +1,64 @@
|
||||
"use strict";
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = noDatabaseDbHandler;
|
||||
const fs_1 = __importDefault(require("fs"));
|
||||
const serverError_1 = __importDefault(require("./serverError"));
|
||||
const NO_DB_HANDLER_1 = __importDefault(require("../../../package-shared/utils/backend/global-db/NO_DB_HANDLER"));
|
||||
/**
|
||||
* # No Database DB Handler
|
||||
*/
|
||||
function noDatabaseDbHandler(queryString) {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
var _a;
|
||||
((_a = process.env.NODE_ENV) === null || _a === void 0 ? void 0 : _a.match(/dev/)) &&
|
||||
fs_1.default.appendFileSync("./.tmp/sqlQuery.sql", queryString + "\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 {
|
||||
/** ********************* Run Query */
|
||||
results = yield (0, NO_DB_HANDLER_1.default)(queryString);
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
}
|
||||
catch ( /** @type {any} */error) {
|
||||
(0, serverError_1.default)({
|
||||
component: "noDatabaseDbHandler",
|
||||
message: error.message,
|
||||
});
|
||||
console.log("ERROR in noDatabaseDbHandler =>", error.message);
|
||||
}
|
||||
/**
|
||||
* Return results
|
||||
*
|
||||
* @description Return results add to cache if "req" param is passed
|
||||
*/
|
||||
if (results) {
|
||||
return results;
|
||||
}
|
||||
else {
|
||||
return null;
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
type Param = {
|
||||
unparsedResults: any[];
|
||||
tableSchema?: import("../../types").DSQL_TableSchemaType;
|
||||
};
|
||||
/**
|
||||
* Parse Database results
|
||||
* ==============================================================================
|
||||
* @description this function takes a database results array gotten from a DB handler
|
||||
* function, decrypts encrypted fields, and returns an updated array with no encrypted
|
||||
* fields
|
||||
*/
|
||||
export default function parseDbResults({ unparsedResults, tableSchema, }: Param): Promise<any[] | null>;
|
||||
export {};
|
||||
@@ -0,0 +1,76 @@
|
||||
"use strict";
|
||||
// @ts-check
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = parseDbResults;
|
||||
const decrypt_1 = __importDefault(require("../dsql/decrypt"));
|
||||
const defaultFieldsRegexp_1 = __importDefault(require("./defaultFieldsRegexp"));
|
||||
/**
|
||||
* Parse Database results
|
||||
* ==============================================================================
|
||||
* @description this function takes a database results array gotten from a DB handler
|
||||
* function, decrypts encrypted fields, and returns an updated array with no encrypted
|
||||
* fields
|
||||
*/
|
||||
function parseDbResults(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ unparsedResults, tableSchema, }) {
|
||||
/**
|
||||
* Declare variables
|
||||
*
|
||||
* @description Declare "results" variable
|
||||
*/
|
||||
let parsedResults = [];
|
||||
try {
|
||||
/**
|
||||
* Declare variables
|
||||
*
|
||||
* @description Declare "results" variable
|
||||
*/
|
||||
for (let pr = 0; pr < unparsedResults.length; pr++) {
|
||||
let result = unparsedResults[pr];
|
||||
let resultFieldNames = Object.keys(result);
|
||||
for (let i = 0; i < resultFieldNames.length; i++) {
|
||||
const resultFieldName = resultFieldNames[i];
|
||||
let resultFieldSchema = tableSchema === null || tableSchema === void 0 ? void 0 : tableSchema.fields[i];
|
||||
if (resultFieldName === null || resultFieldName === void 0 ? void 0 : resultFieldName.match(defaultFieldsRegexp_1.default)) {
|
||||
continue;
|
||||
}
|
||||
let value = result[resultFieldName];
|
||||
if (typeof value !== "number" && !value) {
|
||||
// parsedResults.push(result);
|
||||
continue;
|
||||
}
|
||||
if (resultFieldSchema === null || resultFieldSchema === void 0 ? void 0 : resultFieldSchema.encrypted) {
|
||||
if (value === null || value === void 0 ? void 0 : value.match(/./)) {
|
||||
result[resultFieldName] = (0, decrypt_1.default)({
|
||||
encryptedString: value,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
parsedResults.push(result);
|
||||
}
|
||||
/**
|
||||
* Declare variables
|
||||
*
|
||||
* @description Declare "results" variable
|
||||
*/
|
||||
return parsedResults;
|
||||
}
|
||||
catch ( /** @type {any} */error) {
|
||||
console.log("ERROR in parseDbResults Function =>", error.message);
|
||||
return unparsedResults;
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
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
|
||||
*/
|
||||
export default function serverError({ user, message, component, noMail, req, }: Param): Promise<void>;
|
||||
export {};
|
||||
@@ -0,0 +1,77 @@
|
||||
"use strict";
|
||||
// @ts-check
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = serverError;
|
||||
const fs_1 = __importDefault(require("fs"));
|
||||
/**
|
||||
* # Server Error
|
||||
*/
|
||||
function serverError(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ user, message, component, noMail, req, }) {
|
||||
const date = new Date();
|
||||
const reqIp = (() => {
|
||||
if (!req)
|
||||
return null;
|
||||
try {
|
||||
const forwarded = req.headers["x-forwarded-for"];
|
||||
const realIp = req.headers["x-real-ip"];
|
||||
const cloudflareIp = req.headers["cf-connecting-ip"];
|
||||
// Convert forwarded IPs to string and get the first IP if multiple exist
|
||||
const forwardedIp = Array.isArray(forwarded)
|
||||
? forwarded[0]
|
||||
: forwarded === null || forwarded === void 0 ? void 0 : forwarded.split(",")[0];
|
||||
const clientIp = cloudflareIp ||
|
||||
forwardedIp ||
|
||||
realIp ||
|
||||
req.socket.remoteAddress;
|
||||
if (!clientIp)
|
||||
return null;
|
||||
return String(clientIp);
|
||||
}
|
||||
catch (error) {
|
||||
return null;
|
||||
}
|
||||
})();
|
||||
try {
|
||||
let log = `🚀 SERVER ERROR ===========================\nError Message: ${message}\nComponent: ${component}`;
|
||||
if ((user === null || user === void 0 ? void 0 : user.id) && (user === null || user === void 0 ? void 0 : user.first_name) && (user === null || user === void 0 ? void 0 : user.last_name) && (user === null || user === void 0 ? void 0 : user.email)) {
|
||||
log += `\nUser Id: ${user === null || user === void 0 ? void 0 : user.id}\nUser Name: ${user === null || user === void 0 ? void 0 : user.first_name} ${user === null || user === void 0 ? void 0 : user.last_name}\nUser Email: ${user === null || user === void 0 ? void 0 : user.email}`;
|
||||
}
|
||||
if (req === null || req === void 0 ? void 0 : req.url) {
|
||||
log += `\nURL: ${req.url}`;
|
||||
}
|
||||
if (req === null || req === void 0 ? void 0 : req.body) {
|
||||
log += `\nRequest Body: ${JSON.stringify(req.body, null, 4)}`;
|
||||
}
|
||||
if (reqIp) {
|
||||
log += `\nIP: ${reqIp}`;
|
||||
}
|
||||
log += `\nDate: ${date.toDateString()}`;
|
||||
log += "\n========================================";
|
||||
if (!fs_1.default.existsSync(`./.tmp/error.log`)) {
|
||||
fs_1.default.writeFileSync(`./.tmp/error.log`, "", "utf-8");
|
||||
}
|
||||
const initialText = fs_1.default.readFileSync(`./.tmp/error.log`, "utf-8");
|
||||
fs_1.default.writeFileSync(`./.tmp/error.log`, log);
|
||||
fs_1.default.appendFileSync(`./.tmp/error.log`, `\n\n\n\n\n${initialText}`);
|
||||
}
|
||||
catch ( /** @type {any} */error) {
|
||||
console.log("Server Error Reporting Error:", error.message);
|
||||
}
|
||||
});
|
||||
}
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
@@ -0,0 +1,16 @@
|
||||
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;
|
||||
export {};
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
@@ -0,0 +1,32 @@
|
||||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = setUserSchemaData;
|
||||
const serverError_1 = __importDefault(require("./serverError"));
|
||||
const fs_1 = __importDefault(require("fs"));
|
||||
const path_1 = __importDefault(require("path"));
|
||||
/**
|
||||
* # Set User Schema Data
|
||||
*/
|
||||
function setUserSchemaData({ userId, schemaData, }) {
|
||||
try {
|
||||
const userSchemaFilePath = path_1.default.resolve(process.cwd(), `${process.env.DSQL_USER_DB_SCHEMA_PATH}/user-${userId}/main.json`);
|
||||
fs_1.default.writeFileSync(userSchemaFilePath, JSON.stringify(schemaData), "utf8");
|
||||
return true;
|
||||
}
|
||||
catch (error) {
|
||||
(0, serverError_1.default)({
|
||||
component: "/functions/backend/setUserSchemaData",
|
||||
message: error.message,
|
||||
});
|
||||
return false;
|
||||
}
|
||||
}
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
@@ -0,0 +1,8 @@
|
||||
import { IncomingMessage } from "http";
|
||||
export default function (req: IncomingMessage): Promise<{
|
||||
email: string;
|
||||
password: string;
|
||||
authKey: string;
|
||||
logged_in_status: boolean;
|
||||
date: number;
|
||||
} | null>;
|
||||
@@ -0,0 +1,47 @@
|
||||
"use strict";
|
||||
// @ts-check
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = default_1;
|
||||
const parseCookies_1 = __importDefault(require("../../utils/backend/parseCookies"));
|
||||
const decrypt_1 = __importDefault(require("../dsql/decrypt"));
|
||||
const get_auth_cookie_names_1 = __importDefault(require("./cookies/get-auth-cookie-names"));
|
||||
function default_1(req) {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
const { keyCookieName, csrfCookieName } = (0, get_auth_cookie_names_1.default)();
|
||||
const suKeyName = `${keyCookieName}_su`;
|
||||
const cookies = (0, parseCookies_1.default)({ request: req });
|
||||
if (!(cookies === null || cookies === void 0 ? void 0 : cookies[suKeyName])) {
|
||||
return null;
|
||||
}
|
||||
/** ********************* Grab the payload */
|
||||
let userPayload = (0, decrypt_1.default)({
|
||||
encryptedString: cookies[suKeyName],
|
||||
});
|
||||
/** ********************* Return if no payload */
|
||||
if (!userPayload)
|
||||
return null;
|
||||
/** ********************* Parse the payload */
|
||||
let userObject = JSON.parse(userPayload);
|
||||
if (userObject.password !== process.env.DSQL_USER_KEY)
|
||||
return null;
|
||||
if (userObject.authKey !== process.env.DSQL_SPECIAL_KEY)
|
||||
return null;
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
/** ********************* return user object */
|
||||
return userObject;
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
type Param = {
|
||||
userId: number | string;
|
||||
database: string;
|
||||
newFields?: string[];
|
||||
newPayload?: {
|
||||
[s: string]: any;
|
||||
};
|
||||
};
|
||||
/**
|
||||
* # Add User Table to Database
|
||||
*/
|
||||
export default function updateUsersTableSchema({ userId, database, newFields, newPayload, }: Param): Promise<any>;
|
||||
export {};
|
||||
@@ -0,0 +1,64 @@
|
||||
"use strict";
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = updateUsersTableSchema;
|
||||
const serverError_1 = __importDefault(require("./serverError"));
|
||||
const grabUserSchemaData_1 = __importDefault(require("./grabUserSchemaData"));
|
||||
const setUserSchemaData_1 = __importDefault(require("./setUserSchemaData"));
|
||||
const createDbFromSchema_1 = __importDefault(require("../../shell/createDbFromSchema"));
|
||||
const grabSchemaFieldsFromData_1 = __importDefault(require("./grabSchemaFieldsFromData"));
|
||||
/**
|
||||
* # Add User Table to Database
|
||||
*/
|
||||
function updateUsersTableSchema(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ userId, database, newFields, newPayload, }) {
|
||||
var _b, _c;
|
||||
try {
|
||||
const dbFullName = database;
|
||||
const userSchemaData = (0, grabUserSchemaData_1.default)({ userId });
|
||||
if (!userSchemaData)
|
||||
throw new Error("User schema data not found!");
|
||||
let targetDatabaseIndex = userSchemaData.findIndex((db) => db.dbFullName === database);
|
||||
if (targetDatabaseIndex < 0) {
|
||||
throw new Error("Couldn't Find Target Database!");
|
||||
}
|
||||
let existingTableIndex = (_b = userSchemaData[targetDatabaseIndex]) === null || _b === void 0 ? void 0 : _b.tables.findIndex((table) => table.tableName === "users");
|
||||
const usersTable = userSchemaData[targetDatabaseIndex].tables[existingTableIndex];
|
||||
if (!((_c = usersTable === null || usersTable === void 0 ? void 0 : usersTable.fields) === null || _c === void 0 ? void 0 : _c[0]))
|
||||
throw new Error("Users Table Not Found!");
|
||||
const additionalFields = (0, grabSchemaFieldsFromData_1.default)({
|
||||
fields: newFields,
|
||||
data: newPayload,
|
||||
});
|
||||
const spliceStartIndex = usersTable.fields.findIndex((field) => field.fieldName === "date_created");
|
||||
const finalSpliceStartIndex = spliceStartIndex >= 0 ? spliceStartIndex : 0;
|
||||
usersTable.fields.splice(finalSpliceStartIndex, 0, ...additionalFields);
|
||||
(0, setUserSchemaData_1.default)({ schemaData: userSchemaData, userId });
|
||||
const dbShellUpdate = yield (0, createDbFromSchema_1.default)({
|
||||
userId,
|
||||
targetDatabase: dbFullName,
|
||||
});
|
||||
return `Done!`;
|
||||
}
|
||||
catch (error) {
|
||||
console.log(`addUsersTableToDb.js ERROR: ${error.message}`);
|
||||
(0, serverError_1.default)({
|
||||
component: "addUsersTableToDb",
|
||||
message: error.message,
|
||||
user: { id: userId },
|
||||
});
|
||||
return error.message;
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
type Param = {
|
||||
queryString: string;
|
||||
queryValuesArray?: any[];
|
||||
database?: string;
|
||||
tableSchema?: import("../../types").DSQL_TableSchemaType;
|
||||
useLocal?: boolean;
|
||||
};
|
||||
/**
|
||||
* # DB handler for specific database
|
||||
*/
|
||||
export default function varDatabaseDbHandler({ queryString, queryValuesArray, database, tableSchema, useLocal, }: Param): Promise<any>;
|
||||
export {};
|
||||
@@ -0,0 +1,108 @@
|
||||
"use strict";
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = varDatabaseDbHandler;
|
||||
const parseDbResults_1 = __importDefault(require("./parseDbResults"));
|
||||
const serverError_1 = __importDefault(require("./serverError"));
|
||||
const DB_HANDLER_1 = __importDefault(require("../../utils/backend/global-db/DB_HANDLER"));
|
||||
const DSQL_USER_DB_HANDLER_1 = __importDefault(require("../../utils/backend/global-db/DSQL_USER_DB_HANDLER"));
|
||||
const LOCAL_DB_HANDLER_1 = __importDefault(require("../../utils/backend/global-db/LOCAL_DB_HANDLER"));
|
||||
/**
|
||||
* # DB handler for specific database
|
||||
*/
|
||||
function varDatabaseDbHandler(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ queryString, queryValuesArray, database, tableSchema, useLocal, }) {
|
||||
/**
|
||||
* Declare variables
|
||||
*
|
||||
* @description Declare "results" variable
|
||||
*/
|
||||
const isMaster = useLocal
|
||||
? true
|
||||
: (database === null || database === void 0 ? void 0 : database.match(/^datasquirel$/))
|
||||
? true
|
||||
: false;
|
||||
/** @type {any} */
|
||||
const FINAL_DB_HANDLER = useLocal
|
||||
? LOCAL_DB_HANDLER_1.default
|
||||
: isMaster
|
||||
? DB_HANDLER_1.default
|
||||
: DSQL_USER_DB_HANDLER_1.default;
|
||||
let results;
|
||||
/**
|
||||
* Fetch from db
|
||||
*
|
||||
* @description Fetch data from db if no cache
|
||||
*/
|
||||
try {
|
||||
if (queryString &&
|
||||
queryValuesArray &&
|
||||
Array.isArray(queryValuesArray) &&
|
||||
queryValuesArray[0]) {
|
||||
results = isMaster
|
||||
? yield FINAL_DB_HANDLER(queryString, queryValuesArray)
|
||||
: yield FINAL_DB_HANDLER({
|
||||
paradigm: "Full Access",
|
||||
database,
|
||||
queryString,
|
||||
queryValues: queryValuesArray,
|
||||
});
|
||||
}
|
||||
else {
|
||||
results = isMaster
|
||||
? yield FINAL_DB_HANDLER(queryString)
|
||||
: yield FINAL_DB_HANDLER({
|
||||
paradigm: "Full Access",
|
||||
database,
|
||||
queryString,
|
||||
});
|
||||
}
|
||||
}
|
||||
catch (error) {
|
||||
(0, serverError_1.default)({
|
||||
component: "varDatabaseDbHandler/lines-29-32",
|
||||
message: error.message,
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Return results
|
||||
*
|
||||
* @description Return results add to cache if "req" param is passed
|
||||
*/
|
||||
if (results && tableSchema) {
|
||||
try {
|
||||
const unparsedResults = results;
|
||||
const parsedResults = yield (0, parseDbResults_1.default)({
|
||||
unparsedResults: unparsedResults,
|
||||
tableSchema: tableSchema,
|
||||
});
|
||||
return parsedResults;
|
||||
}
|
||||
catch (error) {
|
||||
console.log("\x1b[31mvarDatabaseDbHandler ERROR\x1b[0m =>", database, error);
|
||||
(0, serverError_1.default)({
|
||||
component: "varDatabaseDbHandler/lines-52-53",
|
||||
message: error.message,
|
||||
});
|
||||
return null;
|
||||
}
|
||||
}
|
||||
else if (results) {
|
||||
return results;
|
||||
}
|
||||
else {
|
||||
return null;
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
type Param = {
|
||||
queryString: string;
|
||||
database: string;
|
||||
queryValuesArray?: string[];
|
||||
tableSchema?: import("../../types").DSQL_TableSchemaType;
|
||||
useLocal?: boolean;
|
||||
};
|
||||
/**
|
||||
* # Read Only Db Handler with Varaibles
|
||||
* @returns
|
||||
*/
|
||||
export default function varReadOnlyDatabaseDbHandler({ queryString, database, queryValuesArray, tableSchema, useLocal, }: Param): Promise<any>;
|
||||
export {};
|
||||
@@ -0,0 +1,78 @@
|
||||
"use strict";
|
||||
// @ts-check
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = varReadOnlyDatabaseDbHandler;
|
||||
const serverError_1 = __importDefault(require("./serverError"));
|
||||
const parseDbResults_1 = __importDefault(require("./parseDbResults"));
|
||||
const DSQL_USER_DB_HANDLER_1 = __importDefault(require("../../utils/backend/global-db/DSQL_USER_DB_HANDLER"));
|
||||
const LOCAL_DB_HANDLER_1 = __importDefault(require("../../utils/backend/global-db/LOCAL_DB_HANDLER"));
|
||||
/**
|
||||
* # Read Only Db Handler with Varaibles
|
||||
* @returns
|
||||
*/
|
||||
function varReadOnlyDatabaseDbHandler(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ queryString, database, queryValuesArray, tableSchema, useLocal, }) {
|
||||
/**
|
||||
* Declare variables
|
||||
*
|
||||
* @description Declare "results" variable
|
||||
*/
|
||||
let results;
|
||||
/**
|
||||
* Fetch from db
|
||||
*
|
||||
* @description Fetch data from db if no cache
|
||||
*/
|
||||
try {
|
||||
results = useLocal
|
||||
? yield (0, LOCAL_DB_HANDLER_1.default)(queryString, queryValuesArray)
|
||||
: yield (0, DSQL_USER_DB_HANDLER_1.default)({
|
||||
paradigm: "Read Only",
|
||||
database,
|
||||
queryString,
|
||||
queryValues: queryValuesArray,
|
||||
});
|
||||
////////////////////////////////////////
|
||||
}
|
||||
catch ( /** @type {any} */error) {
|
||||
////////////////////////////////////////
|
||||
(0, serverError_1.default)({
|
||||
component: "varReadOnlyDatabaseDbHandler",
|
||||
message: error.message,
|
||||
noMail: true,
|
||||
});
|
||||
/**
|
||||
* Return error
|
||||
*/
|
||||
return error.message;
|
||||
}
|
||||
/**
|
||||
* Return results
|
||||
*
|
||||
* @description Return results add to cache if "req" param is passed
|
||||
*/
|
||||
if (results) {
|
||||
const unparsedResults = results;
|
||||
const parsedResults = yield (0, parseDbResults_1.default)({
|
||||
unparsedResults: unparsedResults,
|
||||
tableSchema: tableSchema,
|
||||
});
|
||||
return parsedResults;
|
||||
}
|
||||
else {
|
||||
return null;
|
||||
}
|
||||
});
|
||||
}
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
type Param = {
|
||||
encryptedString: string;
|
||||
encryptionKey?: string;
|
||||
encryptionSalt?: string;
|
||||
};
|
||||
/**
|
||||
* # Decrypt Function
|
||||
*/
|
||||
export default function decrypt({ encryptedString, encryptionKey, encryptionSalt, }: Param): string;
|
||||
export {};
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
"use strict";
|
||||
// @ts-check
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = decrypt;
|
||||
const crypto_1 = require("crypto");
|
||||
const buffer_1 = require("buffer");
|
||||
/**
|
||||
* # Decrypt Function
|
||||
*/
|
||||
function decrypt({ encryptedString, encryptionKey, encryptionSalt, }) {
|
||||
if (!(encryptedString === null || encryptedString === void 0 ? void 0 : encryptedString.match(/./))) {
|
||||
console.log("Encrypted string is invalid");
|
||||
return encryptedString;
|
||||
}
|
||||
const finalEncryptionKey = encryptionKey || process.env.DSQL_ENCRYPTION_PASSWORD;
|
||||
const finalEncryptionSalt = encryptionSalt || process.env.DSQL_ENCRYPTION_SALT;
|
||||
const finalKeyLen = process.env.DSQL_ENCRYPTION_KEY_LENGTH
|
||||
? Number(process.env.DSQL_ENCRYPTION_KEY_LENGTH)
|
||||
: 24;
|
||||
if (!(finalEncryptionKey === null || finalEncryptionKey === void 0 ? void 0 : finalEncryptionKey.match(/.{8,}/))) {
|
||||
console.log("Decrption key is invalid");
|
||||
return encryptedString;
|
||||
}
|
||||
if (!(finalEncryptionSalt === null || finalEncryptionSalt === void 0 ? void 0 : finalEncryptionSalt.match(/.{8,}/))) {
|
||||
console.log("Decrption salt is invalid");
|
||||
return encryptedString;
|
||||
}
|
||||
const algorithm = "aes-192-cbc";
|
||||
let key = (0, crypto_1.scryptSync)(finalEncryptionKey, finalEncryptionSalt, finalKeyLen);
|
||||
let iv = buffer_1.Buffer.alloc(16, 0);
|
||||
const decipher = (0, crypto_1.createDecipheriv)(algorithm, key, iv);
|
||||
try {
|
||||
let decrypted = decipher.update(encryptedString, "hex", "utf8");
|
||||
decrypted += decipher.final("utf8");
|
||||
return decrypted;
|
||||
}
|
||||
catch (error) {
|
||||
console.log("Error in decrypting =>", error.message);
|
||||
return encryptedString;
|
||||
}
|
||||
}
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
type Param = {
|
||||
data: string;
|
||||
encryptionKey?: string;
|
||||
encryptionSalt?: string;
|
||||
};
|
||||
/**
|
||||
* # Encrypt String
|
||||
*/
|
||||
export default function encrypt({ data, encryptionKey, encryptionSalt, }: Param): string | null;
|
||||
export {};
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
"use strict";
|
||||
// @ts-check
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = encrypt;
|
||||
const crypto_1 = require("crypto");
|
||||
const buffer_1 = require("buffer");
|
||||
/**
|
||||
* # Encrypt String
|
||||
*/
|
||||
function encrypt({ data, encryptionKey, encryptionSalt, }) {
|
||||
if (!(data === null || data === void 0 ? void 0 : data.match(/./))) {
|
||||
console.log("Encryption string is invalid");
|
||||
return data;
|
||||
}
|
||||
const finalEncryptionKey = encryptionKey || process.env.DSQL_ENCRYPTION_PASSWORD;
|
||||
const finalEncryptionSalt = encryptionSalt || process.env.DSQL_ENCRYPTION_SALT;
|
||||
const finalKeyLen = process.env.DSQL_ENCRYPTION_KEY_LENGTH
|
||||
? Number(process.env.DSQL_ENCRYPTION_KEY_LENGTH)
|
||||
: 24;
|
||||
if (!(finalEncryptionKey === null || finalEncryptionKey === void 0 ? void 0 : finalEncryptionKey.match(/.{8,}/))) {
|
||||
console.log("Encryption key is invalid");
|
||||
return data;
|
||||
}
|
||||
if (!(finalEncryptionSalt === null || finalEncryptionSalt === void 0 ? void 0 : finalEncryptionSalt.match(/.{8,}/))) {
|
||||
console.log("Encryption salt is invalid");
|
||||
return data;
|
||||
}
|
||||
const algorithm = "aes-192-cbc";
|
||||
const password = finalEncryptionKey;
|
||||
let key = (0, crypto_1.scryptSync)(password, finalEncryptionSalt, finalKeyLen);
|
||||
let iv = buffer_1.Buffer.alloc(16, 0);
|
||||
// @ts-ignore
|
||||
const cipher = (0, crypto_1.createCipheriv)(algorithm, key, iv);
|
||||
try {
|
||||
let encrypted = cipher.update(data, "utf8", "hex");
|
||||
encrypted += cipher.final("hex");
|
||||
return encrypted;
|
||||
}
|
||||
catch ( /** @type {*} */error) {
|
||||
console.log("Error in encrypting =>", error.message);
|
||||
return data;
|
||||
}
|
||||
}
|
||||
module.exports = encrypt;
|
||||
@@ -0,0 +1,9 @@
|
||||
type Param = {
|
||||
password: string;
|
||||
encryptionKey?: string;
|
||||
};
|
||||
/**
|
||||
* # Hash password Function
|
||||
*/
|
||||
export default function hashPassword({ password, encryptionKey, }: Param): string;
|
||||
export {};
|
||||
@@ -0,0 +1,17 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = hashPassword;
|
||||
const crypto_1 = require("crypto");
|
||||
/**
|
||||
* # Hash password Function
|
||||
*/
|
||||
function hashPassword({ password, encryptionKey, }) {
|
||||
const finalEncryptionKey = encryptionKey || process.env.DSQL_ENCRYPTION_PASSWORD;
|
||||
if (!(finalEncryptionKey === null || finalEncryptionKey === void 0 ? void 0 : finalEncryptionKey.match(/.{8,}/))) {
|
||||
throw new Error("Encryption key is invalid");
|
||||
}
|
||||
const hmac = (0, crypto_1.createHmac)("sha512", finalEncryptionKey);
|
||||
hmac.update(password);
|
||||
let hashed = hmac.digest("base64");
|
||||
return hashed;
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
interface SQLDeleteGenReturn {
|
||||
query: string;
|
||||
values: string[];
|
||||
}
|
||||
/**
|
||||
* # SQL Delete Generator
|
||||
*/
|
||||
export default function sqlDeleteGenerator({ tableName, data, }: {
|
||||
data: any;
|
||||
tableName: string;
|
||||
}): SQLDeleteGenReturn | undefined;
|
||||
export {};
|
||||
@@ -0,0 +1,26 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = sqlDeleteGenerator;
|
||||
/**
|
||||
* # SQL Delete Generator
|
||||
*/
|
||||
function sqlDeleteGenerator({ tableName, data, }) {
|
||||
try {
|
||||
let queryStr = `DELETE FROM ${tableName}`;
|
||||
let deleteBatch = [];
|
||||
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;
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user