Updates
This commit is contained in:
+11
-2
@@ -16,6 +16,7 @@ exports.default = queryDSQLAPI;
|
||||
const path_1 = __importDefault(require("path"));
|
||||
const grab_host_names_1 = __importDefault(require("../../utils/grab-host-names"));
|
||||
const serialize_query_1 = __importDefault(require("../../utils/serialize-query"));
|
||||
const lodash_1 = __importDefault(require("lodash"));
|
||||
/**
|
||||
* # Query DSQL API
|
||||
*/
|
||||
@@ -88,7 +89,12 @@ function queryDSQLAPI(_a) {
|
||||
payload: undefined,
|
||||
msg: `An error occurred while parsing the response`,
|
||||
error: error.message,
|
||||
errorData: { requestOptions, grabedHostNames },
|
||||
errorData: {
|
||||
requestOptions,
|
||||
grabedHostNames: lodash_1.default.omit(grabedHostNames, [
|
||||
"scheme",
|
||||
]),
|
||||
},
|
||||
});
|
||||
}
|
||||
});
|
||||
@@ -108,7 +114,10 @@ function queryDSQLAPI(_a) {
|
||||
payload: undefined,
|
||||
msg: `An error occurred while making the request`,
|
||||
error: err.message,
|
||||
errorData: { requestOptions, grabedHostNames },
|
||||
errorData: {
|
||||
requestOptions,
|
||||
grabedHostNames: lodash_1.default.omit(grabedHostNames, ["scheme"]),
|
||||
},
|
||||
});
|
||||
});
|
||||
if (reqPayload) {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { APILoginFunctionReturn, HandleSocialDbFunctionParams } from "../../../types";
|
||||
import { APIResponseObject, HandleSocialDbFunctionParams } from "../../../types";
|
||||
/**
|
||||
* # Handle Social DB
|
||||
*/
|
||||
export default function handleSocialDb({ database, email, social_platform, payload, invitation, supEmail, additionalFields, debug, loginOnly, apiUserId, }: HandleSocialDbFunctionParams): Promise<APILoginFunctionReturn>;
|
||||
export default function handleSocialDb({ database, email, social_platform, payload, invitation, supEmail, additionalFields, debug, loginOnly, apiUserId, }: HandleSocialDbFunctionParams): Promise<APIResponseObject>;
|
||||
|
||||
@@ -15,7 +15,6 @@ 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 dbHandler_1 = __importDefault(require("../../backend/dbHandler"));
|
||||
const encrypt_1 = __importDefault(require("../../dsql/encrypt"));
|
||||
@@ -162,26 +161,19 @@ function handleSocialDb(_a) {
|
||||
.replace(/{{token}}/, generatedToken || ""),
|
||||
}).then(() => { });
|
||||
}
|
||||
const { STATIC_ROOT } = (0, grab_dir_names_1.default)();
|
||||
if (!STATIC_ROOT) {
|
||||
console.log("Static File ENV not Found!");
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: "Static File ENV not Found!",
|
||||
};
|
||||
}
|
||||
const { userPrivateMediaDir, userPublicMediaDir } = (0, grab_dir_names_1.default)({
|
||||
userId: newUser.payload.insertId,
|
||||
});
|
||||
/**
|
||||
* 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.payload.insertId}`;
|
||||
let newUserMediaFolderPath = path_1.default.join(STATIC_ROOT, `images/user-images/user-${newUser.payload.insertId}`);
|
||||
fs_1.default.mkdirSync(newUserSchemaFolderPath);
|
||||
fs_1.default.mkdirSync(newUserMediaFolderPath);
|
||||
fs_1.default.writeFileSync(`${newUserSchemaFolderPath}/main.json`, JSON.stringify([]), "utf8");
|
||||
userPublicMediaDir &&
|
||||
fs_1.default.mkdirSync(userPublicMediaDir, { recursive: true });
|
||||
userPrivateMediaDir &&
|
||||
fs_1.default.mkdirSync(userPrivateMediaDir, { recursive: true });
|
||||
}
|
||||
return yield (0, loginSocialUser_1.default)({
|
||||
user: newUserQueried[0],
|
||||
|
||||
@@ -1,10 +1,7 @@
|
||||
import { APILoginFunctionReturn } from "../../../types";
|
||||
import { APIResponseObject } from "../../../types";
|
||||
type Param = {
|
||||
user: {
|
||||
first_name: string;
|
||||
last_name: string;
|
||||
email: string;
|
||||
social_id: string | number;
|
||||
};
|
||||
social_platform: string;
|
||||
invitation?: any;
|
||||
@@ -18,5 +15,5 @@ type Param = {
|
||||
* @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, debug, }: Param): Promise<APILoginFunctionReturn>;
|
||||
export default function loginSocialUser({ user, social_platform, invitation, database, additionalFields, debug, }: Param): Promise<APIResponseObject>;
|
||||
export {};
|
||||
|
||||
@@ -13,8 +13,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = loginSocialUser;
|
||||
const addAdminUserOnLogin_1 = __importDefault(require("../../backend/addAdminUserOnLogin"));
|
||||
const dbHandler_1 = __importDefault(require("../../backend/dbHandler"));
|
||||
const login_user_1 = __importDefault(require("../../../actions/users/login-user"));
|
||||
/**
|
||||
* Function to login social user
|
||||
* ==============================================================================
|
||||
@@ -24,57 +23,15 @@ const dbHandler_1 = __importDefault(require("../../backend/dbHandler"));
|
||||
function loginSocialUser(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ user, social_platform, invitation, database, additionalFields, debug, }) {
|
||||
const finalDbName = database ? database : "datasquirel";
|
||||
const dbAppend = database ? `\`${finalDbName}\`.` : "";
|
||||
const foundUserQuery = `SELECT * FROM ${dbAppend}\`users\` WHERE email=?`;
|
||||
const foundUserValues = [user.email];
|
||||
const foundUser = (yield (0, dbHandler_1.default)({
|
||||
query: foundUserQuery,
|
||||
values: foundUserValues,
|
||||
let userPayload = yield (0, login_user_1.default)({
|
||||
database: finalDbName,
|
||||
}));
|
||||
if (!(foundUser === null || foundUser === void 0 ? void 0 : foundUser[0]))
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: "Couldn't find Social User.",
|
||||
};
|
||||
let csrfKey = Math.random().toString(36).substring(2) +
|
||||
"-" +
|
||||
Math.random().toString(36).substring(2);
|
||||
let userPayload = {
|
||||
id: foundUser[0].id,
|
||||
uuid: foundUser[0].uuid,
|
||||
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,
|
||||
});
|
||||
}
|
||||
let result = {
|
||||
success: true,
|
||||
payload: userPayload,
|
||||
csrf: csrfKey,
|
||||
};
|
||||
return result;
|
||||
payload: { email: user.email },
|
||||
skipPassword: true,
|
||||
skipWriteAuthFile: true,
|
||||
additionalFields,
|
||||
debug,
|
||||
useLocal: true,
|
||||
});
|
||||
return userPayload;
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { APIGoogleLoginFunctionParams, APILoginFunctionReturn } from "../../../../types";
|
||||
import { APIGoogleLoginFunctionParams } from "../../../../types";
|
||||
import { APIResponseObject } from "../../../../types";
|
||||
/**
|
||||
* # API google login
|
||||
*/
|
||||
export default function apiGoogleLogin({ token, database, additionalFields, additionalData, debug, loginOnly, apiUserId, }: APIGoogleLoginFunctionParams): Promise<APILoginFunctionReturn>;
|
||||
export default function apiGoogleLogin({ token, database, additionalFields, additionalData, debug, loginOnly, apiUserId, }: APIGoogleLoginFunctionParams): Promise<APIResponseObject>;
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
import { ServerResponse } from "http";
|
||||
import { APIResponseObject } from "../../../types";
|
||||
type Params = {
|
||||
database: string;
|
||||
httpResponse: APIResponseObject;
|
||||
response?: ServerResponse & {
|
||||
[s: string]: any;
|
||||
};
|
||||
encryptionKey?: string;
|
||||
encryptionSalt?: string;
|
||||
debug?: boolean;
|
||||
skipWriteAuthFile?: boolean;
|
||||
token?: boolean;
|
||||
cleanupTokens?: boolean;
|
||||
secureCookie?: boolean;
|
||||
};
|
||||
/**
|
||||
* # Login A user
|
||||
*/
|
||||
export default function postLoginResponseHandler({ database, httpResponse, response, encryptionKey, encryptionSalt, debug, token, skipWriteAuthFile, cleanupTokens, secureCookie, }: Params): boolean;
|
||||
export {};
|
||||
@@ -0,0 +1,63 @@
|
||||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = postLoginResponseHandler;
|
||||
const encrypt_1 = __importDefault(require("../../dsql/encrypt"));
|
||||
const debug_log_1 = __importDefault(require("../../../utils/logging/debug-log"));
|
||||
const get_auth_cookie_names_1 = __importDefault(require("../cookies/get-auth-cookie-names"));
|
||||
const write_auth_files_1 = require("./write-auth-files");
|
||||
const grab_cookie_expirt_date_1 = __importDefault(require("../../../utils/grab-cookie-expirt-date"));
|
||||
function debugFn(log, label) {
|
||||
(0, debug_log_1.default)({ log, addTime: true, title: "loginUser", label });
|
||||
}
|
||||
/**
|
||||
* # Login A user
|
||||
*/
|
||||
function postLoginResponseHandler({ database, httpResponse, response, encryptionKey, encryptionSalt, debug, token, skipWriteAuthFile, cleanupTokens, secureCookie, }) {
|
||||
var _a, _b;
|
||||
const COOKIE_EXPIRY_DATE = (0, grab_cookie_expirt_date_1.default)();
|
||||
if (httpResponse === null || httpResponse === void 0 ? void 0 : httpResponse.success) {
|
||||
let encryptedPayload = (0, encrypt_1.default)({
|
||||
data: JSON.stringify(httpResponse.payload),
|
||||
encryptionKey,
|
||||
encryptionSalt,
|
||||
});
|
||||
try {
|
||||
if (token && encryptedPayload)
|
||||
httpResponse["token"] = encryptedPayload;
|
||||
}
|
||||
catch (error) {
|
||||
console.log("Login User HTTP Response Error:", error.message);
|
||||
}
|
||||
const cookieNames = (0, get_auth_cookie_names_1.default)({
|
||||
database,
|
||||
});
|
||||
if (httpResponse.csrf && !skipWriteAuthFile) {
|
||||
(0, write_auth_files_1.writeAuthFile)(httpResponse.csrf, JSON.stringify(httpResponse.payload), cleanupTokens && ((_a = httpResponse.payload) === null || _a === void 0 ? void 0 : _a.id)
|
||||
? { userId: httpResponse.payload.id }
|
||||
: undefined);
|
||||
}
|
||||
httpResponse["cookieNames"] = cookieNames;
|
||||
httpResponse["key"] = String(encryptedPayload);
|
||||
const authKeyName = cookieNames.keyCookieName;
|
||||
const csrfName = cookieNames.csrfCookieName;
|
||||
if (debug) {
|
||||
debugFn(authKeyName, "authKeyName");
|
||||
debugFn(csrfName, "csrfName");
|
||||
debugFn(encryptedPayload, "encryptedPayload");
|
||||
}
|
||||
response === null || response === void 0 ? void 0 : response.setHeader("Set-Cookie", [
|
||||
`${authKeyName}=${encryptedPayload};samesite=strict;path=/;HttpOnly=true;Expires=${COOKIE_EXPIRY_DATE}${secureCookie ? ";Secure=true" : ""}`,
|
||||
`${csrfName}=${(_b = httpResponse.payload) === null || _b === void 0 ? void 0 : _b.csrf_k};samesite=strict;path=/;HttpOnly=true;Expires=${COOKIE_EXPIRY_DATE}`,
|
||||
]);
|
||||
if (debug) {
|
||||
debugFn("Response Sent!");
|
||||
}
|
||||
return true;
|
||||
}
|
||||
else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -22,7 +22,7 @@ function suAddBackup(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ targetUserId, }) {
|
||||
var _b, _c;
|
||||
try {
|
||||
const { mainBackupDir, userBackupDir } = (0, grab_dir_names_1.default)({
|
||||
const { mainBackupDir, userBackupDir, STATIC_ROOT, privateDataDir } = (0, grab_dir_names_1.default)({
|
||||
userId: targetUserId,
|
||||
});
|
||||
if (targetUserId && !userBackupDir) {
|
||||
|
||||
+1
-1
@@ -22,7 +22,7 @@ const export_mariadb_database_1 = __importDefault(require("../../../../../utils/
|
||||
function writeBackupFiles(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ backup, }) {
|
||||
try {
|
||||
const { mainBackupDir, userBackupDir, sqlBackupDirName, schemasBackupDirName, targetUserPrivateDir, oldSchemasDir, } = (0, grab_dir_names_1.default)({
|
||||
const { mainBackupDir, userBackupDir, sqlBackupDirName, schemasBackupDirName, targetUserPrivateDir, oldSchemasDir, STATIC_ROOT, privateDataDir, } = (0, grab_dir_names_1.default)({
|
||||
userId: backup.user_id,
|
||||
});
|
||||
if (backup.user_id && !userBackupDir) {
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
import { DSQL_DATASQUIREL_BACKUPS } from "../../../../types/dsql";
|
||||
import { APIResponseObject } from "../../../../types";
|
||||
import { NextApiResponse } from "next";
|
||||
type Params = {
|
||||
backup: DSQL_DATASQUIREL_BACKUPS;
|
||||
res: NextApiResponse;
|
||||
};
|
||||
export default function downloadBackup({ backup, res, }: Params): Promise<APIResponseObject>;
|
||||
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 = downloadBackup;
|
||||
const fs_1 = __importDefault(require("fs"));
|
||||
const path_1 = __importDefault(require("path"));
|
||||
const grab_dir_names_1 = __importDefault(require("../../../../utils/backend/names/grab-dir-names"));
|
||||
const child_process_1 = require("child_process");
|
||||
function downloadBackup(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ backup, res, }) {
|
||||
try {
|
||||
const { mainBackupDir, userBackupDir, tempBackupExportName } = (0, grab_dir_names_1.default)({
|
||||
userId: backup.user_id,
|
||||
});
|
||||
if (backup.user_id && !userBackupDir) {
|
||||
return {
|
||||
success: false,
|
||||
msg: `Error grabbing user backup directory`,
|
||||
};
|
||||
}
|
||||
if (!backup.uuid) {
|
||||
return {
|
||||
success: false,
|
||||
msg: `No UUID found for backup`,
|
||||
};
|
||||
}
|
||||
const allBackupsDir = backup.user_id && userBackupDir ? userBackupDir : mainBackupDir;
|
||||
const targetBackupDir = path_1.default.join(allBackupsDir, backup.uuid);
|
||||
const zipFilesCmd = (0, child_process_1.execSync)(`tar -cJf ${tempBackupExportName} ${backup.uuid}`, {
|
||||
cwd: allBackupsDir,
|
||||
});
|
||||
const exportFilePath = path_1.default.join(allBackupsDir, tempBackupExportName);
|
||||
const readStream = fs_1.default.createReadStream(exportFilePath);
|
||||
readStream.pipe(res);
|
||||
readStream.on("end", () => {
|
||||
console.log("Pipe Complete!");
|
||||
setTimeout(() => {
|
||||
(0, child_process_1.execSync)(`rm -f ${tempBackupExportName}`, {
|
||||
cwd: allBackupsDir,
|
||||
});
|
||||
}, 1000);
|
||||
});
|
||||
return { success: true };
|
||||
}
|
||||
catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
msg: `Failed to write backup files`,
|
||||
error: error.message,
|
||||
};
|
||||
}
|
||||
});
|
||||
}
|
||||
+12
-41
@@ -13,15 +13,13 @@ var __importDefault = (this && this.__importDefault) || function (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 lodash_1 = __importDefault(require("lodash"));
|
||||
const encrypt_1 = __importDefault(require("../../dsql/encrypt"));
|
||||
const conn_db_handler_1 = __importDefault(require("../../../utils/db/conn-db-handler"));
|
||||
const check_if_is_master_1 = __importDefault(require("../../../utils/check-if-is-master"));
|
||||
const debug_log_1 = __importDefault(require("../../../utils/logging/debug-log"));
|
||||
const purge_default_fields_1 = __importDefault(require("../../../utils/purge-default-fields"));
|
||||
const grab_parsed_value_1 = __importDefault(require("./grab-parsed-value"));
|
||||
/**
|
||||
* Add a db Entry Function
|
||||
*/
|
||||
@@ -74,7 +72,6 @@ function addDbEntry(_a) {
|
||||
}
|
||||
}
|
||||
function generateQuery(data) {
|
||||
var _a, _b;
|
||||
const dataKeys = Object.keys(data);
|
||||
let insertKeysArray = [];
|
||||
let insertValuesArray = [];
|
||||
@@ -82,47 +79,21 @@ function addDbEntry(_a) {
|
||||
try {
|
||||
const dataKey = dataKeys[i];
|
||||
let value = data[dataKey];
|
||||
const targetFieldSchemaArray = tableSchema
|
||||
? (_a = tableSchema === null || tableSchema === void 0 ? void 0 : tableSchema.fields) === null || _a === void 0 ? void 0 : _a.filter((field) => field.fieldName == dataKey)
|
||||
: null;
|
||||
const targetFieldSchema = targetFieldSchemaArray && targetFieldSchemaArray[0]
|
||||
? targetFieldSchemaArray[0]
|
||||
: null;
|
||||
if (value == null || value == undefined)
|
||||
const parsedValue = (0, grab_parsed_value_1.default)({
|
||||
dataKey,
|
||||
encryptionKey,
|
||||
encryptionSalt,
|
||||
tableSchema,
|
||||
value,
|
||||
});
|
||||
if (typeof parsedValue == "undefined")
|
||||
continue;
|
||||
if (((_b = targetFieldSchema === null || targetFieldSchema === void 0 ? void 0 : targetFieldSchema.dataType) === null || _b === void 0 ? void 0 : _b.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));
|
||||
if (typeof parsedValue == "number") {
|
||||
insertValuesArray.push(String(parsedValue));
|
||||
}
|
||||
else {
|
||||
insertValuesArray.push(value);
|
||||
insertValuesArray.push(parsedValue);
|
||||
}
|
||||
}
|
||||
catch (error) {
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
import { DSQL_TableSchemaType } from "../../../types";
|
||||
type Param = {
|
||||
value?: any;
|
||||
tableSchema?: DSQL_TableSchemaType;
|
||||
encryptionKey?: string;
|
||||
encryptionSalt?: string;
|
||||
dataKey: string;
|
||||
};
|
||||
/**
|
||||
* # Update DB Function
|
||||
* @description
|
||||
*/
|
||||
export default function grabParsedValue({ value, tableSchema, encryptionKey, encryptionSalt, dataKey, }: Param): any;
|
||||
export {};
|
||||
@@ -0,0 +1,68 @@
|
||||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = grabParsedValue;
|
||||
const sanitize_html_1 = __importDefault(require("sanitize-html"));
|
||||
const sanitizeHtmlOptions_1 = __importDefault(require("../html/sanitizeHtmlOptions"));
|
||||
const encrypt_1 = __importDefault(require("../../dsql/encrypt"));
|
||||
/**
|
||||
* # Update DB Function
|
||||
* @description
|
||||
*/
|
||||
function grabParsedValue({ value, tableSchema, encryptionKey, encryptionSalt, dataKey, }) {
|
||||
var _a, _b;
|
||||
let newValue = value;
|
||||
const targetFieldSchemaArray = tableSchema
|
||||
? (_a = tableSchema === null || tableSchema === void 0 ? void 0 : tableSchema.fields) === null || _a === void 0 ? void 0 : _a.filter((field) => field.fieldName === dataKey)
|
||||
: null;
|
||||
const targetFieldSchema = targetFieldSchemaArray && targetFieldSchemaArray[0]
|
||||
? targetFieldSchemaArray[0]
|
||||
: null;
|
||||
if (typeof newValue == "undefined")
|
||||
return;
|
||||
if (typeof newValue == "object" && !newValue)
|
||||
newValue = "";
|
||||
const htmlRegex = /<[^>]+>/g;
|
||||
if ((targetFieldSchema === null || targetFieldSchema === void 0 ? void 0 : targetFieldSchema.richText) || String(newValue).match(htmlRegex)) {
|
||||
newValue = (0, sanitize_html_1.default)(newValue, sanitizeHtmlOptions_1.default);
|
||||
}
|
||||
if (((_b = targetFieldSchema === null || targetFieldSchema === void 0 ? void 0 : targetFieldSchema.dataType) === null || _b === void 0 ? void 0 : _b.match(/int$/i)) &&
|
||||
typeof value == "string" &&
|
||||
!(value === null || value === void 0 ? void 0 : value.match(/./))) {
|
||||
value = "";
|
||||
}
|
||||
if (targetFieldSchema === null || targetFieldSchema === void 0 ? void 0 : targetFieldSchema.encrypted) {
|
||||
newValue = (0, encrypt_1.default)({
|
||||
data: newValue,
|
||||
encryptionKey,
|
||||
encryptionSalt,
|
||||
});
|
||||
}
|
||||
if (typeof newValue === "object") {
|
||||
newValue = JSON.stringify(newValue);
|
||||
}
|
||||
if (targetFieldSchema === null || targetFieldSchema === void 0 ? void 0 : targetFieldSchema.pattern) {
|
||||
const pattern = new RegExp(targetFieldSchema.pattern, targetFieldSchema.patternFlags || "");
|
||||
if (!pattern.test(newValue)) {
|
||||
console.log("DSQL: Pattern not matched =>", newValue);
|
||||
newValue = "";
|
||||
}
|
||||
}
|
||||
if (typeof newValue === "string" && newValue.match(/^null$/i)) {
|
||||
newValue = {
|
||||
toSqlString: function () {
|
||||
return "NULL";
|
||||
},
|
||||
};
|
||||
}
|
||||
if (typeof newValue === "string" && !newValue.match(/./i)) {
|
||||
newValue = {
|
||||
toSqlString: function () {
|
||||
return "NULL";
|
||||
},
|
||||
};
|
||||
}
|
||||
return newValue;
|
||||
}
|
||||
+12
-49
@@ -13,20 +13,17 @@ var __importDefault = (this && this.__importDefault) || function (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 encrypt_1 = __importDefault(require("../../dsql/encrypt"));
|
||||
const check_if_is_master_1 = __importDefault(require("../../../utils/check-if-is-master"));
|
||||
const conn_db_handler_1 = __importDefault(require("../../../utils/db/conn-db-handler"));
|
||||
const lodash_1 = __importDefault(require("lodash"));
|
||||
const purge_default_fields_1 = __importDefault(require("../../../utils/purge-default-fields"));
|
||||
const grab_parsed_value_1 = __importDefault(require("./grab-parsed-value"));
|
||||
/**
|
||||
* # Update DB Function
|
||||
* @description
|
||||
*/
|
||||
function updateDbEntry(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ dbContext, dbFullName, tableName, data, tableSchema, identifierColumnName, identifierValue, encryptionKey, encryptionSalt, forceLocal, debug, }) {
|
||||
var _b;
|
||||
/**
|
||||
* Check if data is valid
|
||||
*/
|
||||
@@ -57,55 +54,21 @@ function updateDbEntry(_a) {
|
||||
try {
|
||||
const dataKey = dataKeys[i];
|
||||
let value = newData[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)
|
||||
const parsedValue = (0, grab_parsed_value_1.default)({
|
||||
dataKey,
|
||||
encryptionKey,
|
||||
encryptionSalt,
|
||||
tableSchema,
|
||||
value,
|
||||
});
|
||||
if (typeof parsedValue == "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));
|
||||
if (typeof parsedValue == "number") {
|
||||
updateValues.push(String(parsedValue));
|
||||
}
|
||||
else {
|
||||
updateValues.push(value);
|
||||
updateValues.push(parsedValue);
|
||||
}
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
+13
-6
@@ -21,7 +21,7 @@ function handleBackup(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ appBackup, userId, }) {
|
||||
var _b;
|
||||
const { appConfig } = (0, grab_config_1.default)();
|
||||
const maxBackups = ((_b = appConfig.main.max_backups) === null || _b === void 0 ? void 0 : _b.value) || 20;
|
||||
const maxBackups = ((_b = appConfig.main.max_backups) === null || _b === void 0 ? void 0 : _b.value) || 4;
|
||||
const { count: existingAppBackupsCount } = yield (0, grab_user_resource_1.default)({
|
||||
tableName: "backups",
|
||||
isSuperUser: true,
|
||||
@@ -36,7 +36,8 @@ function handleBackup(_a) {
|
||||
countOnly: true,
|
||||
});
|
||||
if (existingAppBackupsCount && existingAppBackupsCount >= maxBackups) {
|
||||
const { single: oldestAppBackup } = yield (0, grab_user_resource_1.default)({
|
||||
console.log(`Backups exceed Limit ...`);
|
||||
const { batch: oldestAppBackups } = yield (0, grab_user_resource_1.default)({
|
||||
tableName: "backups",
|
||||
isSuperUser: true,
|
||||
query: {
|
||||
@@ -48,13 +49,19 @@ function handleBackup(_a) {
|
||||
},
|
||||
order: {
|
||||
field: "id",
|
||||
strategy: "ASC",
|
||||
strategy: "DESC",
|
||||
},
|
||||
limit: 1,
|
||||
},
|
||||
});
|
||||
if (oldestAppBackup === null || oldestAppBackup === void 0 ? void 0 : oldestAppBackup.id) {
|
||||
yield (0, delete_backup_1.default)({ backup: oldestAppBackup });
|
||||
if (oldestAppBackups) {
|
||||
for (let i = 0; i < oldestAppBackups.length; i++) {
|
||||
const backup = oldestAppBackups[i];
|
||||
console.log(`Handling Backup ${backup.uuid} ...`);
|
||||
if (i < maxBackups - 1)
|
||||
continue;
|
||||
console.log(`Deleting Backup ${backup.uuid} ...`);
|
||||
yield (0, delete_backup_1.default)({ backup: backup });
|
||||
}
|
||||
}
|
||||
}
|
||||
yield (0, add_backup_1.default)({ targetUserId: userId });
|
||||
|
||||
+2
-1
@@ -3,6 +3,7 @@ type Param = {
|
||||
url?: string;
|
||||
method?: string;
|
||||
hostname?: string;
|
||||
host?: string;
|
||||
path?: string;
|
||||
port?: number | string;
|
||||
headers?: object;
|
||||
@@ -11,5 +12,5 @@ type Param = {
|
||||
/**
|
||||
* # Make Https Request
|
||||
*/
|
||||
export default function httpsRequest({ url, method, hostname, path, headers, body, port, scheme, }: Param): Promise<unknown>;
|
||||
export default function httpsRequest<Res extends any = any>({ url, method, hostname, host, path, headers, body, port, scheme, }: Param): Promise<Res>;
|
||||
export {};
|
||||
|
||||
+9
-21
@@ -10,17 +10,13 @@ const url_1 = require("url");
|
||||
/**
|
||||
* # Make Https Request
|
||||
*/
|
||||
function httpsRequest({ url, method, hostname, path, headers, body, port, scheme, }) {
|
||||
function httpsRequest({ url, method, hostname, host, 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,
|
||||
hostname: PARSED_URL ? PARSED_URL.hostname : host || hostname,
|
||||
port: (scheme === null || scheme === void 0 ? void 0 : scheme.match(/https/i))
|
||||
? 443
|
||||
: PARSED_URL
|
||||
@@ -34,7 +30,6 @@ function httpsRequest({ url, method, hostname, path, headers, body, port, scheme
|
||||
};
|
||||
if (path)
|
||||
requestOptions.path = path;
|
||||
// if (href) requestOptions.href = href;
|
||||
if (headers)
|
||||
requestOptions.headers = headers;
|
||||
if (body) {
|
||||
@@ -43,31 +38,24 @@ function httpsRequest({ url, method, hostname, path, headers, body, port, scheme
|
||||
? 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) => {
|
||||
: http_1.default).request(requestOptions, (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);
|
||||
try {
|
||||
res(JSON.parse(str));
|
||||
}
|
||||
catch (error) {
|
||||
res(str);
|
||||
}
|
||||
});
|
||||
response.on("error", (error) => {
|
||||
console.log("HTTP response error =>", error.message);
|
||||
|
||||
Reference in New Issue
Block a user