Updates
This commit is contained in:
+50
-67
@@ -1,76 +1,59 @@
|
||||
"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 = deleteFile;
|
||||
const grab_host_names_1 = __importDefault(require("../utils/grab-host-names"));
|
||||
import grabHostNames from "../utils/grab-host-names";
|
||||
/**
|
||||
* # Delete File via API
|
||||
*/
|
||||
function deleteFile(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ key, url, user_id, }) {
|
||||
const grabedHostNames = (0, grab_host_names_1.default)();
|
||||
const { host, port, scheme } = grabedHostNames;
|
||||
try {
|
||||
export default async function deleteFile({ key, url, user_id, }) {
|
||||
const grabedHostNames = grabHostNames();
|
||||
const { host, port, scheme } = grabedHostNames;
|
||||
try {
|
||||
/**
|
||||
* Make https request
|
||||
*
|
||||
* @description make a request to datasquirel.com
|
||||
*/
|
||||
const httpResponse = await new Promise((resolve, reject) => {
|
||||
const reqPayload = JSON.stringify({ url: url });
|
||||
const httpsRequest = scheme.request({
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Content-Length": Buffer.from(reqPayload).length,
|
||||
Authorization: key ||
|
||||
process.env.DSQL_FULL_ACCESS_API_KEY ||
|
||||
process.env.DSQL_API_KEY,
|
||||
},
|
||||
port,
|
||||
hostname: host,
|
||||
path: `/api/query/${user_id || grabedHostNames.user_id}/delete-file`,
|
||||
},
|
||||
/**
|
||||
* Make https request
|
||||
* Callback Function
|
||||
*
|
||||
* @description make a request to datasquirel.com
|
||||
* @description https request callback
|
||||
*/
|
||||
const httpResponse = yield new Promise((resolve, reject) => {
|
||||
const reqPayload = JSON.stringify({ url: url });
|
||||
const httpsRequest = scheme.request({
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Content-Length": Buffer.from(reqPayload).length,
|
||||
Authorization: key ||
|
||||
process.env.DSQL_FULL_ACCESS_API_KEY ||
|
||||
process.env.DSQL_API_KEY,
|
||||
},
|
||||
port,
|
||||
hostname: host,
|
||||
path: `/api/query/${user_id || grabedHostNames.user_id}/delete-file`,
|
||||
},
|
||||
/**
|
||||
* Callback Function
|
||||
*
|
||||
* @description https request callback
|
||||
*/
|
||||
(response) => {
|
||||
var str = "";
|
||||
response.on("data", function (chunk) {
|
||||
str += chunk;
|
||||
});
|
||||
response.on("end", function () {
|
||||
resolve(JSON.parse(str));
|
||||
});
|
||||
response.on("error", (err) => {
|
||||
reject(err);
|
||||
});
|
||||
(response) => {
|
||||
var str = "";
|
||||
response.on("data", function (chunk) {
|
||||
str += chunk;
|
||||
});
|
||||
response.on("end", function () {
|
||||
resolve(JSON.parse(str));
|
||||
});
|
||||
response.on("error", (err) => {
|
||||
reject(err);
|
||||
});
|
||||
httpsRequest.write(reqPayload);
|
||||
httpsRequest.end();
|
||||
});
|
||||
return httpResponse;
|
||||
}
|
||||
catch ( /** @type {*} */error) {
|
||||
console.log("Error deleting file: ", error.message);
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: error.message,
|
||||
};
|
||||
}
|
||||
});
|
||||
httpsRequest.write(reqPayload);
|
||||
httpsRequest.end();
|
||||
});
|
||||
return httpResponse;
|
||||
}
|
||||
catch ( /** @type {*} */error) {
|
||||
console.log("Error deleting file: ", error.message);
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: error.message,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
+1
-4
@@ -1,6 +1,3 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = getCsrfHeaderName;
|
||||
function getCsrfHeaderName() {
|
||||
export default function getCsrfHeaderName() {
|
||||
return "x-dsql-csrf-key";
|
||||
}
|
||||
|
||||
+44
-61
@@ -1,69 +1,52 @@
|
||||
"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 = getSchema;
|
||||
const grab_host_names_1 = __importDefault(require("../utils/grab-host-names"));
|
||||
import grabHostNames from "../utils/grab-host-names";
|
||||
/**
|
||||
* # Get Schema for Database, table, or field *
|
||||
*/
|
||||
function getSchema(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ key, database, field, table, user_id, env, }) {
|
||||
const grabedHostNames = (0, grab_host_names_1.default)({ env });
|
||||
const { host, port, scheme } = grabedHostNames;
|
||||
export default async function getSchema({ key, database, field, table, user_id, env, }) {
|
||||
const grabedHostNames = grabHostNames({ env });
|
||||
const { host, port, scheme } = grabedHostNames;
|
||||
/**
|
||||
* Make https request
|
||||
*
|
||||
* @description make a request to datasquirel.com
|
||||
*/
|
||||
const httpResponse = await new Promise((resolve, reject) => {
|
||||
const queryObject = { database, field, table };
|
||||
let query = Object.keys(queryObject)
|
||||
.filter((k) => queryObject[k])
|
||||
.map((k) => `${k}=${queryObject[k]}`)
|
||||
.join("&");
|
||||
scheme
|
||||
.request({
|
||||
method: "GET",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: key ||
|
||||
process.env.DSQL_FULL_ACCESS_API_KEY ||
|
||||
process.env.DSQL_API_KEY,
|
||||
},
|
||||
port,
|
||||
hostname: host,
|
||||
path: `/api/query/${user_id || grabedHostNames.user_id}/get-schema` + ((query === null || query === void 0 ? void 0 : query.match(/./)) ? `?${query}` : ""),
|
||||
},
|
||||
/**
|
||||
* Make https request
|
||||
* Callback Function
|
||||
*
|
||||
* @description make a request to datasquirel.com
|
||||
* @description https request callback
|
||||
*/
|
||||
const httpResponse = yield new Promise((resolve, reject) => {
|
||||
const queryObject = { database, field, table };
|
||||
let query = Object.keys(queryObject)
|
||||
.filter((k) => queryObject[k])
|
||||
.map((k) => `${k}=${queryObject[k]}`)
|
||||
.join("&");
|
||||
scheme
|
||||
.request({
|
||||
method: "GET",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: key ||
|
||||
process.env.DSQL_FULL_ACCESS_API_KEY ||
|
||||
process.env.DSQL_API_KEY,
|
||||
},
|
||||
port,
|
||||
hostname: host,
|
||||
path: `/api/query/${user_id || grabedHostNames.user_id}/get-schema` + ((query === null || query === void 0 ? void 0 : query.match(/./)) ? `?${query}` : ""),
|
||||
},
|
||||
/**
|
||||
* Callback Function
|
||||
*
|
||||
* @description https request callback
|
||||
*/
|
||||
(response) => {
|
||||
var str = "";
|
||||
response.on("data", function (chunk) {
|
||||
str += chunk;
|
||||
});
|
||||
response.on("end", function () {
|
||||
resolve(JSON.parse(str));
|
||||
});
|
||||
response.on("error", (err) => {
|
||||
resolve(null);
|
||||
});
|
||||
})
|
||||
.end();
|
||||
});
|
||||
return httpResponse;
|
||||
(response) => {
|
||||
var str = "";
|
||||
response.on("data", function (chunk) {
|
||||
str += chunk;
|
||||
});
|
||||
response.on("end", function () {
|
||||
resolve(JSON.parse(str));
|
||||
});
|
||||
response.on("error", (err) => {
|
||||
resolve(null);
|
||||
});
|
||||
})
|
||||
.end();
|
||||
});
|
||||
return httpResponse;
|
||||
}
|
||||
|
||||
Vendored
+107
-124
@@ -1,132 +1,115 @@
|
||||
"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 = get;
|
||||
const path_1 = __importDefault(require("path"));
|
||||
const fs_1 = __importDefault(require("fs"));
|
||||
const grab_host_names_1 = __importDefault(require("../utils/grab-host-names"));
|
||||
const get_1 = __importDefault(require("../functions/api/query/get"));
|
||||
const serialize_query_1 = __importDefault(require("../utils/serialize-query"));
|
||||
const grab_query_and_values_1 = __importDefault(require("../utils/grab-query-and-values"));
|
||||
const debug_log_1 = __importDefault(require("../utils/logging/debug-log"));
|
||||
import path from "path";
|
||||
import fs from "fs";
|
||||
import grabHostNames from "../utils/grab-host-names";
|
||||
import apiGet from "../functions/api/query/get";
|
||||
import serializeQuery from "../utils/serialize-query";
|
||||
import apiGetGrabQueryAndValues from "../utils/grab-query-and-values";
|
||||
import debugLog from "../utils/logging/debug-log";
|
||||
/**
|
||||
* # Make a get request to Datasquirel API
|
||||
*/
|
||||
function get(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ key, db, query, queryValues, tableName, user_id, debug, forceLocal, }) {
|
||||
const grabedHostNames = (0, grab_host_names_1.default)();
|
||||
const { host, port, scheme } = grabedHostNames;
|
||||
function debugFn(log, label) {
|
||||
(0, debug_log_1.default)({ log, addTime: true, title: "apiGet", label });
|
||||
export default async function get({ key, db, query, queryValues, tableName, user_id, debug, forceLocal, }) {
|
||||
const grabedHostNames = grabHostNames();
|
||||
const { host, port, scheme } = grabedHostNames;
|
||||
function debugFn(log, label) {
|
||||
debugLog({ log, addTime: true, title: "apiGet", label });
|
||||
}
|
||||
/**
|
||||
* Check for local DB settings
|
||||
*
|
||||
* @description Look for local db settings in `.env` file and by pass the http request if available
|
||||
*/
|
||||
const { DSQL_DB_NAME } = process.env;
|
||||
if ((DSQL_DB_NAME === null || DSQL_DB_NAME === void 0 ? void 0 : DSQL_DB_NAME.match(/./)) && global.DSQL_USE_LOCAL) {
|
||||
let dbSchema;
|
||||
try {
|
||||
const localDbSchemaPath = path.resolve(process.cwd(), "dsql.schema.json");
|
||||
dbSchema = JSON.parse(fs.readFileSync(localDbSchemaPath, "utf8"));
|
||||
}
|
||||
/**
|
||||
* Check for local DB settings
|
||||
*
|
||||
* @description Look for local db settings in `.env` file and by pass the http request if available
|
||||
*/
|
||||
const { DSQL_DB_NAME } = process.env;
|
||||
if ((DSQL_DB_NAME === null || DSQL_DB_NAME === void 0 ? void 0 : DSQL_DB_NAME.match(/./)) && global.DSQL_USE_LOCAL) {
|
||||
let dbSchema;
|
||||
try {
|
||||
const localDbSchemaPath = path_1.default.resolve(process.cwd(), "dsql.schema.json");
|
||||
dbSchema = JSON.parse(fs_1.default.readFileSync(localDbSchemaPath, "utf8"));
|
||||
}
|
||||
catch (error) { }
|
||||
if (debug) {
|
||||
debugFn("Running Locally ...");
|
||||
}
|
||||
return yield (0, get_1.default)({
|
||||
dbFullName: DSQL_DB_NAME,
|
||||
query,
|
||||
queryValues,
|
||||
tableName,
|
||||
dbSchema,
|
||||
debug,
|
||||
forceLocal,
|
||||
});
|
||||
catch (error) { }
|
||||
if (debug) {
|
||||
debugFn("Running Locally ...");
|
||||
}
|
||||
/**
|
||||
* Make https request
|
||||
*
|
||||
* @description make a request to datasquirel.com
|
||||
*/
|
||||
const httpResponse = yield new Promise((resolve, reject) => {
|
||||
const queryAndValues = (0, grab_query_and_values_1.default)({
|
||||
query,
|
||||
values: queryValues,
|
||||
});
|
||||
const queryObject = {
|
||||
db: process.env.DSQL_API_DB_NAME || String(db),
|
||||
query: queryAndValues.query,
|
||||
queryValues: queryAndValues.valuesString,
|
||||
tableName,
|
||||
debug,
|
||||
};
|
||||
if (debug) {
|
||||
debugFn(queryObject, "queryObject");
|
||||
}
|
||||
const queryString = (0, serialize_query_1.default)(Object.assign({}, queryObject));
|
||||
if (debug) {
|
||||
debugFn(queryString, "queryString");
|
||||
}
|
||||
let path = `/api/query/${user_id || grabedHostNames.user_id}/get${queryString}`;
|
||||
if (debug) {
|
||||
debugFn(path, "path");
|
||||
}
|
||||
const requestObject = {
|
||||
method: "GET",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: key ||
|
||||
process.env.DSQL_READ_ONLY_API_KEY ||
|
||||
process.env.DSQL_FULL_ACCESS_API_KEY ||
|
||||
process.env.DSQL_API_KEY,
|
||||
},
|
||||
port,
|
||||
hostname: host,
|
||||
path,
|
||||
};
|
||||
scheme
|
||||
.request(requestObject,
|
||||
/**
|
||||
* Callback Function
|
||||
*
|
||||
* @description https request callback
|
||||
*/
|
||||
(response) => {
|
||||
var str = "";
|
||||
response.on("data", function (chunk) {
|
||||
str += chunk;
|
||||
});
|
||||
response.on("end", function () {
|
||||
try {
|
||||
resolve(JSON.parse(str));
|
||||
}
|
||||
catch ( /** @type {any} */error) {
|
||||
reject({
|
||||
error: error.message,
|
||||
result: str,
|
||||
});
|
||||
}
|
||||
});
|
||||
response.on("error", (err) => {
|
||||
console.log("DSQL get Error,", err.message);
|
||||
resolve(null);
|
||||
});
|
||||
})
|
||||
.end();
|
||||
return await apiGet({
|
||||
dbFullName: DSQL_DB_NAME,
|
||||
query,
|
||||
queryValues,
|
||||
tableName,
|
||||
dbSchema,
|
||||
debug,
|
||||
forceLocal,
|
||||
});
|
||||
return httpResponse;
|
||||
}
|
||||
/**
|
||||
* Make https request
|
||||
*
|
||||
* @description make a request to datasquirel.com
|
||||
*/
|
||||
const httpResponse = await new Promise((resolve, reject) => {
|
||||
const queryAndValues = apiGetGrabQueryAndValues({
|
||||
query,
|
||||
values: queryValues,
|
||||
});
|
||||
const queryObject = {
|
||||
db: process.env.DSQL_API_DB_NAME || String(db),
|
||||
query: queryAndValues.query,
|
||||
queryValues: queryAndValues.valuesString,
|
||||
tableName,
|
||||
debug,
|
||||
};
|
||||
if (debug) {
|
||||
debugFn(queryObject, "queryObject");
|
||||
}
|
||||
const queryString = serializeQuery(Object.assign({}, queryObject));
|
||||
if (debug) {
|
||||
debugFn(queryString, "queryString");
|
||||
}
|
||||
let path = `/api/query/${user_id || grabedHostNames.user_id}/get${queryString}`;
|
||||
if (debug) {
|
||||
debugFn(path, "path");
|
||||
}
|
||||
const requestObject = {
|
||||
method: "GET",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: key ||
|
||||
process.env.DSQL_READ_ONLY_API_KEY ||
|
||||
process.env.DSQL_FULL_ACCESS_API_KEY ||
|
||||
process.env.DSQL_API_KEY,
|
||||
},
|
||||
port,
|
||||
hostname: host,
|
||||
path,
|
||||
};
|
||||
scheme
|
||||
.request(requestObject,
|
||||
/**
|
||||
* Callback Function
|
||||
*
|
||||
* @description https request callback
|
||||
*/
|
||||
(response) => {
|
||||
var str = "";
|
||||
response.on("data", function (chunk) {
|
||||
str += chunk;
|
||||
});
|
||||
response.on("end", function () {
|
||||
try {
|
||||
resolve(JSON.parse(str));
|
||||
}
|
||||
catch ( /** @type {any} */error) {
|
||||
reject({
|
||||
error: error.message,
|
||||
result: str,
|
||||
});
|
||||
}
|
||||
});
|
||||
response.on("error", (err) => {
|
||||
console.log("DSQL get Error,", err.message);
|
||||
resolve(null);
|
||||
});
|
||||
})
|
||||
.end();
|
||||
});
|
||||
return httpResponse;
|
||||
}
|
||||
|
||||
Vendored
+111
-128
@@ -1,149 +1,132 @@
|
||||
"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 = post;
|
||||
const path_1 = __importDefault(require("path"));
|
||||
const fs_1 = __importDefault(require("fs"));
|
||||
const grab_host_names_1 = __importDefault(require("../utils/grab-host-names"));
|
||||
const post_1 = __importDefault(require("../functions/api/query/post"));
|
||||
const debug_log_1 = __importDefault(require("../utils/logging/debug-log"));
|
||||
import path from "path";
|
||||
import fs from "fs";
|
||||
import grabHostNames from "../utils/grab-host-names";
|
||||
import apiPost from "../functions/api/query/post";
|
||||
import debugLog from "../utils/logging/debug-log";
|
||||
/**
|
||||
* # Make a post request to Datasquirel API
|
||||
*/
|
||||
function post(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ key, query, queryValues, database, tableName, user_id, forceLocal, debug, }) {
|
||||
const grabedHostNames = (0, grab_host_names_1.default)();
|
||||
const { host, port, scheme } = grabedHostNames;
|
||||
export default async function post({ key, query, queryValues, database, tableName, user_id, forceLocal, debug, }) {
|
||||
const grabedHostNames = grabHostNames();
|
||||
const { host, port, scheme } = grabedHostNames;
|
||||
if (debug) {
|
||||
debugLog({
|
||||
log: grabedHostNames,
|
||||
addTime: true,
|
||||
label: "grabedHostNames",
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Check for local DB settings
|
||||
*
|
||||
* @description Look for local db settings in `.env` file and by pass the http request if available
|
||||
*/
|
||||
const { DSQL_DB_HOST, DSQL_DB_USERNAME, DSQL_DB_PASSWORD, DSQL_DB_NAME } = process.env;
|
||||
if ((DSQL_DB_HOST === null || DSQL_DB_HOST === void 0 ? void 0 : DSQL_DB_HOST.match(/./)) &&
|
||||
(DSQL_DB_USERNAME === null || DSQL_DB_USERNAME === void 0 ? void 0 : DSQL_DB_USERNAME.match(/./)) &&
|
||||
(DSQL_DB_PASSWORD === null || DSQL_DB_PASSWORD === void 0 ? void 0 : DSQL_DB_PASSWORD.match(/./)) &&
|
||||
(DSQL_DB_NAME === null || DSQL_DB_NAME === void 0 ? void 0 : DSQL_DB_NAME.match(/./)) &&
|
||||
global.DSQL_USE_LOCAL) {
|
||||
/** @type {import("../types").DSQL_DatabaseSchemaType | undefined} */
|
||||
let dbSchema;
|
||||
try {
|
||||
const localDbSchemaPath = path.resolve(process.cwd(), "dsql.schema.json");
|
||||
dbSchema = JSON.parse(fs.readFileSync(localDbSchemaPath, "utf8"));
|
||||
}
|
||||
catch (error) { }
|
||||
if (debug) {
|
||||
(0, debug_log_1.default)({
|
||||
log: grabedHostNames,
|
||||
debugLog({
|
||||
log: "Using Local DB ...",
|
||||
addTime: true,
|
||||
label: "grabedHostNames",
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Check for local DB settings
|
||||
*
|
||||
* @description Look for local db settings in `.env` file and by pass the http request if available
|
||||
*/
|
||||
const { DSQL_DB_HOST, DSQL_DB_USERNAME, DSQL_DB_PASSWORD, DSQL_DB_NAME } = process.env;
|
||||
if ((DSQL_DB_HOST === null || DSQL_DB_HOST === void 0 ? void 0 : DSQL_DB_HOST.match(/./)) &&
|
||||
(DSQL_DB_USERNAME === null || DSQL_DB_USERNAME === void 0 ? void 0 : DSQL_DB_USERNAME.match(/./)) &&
|
||||
(DSQL_DB_PASSWORD === null || DSQL_DB_PASSWORD === void 0 ? void 0 : DSQL_DB_PASSWORD.match(/./)) &&
|
||||
(DSQL_DB_NAME === null || DSQL_DB_NAME === void 0 ? void 0 : DSQL_DB_NAME.match(/./)) &&
|
||||
global.DSQL_USE_LOCAL) {
|
||||
/** @type {import("../types").DSQL_DatabaseSchemaType | undefined} */
|
||||
let dbSchema;
|
||||
try {
|
||||
const localDbSchemaPath = path_1.default.resolve(process.cwd(), "dsql.schema.json");
|
||||
dbSchema = JSON.parse(fs_1.default.readFileSync(localDbSchemaPath, "utf8"));
|
||||
}
|
||||
catch (error) { }
|
||||
if (debug) {
|
||||
(0, debug_log_1.default)({
|
||||
log: "Using Local DB ...",
|
||||
addTime: true,
|
||||
});
|
||||
}
|
||||
return yield (0, post_1.default)({
|
||||
dbFullName: DSQL_DB_NAME,
|
||||
query,
|
||||
dbSchema,
|
||||
queryValues,
|
||||
tableName,
|
||||
forceLocal,
|
||||
debug,
|
||||
});
|
||||
return await apiPost({
|
||||
dbFullName: database || DSQL_DB_NAME,
|
||||
query,
|
||||
dbSchema,
|
||||
queryValues,
|
||||
tableName,
|
||||
forceLocal,
|
||||
debug,
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Make https request
|
||||
*
|
||||
* @description make a request to datasquirel.com
|
||||
*/
|
||||
const httpResponse = await new Promise((resolve, reject) => {
|
||||
var _a;
|
||||
const reqPayloadString = JSON.stringify({
|
||||
query,
|
||||
queryValues,
|
||||
database: process.env.DSQL_API_DB_NAME || database,
|
||||
tableName: tableName ? tableName : null,
|
||||
}).replace(/\n|\r|\n\r/gm, "");
|
||||
try {
|
||||
JSON.parse(reqPayloadString);
|
||||
}
|
||||
catch (error) {
|
||||
(_a = global.ERROR_CALLBACK) === null || _a === void 0 ? void 0 : _a.call(global, `Error Parsing HTTP response for post action`, error);
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
error: "Query object is invalid. Please Check query data values",
|
||||
};
|
||||
}
|
||||
const reqPayload = reqPayloadString;
|
||||
const requPath = `/api/query/${user_id || grabedHostNames.user_id}/post`;
|
||||
const httpsRequest = scheme.request({
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Content-Length": Buffer.from(reqPayload).length,
|
||||
Authorization: key ||
|
||||
process.env.DSQL_FULL_ACCESS_API_KEY ||
|
||||
process.env.DSQL_API_KEY,
|
||||
},
|
||||
port,
|
||||
hostname: host,
|
||||
path: requPath,
|
||||
},
|
||||
/**
|
||||
* Make https request
|
||||
* Callback Function
|
||||
*
|
||||
* @description make a request to datasquirel.com
|
||||
* @description https request callback
|
||||
*/
|
||||
const httpResponse = yield new Promise((resolve, reject) => {
|
||||
var _a;
|
||||
const reqPayloadString = JSON.stringify({
|
||||
query,
|
||||
queryValues,
|
||||
database: process.env.DSQL_API_DB_NAME || database,
|
||||
tableName: tableName ? tableName : null,
|
||||
}).replace(/\n|\r|\n\r/gm, "");
|
||||
try {
|
||||
JSON.parse(reqPayloadString);
|
||||
}
|
||||
catch (error) {
|
||||
(_a = global.ERROR_CALLBACK) === null || _a === void 0 ? void 0 : _a.call(global, `Error Parsing HTTP response for post action`, error);
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
error: "Query object is invalid. Please Check query data values",
|
||||
};
|
||||
}
|
||||
const reqPayload = reqPayloadString;
|
||||
const requPath = `/api/query/${user_id || grabedHostNames.user_id}/post`;
|
||||
const httpsRequest = scheme.request({
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Content-Length": Buffer.from(reqPayload).length,
|
||||
Authorization: key ||
|
||||
process.env.DSQL_FULL_ACCESS_API_KEY ||
|
||||
process.env.DSQL_API_KEY,
|
||||
},
|
||||
port,
|
||||
hostname: host,
|
||||
path: requPath,
|
||||
},
|
||||
/**
|
||||
* Callback Function
|
||||
*
|
||||
* @description https request callback
|
||||
*/
|
||||
(response) => {
|
||||
var str = "";
|
||||
response.on("data", function (chunk) {
|
||||
str += chunk;
|
||||
});
|
||||
response.on("end", function () {
|
||||
try {
|
||||
resolve(JSON.parse(str));
|
||||
}
|
||||
catch (error) {
|
||||
console.log("Route ERROR:", error.message);
|
||||
resolve({
|
||||
success: false,
|
||||
payload: null,
|
||||
error: error.message,
|
||||
errPayload: str,
|
||||
});
|
||||
}
|
||||
});
|
||||
response.on("error", (err) => {
|
||||
(response) => {
|
||||
var str = "";
|
||||
response.on("data", function (chunk) {
|
||||
str += chunk;
|
||||
});
|
||||
response.on("end", function () {
|
||||
try {
|
||||
resolve(JSON.parse(str));
|
||||
}
|
||||
catch (error) {
|
||||
console.log("Route ERROR:", error.message);
|
||||
resolve({
|
||||
success: false,
|
||||
payload: null,
|
||||
error: err.message,
|
||||
error: error.message,
|
||||
errPayload: str,
|
||||
});
|
||||
}
|
||||
});
|
||||
response.on("error", (err) => {
|
||||
resolve({
|
||||
success: false,
|
||||
payload: null,
|
||||
error: err.message,
|
||||
});
|
||||
});
|
||||
httpsRequest.write(reqPayload);
|
||||
httpsRequest.on("error", (error) => {
|
||||
console.log("HTTPS request ERROR =>", error);
|
||||
});
|
||||
httpsRequest.end();
|
||||
});
|
||||
return httpResponse;
|
||||
httpsRequest.write(reqPayload);
|
||||
httpsRequest.on("error", (error) => {
|
||||
console.log("HTTPS request ERROR =>", error);
|
||||
});
|
||||
httpsRequest.end();
|
||||
});
|
||||
return httpResponse;
|
||||
}
|
||||
|
||||
+52
-69
@@ -1,78 +1,61 @@
|
||||
"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 = uploadImage;
|
||||
const grab_host_names_1 = __importDefault(require("../utils/grab-host-names"));
|
||||
import grabHostNames from "../utils/grab-host-names";
|
||||
/**
|
||||
* # Upload File via API
|
||||
*/
|
||||
function uploadImage(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ key, payload, user_id, useDefault, }) {
|
||||
var _b;
|
||||
const grabedHostNames = (0, grab_host_names_1.default)({ useDefault });
|
||||
const { host, port, scheme } = grabedHostNames;
|
||||
try {
|
||||
export default async function uploadImage({ key, payload, user_id, useDefault, }) {
|
||||
var _a;
|
||||
const grabedHostNames = grabHostNames({ useDefault });
|
||||
const { host, port, scheme } = grabedHostNames;
|
||||
try {
|
||||
/**
|
||||
* Make https request
|
||||
*
|
||||
* @description make a request to datasquirel.com
|
||||
*/
|
||||
const httpResponse = await new Promise((resolve, reject) => {
|
||||
const reqPayload = JSON.stringify(payload);
|
||||
const httpsRequest = scheme.request({
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Content-Length": Buffer.from(reqPayload).length,
|
||||
Authorization: key ||
|
||||
process.env.DSQL_FULL_ACCESS_API_KEY ||
|
||||
process.env.DSQL_API_KEY,
|
||||
},
|
||||
port,
|
||||
hostname: host,
|
||||
path: `/api/query/${user_id || grabedHostNames.user_id}/add-file`,
|
||||
},
|
||||
/**
|
||||
* Make https request
|
||||
* Callback Function
|
||||
*
|
||||
* @description make a request to datasquirel.com
|
||||
* @description https request callback
|
||||
*/
|
||||
const httpResponse = yield new Promise((resolve, reject) => {
|
||||
const reqPayload = JSON.stringify(payload);
|
||||
const httpsRequest = scheme.request({
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Content-Length": Buffer.from(reqPayload).length,
|
||||
Authorization: key ||
|
||||
process.env.DSQL_FULL_ACCESS_API_KEY ||
|
||||
process.env.DSQL_API_KEY,
|
||||
},
|
||||
port,
|
||||
hostname: host,
|
||||
path: `/api/query/${user_id || grabedHostNames.user_id}/add-file`,
|
||||
},
|
||||
/**
|
||||
* Callback Function
|
||||
*
|
||||
* @description https request callback
|
||||
*/
|
||||
(response) => {
|
||||
var str = "";
|
||||
response.on("data", function (chunk) {
|
||||
str += chunk;
|
||||
});
|
||||
response.on("end", function () {
|
||||
resolve(JSON.parse(str));
|
||||
});
|
||||
response.on("error", (err) => {
|
||||
reject(err);
|
||||
});
|
||||
(response) => {
|
||||
var str = "";
|
||||
response.on("data", function (chunk) {
|
||||
str += chunk;
|
||||
});
|
||||
response.on("end", function () {
|
||||
resolve(JSON.parse(str));
|
||||
});
|
||||
response.on("error", (err) => {
|
||||
reject(err);
|
||||
});
|
||||
httpsRequest.write(reqPayload);
|
||||
httpsRequest.end();
|
||||
});
|
||||
return httpResponse;
|
||||
}
|
||||
catch (error) {
|
||||
console.log("Error in uploading file: ", error.message);
|
||||
(_b = global.ERROR_CALLBACK) === null || _b === void 0 ? void 0 : _b.call(global, `Error Uploading File`, error);
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: error.message,
|
||||
};
|
||||
}
|
||||
});
|
||||
httpsRequest.write(reqPayload);
|
||||
httpsRequest.end();
|
||||
});
|
||||
return httpResponse;
|
||||
}
|
||||
catch (error) {
|
||||
console.log("Error in uploading file: ", error.message);
|
||||
(_a = global.ERROR_CALLBACK) === null || _a === void 0 ? void 0 : _a.call(global, `Error Uploading File`, error);
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: error.message,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
+52
-69
@@ -1,78 +1,61 @@
|
||||
"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 = uploadImage;
|
||||
const grab_host_names_1 = __importDefault(require("../utils/grab-host-names"));
|
||||
import grabHostNames from "../utils/grab-host-names";
|
||||
/**
|
||||
* # Upload Image via API
|
||||
*/
|
||||
function uploadImage(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ key, payload, user_id, useDefault, }) {
|
||||
var _b;
|
||||
const grabedHostNames = (0, grab_host_names_1.default)({ useDefault });
|
||||
const { host, port, scheme } = grabedHostNames;
|
||||
try {
|
||||
export default async function uploadImage({ key, payload, user_id, useDefault, }) {
|
||||
var _a;
|
||||
const grabedHostNames = grabHostNames({ useDefault });
|
||||
const { host, port, scheme } = grabedHostNames;
|
||||
try {
|
||||
/**
|
||||
* Make https request
|
||||
*
|
||||
* @description make a request to datasquirel.com
|
||||
*/
|
||||
const httpResponse = await new Promise((resolve, reject) => {
|
||||
const reqPayload = JSON.stringify(payload);
|
||||
const httpsRequest = scheme.request({
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Content-Length": Buffer.from(reqPayload).length,
|
||||
Authorization: key ||
|
||||
process.env.DSQL_FULL_ACCESS_API_KEY ||
|
||||
process.env.DSQL_API_KEY,
|
||||
},
|
||||
port,
|
||||
hostname: host,
|
||||
path: `/api/query/${user_id || grabedHostNames.user_id}/add-image`,
|
||||
},
|
||||
/**
|
||||
* Make https request
|
||||
* Callback Function
|
||||
*
|
||||
* @description make a request to datasquirel.com
|
||||
* @description https request callback
|
||||
*/
|
||||
const httpResponse = yield new Promise((resolve, reject) => {
|
||||
const reqPayload = JSON.stringify(payload);
|
||||
const httpsRequest = scheme.request({
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Content-Length": Buffer.from(reqPayload).length,
|
||||
Authorization: key ||
|
||||
process.env.DSQL_FULL_ACCESS_API_KEY ||
|
||||
process.env.DSQL_API_KEY,
|
||||
},
|
||||
port,
|
||||
hostname: host,
|
||||
path: `/api/query/${user_id || grabedHostNames.user_id}/add-image`,
|
||||
},
|
||||
/**
|
||||
* Callback Function
|
||||
*
|
||||
* @description https request callback
|
||||
*/
|
||||
(response) => {
|
||||
var str = "";
|
||||
response.on("data", function (chunk) {
|
||||
str += chunk;
|
||||
});
|
||||
response.on("end", function () {
|
||||
resolve(JSON.parse(str));
|
||||
});
|
||||
response.on("error", (err) => {
|
||||
reject(err);
|
||||
});
|
||||
(response) => {
|
||||
var str = "";
|
||||
response.on("data", function (chunk) {
|
||||
str += chunk;
|
||||
});
|
||||
response.on("end", function () {
|
||||
resolve(JSON.parse(str));
|
||||
});
|
||||
response.on("error", (err) => {
|
||||
reject(err);
|
||||
});
|
||||
httpsRequest.write(reqPayload);
|
||||
httpsRequest.end();
|
||||
});
|
||||
return httpResponse;
|
||||
}
|
||||
catch (error) {
|
||||
console.log("Error in uploading image: ", error.message);
|
||||
(_b = global.ERROR_CALLBACK) === null || _b === void 0 ? void 0 : _b.call(global, `Error Uploading Image`, error);
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: error.message,
|
||||
};
|
||||
}
|
||||
});
|
||||
httpsRequest.write(reqPayload);
|
||||
httpsRequest.end();
|
||||
});
|
||||
return httpResponse;
|
||||
}
|
||||
catch (error) {
|
||||
console.log("Error in uploading image: ", error.message);
|
||||
(_a = global.ERROR_CALLBACK) === null || _a === void 0 ? void 0 : _a.call(global, `Error Uploading Image`, error);
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: error.message,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
+74
-91
@@ -1,98 +1,81 @@
|
||||
"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 = addUser;
|
||||
const path_1 = __importDefault(require("path"));
|
||||
const fs_1 = __importDefault(require("fs"));
|
||||
const grab_host_names_1 = __importDefault(require("../../utils/grab-host-names"));
|
||||
const api_create_user_1 = __importDefault(require("../../functions/api/users/api-create-user"));
|
||||
import path from "path";
|
||||
import fs from "fs";
|
||||
import grabHostNames from "../../utils/grab-host-names";
|
||||
import apiCreateUser from "../../functions/api/users/api-create-user";
|
||||
/**
|
||||
* # Add User to Database
|
||||
*/
|
||||
function addUser(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ key, payload, database, encryptionKey, user_id, apiUserId, }) {
|
||||
/**
|
||||
* Check for local DB settings
|
||||
*
|
||||
* @description Look for local db settings in `.env` file and by pass the http request if available
|
||||
*/
|
||||
const { DSQL_DB_HOST, DSQL_DB_USERNAME, DSQL_DB_PASSWORD, DSQL_DB_NAME, DSQL_API_USER_ID, } = process.env;
|
||||
const grabedHostNames = (0, grab_host_names_1.default)();
|
||||
const { host, port, scheme } = grabedHostNames;
|
||||
if ((DSQL_DB_HOST === null || DSQL_DB_HOST === void 0 ? void 0 : DSQL_DB_HOST.match(/./)) &&
|
||||
(DSQL_DB_USERNAME === null || DSQL_DB_USERNAME === void 0 ? void 0 : DSQL_DB_USERNAME.match(/./)) &&
|
||||
(DSQL_DB_PASSWORD === null || DSQL_DB_PASSWORD === void 0 ? void 0 : DSQL_DB_PASSWORD.match(/./)) &&
|
||||
(DSQL_DB_NAME === null || DSQL_DB_NAME === void 0 ? void 0 : DSQL_DB_NAME.match(/./)) &&
|
||||
global.DSQL_USE_LOCAL) {
|
||||
/** @type {import("../../types").DSQL_DatabaseSchemaType | undefined} */
|
||||
let dbSchema;
|
||||
try {
|
||||
const localDbSchemaPath = path_1.default.resolve(process.cwd(), "dsql.schema.json");
|
||||
dbSchema = JSON.parse(fs_1.default.readFileSync(localDbSchemaPath, "utf8"));
|
||||
}
|
||||
catch (error) { }
|
||||
return yield (0, api_create_user_1.default)({
|
||||
database: DSQL_DB_NAME,
|
||||
encryptionKey,
|
||||
payload,
|
||||
userId: apiUserId,
|
||||
});
|
||||
export default async function addUser({ key, payload, database, encryptionKey, user_id, apiUserId, }) {
|
||||
/**
|
||||
* Check for local DB settings
|
||||
*
|
||||
* @description Look for local db settings in `.env` file and by pass the http request if available
|
||||
*/
|
||||
const { DSQL_DB_HOST, DSQL_DB_USERNAME, DSQL_DB_PASSWORD, DSQL_DB_NAME, DSQL_API_USER_ID, } = process.env;
|
||||
const grabedHostNames = grabHostNames();
|
||||
const { host, port, scheme } = grabedHostNames;
|
||||
if ((DSQL_DB_HOST === null || DSQL_DB_HOST === void 0 ? void 0 : DSQL_DB_HOST.match(/./)) &&
|
||||
(DSQL_DB_USERNAME === null || DSQL_DB_USERNAME === void 0 ? void 0 : DSQL_DB_USERNAME.match(/./)) &&
|
||||
(DSQL_DB_PASSWORD === null || DSQL_DB_PASSWORD === void 0 ? void 0 : DSQL_DB_PASSWORD.match(/./)) &&
|
||||
(DSQL_DB_NAME === null || DSQL_DB_NAME === void 0 ? void 0 : DSQL_DB_NAME.match(/./)) &&
|
||||
global.DSQL_USE_LOCAL) {
|
||||
/** @type {import("../../types").DSQL_DatabaseSchemaType | undefined} */
|
||||
let dbSchema;
|
||||
try {
|
||||
const localDbSchemaPath = path.resolve(process.cwd(), "dsql.schema.json");
|
||||
dbSchema = JSON.parse(fs.readFileSync(localDbSchemaPath, "utf8"));
|
||||
}
|
||||
/**
|
||||
* Make https request
|
||||
*
|
||||
* @description make a request to datasquirel.com
|
||||
*/
|
||||
const httpResponse = yield new Promise((resolve, reject) => {
|
||||
const reqPayload = JSON.stringify({
|
||||
payload,
|
||||
database,
|
||||
encryptionKey,
|
||||
});
|
||||
const httpsRequest = scheme.request({
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Content-Length": Buffer.from(reqPayload).length,
|
||||
Authorization: key ||
|
||||
process.env.DSQL_FULL_ACCESS_API_KEY ||
|
||||
process.env.DSQL_API_KEY,
|
||||
},
|
||||
port,
|
||||
hostname: host,
|
||||
path: `/api/user/${user_id || grabedHostNames.user_id}/add-user`,
|
||||
},
|
||||
/**
|
||||
* Callback Function
|
||||
*
|
||||
* @description https request callback
|
||||
*/
|
||||
(response) => {
|
||||
var str = "";
|
||||
response.on("data", function (chunk) {
|
||||
str += chunk;
|
||||
});
|
||||
response.on("end", function () {
|
||||
resolve(JSON.parse(str));
|
||||
});
|
||||
response.on("error", (err) => {
|
||||
reject(err);
|
||||
});
|
||||
});
|
||||
httpsRequest.write(reqPayload);
|
||||
httpsRequest.end();
|
||||
catch (error) { }
|
||||
return await apiCreateUser({
|
||||
database: DSQL_DB_NAME,
|
||||
encryptionKey,
|
||||
payload,
|
||||
userId: apiUserId,
|
||||
});
|
||||
return httpResponse;
|
||||
}
|
||||
/**
|
||||
* Make https request
|
||||
*
|
||||
* @description make a request to datasquirel.com
|
||||
*/
|
||||
const httpResponse = await new Promise((resolve, reject) => {
|
||||
const reqPayload = JSON.stringify({
|
||||
payload,
|
||||
database,
|
||||
encryptionKey,
|
||||
});
|
||||
const httpsRequest = scheme.request({
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Content-Length": Buffer.from(reqPayload).length,
|
||||
Authorization: key ||
|
||||
process.env.DSQL_FULL_ACCESS_API_KEY ||
|
||||
process.env.DSQL_API_KEY,
|
||||
},
|
||||
port,
|
||||
hostname: host,
|
||||
path: `/api/user/${user_id || grabedHostNames.user_id}/add-user`,
|
||||
},
|
||||
/**
|
||||
* Callback Function
|
||||
*
|
||||
* @description https request callback
|
||||
*/
|
||||
(response) => {
|
||||
var str = "";
|
||||
response.on("data", function (chunk) {
|
||||
str += chunk;
|
||||
});
|
||||
response.on("end", function () {
|
||||
resolve(JSON.parse(str));
|
||||
});
|
||||
response.on("error", (err) => {
|
||||
reject(err);
|
||||
});
|
||||
});
|
||||
httpsRequest.write(reqPayload);
|
||||
httpsRequest.end();
|
||||
});
|
||||
return httpResponse;
|
||||
}
|
||||
|
||||
+68
-85
@@ -1,95 +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 = deleteUser;
|
||||
const path_1 = __importDefault(require("path"));
|
||||
const fs_1 = __importDefault(require("fs"));
|
||||
const grab_host_names_1 = __importDefault(require("../../utils/grab-host-names"));
|
||||
const api_delete_user_1 = __importDefault(require("../../functions/api/users/api-delete-user"));
|
||||
import path from "path";
|
||||
import fs from "fs";
|
||||
import grabHostNames from "../../utils/grab-host-names";
|
||||
import apiDeleteUser from "../../functions/api/users/api-delete-user";
|
||||
/**
|
||||
* # Update User
|
||||
*/
|
||||
function deleteUser(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ key, database, user_id, deletedUserId, }) {
|
||||
/**
|
||||
* Check for local DB settings
|
||||
*
|
||||
* @description Look for local db settings in `.env` file and by pass the http request if available
|
||||
*/
|
||||
const { DSQL_DB_HOST, DSQL_DB_USERNAME, DSQL_DB_PASSWORD, DSQL_DB_NAME } = process.env;
|
||||
const grabedHostNames = (0, grab_host_names_1.default)();
|
||||
const { host, port, scheme } = grabedHostNames;
|
||||
if ((DSQL_DB_HOST === null || DSQL_DB_HOST === void 0 ? void 0 : DSQL_DB_HOST.match(/./)) &&
|
||||
(DSQL_DB_USERNAME === null || DSQL_DB_USERNAME === void 0 ? void 0 : DSQL_DB_USERNAME.match(/./)) &&
|
||||
(DSQL_DB_PASSWORD === null || DSQL_DB_PASSWORD === void 0 ? void 0 : DSQL_DB_PASSWORD.match(/./)) &&
|
||||
(DSQL_DB_NAME === null || DSQL_DB_NAME === void 0 ? void 0 : DSQL_DB_NAME.match(/./)) &&
|
||||
global.DSQL_USE_LOCAL) {
|
||||
/** @type {import("../../types").DSQL_DatabaseSchemaType | undefined} */
|
||||
let dbSchema;
|
||||
try {
|
||||
const localDbSchemaPath = path_1.default.resolve(process.cwd(), "dsql.schema.json");
|
||||
dbSchema = JSON.parse(fs_1.default.readFileSync(localDbSchemaPath, "utf8"));
|
||||
}
|
||||
catch (error) { }
|
||||
return yield (0, api_delete_user_1.default)({
|
||||
dbFullName: DSQL_DB_NAME,
|
||||
deletedUserId,
|
||||
});
|
||||
export default async function deleteUser({ key, database, user_id, deletedUserId, }) {
|
||||
/**
|
||||
* Check for local DB settings
|
||||
*
|
||||
* @description Look for local db settings in `.env` file and by pass the http request if available
|
||||
*/
|
||||
const { DSQL_DB_HOST, DSQL_DB_USERNAME, DSQL_DB_PASSWORD, DSQL_DB_NAME } = process.env;
|
||||
const grabedHostNames = grabHostNames();
|
||||
const { host, port, scheme } = grabedHostNames;
|
||||
if ((DSQL_DB_HOST === null || DSQL_DB_HOST === void 0 ? void 0 : DSQL_DB_HOST.match(/./)) &&
|
||||
(DSQL_DB_USERNAME === null || DSQL_DB_USERNAME === void 0 ? void 0 : DSQL_DB_USERNAME.match(/./)) &&
|
||||
(DSQL_DB_PASSWORD === null || DSQL_DB_PASSWORD === void 0 ? void 0 : DSQL_DB_PASSWORD.match(/./)) &&
|
||||
(DSQL_DB_NAME === null || DSQL_DB_NAME === void 0 ? void 0 : DSQL_DB_NAME.match(/./)) &&
|
||||
global.DSQL_USE_LOCAL) {
|
||||
/** @type {import("../../types").DSQL_DatabaseSchemaType | undefined} */
|
||||
let dbSchema;
|
||||
try {
|
||||
const localDbSchemaPath = path.resolve(process.cwd(), "dsql.schema.json");
|
||||
dbSchema = JSON.parse(fs.readFileSync(localDbSchemaPath, "utf8"));
|
||||
}
|
||||
catch (error) { }
|
||||
return await apiDeleteUser({
|
||||
dbFullName: DSQL_DB_NAME,
|
||||
deletedUserId,
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Make https request
|
||||
*
|
||||
* @description make a request to datasquirel.com
|
||||
*/
|
||||
const httpResponse = (await new Promise((resolve, reject) => {
|
||||
const reqPayload = JSON.stringify({
|
||||
database,
|
||||
deletedUserId,
|
||||
});
|
||||
const httpsRequest = scheme.request({
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Content-Length": Buffer.from(reqPayload).length,
|
||||
Authorization: process.env.DSQL_FULL_ACCESS_API_KEY ||
|
||||
process.env.DSQL_API_KEY ||
|
||||
key,
|
||||
},
|
||||
port,
|
||||
hostname: host,
|
||||
path: `/api/user/${user_id || grabedHostNames.user_id}/delete-user`,
|
||||
},
|
||||
/**
|
||||
* Make https request
|
||||
* Callback Function
|
||||
*
|
||||
* @description make a request to datasquirel.com
|
||||
* @description https request callback
|
||||
*/
|
||||
const httpResponse = (yield new Promise((resolve, reject) => {
|
||||
const reqPayload = JSON.stringify({
|
||||
database,
|
||||
deletedUserId,
|
||||
(response) => {
|
||||
var str = "";
|
||||
response.on("data", function (chunk) {
|
||||
str += chunk;
|
||||
});
|
||||
const httpsRequest = scheme.request({
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Content-Length": Buffer.from(reqPayload).length,
|
||||
Authorization: process.env.DSQL_FULL_ACCESS_API_KEY ||
|
||||
process.env.DSQL_API_KEY ||
|
||||
key,
|
||||
},
|
||||
port,
|
||||
hostname: host,
|
||||
path: `/api/user/${user_id || grabedHostNames.user_id}/delete-user`,
|
||||
},
|
||||
/**
|
||||
* Callback Function
|
||||
*
|
||||
* @description https request callback
|
||||
*/
|
||||
(response) => {
|
||||
var str = "";
|
||||
response.on("data", function (chunk) {
|
||||
str += chunk;
|
||||
});
|
||||
response.on("end", function () {
|
||||
resolve(JSON.parse(str));
|
||||
});
|
||||
response.on("error", (err) => {
|
||||
reject(err);
|
||||
});
|
||||
response.on("end", function () {
|
||||
resolve(JSON.parse(str));
|
||||
});
|
||||
httpsRequest.write(reqPayload);
|
||||
httpsRequest.end();
|
||||
}));
|
||||
return httpResponse;
|
||||
});
|
||||
response.on("error", (err) => {
|
||||
reject(err);
|
||||
});
|
||||
});
|
||||
httpsRequest.write(reqPayload);
|
||||
httpsRequest.end();
|
||||
}));
|
||||
return httpResponse;
|
||||
}
|
||||
|
||||
+7
-13
@@ -1,19 +1,13 @@
|
||||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = getToken;
|
||||
const decrypt_1 = __importDefault(require("../../functions/dsql/decrypt"));
|
||||
const get_auth_cookie_names_1 = __importDefault(require("../../functions/backend/cookies/get-auth-cookie-names"));
|
||||
const parseCookies_1 = __importDefault(require("../../utils/backend/parseCookies"));
|
||||
import decrypt from "../../functions/dsql/decrypt";
|
||||
import getAuthCookieNames from "../../functions/backend/cookies/get-auth-cookie-names";
|
||||
import parseCookies from "../../utils/backend/parseCookies";
|
||||
/**
|
||||
* Get just the access token for user
|
||||
* ==============================================================================
|
||||
* @description This Function takes in a request object and returns a user token
|
||||
* string and csrf token string
|
||||
*/
|
||||
function getToken({ request, encryptionKey, encryptionSalt, cookieString, }) {
|
||||
export default function getToken({ request, encryptionKey, encryptionSalt, cookieString, }) {
|
||||
var _a;
|
||||
try {
|
||||
/**
|
||||
@@ -21,8 +15,8 @@ function getToken({ request, encryptionKey, encryptionSalt, cookieString, }) {
|
||||
*
|
||||
* @description Grab the payload
|
||||
*/
|
||||
const cookies = (0, parseCookies_1.default)({ request, cookieString });
|
||||
const keynames = (0, get_auth_cookie_names_1.default)();
|
||||
const cookies = parseCookies({ request, cookieString });
|
||||
const keynames = getAuthCookieNames();
|
||||
const authKeyName = keynames.keyCookieName;
|
||||
const csrfName = keynames.csrfCookieName;
|
||||
const key = cookies[authKeyName];
|
||||
@@ -32,7 +26,7 @@ function getToken({ request, encryptionKey, encryptionSalt, cookieString, }) {
|
||||
*
|
||||
* @description Grab the payload
|
||||
*/
|
||||
let userPayload = (0, decrypt_1.default)({
|
||||
let userPayload = decrypt({
|
||||
encryptedString: key,
|
||||
encryptionKey,
|
||||
encryptionSalt,
|
||||
|
||||
+98
-115
@@ -1,120 +1,103 @@
|
||||
"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 = getUser;
|
||||
const path_1 = __importDefault(require("path"));
|
||||
const fs_1 = __importDefault(require("fs"));
|
||||
const grab_host_names_1 = __importDefault(require("../../utils/grab-host-names"));
|
||||
const api_get_user_1 = __importDefault(require("../../functions/api/users/api-get-user"));
|
||||
import path from "path";
|
||||
import fs from "fs";
|
||||
import grabHostNames from "../../utils/grab-host-names";
|
||||
import apiGetUser from "../../functions/api/users/api-get-user";
|
||||
/**
|
||||
* # Get User
|
||||
*/
|
||||
function getUser(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ key, userId, database, fields, apiUserId, }) {
|
||||
/**
|
||||
* Initialize
|
||||
*/
|
||||
const defaultFields = [
|
||||
"id",
|
||||
"first_name",
|
||||
"last_name",
|
||||
"email",
|
||||
"username",
|
||||
"image",
|
||||
"image_thumbnail",
|
||||
"verification_status",
|
||||
"date_created",
|
||||
"date_created_code",
|
||||
"date_created_timestamp",
|
||||
"date_updated",
|
||||
"date_updated_code",
|
||||
"date_updated_timestamp",
|
||||
];
|
||||
const updatedFields = fields && fields[0] ? [...defaultFields, ...fields] : defaultFields;
|
||||
const reqPayload = JSON.stringify({
|
||||
userId,
|
||||
database,
|
||||
fields: [...new Set(updatedFields)],
|
||||
});
|
||||
const grabedHostNames = (0, grab_host_names_1.default)();
|
||||
const { host, port, scheme } = grabedHostNames;
|
||||
/**
|
||||
* Check for local DB settings
|
||||
*
|
||||
* @description Look for local db settings in `.env` file and by pass the http request if available
|
||||
*/
|
||||
const { DSQL_DB_HOST, DSQL_DB_USERNAME, DSQL_DB_PASSWORD, DSQL_DB_NAME } = process.env;
|
||||
if ((DSQL_DB_HOST === null || DSQL_DB_HOST === void 0 ? void 0 : DSQL_DB_HOST.match(/./)) &&
|
||||
(DSQL_DB_USERNAME === null || DSQL_DB_USERNAME === void 0 ? void 0 : DSQL_DB_USERNAME.match(/./)) &&
|
||||
(DSQL_DB_PASSWORD === null || DSQL_DB_PASSWORD === void 0 ? void 0 : DSQL_DB_PASSWORD.match(/./)) &&
|
||||
(DSQL_DB_NAME === null || DSQL_DB_NAME === void 0 ? void 0 : DSQL_DB_NAME.match(/./)) &&
|
||||
global.DSQL_USE_LOCAL) {
|
||||
/** @type {import("../../types").DSQL_DatabaseSchemaType | undefined} */
|
||||
let dbSchema;
|
||||
try {
|
||||
const localDbSchemaPath = path_1.default.resolve(process.cwd(), "dsql.schema.json");
|
||||
dbSchema = JSON.parse(fs_1.default.readFileSync(localDbSchemaPath, "utf8"));
|
||||
}
|
||||
catch (error) { }
|
||||
return yield (0, api_get_user_1.default)({
|
||||
userId,
|
||||
fields: [...new Set(updatedFields)],
|
||||
dbFullName: DSQL_DB_NAME,
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Make https request
|
||||
*
|
||||
* @description make a request to datasquirel.com
|
||||
*/
|
||||
const httpResponse = yield new Promise((resolve, reject) => {
|
||||
const httpsRequest = scheme.request({
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Content-Length": Buffer.from(reqPayload).length,
|
||||
Authorization: key ||
|
||||
process.env.DSQL_FULL_ACCESS_API_KEY ||
|
||||
process.env.DSQL_API_KEY,
|
||||
},
|
||||
port,
|
||||
hostname: host,
|
||||
path: `/api/user/${apiUserId || grabedHostNames.user_id}/get-user`,
|
||||
},
|
||||
/**
|
||||
* Callback Function
|
||||
*
|
||||
* @description https request callback
|
||||
*/
|
||||
(response) => {
|
||||
var str = "";
|
||||
response.on("data", function (chunk) {
|
||||
str += chunk;
|
||||
});
|
||||
response.on("end", function () {
|
||||
resolve(JSON.parse(str));
|
||||
});
|
||||
response.on("error", (err) => {
|
||||
reject(err);
|
||||
});
|
||||
});
|
||||
httpsRequest.write(reqPayload);
|
||||
httpsRequest.end();
|
||||
});
|
||||
/** ********************************************** */
|
||||
/** ********************************************** */
|
||||
/** ********************************************** */
|
||||
return httpResponse;
|
||||
export default async function getUser({ key, userId, database, fields, apiUserId, }) {
|
||||
/**
|
||||
* Initialize
|
||||
*/
|
||||
const defaultFields = [
|
||||
"id",
|
||||
"first_name",
|
||||
"last_name",
|
||||
"email",
|
||||
"username",
|
||||
"image",
|
||||
"image_thumbnail",
|
||||
"verification_status",
|
||||
"date_created",
|
||||
"date_created_code",
|
||||
"date_created_timestamp",
|
||||
"date_updated",
|
||||
"date_updated_code",
|
||||
"date_updated_timestamp",
|
||||
];
|
||||
const updatedFields = fields && fields[0] ? [...defaultFields, ...fields] : defaultFields;
|
||||
const reqPayload = JSON.stringify({
|
||||
userId,
|
||||
database,
|
||||
fields: [...new Set(updatedFields)],
|
||||
});
|
||||
const grabedHostNames = grabHostNames();
|
||||
const { host, port, scheme } = grabedHostNames;
|
||||
/**
|
||||
* Check for local DB settings
|
||||
*
|
||||
* @description Look for local db settings in `.env` file and by pass the http request if available
|
||||
*/
|
||||
const { DSQL_DB_HOST, DSQL_DB_USERNAME, DSQL_DB_PASSWORD, DSQL_DB_NAME } = process.env;
|
||||
if ((DSQL_DB_HOST === null || DSQL_DB_HOST === void 0 ? void 0 : DSQL_DB_HOST.match(/./)) &&
|
||||
(DSQL_DB_USERNAME === null || DSQL_DB_USERNAME === void 0 ? void 0 : DSQL_DB_USERNAME.match(/./)) &&
|
||||
(DSQL_DB_PASSWORD === null || DSQL_DB_PASSWORD === void 0 ? void 0 : DSQL_DB_PASSWORD.match(/./)) &&
|
||||
(DSQL_DB_NAME === null || DSQL_DB_NAME === void 0 ? void 0 : DSQL_DB_NAME.match(/./)) &&
|
||||
global.DSQL_USE_LOCAL) {
|
||||
/** @type {import("../../types").DSQL_DatabaseSchemaType | undefined} */
|
||||
let dbSchema;
|
||||
try {
|
||||
const localDbSchemaPath = path.resolve(process.cwd(), "dsql.schema.json");
|
||||
dbSchema = JSON.parse(fs.readFileSync(localDbSchemaPath, "utf8"));
|
||||
}
|
||||
catch (error) { }
|
||||
return await apiGetUser({
|
||||
userId,
|
||||
fields: [...new Set(updatedFields)],
|
||||
dbFullName: DSQL_DB_NAME,
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Make https request
|
||||
*
|
||||
* @description make a request to datasquirel.com
|
||||
*/
|
||||
const httpResponse = await new Promise((resolve, reject) => {
|
||||
const httpsRequest = scheme.request({
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Content-Length": Buffer.from(reqPayload).length,
|
||||
Authorization: key ||
|
||||
process.env.DSQL_FULL_ACCESS_API_KEY ||
|
||||
process.env.DSQL_API_KEY,
|
||||
},
|
||||
port,
|
||||
hostname: host,
|
||||
path: `/api/user/${apiUserId || grabedHostNames.user_id}/get-user`,
|
||||
},
|
||||
/**
|
||||
* Callback Function
|
||||
*
|
||||
* @description https request callback
|
||||
*/
|
||||
(response) => {
|
||||
var str = "";
|
||||
response.on("data", function (chunk) {
|
||||
str += chunk;
|
||||
});
|
||||
response.on("end", function () {
|
||||
resolve(JSON.parse(str));
|
||||
});
|
||||
response.on("error", (err) => {
|
||||
reject(err);
|
||||
});
|
||||
});
|
||||
httpsRequest.write(reqPayload);
|
||||
httpsRequest.end();
|
||||
});
|
||||
/** ********************************************** */
|
||||
/** ********************************************** */
|
||||
/** ********************************************** */
|
||||
return httpResponse;
|
||||
}
|
||||
|
||||
+2
-34
@@ -1,37 +1,5 @@
|
||||
import http from "http";
|
||||
import { APILoginFunctionReturn } from "../../types";
|
||||
type Param = {
|
||||
key?: string;
|
||||
database: string;
|
||||
payload: {
|
||||
email?: string;
|
||||
username?: string;
|
||||
password?: string;
|
||||
};
|
||||
additionalFields?: string[];
|
||||
request?: http.IncomingMessage & {
|
||||
[s: string]: any;
|
||||
};
|
||||
response?: http.ServerResponse & {
|
||||
[s: string]: any;
|
||||
};
|
||||
encryptionKey?: string;
|
||||
encryptionSalt?: string;
|
||||
email_login?: boolean;
|
||||
email_login_code?: string;
|
||||
temp_code_field?: string;
|
||||
token?: boolean;
|
||||
user_id?: string | number;
|
||||
skipPassword?: boolean;
|
||||
debug?: boolean;
|
||||
skipWriteAuthFile?: boolean;
|
||||
apiUserID?: string | number;
|
||||
dbUserId?: string | number;
|
||||
cleanupTokens?: boolean;
|
||||
secureCookie?: boolean;
|
||||
};
|
||||
import { APILoginFunctionReturn, LoginUserParam } from "../../types";
|
||||
/**
|
||||
* # Login A user
|
||||
*/
|
||||
export default function loginUser({ key, payload, database, additionalFields, response, encryptionKey, encryptionSalt, email_login, email_login_code, temp_code_field, token, user_id, skipPassword, apiUserID, skipWriteAuthFile, dbUserId, debug, cleanupTokens, secureCookie, request, }: Param): Promise<APILoginFunctionReturn>;
|
||||
export {};
|
||||
export default function loginUser({ key, payload, database, additionalFields, response, encryptionKey, encryptionSalt, email_login, email_login_code, temp_code_field, token, user_id, skipPassword, apiUserID, skipWriteAuthFile, dbUserId, debug, cleanupTokens, secureCookie, request, }: LoginUserParam): Promise<APILoginFunctionReturn>;
|
||||
|
||||
+164
-181
@@ -1,200 +1,183 @@
|
||||
"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 = loginUser;
|
||||
const fs_1 = __importDefault(require("fs"));
|
||||
const path_1 = __importDefault(require("path"));
|
||||
const encrypt_1 = __importDefault(require("../../functions/dsql/encrypt"));
|
||||
const grab_host_names_1 = __importDefault(require("../../utils/grab-host-names"));
|
||||
const api_login_1 = __importDefault(require("../../functions/api/users/api-login"));
|
||||
const get_auth_cookie_names_1 = __importDefault(require("../../functions/backend/cookies/get-auth-cookie-names"));
|
||||
const write_auth_files_1 = require("../../functions/backend/auth/write-auth-files");
|
||||
const debug_log_1 = __importDefault(require("../../utils/logging/debug-log"));
|
||||
const grab_cookie_expirt_date_1 = __importDefault(require("../../utils/grab-cookie-expirt-date"));
|
||||
import fs from "fs";
|
||||
import path from "path";
|
||||
import encrypt from "../../functions/dsql/encrypt";
|
||||
import grabHostNames from "../../utils/grab-host-names";
|
||||
import apiLoginUser from "../../functions/api/users/api-login";
|
||||
import getAuthCookieNames from "../../functions/backend/cookies/get-auth-cookie-names";
|
||||
import { writeAuthFile } from "../../functions/backend/auth/write-auth-files";
|
||||
import debugLog from "../../utils/logging/debug-log";
|
||||
import grabCookieExpiryDate from "../../utils/grab-cookie-expirt-date";
|
||||
/**
|
||||
* # Login A user
|
||||
*/
|
||||
function loginUser(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ key, payload, database, additionalFields, response, encryptionKey, encryptionSalt, email_login, email_login_code, temp_code_field, token, user_id, skipPassword, apiUserID, skipWriteAuthFile, dbUserId, debug, cleanupTokens, secureCookie, request, }) {
|
||||
var _b, _c, _d;
|
||||
const grabedHostNames = (0, grab_host_names_1.default)({ userId: user_id || apiUserID });
|
||||
const { host, port, scheme } = grabedHostNames;
|
||||
const COOKIE_EXPIRY_DATE = (0, grab_cookie_expirt_date_1.default)();
|
||||
const defaultTempLoginFieldName = "temp_login_code";
|
||||
const emailLoginTempCodeFieldName = email_login
|
||||
export default async function loginUser({ key, payload, database, additionalFields, response, encryptionKey, encryptionSalt, email_login, email_login_code, temp_code_field, token, user_id, skipPassword, apiUserID, skipWriteAuthFile, dbUserId, debug, cleanupTokens, secureCookie, request, }) {
|
||||
var _a, _b, _c;
|
||||
const grabedHostNames = grabHostNames({ userId: user_id || apiUserID });
|
||||
const { host, port, scheme } = grabedHostNames;
|
||||
const COOKIE_EXPIRY_DATE = grabCookieExpiryDate();
|
||||
const defaultTempLoginFieldName = "temp_login_code";
|
||||
const emailLoginTempCodeFieldName = email_login
|
||||
? temp_code_field
|
||||
? temp_code_field
|
||||
? temp_code_field
|
||||
: defaultTempLoginFieldName
|
||||
: undefined;
|
||||
const finalEncryptionKey = encryptionKey || process.env.DSQL_ENCRYPTION_PASSWORD;
|
||||
const finalEncryptionSalt = encryptionSalt || process.env.DSQL_ENCRYPTION_SALT;
|
||||
function debugFn(log, label) {
|
||||
(0, debug_log_1.default)({ log, addTime: true, title: "loginUser", label });
|
||||
}
|
||||
if (!(finalEncryptionKey === null || finalEncryptionKey === void 0 ? void 0 : finalEncryptionKey.match(/.{8,}/))) {
|
||||
console.log("Encryption key is invalid");
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: "Encryption key is invalid",
|
||||
};
|
||||
}
|
||||
if (!(finalEncryptionSalt === null || finalEncryptionSalt === void 0 ? void 0 : finalEncryptionSalt.match(/.{8,}/))) {
|
||||
console.log("Encryption salt is invalid");
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: "Encryption salt is invalid",
|
||||
};
|
||||
}
|
||||
/**
|
||||
* Check required fields
|
||||
*
|
||||
* @description Check required fields
|
||||
*/
|
||||
// const isEmailValid = await validateEmail({ email: payload.email });
|
||||
// if (!payload.email) {
|
||||
// return {
|
||||
// success: false,
|
||||
// payload: null,
|
||||
// msg: isEmailValid.message,
|
||||
// };
|
||||
// }
|
||||
/**
|
||||
* Initialize HTTP response variable
|
||||
*/
|
||||
let httpResponse = {
|
||||
: defaultTempLoginFieldName
|
||||
: undefined;
|
||||
const finalEncryptionKey = encryptionKey || process.env.DSQL_ENCRYPTION_PASSWORD;
|
||||
const finalEncryptionSalt = encryptionSalt || process.env.DSQL_ENCRYPTION_SALT;
|
||||
function debugFn(log, label) {
|
||||
debugLog({ log, addTime: true, title: "loginUser", label });
|
||||
}
|
||||
if (!(finalEncryptionKey === null || finalEncryptionKey === void 0 ? void 0 : finalEncryptionKey.match(/.{8,}/))) {
|
||||
console.log("Encryption key is invalid");
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: "Encryption key is invalid",
|
||||
};
|
||||
/**
|
||||
* Check for local DB settings
|
||||
*
|
||||
* @description Look for local db settings in `.env` file and by pass the http request if available
|
||||
*/
|
||||
const { DSQL_DB_HOST, DSQL_DB_USERNAME, DSQL_DB_PASSWORD, DSQL_DB_NAME } = process.env;
|
||||
if ((DSQL_DB_HOST === null || DSQL_DB_HOST === void 0 ? void 0 : DSQL_DB_HOST.match(/./)) &&
|
||||
(DSQL_DB_USERNAME === null || DSQL_DB_USERNAME === void 0 ? void 0 : DSQL_DB_USERNAME.match(/./)) &&
|
||||
(DSQL_DB_PASSWORD === null || DSQL_DB_PASSWORD === void 0 ? void 0 : DSQL_DB_PASSWORD.match(/./)) &&
|
||||
(DSQL_DB_NAME === null || DSQL_DB_NAME === void 0 ? void 0 : DSQL_DB_NAME.match(/./)) &&
|
||||
global.DSQL_USE_LOCAL) {
|
||||
let dbSchema;
|
||||
try {
|
||||
const localDbSchemaPath = path_1.default.resolve(process.cwd(), "dsql.schema.json");
|
||||
dbSchema = JSON.parse(fs_1.default.readFileSync(localDbSchemaPath, "utf8"));
|
||||
}
|
||||
catch (error) { }
|
||||
httpResponse = yield (0, api_login_1.default)({
|
||||
database: process.env.DSQL_DB_NAME || "",
|
||||
email: payload.email,
|
||||
username: payload.username,
|
||||
password: payload.password,
|
||||
skipPassword,
|
||||
}
|
||||
if (!(finalEncryptionSalt === null || finalEncryptionSalt === void 0 ? void 0 : finalEncryptionSalt.match(/.{8,}/))) {
|
||||
console.log("Encryption salt is invalid");
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: "Encryption salt is invalid",
|
||||
};
|
||||
}
|
||||
/**
|
||||
* Check required fields
|
||||
*
|
||||
* @description Check required fields
|
||||
*/
|
||||
// const isEmailValid = await validateEmail({ email: payload.email });
|
||||
// if (!payload.email) {
|
||||
// return {
|
||||
// success: false,
|
||||
// payload: null,
|
||||
// msg: isEmailValid.message,
|
||||
// };
|
||||
// }
|
||||
/**
|
||||
* Initialize HTTP response variable
|
||||
*/
|
||||
let httpResponse = {
|
||||
success: false,
|
||||
};
|
||||
/**
|
||||
* Check for local DB settings
|
||||
*
|
||||
* @description Look for local db settings in `.env` file and by pass the http request if available
|
||||
*/
|
||||
const { DSQL_DB_HOST, DSQL_DB_USERNAME, DSQL_DB_PASSWORD, DSQL_DB_NAME } = process.env;
|
||||
if ((DSQL_DB_HOST === null || DSQL_DB_HOST === void 0 ? void 0 : DSQL_DB_HOST.match(/./)) &&
|
||||
(DSQL_DB_USERNAME === null || DSQL_DB_USERNAME === void 0 ? void 0 : DSQL_DB_USERNAME.match(/./)) &&
|
||||
(DSQL_DB_PASSWORD === null || DSQL_DB_PASSWORD === void 0 ? void 0 : DSQL_DB_PASSWORD.match(/./)) &&
|
||||
(DSQL_DB_NAME === null || DSQL_DB_NAME === void 0 ? void 0 : DSQL_DB_NAME.match(/./)) &&
|
||||
global.DSQL_USE_LOCAL) {
|
||||
let dbSchema;
|
||||
try {
|
||||
const localDbSchemaPath = path.resolve(process.cwd(), "dsql.schema.json");
|
||||
dbSchema = JSON.parse(fs.readFileSync(localDbSchemaPath, "utf8"));
|
||||
}
|
||||
catch (error) { }
|
||||
httpResponse = await apiLoginUser({
|
||||
database: database || process.env.DSQL_DB_NAME || "",
|
||||
email: payload.email,
|
||||
username: payload.username,
|
||||
password: payload.password,
|
||||
skipPassword,
|
||||
encryptionKey: finalEncryptionKey,
|
||||
additionalFields,
|
||||
email_login,
|
||||
email_login_code,
|
||||
email_login_field: emailLoginTempCodeFieldName,
|
||||
token,
|
||||
dbUserId,
|
||||
debug,
|
||||
});
|
||||
}
|
||||
else {
|
||||
httpResponse = await new Promise((resolve, reject) => {
|
||||
const reqPayload = {
|
||||
encryptionKey: finalEncryptionKey,
|
||||
payload,
|
||||
database,
|
||||
additionalFields,
|
||||
email_login,
|
||||
email_login_code,
|
||||
email_login_field: emailLoginTempCodeFieldName,
|
||||
token,
|
||||
dbUserId,
|
||||
debug,
|
||||
});
|
||||
}
|
||||
else {
|
||||
httpResponse = yield new Promise((resolve, reject) => {
|
||||
const reqPayload = {
|
||||
encryptionKey: finalEncryptionKey,
|
||||
payload,
|
||||
database,
|
||||
additionalFields,
|
||||
email_login,
|
||||
email_login_code,
|
||||
email_login_field: emailLoginTempCodeFieldName,
|
||||
token,
|
||||
skipPassword: skipPassword,
|
||||
dbUserId: dbUserId || 0,
|
||||
};
|
||||
const reqPayloadJSON = JSON.stringify(reqPayload);
|
||||
const httpsRequest = scheme.request({
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Content-Length": Buffer.from(reqPayloadJSON).length,
|
||||
Authorization: key ||
|
||||
process.env.DSQL_FULL_ACCESS_API_KEY ||
|
||||
process.env.DSQL_API_KEY,
|
||||
},
|
||||
port,
|
||||
hostname: host,
|
||||
path: `/api/user/${user_id || grabedHostNames.user_id}/login-user`,
|
||||
}, (res) => {
|
||||
var str = "";
|
||||
res.on("data", function (chunk) {
|
||||
str += chunk;
|
||||
});
|
||||
res.on("end", function () {
|
||||
resolve(JSON.parse(str));
|
||||
});
|
||||
res.on("error", (err) => {
|
||||
reject(err);
|
||||
});
|
||||
skipPassword: skipPassword,
|
||||
dbUserId: dbUserId || 0,
|
||||
};
|
||||
const reqPayloadJSON = JSON.stringify(reqPayload);
|
||||
const httpsRequest = scheme.request({
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Content-Length": Buffer.from(reqPayloadJSON).length,
|
||||
Authorization: key ||
|
||||
process.env.DSQL_FULL_ACCESS_API_KEY ||
|
||||
process.env.DSQL_API_KEY,
|
||||
},
|
||||
port,
|
||||
hostname: host,
|
||||
path: `/api/user/${user_id || grabedHostNames.user_id}/login-user`,
|
||||
}, (res) => {
|
||||
var str = "";
|
||||
res.on("data", function (chunk) {
|
||||
str += chunk;
|
||||
});
|
||||
res.on("end", function () {
|
||||
resolve(JSON.parse(str));
|
||||
});
|
||||
res.on("error", (err) => {
|
||||
reject(err);
|
||||
});
|
||||
httpsRequest.write(reqPayloadJSON);
|
||||
httpsRequest.end();
|
||||
});
|
||||
httpsRequest.write(reqPayloadJSON);
|
||||
httpsRequest.end();
|
||||
});
|
||||
}
|
||||
if (debug) {
|
||||
debugFn(httpResponse, "httpResponse");
|
||||
}
|
||||
if (httpResponse === null || httpResponse === void 0 ? void 0 : httpResponse.success) {
|
||||
let encryptedPayload = encrypt({
|
||||
data: JSON.stringify(httpResponse.payload),
|
||||
encryptionKey: finalEncryptionKey,
|
||||
encryptionSalt: finalEncryptionSalt,
|
||||
});
|
||||
try {
|
||||
if (token && encryptedPayload)
|
||||
httpResponse["token"] = encryptedPayload;
|
||||
}
|
||||
catch (error) {
|
||||
(_a = global.ERROR_CALLBACK) === null || _a === void 0 ? void 0 : _a.call(global, `Login User HTTP Response Error`, error);
|
||||
}
|
||||
const cookieNames = getAuthCookieNames({
|
||||
database,
|
||||
userId: grabedHostNames.user_id,
|
||||
});
|
||||
if (httpResponse.csrf && !skipWriteAuthFile) {
|
||||
writeAuthFile(httpResponse.csrf, JSON.stringify(httpResponse.payload), cleanupTokens && ((_b = httpResponse.payload) === null || _b === void 0 ? void 0 : _b.id)
|
||||
? { userId: httpResponse.payload.id }
|
||||
: undefined);
|
||||
}
|
||||
httpResponse["cookieNames"] = cookieNames;
|
||||
httpResponse["key"] = String(encryptedPayload);
|
||||
const authKeyName = cookieNames.keyCookieName;
|
||||
const csrfName = cookieNames.csrfCookieName;
|
||||
if (debug) {
|
||||
debugFn(httpResponse, "httpResponse");
|
||||
debugFn(authKeyName, "authKeyName");
|
||||
debugFn(csrfName, "csrfName");
|
||||
debugFn(encryptedPayload, "encryptedPayload");
|
||||
}
|
||||
if (httpResponse === null || httpResponse === void 0 ? void 0 : httpResponse.success) {
|
||||
let encryptedPayload = (0, encrypt_1.default)({
|
||||
data: JSON.stringify(httpResponse.payload),
|
||||
encryptionKey: finalEncryptionKey,
|
||||
encryptionSalt: finalEncryptionSalt,
|
||||
});
|
||||
try {
|
||||
if (token && encryptedPayload)
|
||||
httpResponse["token"] = encryptedPayload;
|
||||
}
|
||||
catch (error) {
|
||||
(_b = global.ERROR_CALLBACK) === null || _b === void 0 ? void 0 : _b.call(global, `Login User HTTP Response Error`, error);
|
||||
}
|
||||
const cookieNames = (0, get_auth_cookie_names_1.default)({
|
||||
database,
|
||||
userId: grabedHostNames.user_id,
|
||||
});
|
||||
if (httpResponse.csrf && !skipWriteAuthFile) {
|
||||
(0, write_auth_files_1.writeAuthFile)(httpResponse.csrf, JSON.stringify(httpResponse.payload), cleanupTokens && ((_c = httpResponse.payload) === null || _c === void 0 ? void 0 : _c.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}=${(_d = httpResponse.payload) === null || _d === void 0 ? void 0 : _d.csrf_k};samesite=strict;path=/;HttpOnly=true;Expires=${COOKIE_EXPIRY_DATE}`,
|
||||
]);
|
||||
if (debug) {
|
||||
debugFn("Response Sent!");
|
||||
}
|
||||
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}=${(_c = httpResponse.payload) === null || _c === void 0 ? void 0 : _c.csrf_k};samesite=strict;path=/;HttpOnly=true;Expires=${COOKIE_EXPIRY_DATE}`,
|
||||
]);
|
||||
if (debug) {
|
||||
debugFn("Response Sent!");
|
||||
}
|
||||
return httpResponse;
|
||||
});
|
||||
}
|
||||
return httpResponse;
|
||||
}
|
||||
|
||||
+16
-22
@@ -1,20 +1,14 @@
|
||||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = logoutUser;
|
||||
const get_auth_cookie_names_1 = __importDefault(require("../../functions/backend/cookies/get-auth-cookie-names"));
|
||||
const decrypt_1 = __importDefault(require("../../functions/dsql/decrypt"));
|
||||
const ejson_1 = __importDefault(require("../../utils/ejson"));
|
||||
const write_auth_files_1 = require("../../functions/backend/auth/write-auth-files");
|
||||
const parseCookies_1 = __importDefault(require("../../utils/backend/parseCookies"));
|
||||
const grab_host_names_1 = __importDefault(require("../../utils/grab-host-names"));
|
||||
const debug_log_1 = __importDefault(require("../../utils/logging/debug-log"));
|
||||
import getAuthCookieNames from "../../functions/backend/cookies/get-auth-cookie-names";
|
||||
import decrypt from "../../functions/dsql/decrypt";
|
||||
import EJSON from "../../utils/ejson";
|
||||
import { deleteAuthFile } from "../../functions/backend/auth/write-auth-files";
|
||||
import parseCookies from "../../utils/backend/parseCookies";
|
||||
import grabHostNames from "../../utils/grab-host-names";
|
||||
import debugLog from "../../utils/logging/debug-log";
|
||||
/**
|
||||
* # Logout user
|
||||
*/
|
||||
function logoutUser({ response, database, dsqlUserId, encryptedUserString, request, cookieString, debug, }) {
|
||||
export default function logoutUser({ response, database, dsqlUserId, encryptedUserString, request, cookieString, debug, }) {
|
||||
var _a;
|
||||
/**
|
||||
* Check Encryption Keys
|
||||
@@ -22,13 +16,13 @@ function logoutUser({ response, database, dsqlUserId, encryptedUserString, reque
|
||||
* @description Check Encryption Keys
|
||||
*/
|
||||
try {
|
||||
const { user_id } = (0, grab_host_names_1.default)({ userId: dsqlUserId });
|
||||
const cookieNames = (0, get_auth_cookie_names_1.default)({
|
||||
const { user_id } = grabHostNames({ userId: dsqlUserId });
|
||||
const cookieNames = getAuthCookieNames({
|
||||
database,
|
||||
userId: user_id,
|
||||
});
|
||||
function debugFn(log, label) {
|
||||
(0, debug_log_1.default)({ log, addTime: true, title: "logoutUser", label });
|
||||
debugLog({ log, addTime: true, title: "logoutUser", label });
|
||||
}
|
||||
if (debug) {
|
||||
debugFn(cookieNames, "cookieNames");
|
||||
@@ -39,16 +33,16 @@ function logoutUser({ response, database, dsqlUserId, encryptedUserString, reque
|
||||
const decryptedUserJSON = (() => {
|
||||
try {
|
||||
if (request) {
|
||||
const cookiesObject = (0, parseCookies_1.default)({
|
||||
const cookiesObject = parseCookies({
|
||||
request,
|
||||
cookieString,
|
||||
});
|
||||
return (0, decrypt_1.default)({
|
||||
return decrypt({
|
||||
encryptedString: cookiesObject[authKeyName],
|
||||
});
|
||||
}
|
||||
else if (encryptedUserString) {
|
||||
return (0, decrypt_1.default)({
|
||||
return decrypt({
|
||||
encryptedString: encryptedUserString,
|
||||
});
|
||||
}
|
||||
@@ -66,7 +60,7 @@ function logoutUser({ response, database, dsqlUserId, encryptedUserString, reque
|
||||
}
|
||||
if (!decryptedUserJSON)
|
||||
throw new Error("Invalid User");
|
||||
const userObject = ejson_1.default.parse(decryptedUserJSON);
|
||||
const userObject = EJSON.parse(decryptedUserJSON);
|
||||
if (!(userObject === null || userObject === void 0 ? void 0 : userObject.csrf_k))
|
||||
throw new Error("Invalid User. Please check key");
|
||||
response === null || response === void 0 ? void 0 : response.setHeader("Set-Cookie", [
|
||||
@@ -75,7 +69,7 @@ function logoutUser({ response, database, dsqlUserId, encryptedUserString, reque
|
||||
`${oneTimeCodeName}=null;max-age=0`,
|
||||
]);
|
||||
const csrf = userObject.csrf_k;
|
||||
(0, write_auth_files_1.deleteAuthFile)(csrf);
|
||||
deleteAuthFile(csrf);
|
||||
return {
|
||||
success: true,
|
||||
msg: "User Logged Out",
|
||||
|
||||
+157
-174
@@ -1,179 +1,162 @@
|
||||
"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 = reauthUser;
|
||||
const user_auth_1 = __importDefault(require("./user-auth"));
|
||||
const grab_host_names_1 = __importDefault(require("../../utils/grab-host-names"));
|
||||
const login_user_1 = __importDefault(require("./login-user"));
|
||||
import userAuth from "./user-auth";
|
||||
import grabHostNames from "../../utils/grab-host-names";
|
||||
import loginUser from "./login-user";
|
||||
/**
|
||||
* # Reauthorize User
|
||||
*/
|
||||
function reauthUser(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ key, database, response, request, level, encryptionKey, encryptionSalt, additionalFields, encryptedUserString, user_id, secureCookie, }) {
|
||||
var _b;
|
||||
/**
|
||||
* Check Encryption Keys
|
||||
*
|
||||
* @description Check Encryption Keys
|
||||
*/
|
||||
const grabedHostNames = (0, grab_host_names_1.default)();
|
||||
// const { host, port, scheme } = grabedHostNames;
|
||||
// const COOKIE_EXPIRY_DATE = grabCookieExpiryDate();
|
||||
const finalEncryptionKey = encryptionKey || process.env.DSQL_ENCRYPTION_PASSWORD;
|
||||
const finalEncryptionSalt = encryptionSalt || process.env.DSQL_ENCRYPTION_SALT;
|
||||
const existingUser = (0, user_auth_1.default)({
|
||||
database,
|
||||
encryptionKey: finalEncryptionKey,
|
||||
encryptionSalt: finalEncryptionSalt,
|
||||
level,
|
||||
request,
|
||||
encryptedUserString,
|
||||
});
|
||||
if (!((_b = existingUser === null || existingUser === void 0 ? void 0 : existingUser.payload) === null || _b === void 0 ? void 0 : _b.id)) {
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: "Cookie Credentials Invalid",
|
||||
};
|
||||
}
|
||||
return yield (0, login_user_1.default)({
|
||||
database: database || "",
|
||||
payload: {
|
||||
email: existingUser.payload.email,
|
||||
},
|
||||
additionalFields,
|
||||
skipPassword: true,
|
||||
response,
|
||||
request,
|
||||
user_id,
|
||||
secureCookie,
|
||||
key,
|
||||
});
|
||||
/**
|
||||
* Initialize HTTP response variable
|
||||
*/
|
||||
let httpResponse;
|
||||
/**
|
||||
* Check for local DB settings
|
||||
*
|
||||
* @description Look for local db settings in `.env` file and by pass the http request if available
|
||||
*/
|
||||
// const { DSQL_DB_HOST, DSQL_DB_USERNAME, DSQL_DB_PASSWORD, DSQL_DB_NAME } =
|
||||
// process.env;
|
||||
// if (
|
||||
// DSQL_DB_HOST?.match(/./) &&
|
||||
// DSQL_DB_USERNAME?.match(/./) &&
|
||||
// DSQL_DB_PASSWORD?.match(/./) &&
|
||||
// DSQL_DB_NAME?.match(/./) &&
|
||||
// global.DSQL_USE_LOCAL
|
||||
// ) {
|
||||
// let dbSchema: import("../../types").DSQL_DatabaseSchemaType | undefined;
|
||||
// try {
|
||||
// const localDbSchemaPath = path.resolve(
|
||||
// process.cwd(),
|
||||
// "dsql.schema.json"
|
||||
// );
|
||||
// dbSchema = JSON.parse(fs.readFileSync(localDbSchemaPath, "utf8"));
|
||||
// } catch (error) {}
|
||||
// httpResponse = await apiReauthUser({
|
||||
// existingUser: existingUser.payload,
|
||||
// additionalFields,
|
||||
// });
|
||||
// } else {
|
||||
// /**
|
||||
// * Make https request
|
||||
// *
|
||||
// * @description make a request to datasquirel.com
|
||||
// */
|
||||
// httpResponse = (await new Promise((resolve, reject) => {
|
||||
// const reqPayload = JSON.stringify({
|
||||
// existingUser: existingUser.payload,
|
||||
// database,
|
||||
// additionalFields,
|
||||
// });
|
||||
// const httpsRequest = scheme.request(
|
||||
// {
|
||||
// method: "POST",
|
||||
// headers: {
|
||||
// "Content-Type": "application/json",
|
||||
// "Content-Length": Buffer.from(reqPayload).length,
|
||||
// Authorization:
|
||||
// key ||
|
||||
// process.env.DSQL_FULL_ACCESS_API_KEY ||
|
||||
// process.env.DSQL_API_KEY,
|
||||
// },
|
||||
// port,
|
||||
// hostname: host,
|
||||
// path: `/api/user/${
|
||||
// user_id || grabedHostNames.user_id
|
||||
// }/reauth-user`,
|
||||
// },
|
||||
// /**
|
||||
// * Callback Function
|
||||
// *
|
||||
// * @description https request callback
|
||||
// */
|
||||
// (response) => {
|
||||
// var str = "";
|
||||
// response.on("data", function (chunk) {
|
||||
// str += chunk;
|
||||
// });
|
||||
// response.on("end", function () {
|
||||
// resolve(JSON.parse(str));
|
||||
// });
|
||||
// response.on("error", (err) => {
|
||||
// reject(err);
|
||||
// });
|
||||
// }
|
||||
// );
|
||||
// httpsRequest.write(reqPayload);
|
||||
// httpsRequest.end();
|
||||
// })) as APILoginFunctionReturn;
|
||||
// }
|
||||
// /**
|
||||
// * Make https request
|
||||
// *
|
||||
// * @description make a request to datasquirel.com
|
||||
// */
|
||||
// if (httpResponse?.success) {
|
||||
// let encryptedPayload = encrypt({
|
||||
// data: JSON.stringify(httpResponse.payload),
|
||||
// encryptionKey: finalEncryptionKey,
|
||||
// encryptionSalt: finalEncryptionSalt,
|
||||
// });
|
||||
// const cookieNames = getAuthCookieNames({
|
||||
// database,
|
||||
// userId: user_id || grabedHostNames.user_id,
|
||||
// });
|
||||
// httpResponse["cookieNames"] = cookieNames;
|
||||
// httpResponse["key"] = String(encryptedPayload);
|
||||
// const authKeyName = cookieNames.keyCookieName;
|
||||
// const csrfName = cookieNames.csrfCookieName;
|
||||
// response?.setHeader("Set-Cookie", [
|
||||
// `${authKeyName}=${encryptedPayload};samesite=strict;path=/;HttpOnly=true;Expires=${COOKIE_EXPIRY_DATE}${
|
||||
// secureCookie ? ";Secure=true" : ""
|
||||
// }`,
|
||||
// `${csrfName}=${httpResponse.payload?.csrf_k};samesite=strict;path=/;HttpOnly=true;Expires=${COOKIE_EXPIRY_DATE}`,
|
||||
// ]);
|
||||
// if (httpResponse.csrf) {
|
||||
// deleteAuthFile(String(existingUser.payload.csrf_k));
|
||||
// writeAuthFile(
|
||||
// httpResponse.csrf,
|
||||
// JSON.stringify(httpResponse.payload)
|
||||
// );
|
||||
// }
|
||||
// }
|
||||
// return httpResponse;
|
||||
export default async function reauthUser({ key, database, response, request, level, encryptionKey, encryptionSalt, additionalFields, encryptedUserString, user_id, secureCookie, }) {
|
||||
var _a;
|
||||
/**
|
||||
* Check Encryption Keys
|
||||
*
|
||||
* @description Check Encryption Keys
|
||||
*/
|
||||
const grabedHostNames = grabHostNames();
|
||||
// const { host, port, scheme } = grabedHostNames;
|
||||
// const COOKIE_EXPIRY_DATE = grabCookieExpiryDate();
|
||||
const finalEncryptionKey = encryptionKey || process.env.DSQL_ENCRYPTION_PASSWORD;
|
||||
const finalEncryptionSalt = encryptionSalt || process.env.DSQL_ENCRYPTION_SALT;
|
||||
const existingUser = userAuth({
|
||||
database,
|
||||
encryptionKey: finalEncryptionKey,
|
||||
encryptionSalt: finalEncryptionSalt,
|
||||
level,
|
||||
request,
|
||||
encryptedUserString,
|
||||
});
|
||||
if (!((_a = existingUser === null || existingUser === void 0 ? void 0 : existingUser.payload) === null || _a === void 0 ? void 0 : _a.id)) {
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: "Cookie Credentials Invalid",
|
||||
};
|
||||
}
|
||||
return await loginUser({
|
||||
database: database || "",
|
||||
payload: {
|
||||
email: existingUser.payload.email,
|
||||
},
|
||||
additionalFields,
|
||||
skipPassword: true,
|
||||
response,
|
||||
request,
|
||||
user_id,
|
||||
secureCookie,
|
||||
key,
|
||||
});
|
||||
/**
|
||||
* Initialize HTTP response variable
|
||||
*/
|
||||
let httpResponse;
|
||||
/**
|
||||
* Check for local DB settings
|
||||
*
|
||||
* @description Look for local db settings in `.env` file and by pass the http request if available
|
||||
*/
|
||||
// const { DSQL_DB_HOST, DSQL_DB_USERNAME, DSQL_DB_PASSWORD, DSQL_DB_NAME } =
|
||||
// process.env;
|
||||
// if (
|
||||
// DSQL_DB_HOST?.match(/./) &&
|
||||
// DSQL_DB_USERNAME?.match(/./) &&
|
||||
// DSQL_DB_PASSWORD?.match(/./) &&
|
||||
// DSQL_DB_NAME?.match(/./) &&
|
||||
// global.DSQL_USE_LOCAL
|
||||
// ) {
|
||||
// let dbSchema: import("../../types").DSQL_DatabaseSchemaType | undefined;
|
||||
// try {
|
||||
// const localDbSchemaPath = path.resolve(
|
||||
// process.cwd(),
|
||||
// "dsql.schema.json"
|
||||
// );
|
||||
// dbSchema = JSON.parse(fs.readFileSync(localDbSchemaPath, "utf8"));
|
||||
// } catch (error) {}
|
||||
// httpResponse = await apiReauthUser({
|
||||
// existingUser: existingUser.payload,
|
||||
// additionalFields,
|
||||
// });
|
||||
// } else {
|
||||
// /**
|
||||
// * Make https request
|
||||
// *
|
||||
// * @description make a request to datasquirel.com
|
||||
// */
|
||||
// httpResponse = (await new Promise((resolve, reject) => {
|
||||
// const reqPayload = JSON.stringify({
|
||||
// existingUser: existingUser.payload,
|
||||
// database,
|
||||
// additionalFields,
|
||||
// });
|
||||
// const httpsRequest = scheme.request(
|
||||
// {
|
||||
// method: "POST",
|
||||
// headers: {
|
||||
// "Content-Type": "application/json",
|
||||
// "Content-Length": Buffer.from(reqPayload).length,
|
||||
// Authorization:
|
||||
// key ||
|
||||
// process.env.DSQL_FULL_ACCESS_API_KEY ||
|
||||
// process.env.DSQL_API_KEY,
|
||||
// },
|
||||
// port,
|
||||
// hostname: host,
|
||||
// path: `/api/user/${
|
||||
// user_id || grabedHostNames.user_id
|
||||
// }/reauth-user`,
|
||||
// },
|
||||
// /**
|
||||
// * Callback Function
|
||||
// *
|
||||
// * @description https request callback
|
||||
// */
|
||||
// (response) => {
|
||||
// var str = "";
|
||||
// response.on("data", function (chunk) {
|
||||
// str += chunk;
|
||||
// });
|
||||
// response.on("end", function () {
|
||||
// resolve(JSON.parse(str));
|
||||
// });
|
||||
// response.on("error", (err) => {
|
||||
// reject(err);
|
||||
// });
|
||||
// }
|
||||
// );
|
||||
// httpsRequest.write(reqPayload);
|
||||
// httpsRequest.end();
|
||||
// })) as APILoginFunctionReturn;
|
||||
// }
|
||||
// /**
|
||||
// * Make https request
|
||||
// *
|
||||
// * @description make a request to datasquirel.com
|
||||
// */
|
||||
// if (httpResponse?.success) {
|
||||
// let encryptedPayload = encrypt({
|
||||
// data: JSON.stringify(httpResponse.payload),
|
||||
// encryptionKey: finalEncryptionKey,
|
||||
// encryptionSalt: finalEncryptionSalt,
|
||||
// });
|
||||
// const cookieNames = getAuthCookieNames({
|
||||
// database,
|
||||
// userId: user_id || grabedHostNames.user_id,
|
||||
// });
|
||||
// httpResponse["cookieNames"] = cookieNames;
|
||||
// httpResponse["key"] = String(encryptedPayload);
|
||||
// const authKeyName = cookieNames.keyCookieName;
|
||||
// const csrfName = cookieNames.csrfCookieName;
|
||||
// response?.setHeader("Set-Cookie", [
|
||||
// `${authKeyName}=${encryptedPayload};samesite=strict;path=/;HttpOnly=true;Expires=${COOKIE_EXPIRY_DATE}${
|
||||
// secureCookie ? ";Secure=true" : ""
|
||||
// }`,
|
||||
// `${csrfName}=${httpResponse.payload?.csrf_k};samesite=strict;path=/;HttpOnly=true;Expires=${COOKIE_EXPIRY_DATE}`,
|
||||
// ]);
|
||||
// if (httpResponse.csrf) {
|
||||
// deleteAuthFile(String(existingUser.payload.csrf_k));
|
||||
// writeAuthFile(
|
||||
// httpResponse.csrf,
|
||||
// JSON.stringify(httpResponse.payload)
|
||||
// );
|
||||
// }
|
||||
// }
|
||||
// return httpResponse;
|
||||
}
|
||||
|
||||
+1
-1
@@ -19,5 +19,5 @@ type Param = {
|
||||
/**
|
||||
* # Send Email Code to a User
|
||||
*/
|
||||
export default function sendEmailCode({ key, email, database, temp_code_field_name, mail_domain, mail_password, mail_username, mail_port, sender, user_id, response, extraCookies, }: Param): Promise<SendOneTimeCodeEmailResponse>;
|
||||
export default function sendEmailCode(params: Param): Promise<SendOneTimeCodeEmailResponse>;
|
||||
export {};
|
||||
|
||||
+84
-100
@@ -1,120 +1,104 @@
|
||||
"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 = sendEmailCode;
|
||||
const fs_1 = __importDefault(require("fs"));
|
||||
const path_1 = __importDefault(require("path"));
|
||||
const grab_host_names_1 = __importDefault(require("../../utils/grab-host-names"));
|
||||
const api_send_email_code_1 = __importDefault(require("../../functions/api/users/api-send-email-code"));
|
||||
import fs from "fs";
|
||||
import path from "path";
|
||||
import grabHostNames from "../../utils/grab-host-names";
|
||||
import apiSendEmailCode from "../../functions/api/users/api-send-email-code";
|
||||
/**
|
||||
* # Send Email Code to a User
|
||||
*/
|
||||
function sendEmailCode(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ key, email, database, temp_code_field_name, mail_domain, mail_password, mail_username, mail_port, sender, user_id, response, extraCookies, }) {
|
||||
const grabedHostNames = (0, grab_host_names_1.default)();
|
||||
const { host, port, scheme } = grabedHostNames;
|
||||
const defaultTempLoginFieldName = "temp_login_code";
|
||||
const emailLoginTempCodeFieldName = temp_code_field_name
|
||||
? temp_code_field_name
|
||||
: defaultTempLoginFieldName;
|
||||
const emailHtml = `<p>Please use this code to login</p>\n<h2>{{code}}</h2>\n<p>Please note that this code expires after 15 minutes</p>`;
|
||||
export default async function sendEmailCode(params) {
|
||||
const { key, email, database, temp_code_field_name, mail_domain, mail_password, mail_username, mail_port, sender, user_id, response, extraCookies, } = params;
|
||||
const grabedHostNames = grabHostNames();
|
||||
const { host, port, scheme } = grabedHostNames;
|
||||
const defaultTempLoginFieldName = "temp_login_code";
|
||||
const emailLoginTempCodeFieldName = temp_code_field_name
|
||||
? temp_code_field_name
|
||||
: defaultTempLoginFieldName;
|
||||
const emailHtml = `<p>Please use this code to login</p>\n<h2>{{code}}</h2>\n<p>Please note that this code expires after 15 minutes</p>`;
|
||||
/**
|
||||
* Check for local DB settings
|
||||
*
|
||||
* @description Look for local db settings in `.env` file and by pass the http request if available
|
||||
*/
|
||||
const { DSQL_DB_HOST, DSQL_DB_USERNAME, DSQL_DB_PASSWORD, DSQL_DB_NAME } = process.env;
|
||||
if ((DSQL_DB_HOST === null || DSQL_DB_HOST === void 0 ? void 0 : DSQL_DB_HOST.match(/./)) &&
|
||||
(DSQL_DB_USERNAME === null || DSQL_DB_USERNAME === void 0 ? void 0 : DSQL_DB_USERNAME.match(/./)) &&
|
||||
(DSQL_DB_PASSWORD === null || DSQL_DB_PASSWORD === void 0 ? void 0 : DSQL_DB_PASSWORD.match(/./)) &&
|
||||
(DSQL_DB_NAME === null || DSQL_DB_NAME === void 0 ? void 0 : DSQL_DB_NAME.match(/./)) &&
|
||||
global.DSQL_USE_LOCAL) {
|
||||
/** @type {import("../../types").DSQL_DatabaseSchemaType | undefined} */
|
||||
let dbSchema;
|
||||
try {
|
||||
const localDbSchemaPath = path.resolve(process.cwd(), "dsql.schema.json");
|
||||
dbSchema = JSON.parse(fs.readFileSync(localDbSchemaPath, "utf8"));
|
||||
}
|
||||
catch (error) { }
|
||||
return await apiSendEmailCode({
|
||||
database: DSQL_DB_NAME,
|
||||
email,
|
||||
email_login_field: emailLoginTempCodeFieldName,
|
||||
html: emailHtml,
|
||||
mail_domain,
|
||||
mail_password,
|
||||
mail_port,
|
||||
mail_username,
|
||||
sender,
|
||||
response,
|
||||
extraCookies,
|
||||
});
|
||||
}
|
||||
else {
|
||||
/**
|
||||
* Check for local DB settings
|
||||
* Make https request
|
||||
*
|
||||
* @description Look for local db settings in `.env` file and by pass the http request if available
|
||||
* @description make a request to datasquirel.com
|
||||
*
|
||||
* @type {import("../../types").SendOneTimeCodeEmailResponse}
|
||||
*/
|
||||
const { DSQL_DB_HOST, DSQL_DB_USERNAME, DSQL_DB_PASSWORD, DSQL_DB_NAME } = process.env;
|
||||
if ((DSQL_DB_HOST === null || DSQL_DB_HOST === void 0 ? void 0 : DSQL_DB_HOST.match(/./)) &&
|
||||
(DSQL_DB_USERNAME === null || DSQL_DB_USERNAME === void 0 ? void 0 : DSQL_DB_USERNAME.match(/./)) &&
|
||||
(DSQL_DB_PASSWORD === null || DSQL_DB_PASSWORD === void 0 ? void 0 : DSQL_DB_PASSWORD.match(/./)) &&
|
||||
(DSQL_DB_NAME === null || DSQL_DB_NAME === void 0 ? void 0 : DSQL_DB_NAME.match(/./)) &&
|
||||
global.DSQL_USE_LOCAL) {
|
||||
/** @type {import("../../types").DSQL_DatabaseSchemaType | undefined} */
|
||||
let dbSchema;
|
||||
try {
|
||||
const localDbSchemaPath = path_1.default.resolve(process.cwd(), "dsql.schema.json");
|
||||
dbSchema = JSON.parse(fs_1.default.readFileSync(localDbSchemaPath, "utf8"));
|
||||
}
|
||||
catch (error) { }
|
||||
return yield (0, api_send_email_code_1.default)({
|
||||
database: DSQL_DB_NAME,
|
||||
const httpResponse = await new Promise((resolve, reject) => {
|
||||
const reqPayload = JSON.stringify({
|
||||
email,
|
||||
database,
|
||||
email_login_field: emailLoginTempCodeFieldName,
|
||||
html: emailHtml,
|
||||
mail_domain,
|
||||
mail_password,
|
||||
mail_port,
|
||||
mail_username,
|
||||
mail_port,
|
||||
sender,
|
||||
response,
|
||||
extraCookies,
|
||||
html: emailHtml,
|
||||
});
|
||||
}
|
||||
else {
|
||||
const httpsRequest = scheme.request({
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Content-Length": Buffer.from(reqPayload).length,
|
||||
Authorization: key ||
|
||||
process.env.DSQL_FULL_ACCESS_API_KEY ||
|
||||
process.env.DSQL_API_KEY,
|
||||
},
|
||||
port,
|
||||
hostname: host,
|
||||
path: `/api/user/${user_id || grabedHostNames.user_id}/send-email-code`,
|
||||
},
|
||||
/**
|
||||
* Make https request
|
||||
* Callback Function
|
||||
*
|
||||
* @description make a request to datasquirel.com
|
||||
*
|
||||
* @type {import("../../types").SendOneTimeCodeEmailResponse}
|
||||
* @description https request callback
|
||||
*/
|
||||
const httpResponse = yield new Promise((resolve, reject) => {
|
||||
const reqPayload = JSON.stringify({
|
||||
email,
|
||||
database,
|
||||
email_login_field: emailLoginTempCodeFieldName,
|
||||
mail_domain,
|
||||
mail_password,
|
||||
mail_username,
|
||||
mail_port,
|
||||
sender,
|
||||
html: emailHtml,
|
||||
(res) => {
|
||||
var str = "";
|
||||
res.on("data", function (chunk) {
|
||||
str += chunk;
|
||||
});
|
||||
const httpsRequest = scheme.request({
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Content-Length": Buffer.from(reqPayload).length,
|
||||
Authorization: key ||
|
||||
process.env.DSQL_FULL_ACCESS_API_KEY ||
|
||||
process.env.DSQL_API_KEY,
|
||||
},
|
||||
port,
|
||||
hostname: host,
|
||||
path: `/api/user/${user_id || grabedHostNames.user_id}/send-email-code`,
|
||||
},
|
||||
/**
|
||||
* Callback Function
|
||||
*
|
||||
* @description https request callback
|
||||
*/
|
||||
(res) => {
|
||||
var str = "";
|
||||
res.on("data", function (chunk) {
|
||||
str += chunk;
|
||||
});
|
||||
res.on("end", function () {
|
||||
resolve(JSON.parse(str));
|
||||
});
|
||||
res.on("error", (err) => {
|
||||
reject(err);
|
||||
});
|
||||
res.on("end", function () {
|
||||
resolve(JSON.parse(str));
|
||||
});
|
||||
res.on("error", (err) => {
|
||||
reject(err);
|
||||
});
|
||||
httpsRequest.write(reqPayload);
|
||||
httpsRequest.end();
|
||||
});
|
||||
return httpResponse;
|
||||
}
|
||||
});
|
||||
httpsRequest.write(reqPayload);
|
||||
httpsRequest.end();
|
||||
});
|
||||
return httpResponse;
|
||||
}
|
||||
}
|
||||
|
||||
+145
-162
@@ -1,173 +1,156 @@
|
||||
"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 = githubAuth;
|
||||
const fs_1 = __importDefault(require("fs"));
|
||||
const path_1 = __importDefault(require("path"));
|
||||
const encrypt_1 = __importDefault(require("../../../functions/dsql/encrypt"));
|
||||
const grab_host_names_1 = __importDefault(require("../../../utils/grab-host-names"));
|
||||
const api_github_login_1 = __importDefault(require("../../../functions/api/users/social/api-github-login"));
|
||||
const grab_cookie_expirt_date_1 = __importDefault(require("../../../utils/grab-cookie-expirt-date"));
|
||||
import fs from "fs";
|
||||
import path from "path";
|
||||
import encrypt from "../../../functions/dsql/encrypt";
|
||||
import grabHostNames from "../../../utils/grab-host-names";
|
||||
import apiGithubLogin from "../../../functions/api/users/social/api-github-login";
|
||||
import grabCookieExpiryDate from "../../../utils/grab-cookie-expirt-date";
|
||||
/**
|
||||
* # SERVER FUNCTION: Login with google Function
|
||||
*/
|
||||
function githubAuth(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ key, code, email, database, clientId, clientSecret, response, encryptionKey, encryptionSalt, additionalFields, user_id, additionalData, secureCookie, }) {
|
||||
/**
|
||||
* Check inputs
|
||||
*
|
||||
* @description Check inputs
|
||||
*/
|
||||
const grabedHostNames = (0, grab_host_names_1.default)();
|
||||
const { host, port, scheme } = grabedHostNames;
|
||||
const COOKIE_EXPIRY_DATE = (0, grab_cookie_expirt_date_1.default)();
|
||||
if (!code || (code === null || code === void 0 ? void 0 : code.match(/ /))) {
|
||||
return {
|
||||
success: false,
|
||||
user: null,
|
||||
msg: "Please enter Github Access Token",
|
||||
};
|
||||
export default async function githubAuth({ key, code, email, database, clientId, clientSecret, response, encryptionKey, encryptionSalt, additionalFields, user_id, additionalData, secureCookie, }) {
|
||||
/**
|
||||
* Check inputs
|
||||
*
|
||||
* @description Check inputs
|
||||
*/
|
||||
const grabedHostNames = grabHostNames();
|
||||
const { host, port, scheme } = grabedHostNames;
|
||||
const COOKIE_EXPIRY_DATE = grabCookieExpiryDate();
|
||||
if (!code || (code === null || code === void 0 ? void 0 : code.match(/ /))) {
|
||||
return {
|
||||
success: false,
|
||||
user: null,
|
||||
msg: "Please enter Github Access Token",
|
||||
};
|
||||
}
|
||||
if (!database || (database === null || database === void 0 ? void 0 : database.match(/ /))) {
|
||||
return {
|
||||
success: false,
|
||||
user: null,
|
||||
msg: "Please provide database slug name you want to access",
|
||||
};
|
||||
}
|
||||
if (!clientId || (clientId === null || clientId === void 0 ? void 0 : clientId.match(/ /))) {
|
||||
return {
|
||||
success: false,
|
||||
user: null,
|
||||
msg: "Please enter Github OAUTH client ID",
|
||||
};
|
||||
}
|
||||
/**
|
||||
* Initialize HTTP response variable
|
||||
*/
|
||||
let httpResponse;
|
||||
/**
|
||||
* Check for local DB settings
|
||||
*
|
||||
* @description Look for local db settings in `.env` file and by pass the http request if available
|
||||
*/
|
||||
const { DSQL_DB_HOST, DSQL_DB_USERNAME, DSQL_DB_PASSWORD, DSQL_DB_NAME, DSQL_KEY, DSQL_REF_DB_NAME, DSQL_FULL_SYNC, } = process.env;
|
||||
if ((DSQL_DB_HOST === null || DSQL_DB_HOST === void 0 ? void 0 : DSQL_DB_HOST.match(/./)) &&
|
||||
(DSQL_DB_USERNAME === null || DSQL_DB_USERNAME === void 0 ? void 0 : DSQL_DB_USERNAME.match(/./)) &&
|
||||
(DSQL_DB_PASSWORD === null || DSQL_DB_PASSWORD === void 0 ? void 0 : DSQL_DB_PASSWORD.match(/./)) &&
|
||||
(DSQL_DB_NAME === null || DSQL_DB_NAME === void 0 ? void 0 : DSQL_DB_NAME.match(/./))) {
|
||||
/** @type {import("../../../types").DSQL_DatabaseSchemaType | undefined | undefined} */
|
||||
let dbSchema;
|
||||
try {
|
||||
const localDbSchemaPath = path.resolve(process.cwd(), "dsql.schema.json");
|
||||
dbSchema = JSON.parse(fs.readFileSync(localDbSchemaPath, "utf8"));
|
||||
}
|
||||
if (!database || (database === null || database === void 0 ? void 0 : database.match(/ /))) {
|
||||
return {
|
||||
success: false,
|
||||
user: null,
|
||||
msg: "Please provide database slug name you want to access",
|
||||
};
|
||||
}
|
||||
if (!clientId || (clientId === null || clientId === void 0 ? void 0 : clientId.match(/ /))) {
|
||||
return {
|
||||
success: false,
|
||||
user: null,
|
||||
msg: "Please enter Github OAUTH client ID",
|
||||
};
|
||||
}
|
||||
/**
|
||||
* Initialize HTTP response variable
|
||||
*/
|
||||
let httpResponse;
|
||||
/**
|
||||
* Check for local DB settings
|
||||
*
|
||||
* @description Look for local db settings in `.env` file and by pass the http request if available
|
||||
*/
|
||||
const { DSQL_DB_HOST, DSQL_DB_USERNAME, DSQL_DB_PASSWORD, DSQL_DB_NAME, DSQL_KEY, DSQL_REF_DB_NAME, DSQL_FULL_SYNC, } = process.env;
|
||||
if ((DSQL_DB_HOST === null || DSQL_DB_HOST === void 0 ? void 0 : DSQL_DB_HOST.match(/./)) &&
|
||||
(DSQL_DB_USERNAME === null || DSQL_DB_USERNAME === void 0 ? void 0 : DSQL_DB_USERNAME.match(/./)) &&
|
||||
(DSQL_DB_PASSWORD === null || DSQL_DB_PASSWORD === void 0 ? void 0 : DSQL_DB_PASSWORD.match(/./)) &&
|
||||
(DSQL_DB_NAME === null || DSQL_DB_NAME === void 0 ? void 0 : DSQL_DB_NAME.match(/./))) {
|
||||
/** @type {import("../../../types").DSQL_DatabaseSchemaType | undefined | undefined} */
|
||||
let dbSchema;
|
||||
try {
|
||||
const localDbSchemaPath = path_1.default.resolve(process.cwd(), "dsql.schema.json");
|
||||
dbSchema = JSON.parse(fs_1.default.readFileSync(localDbSchemaPath, "utf8"));
|
||||
}
|
||||
catch (error) { }
|
||||
httpResponse = yield (0, api_github_login_1.default)({
|
||||
code,
|
||||
email: email || undefined,
|
||||
clientId,
|
||||
clientSecret,
|
||||
additionalFields,
|
||||
database: DSQL_DB_NAME,
|
||||
additionalData,
|
||||
});
|
||||
}
|
||||
else {
|
||||
/**
|
||||
* Make https request
|
||||
*
|
||||
* @description make a request to datasquirel.com
|
||||
* @type {FunctionReturn} - Https response object
|
||||
*/
|
||||
httpResponse = (yield new Promise((resolve, reject) => {
|
||||
const reqPayload = JSON.stringify({
|
||||
code,
|
||||
email,
|
||||
clientId,
|
||||
clientSecret,
|
||||
database,
|
||||
additionalFields,
|
||||
additionalData,
|
||||
});
|
||||
const httpsRequest = scheme.request({
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Content-Length": Buffer.from(reqPayload).length,
|
||||
Authorization: key ||
|
||||
process.env.DSQL_FULL_ACCESS_API_KEY ||
|
||||
process.env.DSQL_API_KEY,
|
||||
},
|
||||
port,
|
||||
hostname: host,
|
||||
path: `/api/user/${user_id || grabedHostNames.user_id}/github-login`,
|
||||
},
|
||||
/**
|
||||
* Callback Function
|
||||
*
|
||||
* @description https request callback
|
||||
*/
|
||||
(response) => {
|
||||
var str = "";
|
||||
response.on("data", function (chunk) {
|
||||
str += chunk;
|
||||
});
|
||||
response.on("end", function () {
|
||||
var _a;
|
||||
try {
|
||||
resolve(JSON.parse(str));
|
||||
}
|
||||
catch (error) {
|
||||
(_a = global.ERROR_CALLBACK) === null || _a === void 0 ? void 0 : _a.call(global, `Github Auth Error`, error);
|
||||
resolve({
|
||||
success: false,
|
||||
user: null,
|
||||
msg: "Something went wrong",
|
||||
});
|
||||
}
|
||||
});
|
||||
response.on("error", (err) => {
|
||||
reject(err);
|
||||
});
|
||||
});
|
||||
httpsRequest.write(reqPayload);
|
||||
httpsRequest.end();
|
||||
}));
|
||||
}
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
catch (error) { }
|
||||
httpResponse = await apiGithubLogin({
|
||||
code,
|
||||
email: email || undefined,
|
||||
clientId,
|
||||
clientSecret,
|
||||
additionalFields,
|
||||
database: DSQL_DB_NAME,
|
||||
additionalData,
|
||||
});
|
||||
}
|
||||
else {
|
||||
/**
|
||||
* Make https request
|
||||
*
|
||||
* @description make a request to datasquirel.com
|
||||
* @type {FunctionReturn} - Https response object
|
||||
*/
|
||||
if ((httpResponse === null || httpResponse === void 0 ? void 0 : httpResponse.success) && (httpResponse === null || httpResponse === void 0 ? void 0 : httpResponse.user)) {
|
||||
let encryptedPayload = (0, encrypt_1.default)({
|
||||
data: JSON.stringify(httpResponse.user),
|
||||
encryptionKey,
|
||||
encryptionSalt,
|
||||
httpResponse = (await new Promise((resolve, reject) => {
|
||||
const reqPayload = JSON.stringify({
|
||||
code,
|
||||
email,
|
||||
clientId,
|
||||
clientSecret,
|
||||
database,
|
||||
additionalFields,
|
||||
additionalData,
|
||||
});
|
||||
const { user, dsqlUserId } = httpResponse;
|
||||
const authKeyName = `datasquirel_${dsqlUserId}_${database}_auth_key`;
|
||||
const csrfName = `datasquirel_${dsqlUserId}_${database}_csrf`;
|
||||
response.setHeader("Set-Cookie", [
|
||||
`${authKeyName}=${encryptedPayload};samesite=strict;path=/;HttpOnly=true;Expires=${COOKIE_EXPIRY_DATE}${secureCookie ? ";Secure=true" : ""}`,
|
||||
`${csrfName}=${user.csrf_k};samesite=strict;path=/;HttpOnly=true;Expires=${COOKIE_EXPIRY_DATE}`,
|
||||
]);
|
||||
}
|
||||
return httpResponse;
|
||||
});
|
||||
const httpsRequest = scheme.request({
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Content-Length": Buffer.from(reqPayload).length,
|
||||
Authorization: key ||
|
||||
process.env.DSQL_FULL_ACCESS_API_KEY ||
|
||||
process.env.DSQL_API_KEY,
|
||||
},
|
||||
port,
|
||||
hostname: host,
|
||||
path: `/api/user/${user_id || grabedHostNames.user_id}/github-login`,
|
||||
},
|
||||
/**
|
||||
* Callback Function
|
||||
*
|
||||
* @description https request callback
|
||||
*/
|
||||
(response) => {
|
||||
var str = "";
|
||||
response.on("data", function (chunk) {
|
||||
str += chunk;
|
||||
});
|
||||
response.on("end", function () {
|
||||
var _a;
|
||||
try {
|
||||
resolve(JSON.parse(str));
|
||||
}
|
||||
catch (error) {
|
||||
(_a = global.ERROR_CALLBACK) === null || _a === void 0 ? void 0 : _a.call(global, `Github Auth Error`, error);
|
||||
resolve({
|
||||
success: false,
|
||||
user: null,
|
||||
msg: "Something went wrong",
|
||||
});
|
||||
}
|
||||
});
|
||||
response.on("error", (err) => {
|
||||
reject(err);
|
||||
});
|
||||
});
|
||||
httpsRequest.write(reqPayload);
|
||||
httpsRequest.end();
|
||||
}));
|
||||
}
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
/**
|
||||
* Make https request
|
||||
*
|
||||
* @description make a request to datasquirel.com
|
||||
*/
|
||||
if ((httpResponse === null || httpResponse === void 0 ? void 0 : httpResponse.success) && (httpResponse === null || httpResponse === void 0 ? void 0 : httpResponse.user)) {
|
||||
let encryptedPayload = encrypt({
|
||||
data: JSON.stringify(httpResponse.user),
|
||||
encryptionKey,
|
||||
encryptionSalt,
|
||||
});
|
||||
const { user, dsqlUserId } = httpResponse;
|
||||
const authKeyName = `datasquirel_${dsqlUserId}_${database}_auth_key`;
|
||||
const csrfName = `datasquirel_${dsqlUserId}_${database}_csrf`;
|
||||
response.setHeader("Set-Cookie", [
|
||||
`${authKeyName}=${encryptedPayload};samesite=strict;path=/;HttpOnly=true;Expires=${COOKIE_EXPIRY_DATE}${secureCookie ? ";Secure=true" : ""}`,
|
||||
`${csrfName}=${user.csrf_k};samesite=strict;path=/;HttpOnly=true;Expires=${COOKIE_EXPIRY_DATE}`,
|
||||
]);
|
||||
}
|
||||
return httpResponse;
|
||||
}
|
||||
|
||||
+130
-147
@@ -1,161 +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 = googleAuth;
|
||||
const encrypt_1 = __importDefault(require("../../../functions/dsql/encrypt"));
|
||||
const grab_host_names_1 = __importDefault(require("../../../utils/grab-host-names"));
|
||||
const api_google_login_1 = __importDefault(require("../../../functions/api/users/social/api-google-login"));
|
||||
const get_auth_cookie_names_1 = __importDefault(require("../../../functions/backend/cookies/get-auth-cookie-names"));
|
||||
const write_auth_files_1 = require("../../../functions/backend/auth/write-auth-files");
|
||||
const grab_cookie_expirt_date_1 = __importDefault(require("../../../utils/grab-cookie-expirt-date"));
|
||||
import encrypt from "../../../functions/dsql/encrypt";
|
||||
import grabHostNames from "../../../utils/grab-host-names";
|
||||
import apiGoogleLogin from "../../../functions/api/users/social/api-google-login";
|
||||
import getAuthCookieNames from "../../../functions/backend/cookies/get-auth-cookie-names";
|
||||
import { writeAuthFile } from "../../../functions/backend/auth/write-auth-files";
|
||||
import grabCookieExpiryDate from "../../../utils/grab-cookie-expirt-date";
|
||||
/**
|
||||
* # SERVER FUNCTION: Login with google Function
|
||||
*/
|
||||
function googleAuth(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ key, token, database, response, encryptionKey, encryptionSalt, additionalFields, additionalData, apiUserID, debug, secureCookie, loginOnly, }) {
|
||||
var _b;
|
||||
const grabedHostNames = (0, grab_host_names_1.default)({
|
||||
userId: apiUserID || process.env.DSQL_API_USER_ID,
|
||||
});
|
||||
const { host, port, scheme, user_id } = grabedHostNames;
|
||||
const COOKIE_EXPIRY_DATE = (0, grab_cookie_expirt_date_1.default)();
|
||||
const finalEncryptionKey = encryptionKey || process.env.DSQL_ENCRYPTION_PASSWORD;
|
||||
const finalEncryptionSalt = encryptionSalt || process.env.DSQL_ENCRYPTION_SALT;
|
||||
if (!(finalEncryptionKey === null || finalEncryptionKey === void 0 ? void 0 : finalEncryptionKey.match(/.{8,}/))) {
|
||||
console.log("Encryption key is invalid");
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: "Encryption key is invalid",
|
||||
};
|
||||
}
|
||||
if (!(finalEncryptionSalt === null || finalEncryptionSalt === void 0 ? void 0 : finalEncryptionSalt.match(/.{8,}/))) {
|
||||
console.log("Encryption salt is invalid");
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: "Encryption salt is invalid",
|
||||
};
|
||||
}
|
||||
/**
|
||||
* Check inputs
|
||||
*
|
||||
* @description Check inputs
|
||||
*/
|
||||
if (!token || (token === null || token === void 0 ? void 0 : token.match(/ /))) {
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: "Please enter Google Access Token",
|
||||
};
|
||||
}
|
||||
/**
|
||||
* Initialize HTTP response variable
|
||||
*/
|
||||
let httpResponse = {
|
||||
export default async function googleAuth({ key, token, database, response, encryptionKey, encryptionSalt, additionalFields, additionalData, apiUserID, debug, secureCookie, loginOnly, }) {
|
||||
var _a;
|
||||
const grabedHostNames = grabHostNames({
|
||||
userId: apiUserID || process.env.DSQL_API_USER_ID,
|
||||
});
|
||||
const { host, port, scheme, user_id } = grabedHostNames;
|
||||
const COOKIE_EXPIRY_DATE = grabCookieExpiryDate();
|
||||
const finalEncryptionKey = encryptionKey || process.env.DSQL_ENCRYPTION_PASSWORD;
|
||||
const finalEncryptionSalt = encryptionSalt || process.env.DSQL_ENCRYPTION_SALT;
|
||||
if (!(finalEncryptionKey === null || finalEncryptionKey === void 0 ? void 0 : finalEncryptionKey.match(/.{8,}/))) {
|
||||
console.log("Encryption key is invalid");
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: "Encryption key is invalid",
|
||||
};
|
||||
/**
|
||||
* Check for local DB settings
|
||||
*
|
||||
* @description Look for local db settings in `.env` file and by pass the http request if available
|
||||
*/
|
||||
const { DSQL_DB_HOST, DSQL_DB_USERNAME, DSQL_DB_PASSWORD, DSQL_DB_NAME } = process.env;
|
||||
if ((DSQL_DB_HOST === null || DSQL_DB_HOST === void 0 ? void 0 : DSQL_DB_HOST.match(/./)) &&
|
||||
(DSQL_DB_USERNAME === null || DSQL_DB_USERNAME === void 0 ? void 0 : DSQL_DB_USERNAME.match(/./)) &&
|
||||
(DSQL_DB_PASSWORD === null || DSQL_DB_PASSWORD === void 0 ? void 0 : DSQL_DB_PASSWORD.match(/./)) &&
|
||||
(DSQL_DB_NAME === null || DSQL_DB_NAME === void 0 ? void 0 : DSQL_DB_NAME.match(/./)) &&
|
||||
global.DSQL_USE_LOCAL) {
|
||||
if (debug) {
|
||||
console.log(`Google login with Local Paradigm ...`);
|
||||
}
|
||||
httpResponse = yield (0, api_google_login_1.default)({
|
||||
}
|
||||
if (!(finalEncryptionSalt === null || finalEncryptionSalt === void 0 ? void 0 : finalEncryptionSalt.match(/.{8,}/))) {
|
||||
console.log("Encryption salt is invalid");
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: "Encryption salt is invalid",
|
||||
};
|
||||
}
|
||||
/**
|
||||
* Check inputs
|
||||
*
|
||||
* @description Check inputs
|
||||
*/
|
||||
if (!token || (token === null || token === void 0 ? void 0 : token.match(/ /))) {
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: "Please enter Google Access Token",
|
||||
};
|
||||
}
|
||||
/**
|
||||
* Initialize HTTP response variable
|
||||
*/
|
||||
let httpResponse = {
|
||||
success: false,
|
||||
};
|
||||
/**
|
||||
* Check for local DB settings
|
||||
*
|
||||
* @description Look for local db settings in `.env` file and by pass the http request if available
|
||||
*/
|
||||
const { DSQL_DB_HOST, DSQL_DB_USERNAME, DSQL_DB_PASSWORD, DSQL_DB_NAME } = process.env;
|
||||
if ((DSQL_DB_HOST === null || DSQL_DB_HOST === void 0 ? void 0 : DSQL_DB_HOST.match(/./)) &&
|
||||
(DSQL_DB_USERNAME === null || DSQL_DB_USERNAME === void 0 ? void 0 : DSQL_DB_USERNAME.match(/./)) &&
|
||||
(DSQL_DB_PASSWORD === null || DSQL_DB_PASSWORD === void 0 ? void 0 : DSQL_DB_PASSWORD.match(/./)) &&
|
||||
(DSQL_DB_NAME === null || DSQL_DB_NAME === void 0 ? void 0 : DSQL_DB_NAME.match(/./)) &&
|
||||
global.DSQL_USE_LOCAL) {
|
||||
if (debug) {
|
||||
console.log(`Google login with Local Paradigm ...`);
|
||||
}
|
||||
httpResponse = await apiGoogleLogin({
|
||||
token,
|
||||
additionalFields,
|
||||
additionalData,
|
||||
debug,
|
||||
});
|
||||
}
|
||||
else {
|
||||
httpResponse = await new Promise((resolve, reject) => {
|
||||
const reqPayload = JSON.stringify({
|
||||
token,
|
||||
database,
|
||||
additionalFields,
|
||||
additionalData,
|
||||
debug,
|
||||
});
|
||||
}
|
||||
else {
|
||||
httpResponse = yield new Promise((resolve, reject) => {
|
||||
const reqPayload = JSON.stringify({
|
||||
token,
|
||||
database,
|
||||
additionalFields,
|
||||
additionalData,
|
||||
const httpsRequest = scheme.request({
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Content-Length": Buffer.from(reqPayload).length,
|
||||
Authorization: key ||
|
||||
process.env.DSQL_FULL_ACCESS_API_KEY ||
|
||||
process.env.DSQL_API_KEY,
|
||||
},
|
||||
port,
|
||||
hostname: host,
|
||||
path: `/api/user/${apiUserID || grabedHostNames.user_id}/google-login`,
|
||||
},
|
||||
/**
|
||||
* Callback Function
|
||||
*
|
||||
* @description https request callback
|
||||
*/
|
||||
(response) => {
|
||||
var str = "";
|
||||
response.on("data", function (chunk) {
|
||||
str += chunk;
|
||||
});
|
||||
const httpsRequest = scheme.request({
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Content-Length": Buffer.from(reqPayload).length,
|
||||
Authorization: key ||
|
||||
process.env.DSQL_FULL_ACCESS_API_KEY ||
|
||||
process.env.DSQL_API_KEY,
|
||||
},
|
||||
port,
|
||||
hostname: host,
|
||||
path: `/api/user/${apiUserID || grabedHostNames.user_id}/google-login`,
|
||||
},
|
||||
/**
|
||||
* Callback Function
|
||||
*
|
||||
* @description https request callback
|
||||
*/
|
||||
(response) => {
|
||||
var str = "";
|
||||
response.on("data", function (chunk) {
|
||||
str += chunk;
|
||||
});
|
||||
response.on("end", function () {
|
||||
resolve(JSON.parse(str));
|
||||
});
|
||||
response.on("error", (err) => {
|
||||
reject(err);
|
||||
});
|
||||
response.on("end", function () {
|
||||
resolve(JSON.parse(str));
|
||||
});
|
||||
response.on("error", (err) => {
|
||||
reject(err);
|
||||
});
|
||||
httpsRequest.write(reqPayload);
|
||||
httpsRequest.end();
|
||||
});
|
||||
httpsRequest.write(reqPayload);
|
||||
httpsRequest.end();
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Make https request
|
||||
*
|
||||
* @description make a request to datasquirel.com
|
||||
*/
|
||||
if ((httpResponse === null || httpResponse === void 0 ? void 0 : httpResponse.success) && (httpResponse === null || httpResponse === void 0 ? void 0 : httpResponse.payload)) {
|
||||
let encryptedPayload = encrypt({
|
||||
data: JSON.stringify(httpResponse.payload),
|
||||
encryptionKey: finalEncryptionKey,
|
||||
encryptionSalt: finalEncryptionSalt,
|
||||
});
|
||||
const cookieNames = getAuthCookieNames({
|
||||
database,
|
||||
userId: user_id,
|
||||
});
|
||||
if (httpResponse.csrf) {
|
||||
writeAuthFile(httpResponse.csrf, JSON.stringify(httpResponse.payload));
|
||||
}
|
||||
/**
|
||||
* Make https request
|
||||
*
|
||||
* @description make a request to datasquirel.com
|
||||
*/
|
||||
if ((httpResponse === null || httpResponse === void 0 ? void 0 : httpResponse.success) && (httpResponse === null || httpResponse === void 0 ? void 0 : httpResponse.payload)) {
|
||||
let encryptedPayload = (0, encrypt_1.default)({
|
||||
data: JSON.stringify(httpResponse.payload),
|
||||
encryptionKey: finalEncryptionKey,
|
||||
encryptionSalt: finalEncryptionSalt,
|
||||
});
|
||||
const cookieNames = (0, get_auth_cookie_names_1.default)({
|
||||
database,
|
||||
userId: user_id,
|
||||
});
|
||||
if (httpResponse.csrf) {
|
||||
(0, write_auth_files_1.writeAuthFile)(httpResponse.csrf, JSON.stringify(httpResponse.payload));
|
||||
}
|
||||
httpResponse["cookieNames"] = cookieNames;
|
||||
httpResponse["key"] = String(encryptedPayload);
|
||||
const authKeyName = cookieNames.keyCookieName;
|
||||
const csrfName = cookieNames.csrfCookieName;
|
||||
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}`,
|
||||
]);
|
||||
}
|
||||
return httpResponse;
|
||||
});
|
||||
httpResponse["cookieNames"] = cookieNames;
|
||||
httpResponse["key"] = String(encryptedPayload);
|
||||
const authKeyName = cookieNames.keyCookieName;
|
||||
const csrfName = cookieNames.csrfCookieName;
|
||||
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}=${(_a = httpResponse.payload) === null || _a === void 0 ? void 0 : _a.csrf_k};samesite=strict;path=/;HttpOnly=true;;Expires=${COOKIE_EXPIRY_DATE}`,
|
||||
]);
|
||||
}
|
||||
return httpResponse;
|
||||
}
|
||||
|
||||
+74
-91
@@ -1,98 +1,81 @@
|
||||
"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 = updateUser;
|
||||
const path_1 = __importDefault(require("path"));
|
||||
const fs_1 = __importDefault(require("fs"));
|
||||
const grab_host_names_1 = __importDefault(require("../../utils/grab-host-names"));
|
||||
const api_update_user_1 = __importDefault(require("../../functions/api/users/api-update-user"));
|
||||
import path from "path";
|
||||
import fs from "fs";
|
||||
import grabHostNames from "../../utils/grab-host-names";
|
||||
import apiUpdateUser from "../../functions/api/users/api-update-user";
|
||||
/**
|
||||
* # Update User
|
||||
*/
|
||||
function updateUser(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ key, payload, database, user_id, updatedUserId, }) {
|
||||
/**
|
||||
* Check for local DB settings
|
||||
*
|
||||
* @description Look for local db settings in `.env` file and by pass the http request if available
|
||||
*/
|
||||
const { DSQL_DB_HOST, DSQL_DB_USERNAME, DSQL_DB_PASSWORD, DSQL_DB_NAME } = process.env;
|
||||
const grabedHostNames = (0, grab_host_names_1.default)();
|
||||
const { host, port, scheme } = grabedHostNames;
|
||||
if ((DSQL_DB_HOST === null || DSQL_DB_HOST === void 0 ? void 0 : DSQL_DB_HOST.match(/./)) &&
|
||||
(DSQL_DB_USERNAME === null || DSQL_DB_USERNAME === void 0 ? void 0 : DSQL_DB_USERNAME.match(/./)) &&
|
||||
(DSQL_DB_PASSWORD === null || DSQL_DB_PASSWORD === void 0 ? void 0 : DSQL_DB_PASSWORD.match(/./)) &&
|
||||
(DSQL_DB_NAME === null || DSQL_DB_NAME === void 0 ? void 0 : DSQL_DB_NAME.match(/./)) &&
|
||||
global.DSQL_USE_LOCAL) {
|
||||
/** @type {import("../../types").DSQL_DatabaseSchemaType | undefined} */
|
||||
let dbSchema;
|
||||
try {
|
||||
const localDbSchemaPath = path_1.default.resolve(process.cwd(), "dsql.schema.json");
|
||||
dbSchema = JSON.parse(fs_1.default.readFileSync(localDbSchemaPath, "utf8"));
|
||||
}
|
||||
catch (error) { }
|
||||
return yield (0, api_update_user_1.default)({
|
||||
payload: payload,
|
||||
dbFullName: DSQL_DB_NAME,
|
||||
updatedUserId,
|
||||
dbSchema,
|
||||
});
|
||||
export default async function updateUser({ key, payload, database, user_id, updatedUserId, }) {
|
||||
/**
|
||||
* Check for local DB settings
|
||||
*
|
||||
* @description Look for local db settings in `.env` file and by pass the http request if available
|
||||
*/
|
||||
const { DSQL_DB_HOST, DSQL_DB_USERNAME, DSQL_DB_PASSWORD, DSQL_DB_NAME } = process.env;
|
||||
const grabedHostNames = grabHostNames();
|
||||
const { host, port, scheme } = grabedHostNames;
|
||||
if ((DSQL_DB_HOST === null || DSQL_DB_HOST === void 0 ? void 0 : DSQL_DB_HOST.match(/./)) &&
|
||||
(DSQL_DB_USERNAME === null || DSQL_DB_USERNAME === void 0 ? void 0 : DSQL_DB_USERNAME.match(/./)) &&
|
||||
(DSQL_DB_PASSWORD === null || DSQL_DB_PASSWORD === void 0 ? void 0 : DSQL_DB_PASSWORD.match(/./)) &&
|
||||
(DSQL_DB_NAME === null || DSQL_DB_NAME === void 0 ? void 0 : DSQL_DB_NAME.match(/./)) &&
|
||||
global.DSQL_USE_LOCAL) {
|
||||
/** @type {import("../../types").DSQL_DatabaseSchemaType | undefined} */
|
||||
let dbSchema;
|
||||
try {
|
||||
const localDbSchemaPath = path.resolve(process.cwd(), "dsql.schema.json");
|
||||
dbSchema = JSON.parse(fs.readFileSync(localDbSchemaPath, "utf8"));
|
||||
}
|
||||
/**
|
||||
* Make https request
|
||||
*
|
||||
* @description make a request to datasquirel.com
|
||||
*/
|
||||
const httpResponse = yield new Promise((resolve, reject) => {
|
||||
const reqPayload = JSON.stringify({
|
||||
payload,
|
||||
database,
|
||||
updatedUserId,
|
||||
});
|
||||
const httpsRequest = scheme.request({
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Content-Length": Buffer.from(reqPayload).length,
|
||||
Authorization: process.env.DSQL_FULL_ACCESS_API_KEY ||
|
||||
process.env.DSQL_API_KEY ||
|
||||
key,
|
||||
},
|
||||
port,
|
||||
hostname: host,
|
||||
path: `/api/user/${user_id || grabedHostNames.user_id}/update-user`,
|
||||
},
|
||||
/**
|
||||
* Callback Function
|
||||
*
|
||||
* @description https request callback
|
||||
*/
|
||||
(response) => {
|
||||
var str = "";
|
||||
response.on("data", function (chunk) {
|
||||
str += chunk;
|
||||
});
|
||||
response.on("end", function () {
|
||||
resolve(JSON.parse(str));
|
||||
});
|
||||
response.on("error", (err) => {
|
||||
reject(err);
|
||||
});
|
||||
});
|
||||
httpsRequest.write(reqPayload);
|
||||
httpsRequest.end();
|
||||
catch (error) { }
|
||||
return await apiUpdateUser({
|
||||
payload: payload,
|
||||
dbFullName: DSQL_DB_NAME,
|
||||
updatedUserId,
|
||||
dbSchema,
|
||||
});
|
||||
return httpResponse;
|
||||
}
|
||||
/**
|
||||
* Make https request
|
||||
*
|
||||
* @description make a request to datasquirel.com
|
||||
*/
|
||||
const httpResponse = await new Promise((resolve, reject) => {
|
||||
const reqPayload = JSON.stringify({
|
||||
payload,
|
||||
database,
|
||||
updatedUserId,
|
||||
});
|
||||
const httpsRequest = scheme.request({
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Content-Length": Buffer.from(reqPayload).length,
|
||||
Authorization: process.env.DSQL_FULL_ACCESS_API_KEY ||
|
||||
process.env.DSQL_API_KEY ||
|
||||
key,
|
||||
},
|
||||
port,
|
||||
hostname: host,
|
||||
path: `/api/user/${user_id || grabedHostNames.user_id}/update-user`,
|
||||
},
|
||||
/**
|
||||
* Callback Function
|
||||
*
|
||||
* @description https request callback
|
||||
*/
|
||||
(response) => {
|
||||
var str = "";
|
||||
response.on("data", function (chunk) {
|
||||
str += chunk;
|
||||
});
|
||||
response.on("end", function () {
|
||||
resolve(JSON.parse(str));
|
||||
});
|
||||
response.on("error", (err) => {
|
||||
reject(err);
|
||||
});
|
||||
});
|
||||
httpsRequest.write(reqPayload);
|
||||
httpsRequest.end();
|
||||
});
|
||||
return httpResponse;
|
||||
}
|
||||
|
||||
+19
-25
@@ -1,16 +1,10 @@
|
||||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = userAuth;
|
||||
const decrypt_1 = __importDefault(require("../../functions/dsql/decrypt"));
|
||||
const get_auth_cookie_names_1 = __importDefault(require("../../functions/backend/cookies/get-auth-cookie-names"));
|
||||
const write_auth_files_1 = require("../../functions/backend/auth/write-auth-files");
|
||||
const parseCookies_1 = __importDefault(require("../../utils/backend/parseCookies"));
|
||||
const get_csrf_header_name_1 = __importDefault(require("../../actions/get-csrf-header-name"));
|
||||
const grab_host_names_1 = __importDefault(require("../../utils/grab-host-names"));
|
||||
const debug_log_1 = __importDefault(require("../../utils/logging/debug-log"));
|
||||
import decrypt from "../../functions/dsql/decrypt";
|
||||
import getAuthCookieNames from "../../functions/backend/cookies/get-auth-cookie-names";
|
||||
import { checkAuthFile } from "../../functions/backend/auth/write-auth-files";
|
||||
import parseCookies from "../../utils/backend/parseCookies";
|
||||
import getCsrfHeaderName from "../../actions/get-csrf-header-name";
|
||||
import grabHostNames from "../../utils/grab-host-names";
|
||||
import debugLog from "../../utils/logging/debug-log";
|
||||
const minuteInMilliseconds = 60000;
|
||||
const hourInMilliseconds = minuteInMilliseconds * 60;
|
||||
const dayInMilliseconds = hourInMilliseconds * 24;
|
||||
@@ -23,28 +17,28 @@ const yearInMilliseconds = dayInMilliseconds * 365;
|
||||
* @description This Function takes in a request object and returns a user object
|
||||
* with the user's data
|
||||
*/
|
||||
function userAuth({ request, req, encryptionKey, encryptionSalt, level, database, dsqlUserId, encryptedUserString, expiry = weekInMilliseconds, cookieString, csrfHeaderName, debug, skipFileCheck, }) {
|
||||
export default function userAuth({ request, req, encryptionKey, encryptionSalt, level, database, dsqlUserId, encryptedUserString, expiry = weekInMilliseconds, cookieString, csrfHeaderName, debug, skipFileCheck, }) {
|
||||
var _a;
|
||||
try {
|
||||
const finalRequest = req || request;
|
||||
const { user_id } = (0, grab_host_names_1.default)({ userId: dsqlUserId });
|
||||
const cookies = (0, parseCookies_1.default)({
|
||||
const { user_id } = grabHostNames({ userId: dsqlUserId });
|
||||
const cookies = parseCookies({
|
||||
request: finalRequest,
|
||||
cookieString,
|
||||
});
|
||||
if (debug) {
|
||||
(0, debug_log_1.default)({
|
||||
debugLog({
|
||||
log: cookies,
|
||||
addTime: true,
|
||||
label: "userAuth:cookies",
|
||||
});
|
||||
}
|
||||
const keyNames = (0, get_auth_cookie_names_1.default)({
|
||||
const keyNames = getAuthCookieNames({
|
||||
userId: user_id,
|
||||
database: database || process.env.DSQL_DB_NAME,
|
||||
});
|
||||
if (debug) {
|
||||
(0, debug_log_1.default)({
|
||||
debugLog({
|
||||
log: keyNames,
|
||||
addTime: true,
|
||||
label: "userAuth:keyNames",
|
||||
@@ -54,7 +48,7 @@ function userAuth({ request, req, encryptionKey, encryptionSalt, level, database
|
||||
? encryptedUserString
|
||||
: cookies[keyNames.keyCookieName];
|
||||
if (debug) {
|
||||
(0, debug_log_1.default)({
|
||||
debugLog({
|
||||
log: key,
|
||||
addTime: true,
|
||||
label: "userAuth:key",
|
||||
@@ -65,13 +59,13 @@ function userAuth({ request, req, encryptionKey, encryptionSalt, level, database
|
||||
*
|
||||
* @description Grab the payload
|
||||
*/
|
||||
let userPayloadJSON = (0, decrypt_1.default)({
|
||||
let userPayloadJSON = decrypt({
|
||||
encryptedString: key,
|
||||
encryptionKey,
|
||||
encryptionSalt,
|
||||
});
|
||||
if (debug) {
|
||||
(0, debug_log_1.default)({
|
||||
debugLog({
|
||||
log: userPayloadJSON,
|
||||
addTime: true,
|
||||
label: "userAuth:userPayloadJSON",
|
||||
@@ -92,7 +86,7 @@ function userAuth({ request, req, encryptionKey, encryptionSalt, level, database
|
||||
}
|
||||
let userObject = JSON.parse(userPayloadJSON);
|
||||
if (debug) {
|
||||
(0, debug_log_1.default)({
|
||||
debugLog({
|
||||
log: userObject,
|
||||
addTime: true,
|
||||
label: "userAuth:userObject",
|
||||
@@ -106,7 +100,7 @@ function userAuth({ request, req, encryptionKey, encryptionSalt, level, database
|
||||
cookieNames: keyNames,
|
||||
};
|
||||
}
|
||||
if (!skipFileCheck && !(0, write_auth_files_1.checkAuthFile)(userObject.csrf_k)) {
|
||||
if (!skipFileCheck && !checkAuthFile(userObject.csrf_k)) {
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
@@ -120,7 +114,7 @@ function userAuth({ request, req, encryptionKey, encryptionSalt, level, database
|
||||
* @description Grab the payload
|
||||
*/
|
||||
if ((level === null || level === void 0 ? void 0 : level.match(/deep/i)) && finalRequest) {
|
||||
const finalCsrfHeaderName = csrfHeaderName || (0, get_csrf_header_name_1.default)();
|
||||
const finalCsrfHeaderName = csrfHeaderName || getCsrfHeaderName();
|
||||
if (finalRequest.headers[finalCsrfHeaderName] !== userObject.csrf_k) {
|
||||
return {
|
||||
success: false,
|
||||
|
||||
+26
-43
@@ -1,49 +1,32 @@
|
||||
"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 = validateTempEmailCode;
|
||||
const get_auth_cookie_names_1 = __importDefault(require("../../functions/backend/cookies/get-auth-cookie-names"));
|
||||
const parseCookies_1 = __importDefault(require("../../utils/backend/parseCookies"));
|
||||
const decrypt_1 = __importDefault(require("../../functions/dsql/decrypt"));
|
||||
const ejson_1 = __importDefault(require("../../utils/ejson"));
|
||||
import getAuthCookieNames from "../../functions/backend/cookies/get-auth-cookie-names";
|
||||
import parseCookies from "../../utils/backend/parseCookies";
|
||||
import decrypt from "../../functions/dsql/decrypt";
|
||||
import EJSON from "../../utils/ejson";
|
||||
/**
|
||||
* # Verify the temp email code sent to the user's email address
|
||||
*/
|
||||
function validateTempEmailCode(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ request, email, cookieString, }) {
|
||||
var _b;
|
||||
try {
|
||||
const keyNames = (0, get_auth_cookie_names_1.default)();
|
||||
const oneTimeCodeCookieName = keyNames.oneTimeCodeName;
|
||||
const cookies = (0, parseCookies_1.default)({ request, cookieString });
|
||||
const encryptedOneTimeCode = cookies[oneTimeCodeCookieName];
|
||||
const encryptedPayload = (0, decrypt_1.default)({
|
||||
encryptedString: encryptedOneTimeCode,
|
||||
});
|
||||
const payload = ejson_1.default.parse(encryptedPayload);
|
||||
if ((payload === null || payload === void 0 ? void 0 : payload.email) && !email) {
|
||||
return payload;
|
||||
}
|
||||
if ((payload === null || payload === void 0 ? void 0 : payload.email) && payload.email === email) {
|
||||
return payload;
|
||||
}
|
||||
return null;
|
||||
export default async function validateTempEmailCode({ request, email, cookieString, }) {
|
||||
var _a;
|
||||
try {
|
||||
const keyNames = getAuthCookieNames();
|
||||
const oneTimeCodeCookieName = keyNames.oneTimeCodeName;
|
||||
const cookies = parseCookies({ request, cookieString });
|
||||
const encryptedOneTimeCode = cookies[oneTimeCodeCookieName];
|
||||
const encryptedPayload = decrypt({
|
||||
encryptedString: encryptedOneTimeCode,
|
||||
});
|
||||
const payload = EJSON.parse(encryptedPayload);
|
||||
if ((payload === null || payload === void 0 ? void 0 : payload.email) && !email) {
|
||||
return payload;
|
||||
}
|
||||
catch (error) {
|
||||
(_b = global.ERROR_CALLBACK) === null || _b === void 0 ? void 0 : _b.call(global, `Validate Temp Email Code Error`, error);
|
||||
console.log("validateTempEmailCode error:", error.message);
|
||||
return null;
|
||||
if ((payload === null || payload === void 0 ? void 0 : payload.email) && payload.email === email) {
|
||||
return payload;
|
||||
}
|
||||
});
|
||||
return null;
|
||||
}
|
||||
catch (error) {
|
||||
(_a = global.ERROR_CALLBACK) === null || _a === void 0 ? void 0 : _a.call(global, `Validate Temp Email Code Error`, error);
|
||||
console.log("validateTempEmailCode error:", error.message);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
+3
-9
@@ -1,16 +1,10 @@
|
||||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = validateToken;
|
||||
const decrypt_1 = __importDefault(require("../../functions/dsql/decrypt"));
|
||||
import decrypt from "../../functions/dsql/decrypt";
|
||||
/**
|
||||
* Validate Token
|
||||
* ======================================
|
||||
* @description This Function takes in a encrypted token and returns a user object
|
||||
*/
|
||||
function validateToken({ token, encryptionKey, encryptionSalt, }) {
|
||||
export default function validateToken({ token, encryptionKey, encryptionSalt, }) {
|
||||
var _a;
|
||||
try {
|
||||
/**
|
||||
@@ -24,7 +18,7 @@ function validateToken({ token, encryptionKey, encryptionSalt, }) {
|
||||
*
|
||||
* @description Grab the payload
|
||||
*/
|
||||
let userPayload = (0, decrypt_1.default)({
|
||||
let userPayload = decrypt({
|
||||
encryptedString: key,
|
||||
encryptionKey,
|
||||
encryptionSalt,
|
||||
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
import { SQLDeleteData } from "../../types";
|
||||
type Params<T extends {
|
||||
[key: string]: any;
|
||||
} = {
|
||||
[key: string]: any;
|
||||
}> = {
|
||||
dbName: string;
|
||||
tableName: string;
|
||||
deleteSpec?: T & {
|
||||
deleteKeyValues?: SQLDeleteData<T>[];
|
||||
};
|
||||
targetID?: string | number;
|
||||
};
|
||||
export default function apiCrudDELETE<T extends {
|
||||
[key: string]: any;
|
||||
} = {
|
||||
[key: string]: any;
|
||||
}>({ dbName, tableName, deleteSpec, targetID }: Params<T>): Promise<import("../../types").APIResponseObject<{
|
||||
[k: string]: any;
|
||||
}>>;
|
||||
export {};
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
import path from "path";
|
||||
import queryDSQLAPI from "../../functions/api/query-dsql-api";
|
||||
import grabAPIBasePath from "../../utils/grab-api-base-path";
|
||||
export default async function apiCrudDELETE({ dbName, tableName, deleteSpec, targetID }) {
|
||||
const basePath = grabAPIBasePath({ paradigm: "crud" });
|
||||
const finalID = typeof targetID === "number" ? String(targetID) : targetID;
|
||||
const finalPath = path.join(basePath, dbName, tableName, finalID || "");
|
||||
const GET_RES = await queryDSQLAPI({
|
||||
method: "DELETE",
|
||||
path: finalPath,
|
||||
body: deleteSpec,
|
||||
});
|
||||
return GET_RES;
|
||||
}
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
import { APIResponseObject, DsqlCrudQueryObject } from "../../types";
|
||||
type Params<T extends {
|
||||
[key: string]: any;
|
||||
} = {
|
||||
[key: string]: any;
|
||||
}> = {
|
||||
dbName: string;
|
||||
tableName: string;
|
||||
query?: DsqlCrudQueryObject<T>;
|
||||
targetId?: string | number;
|
||||
};
|
||||
export default function apiCrudGET<T extends {
|
||||
[key: string]: any;
|
||||
} = {
|
||||
[key: string]: any;
|
||||
}>({ dbName, tableName, query, targetId, }: Params<T>): Promise<APIResponseObject>;
|
||||
export {};
|
||||
Vendored
+14
@@ -0,0 +1,14 @@
|
||||
import path from "path";
|
||||
import queryDSQLAPI from "../../functions/api/query-dsql-api";
|
||||
import grabAPIBasePath from "../../utils/grab-api-base-path";
|
||||
export default async function apiCrudGET({ dbName, tableName, query, targetId, }) {
|
||||
const basePath = grabAPIBasePath({ paradigm: "crud" });
|
||||
const finalID = typeof targetId === "number" ? String(targetId) : targetId;
|
||||
const finalPath = path.join(basePath, dbName, tableName, finalID || "");
|
||||
const GET_RES = await queryDSQLAPI({
|
||||
method: "GET",
|
||||
path: finalPath,
|
||||
query,
|
||||
});
|
||||
return GET_RES;
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
import apiCrudGET from "./get";
|
||||
import apiCrudPOST from "./post";
|
||||
import apiCrudPUT from "./put";
|
||||
import apiCrudDELETE from "./delete";
|
||||
declare const crud: {
|
||||
get: typeof apiCrudGET;
|
||||
insert: typeof apiCrudPOST;
|
||||
update: typeof apiCrudPUT;
|
||||
delete: typeof apiCrudDELETE;
|
||||
options: () => Promise<void>;
|
||||
};
|
||||
export default crud;
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
import apiCrudGET from "./get";
|
||||
import apiCrudPOST from "./post";
|
||||
import apiCrudPUT from "./put";
|
||||
import apiCrudDELETE from "./delete";
|
||||
const crud = {
|
||||
get: apiCrudGET,
|
||||
insert: apiCrudPOST,
|
||||
update: apiCrudPUT,
|
||||
delete: apiCrudDELETE,
|
||||
options: async () => { },
|
||||
};
|
||||
export default crud;
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
import { APIResponseObject } from "../../types";
|
||||
export type APICrudPostParams<T extends {
|
||||
[key: string]: any;
|
||||
} = {
|
||||
[key: string]: any;
|
||||
}> = {
|
||||
dbName: string;
|
||||
tableName: string;
|
||||
body: T;
|
||||
update?: boolean;
|
||||
};
|
||||
export default function apiCrudPOST<T extends {
|
||||
[key: string]: any;
|
||||
} = {
|
||||
[key: string]: any;
|
||||
}>({ dbName, tableName, body, update, }: APICrudPostParams<T>): Promise<APIResponseObject>;
|
||||
Vendored
+19
@@ -0,0 +1,19 @@
|
||||
import path from "path";
|
||||
import queryDSQLAPI from "../../functions/api/query-dsql-api";
|
||||
import grabAPIBasePath from "../../utils/grab-api-base-path";
|
||||
export default async function apiCrudPOST({ dbName, tableName, body, update, }) {
|
||||
const basePath = grabAPIBasePath({ paradigm: "crud" });
|
||||
const passedID = body.id;
|
||||
const finalID = update
|
||||
? typeof passedID === "number"
|
||||
? String(passedID)
|
||||
: passedID
|
||||
: undefined;
|
||||
const finalPath = path.join(basePath, dbName, tableName, finalID || "");
|
||||
const GET_RES = await queryDSQLAPI({
|
||||
method: update ? "PUT" : "POST",
|
||||
path: finalPath,
|
||||
body,
|
||||
});
|
||||
return GET_RES;
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
import { APICrudPostParams } from "./post";
|
||||
type Params<T extends {
|
||||
[key: string]: any;
|
||||
} = {
|
||||
[key: string]: any;
|
||||
}> = Omit<APICrudPostParams<T>, "update"> & {
|
||||
targetID: string | number;
|
||||
};
|
||||
export default function apiCrudPUT<T extends {
|
||||
[key: string]: any;
|
||||
} = {
|
||||
[key: string]: any;
|
||||
}>({ dbName, tableName, body, targetID }: Params<T>): Promise<import("../../types").APIResponseObject>;
|
||||
export {};
|
||||
Vendored
+13
@@ -0,0 +1,13 @@
|
||||
import apiCrudPOST from "./post";
|
||||
export default async function apiCrudPUT({ dbName, tableName, body, targetID }) {
|
||||
const updatedBody = Object.assign({}, body);
|
||||
if (targetID) {
|
||||
updatedBody["id"] = targetID;
|
||||
}
|
||||
return await apiCrudPOST({
|
||||
dbName,
|
||||
tableName,
|
||||
body: updatedBody,
|
||||
update: true,
|
||||
});
|
||||
}
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
import { APIResponseObject } from "../../types";
|
||||
import { DSQL_DATASQUIREL_USER_MEDIA } from "../../types/dsql";
|
||||
export default function apiMediaDELETE(params: {
|
||||
mediaID?: string | number;
|
||||
}): Promise<APIResponseObject<DSQL_DATASQUIREL_USER_MEDIA | DSQL_DATASQUIREL_USER_MEDIA[]>>;
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
import queryDSQLAPI from "../../functions/api/query-dsql-api";
|
||||
import path from "path";
|
||||
import grabAPIBasePath from "../../utils/grab-api-base-path";
|
||||
export default async function apiMediaDELETE(params) {
|
||||
const basePath = grabAPIBasePath({ paradigm: "media" });
|
||||
const mediaID = params.mediaID
|
||||
? typeof params.mediaID === "number"
|
||||
? String(params.mediaID)
|
||||
: params.mediaID
|
||||
: undefined;
|
||||
const finalPath = path.join(basePath, mediaID || "");
|
||||
const DELETE_MEDIA_RES = await queryDSQLAPI({
|
||||
method: "DELETE",
|
||||
path: finalPath,
|
||||
});
|
||||
return DELETE_MEDIA_RES;
|
||||
}
|
||||
+3
@@ -0,0 +1,3 @@
|
||||
import { APIGetMediaParams, APIResponseObject } from "../../types";
|
||||
import { DSQL_DATASQUIREL_USER_MEDIA } from "../../types/dsql";
|
||||
export default function apiMediaGET(params: APIGetMediaParams): Promise<APIResponseObject<DSQL_DATASQUIREL_USER_MEDIA | DSQL_DATASQUIREL_USER_MEDIA[]>>;
|
||||
Vendored
+18
@@ -0,0 +1,18 @@
|
||||
import queryDSQLAPI from "../../functions/api/query-dsql-api";
|
||||
import path from "path";
|
||||
import grabAPIBasePath from "../../utils/grab-api-base-path";
|
||||
export default async function apiMediaGET(params) {
|
||||
const basePath = grabAPIBasePath({ paradigm: "media" });
|
||||
const mediaID = params.mediaID
|
||||
? typeof params.mediaID === "number"
|
||||
? String(params.mediaID)
|
||||
: params.mediaID
|
||||
: undefined;
|
||||
const finalPath = path.join(basePath, mediaID || "");
|
||||
const GET_MEDIA_RES = await queryDSQLAPI({
|
||||
method: "GET",
|
||||
path: finalPath,
|
||||
query: params,
|
||||
});
|
||||
return GET_MEDIA_RES;
|
||||
}
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
import apiMediaGET from "./get";
|
||||
import apiMediaPOST from "./post";
|
||||
import apiMediaDELETE from "./delete";
|
||||
declare const media: {
|
||||
get: typeof apiMediaGET;
|
||||
add: typeof apiMediaPOST;
|
||||
delete: typeof apiMediaDELETE;
|
||||
};
|
||||
export default media;
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
import apiMediaGET from "./get";
|
||||
import apiMediaPOST from "./post";
|
||||
import apiMediaDELETE from "./delete";
|
||||
const media = {
|
||||
get: apiMediaGET,
|
||||
add: apiMediaPOST,
|
||||
delete: apiMediaDELETE,
|
||||
};
|
||||
export default media;
|
||||
+3
@@ -0,0 +1,3 @@
|
||||
import { AddMediaAPIBody, APIResponseObject } from "../../types";
|
||||
import { DSQL_DATASQUIREL_USER_MEDIA } from "../../types/dsql";
|
||||
export default function apiMediaPOST(params: AddMediaAPIBody): Promise<APIResponseObject<DSQL_DATASQUIREL_USER_MEDIA | DSQL_DATASQUIREL_USER_MEDIA[]>>;
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
import queryDSQLAPI from "../../functions/api/query-dsql-api";
|
||||
import grabAPIBasePath from "../../utils/grab-api-base-path";
|
||||
export default async function apiMediaPOST(params) {
|
||||
const basePath = grabAPIBasePath({ paradigm: "media" });
|
||||
const POST_MEDIA_RES = await queryDSQLAPI({
|
||||
method: "POST",
|
||||
path: basePath,
|
||||
body: params,
|
||||
});
|
||||
return POST_MEDIA_RES;
|
||||
}
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
declare const user: {};
|
||||
export default user;
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
const user = {};
|
||||
export default user;
|
||||
+87
@@ -0,0 +1,87 @@
|
||||
declare const DataTypes: readonly [{
|
||||
readonly title: "VARCHAR";
|
||||
readonly name: "VARCHAR";
|
||||
readonly value: "0-255";
|
||||
readonly argument: true;
|
||||
readonly description: "Varchar is simply letters and numbers within the range 0 - 255";
|
||||
readonly maxValue: 255;
|
||||
}, {
|
||||
readonly title: "TINYINT";
|
||||
readonly name: "TINYINT";
|
||||
readonly value: "0-100";
|
||||
readonly description: "TINYINT means Integers: 0 to 100";
|
||||
readonly maxValue: 127;
|
||||
}, {
|
||||
readonly title: "SMALLINT";
|
||||
readonly name: "SMALLINT";
|
||||
readonly value: "0-255";
|
||||
readonly description: "SMALLINT means Integers: 0 to 240933";
|
||||
readonly maxValue: 32767;
|
||||
}, {
|
||||
readonly title: "MEDIUMINT";
|
||||
readonly name: "MEDIUMINT";
|
||||
readonly value: "0-255";
|
||||
readonly description: "MEDIUMINT means Integers: 0 to 1245568545560";
|
||||
readonly maxValue: 8388607;
|
||||
}, {
|
||||
readonly title: "INT";
|
||||
readonly name: "INT";
|
||||
readonly value: "0-255";
|
||||
readonly description: "INT means Integers: 0 to 12560";
|
||||
readonly maxValue: 2147483647;
|
||||
}, {
|
||||
readonly title: "BIGINT";
|
||||
readonly name: "BIGINT";
|
||||
readonly value: "0-255";
|
||||
readonly description: "BIGINT means Integers: 0 to 1245569056767568545560";
|
||||
readonly maxValue: 2e+63;
|
||||
}, {
|
||||
readonly title: "TINYTEXT";
|
||||
readonly name: "TINYTEXT";
|
||||
readonly value: "0-255";
|
||||
readonly description: "Text with 255 max characters";
|
||||
readonly maxValue: 127;
|
||||
}, {
|
||||
readonly title: "TEXT";
|
||||
readonly name: "TEXT";
|
||||
readonly value: "0-100";
|
||||
readonly description: "MEDIUMTEXT is just text with max length 16,777,215";
|
||||
}, {
|
||||
readonly title: "MEDIUMTEXT";
|
||||
readonly name: "MEDIUMTEXT";
|
||||
readonly value: "0-255";
|
||||
readonly description: "MEDIUMTEXT is just text with max length 16,777,215";
|
||||
}, {
|
||||
readonly title: "LONGTEXT";
|
||||
readonly name: "LONGTEXT";
|
||||
readonly value: "0-255";
|
||||
readonly description: "LONGTEXT is just text with max length 4,294,967,295";
|
||||
}, {
|
||||
readonly title: "DECIMAL";
|
||||
readonly name: "DECIMAL";
|
||||
readonly description: "Numbers with decimals";
|
||||
readonly integer: "1-100";
|
||||
readonly decimals: "1-4";
|
||||
}, {
|
||||
readonly title: "FLOAT";
|
||||
readonly name: "FLOAT";
|
||||
readonly description: "Numbers with decimals";
|
||||
readonly integer: "1-100";
|
||||
readonly decimals: "1-4";
|
||||
}, {
|
||||
readonly title: "DOUBLE";
|
||||
readonly name: "DOUBLE";
|
||||
readonly description: "Numbers with decimals";
|
||||
readonly integer: "1-100";
|
||||
readonly decimals: "1-4";
|
||||
}, {
|
||||
readonly title: "UUID";
|
||||
readonly name: "UUID";
|
||||
readonly valueLiteral: "UUID()";
|
||||
readonly description: "A Unique ID";
|
||||
}, {
|
||||
readonly title: "TIMESTAMP";
|
||||
readonly name: "TIMESTAMP";
|
||||
readonly description: "Time Stamp";
|
||||
}];
|
||||
export default DataTypes;
|
||||
+103
@@ -0,0 +1,103 @@
|
||||
const DataTypes = [
|
||||
{
|
||||
title: "VARCHAR",
|
||||
name: "VARCHAR",
|
||||
value: "0-255",
|
||||
argument: true,
|
||||
description: "Varchar is simply letters and numbers within the range 0 - 255",
|
||||
maxValue: 255,
|
||||
},
|
||||
{
|
||||
title: "TINYINT",
|
||||
name: "TINYINT",
|
||||
value: "0-100",
|
||||
description: "TINYINT means Integers: 0 to 100",
|
||||
maxValue: 127,
|
||||
},
|
||||
{
|
||||
title: "SMALLINT",
|
||||
name: "SMALLINT",
|
||||
value: "0-255",
|
||||
description: "SMALLINT means Integers: 0 to 240933",
|
||||
maxValue: 32767,
|
||||
},
|
||||
{
|
||||
title: "MEDIUMINT",
|
||||
name: "MEDIUMINT",
|
||||
value: "0-255",
|
||||
description: "MEDIUMINT means Integers: 0 to 1245568545560",
|
||||
maxValue: 8388607,
|
||||
},
|
||||
{
|
||||
title: "INT",
|
||||
name: "INT",
|
||||
value: "0-255",
|
||||
description: "INT means Integers: 0 to 12560",
|
||||
maxValue: 2147483647,
|
||||
},
|
||||
{
|
||||
title: "BIGINT",
|
||||
name: "BIGINT",
|
||||
value: "0-255",
|
||||
description: "BIGINT means Integers: 0 to 1245569056767568545560",
|
||||
maxValue: 2e63,
|
||||
},
|
||||
{
|
||||
title: "TINYTEXT",
|
||||
name: "TINYTEXT",
|
||||
value: "0-255",
|
||||
description: "Text with 255 max characters",
|
||||
maxValue: 127,
|
||||
},
|
||||
{
|
||||
title: "TEXT",
|
||||
name: "TEXT",
|
||||
value: "0-100",
|
||||
description: "MEDIUMTEXT is just text with max length 16,777,215",
|
||||
},
|
||||
{
|
||||
title: "MEDIUMTEXT",
|
||||
name: "MEDIUMTEXT",
|
||||
value: "0-255",
|
||||
description: "MEDIUMTEXT is just text with max length 16,777,215",
|
||||
},
|
||||
{
|
||||
title: "LONGTEXT",
|
||||
name: "LONGTEXT",
|
||||
value: "0-255",
|
||||
description: "LONGTEXT is just text with max length 4,294,967,295",
|
||||
},
|
||||
{
|
||||
title: "DECIMAL",
|
||||
name: "DECIMAL",
|
||||
description: "Numbers with decimals",
|
||||
integer: "1-100",
|
||||
decimals: "1-4",
|
||||
},
|
||||
{
|
||||
title: "FLOAT",
|
||||
name: "FLOAT",
|
||||
description: "Numbers with decimals",
|
||||
integer: "1-100",
|
||||
decimals: "1-4",
|
||||
},
|
||||
{
|
||||
title: "DOUBLE",
|
||||
name: "DOUBLE",
|
||||
description: "Numbers with decimals",
|
||||
integer: "1-100",
|
||||
decimals: "1-4",
|
||||
},
|
||||
{
|
||||
title: "UUID",
|
||||
name: "UUID",
|
||||
valueLiteral: "UUID()",
|
||||
description: "A Unique ID",
|
||||
},
|
||||
{
|
||||
title: "TIMESTAMP",
|
||||
name: "TIMESTAMP",
|
||||
description: "Time Stamp",
|
||||
},
|
||||
];
|
||||
export default DataTypes;
|
||||
+105
@@ -0,0 +1,105 @@
|
||||
const DataTypes = [
|
||||
{
|
||||
title: "VARCHAR",
|
||||
name: "VARCHAR",
|
||||
value: "0-255",
|
||||
argument: true,
|
||||
description:
|
||||
"Varchar is simply letters and numbers within the range 0 - 255",
|
||||
maxValue: 255,
|
||||
},
|
||||
{
|
||||
title: "TINYINT",
|
||||
name: "TINYINT",
|
||||
value: "0-100",
|
||||
description: "TINYINT means Integers: 0 to 100",
|
||||
maxValue: 127,
|
||||
},
|
||||
{
|
||||
title: "SMALLINT",
|
||||
name: "SMALLINT",
|
||||
value: "0-255",
|
||||
description: "SMALLINT means Integers: 0 to 240933",
|
||||
maxValue: 32767,
|
||||
},
|
||||
{
|
||||
title: "MEDIUMINT",
|
||||
name: "MEDIUMINT",
|
||||
value: "0-255",
|
||||
description: "MEDIUMINT means Integers: 0 to 1245568545560",
|
||||
maxValue: 8388607,
|
||||
},
|
||||
{
|
||||
title: "INT",
|
||||
name: "INT",
|
||||
value: "0-255",
|
||||
description: "INT means Integers: 0 to 12560",
|
||||
maxValue: 2147483647,
|
||||
},
|
||||
{
|
||||
title: "BIGINT",
|
||||
name: "BIGINT",
|
||||
value: "0-255",
|
||||
description: "BIGINT means Integers: 0 to 1245569056767568545560",
|
||||
maxValue: 2e63,
|
||||
},
|
||||
{
|
||||
title: "TINYTEXT",
|
||||
name: "TINYTEXT",
|
||||
value: "0-255",
|
||||
description: "Text with 255 max characters",
|
||||
maxValue: 127,
|
||||
},
|
||||
{
|
||||
title: "TEXT",
|
||||
name: "TEXT",
|
||||
value: "0-100",
|
||||
description: "MEDIUMTEXT is just text with max length 16,777,215",
|
||||
},
|
||||
{
|
||||
title: "MEDIUMTEXT",
|
||||
name: "MEDIUMTEXT",
|
||||
value: "0-255",
|
||||
description: "MEDIUMTEXT is just text with max length 16,777,215",
|
||||
},
|
||||
{
|
||||
title: "LONGTEXT",
|
||||
name: "LONGTEXT",
|
||||
value: "0-255",
|
||||
description: "LONGTEXT is just text with max length 4,294,967,295",
|
||||
},
|
||||
{
|
||||
title: "DECIMAL",
|
||||
name: "DECIMAL",
|
||||
description: "Numbers with decimals",
|
||||
integer: "1-100",
|
||||
decimals: "1-4",
|
||||
},
|
||||
{
|
||||
title: "FLOAT",
|
||||
name: "FLOAT",
|
||||
description: "Numbers with decimals",
|
||||
integer: "1-100",
|
||||
decimals: "1-4",
|
||||
},
|
||||
{
|
||||
title: "DOUBLE",
|
||||
name: "DOUBLE",
|
||||
description: "Numbers with decimals",
|
||||
integer: "1-100",
|
||||
decimals: "1-4",
|
||||
},
|
||||
{
|
||||
title: "UUID",
|
||||
name: "UUID",
|
||||
valueLiteral: "UUID()",
|
||||
description: "A Unique ID",
|
||||
},
|
||||
{
|
||||
title: "TIMESTAMP",
|
||||
name: "TIMESTAMP",
|
||||
description: "Time Stamp",
|
||||
},
|
||||
] as const;
|
||||
|
||||
export default DataTypes;
|
||||
+8
@@ -88,6 +88,14 @@
|
||||
"integer": "1-100",
|
||||
"decimals": "1-4"
|
||||
},
|
||||
{
|
||||
"title": "OPTIONS",
|
||||
"name": "VARCHAR",
|
||||
"value": "250",
|
||||
"argument": true,
|
||||
"description": "This is a custom field which is a varchar under the hood",
|
||||
"maxValue": 255
|
||||
},
|
||||
{
|
||||
"title": "UUID",
|
||||
"name": "UUID",
|
||||
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
export declare const AppNames: {
|
||||
readonly MaxScaleUserName: "dsql_maxscale_user";
|
||||
readonly ReplicaUserName: "dsql_replication_user";
|
||||
readonly DsqlDbPrefix: "datasquirel_user_";
|
||||
readonly PrivateMediaProceedureName: "dsql_UpdateUserMedia";
|
||||
readonly PrivateMediaInsertTriggerName: "dsql_trg_user_private_folders_insert";
|
||||
readonly PrivateMediaDeleteTriggerName: "dsql_trg_user_private_folders_delete";
|
||||
};
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
export const AppNames = {
|
||||
MaxScaleUserName: "dsql_maxscale_user",
|
||||
ReplicaUserName: "dsql_replication_user",
|
||||
DsqlDbPrefix: "datasquirel_user_",
|
||||
PrivateMediaProceedureName: "dsql_UpdateUserMedia",
|
||||
PrivateMediaInsertTriggerName: "dsql_trg_user_private_folders_insert",
|
||||
PrivateMediaDeleteTriggerName: "dsql_trg_user_private_folders_delete",
|
||||
};
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
export declare const CookieNames: {
|
||||
readonly OneTimeLoginEmail: "dsql-one-time-login-email";
|
||||
readonly DelegatedUserId: "dsql-delegated-user-id";
|
||||
readonly DelegatedDatabase: "dsql-delegated-database";
|
||||
};
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
export const CookieNames = {
|
||||
OneTimeLoginEmail: "dsql-one-time-login-email",
|
||||
DelegatedUserId: "dsql-delegated-user-id",
|
||||
DelegatedDatabase: "dsql-delegated-database",
|
||||
};
|
||||
@@ -0,0 +1,7 @@
|
||||
export declare const LocalStorageDict: {
|
||||
OneTimeEmail: string;
|
||||
User: string;
|
||||
CSRF: string;
|
||||
CurrentQueue: string;
|
||||
DiskUsage: string;
|
||||
};
|
||||
@@ -0,0 +1,8 @@
|
||||
import getCsrfHeaderName from "../actions/get-csrf-header-name";
|
||||
export const LocalStorageDict = {
|
||||
OneTimeEmail: "dsql-one-time-login-email",
|
||||
User: "user",
|
||||
CSRF: getCsrfHeaderName(),
|
||||
CurrentQueue: "current_queue",
|
||||
DiskUsage: "disk_usage",
|
||||
};
|
||||
@@ -0,0 +1,6 @@
|
||||
declare const ResourceLimits: {
|
||||
readonly user_databases: 20;
|
||||
readonly table_entries: 20;
|
||||
readonly general: 20;
|
||||
};
|
||||
export default ResourceLimits;
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
const ResourceLimits = {
|
||||
user_databases: 20,
|
||||
table_entries: 20,
|
||||
general: 20,
|
||||
};
|
||||
export default ResourceLimits;
|
||||
@@ -0,0 +1,20 @@
|
||||
import { APIResponseObject, DataCrudRequestMethods, DataCrudRequestMethodsLowerCase } from "../../types";
|
||||
type Param<T = {
|
||||
[k: string]: any;
|
||||
}> = {
|
||||
key?: string;
|
||||
body?: T;
|
||||
query?: T;
|
||||
useDefault?: boolean;
|
||||
path: string;
|
||||
method?: (typeof DataCrudRequestMethods)[number] | (typeof DataCrudRequestMethodsLowerCase)[number];
|
||||
};
|
||||
/**
|
||||
* # Query DSQL API
|
||||
*/
|
||||
export default function queryDSQLAPI<T = {
|
||||
[k: string]: any;
|
||||
}, P = {
|
||||
[k: string]: any;
|
||||
}>({ key, body, query, useDefault, path: passedPath, method, }: Param<T>): Promise<APIResponseObject<P>>;
|
||||
export {};
|
||||
@@ -0,0 +1,73 @@
|
||||
import path from "path";
|
||||
import grabHostNames from "../../utils/grab-host-names";
|
||||
import serializeQuery from "../../utils/serialize-query";
|
||||
/**
|
||||
* # Query DSQL API
|
||||
*/
|
||||
export default async function queryDSQLAPI({ key, body, query, useDefault, path: passedPath, method, }) {
|
||||
const grabedHostNames = grabHostNames({ useDefault });
|
||||
const { host, port, scheme } = grabedHostNames;
|
||||
try {
|
||||
/**
|
||||
* Make https request
|
||||
*
|
||||
* @description make a request to datasquirel.com
|
||||
*/
|
||||
const httpResponse = await new Promise((resolve, reject) => {
|
||||
const reqPayload = body ? JSON.stringify(body) : undefined;
|
||||
let headers = {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: key ||
|
||||
(!method || method == "GET" || method == "get"
|
||||
? process.env.DSQL_READ_ONLY_API_KEY
|
||||
: undefined) ||
|
||||
process.env.DSQL_FULL_ACCESS_API_KEY ||
|
||||
process.env.DSQL_API_KEY,
|
||||
};
|
||||
if (reqPayload) {
|
||||
headers["Content-Length"] = Buffer.from(reqPayload).length;
|
||||
}
|
||||
let finalPath = path.join("/", passedPath);
|
||||
if (query) {
|
||||
const queryString = serializeQuery(query);
|
||||
finalPath += `${queryString}`;
|
||||
}
|
||||
const httpsRequest = scheme.request({
|
||||
method: method || "GET",
|
||||
headers,
|
||||
port,
|
||||
hostname: host,
|
||||
path: finalPath,
|
||||
},
|
||||
/**
|
||||
* Callback Function
|
||||
*
|
||||
* @description https request callback
|
||||
*/
|
||||
(response) => {
|
||||
var str = "";
|
||||
response.on("data", function (chunk) {
|
||||
str += chunk;
|
||||
});
|
||||
response.on("end", function () {
|
||||
resolve(JSON.parse(str));
|
||||
});
|
||||
response.on("error", (err) => {
|
||||
reject(err);
|
||||
});
|
||||
});
|
||||
if (reqPayload) {
|
||||
httpsRequest.write(reqPayload);
|
||||
}
|
||||
httpsRequest.end();
|
||||
});
|
||||
return httpResponse;
|
||||
}
|
||||
catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
payload: undefined,
|
||||
msg: error.message,
|
||||
};
|
||||
}
|
||||
}
|
||||
+69
-89
@@ -1,94 +1,74 @@
|
||||
"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 = apiGet;
|
||||
const lodash_1 = __importDefault(require("lodash"));
|
||||
const serverError_1 = __importDefault(require("../../backend/serverError"));
|
||||
const runQuery_1 = __importDefault(require("../../backend/db/runQuery"));
|
||||
const grab_query_and_values_1 = __importDefault(require("../../../utils/grab-query-and-values"));
|
||||
import _ from "lodash";
|
||||
import serverError from "../../backend/serverError";
|
||||
import runQuery from "../../backend/db/runQuery";
|
||||
import apiGetGrabQueryAndValues from "../../../utils/grab-query-and-values";
|
||||
/**
|
||||
* # Get Function FOr API
|
||||
*/
|
||||
function apiGet(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ query, dbFullName, queryValues, tableName, dbSchema, debug, dbContext, forceLocal, }) {
|
||||
var _b, _c;
|
||||
const queryAndValues = (0, grab_query_and_values_1.default)({
|
||||
query,
|
||||
values: queryValues,
|
||||
});
|
||||
if (typeof query == "string" && query.match(/^alter|^delete|^create/i)) {
|
||||
return { success: false, msg: "Wrong Input." };
|
||||
}
|
||||
let results;
|
||||
try {
|
||||
let { result, error } = yield (0, runQuery_1.default)({
|
||||
dbFullName: dbFullName,
|
||||
query: queryAndValues.query,
|
||||
queryValuesArray: queryAndValues.values,
|
||||
readOnly: true,
|
||||
dbSchema,
|
||||
tableName,
|
||||
dbContext,
|
||||
debug,
|
||||
forceLocal,
|
||||
});
|
||||
if (debug && global.DSQL_USE_LOCAL) {
|
||||
console.log("apiGet:result", result);
|
||||
console.log("apiGet:error", error);
|
||||
}
|
||||
let tableSchema;
|
||||
if (dbSchema) {
|
||||
const targetTable = (_b = dbSchema.tables) === null || _b === void 0 ? void 0 : _b.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;
|
||||
const resObject = {
|
||||
success: true,
|
||||
payload: results,
|
||||
schema: tableName && tableSchema ? tableSchema : undefined,
|
||||
};
|
||||
return resObject;
|
||||
}
|
||||
catch (error) {
|
||||
(0, serverError_1.default)({
|
||||
component: "/api/query/get/lines-85-94",
|
||||
message: error.message,
|
||||
});
|
||||
(_c = global.ERROR_CALLBACK) === null || _c === void 0 ? void 0 : _c.call(global, `API Get Error`, error);
|
||||
if (debug && global.DSQL_USE_LOCAL) {
|
||||
console.log("apiGet:error", error.message);
|
||||
console.log("queryAndValues", queryAndValues);
|
||||
}
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
error: error.message,
|
||||
};
|
||||
}
|
||||
export default async function apiGet({ query, dbFullName, queryValues, tableName, dbSchema, debug, dbContext, forceLocal, }) {
|
||||
var _a, _b;
|
||||
const queryAndValues = apiGetGrabQueryAndValues({
|
||||
query,
|
||||
values: queryValues,
|
||||
});
|
||||
if (typeof query == "string" && query.match(/^alter|^delete|^create/i)) {
|
||||
return { success: false, msg: "Wrong Input." };
|
||||
}
|
||||
let results;
|
||||
try {
|
||||
let { result, error } = await runQuery({
|
||||
dbFullName: dbFullName,
|
||||
query: queryAndValues.query,
|
||||
queryValuesArray: queryAndValues.values,
|
||||
readOnly: true,
|
||||
dbSchema,
|
||||
tableName,
|
||||
dbContext,
|
||||
debug,
|
||||
forceLocal,
|
||||
});
|
||||
if (debug && global.DSQL_USE_LOCAL) {
|
||||
console.log("apiGet:result", result);
|
||||
console.log("apiGet:error", error);
|
||||
}
|
||||
let tableSchema;
|
||||
if (dbSchema) {
|
||||
const targetTable = (_a = dbSchema.tables) === null || _a === void 0 ? void 0 : _a.find((table) => table.tableName === tableName);
|
||||
if (targetTable) {
|
||||
const clonedTargetTable = _.cloneDeep(targetTable);
|
||||
delete clonedTargetTable.childTable;
|
||||
delete clonedTargetTable.childrenTables;
|
||||
delete clonedTargetTable.updateData;
|
||||
delete clonedTargetTable.indexes;
|
||||
tableSchema = clonedTargetTable;
|
||||
}
|
||||
}
|
||||
if (error)
|
||||
throw error;
|
||||
if (result.error)
|
||||
throw new Error(result.error);
|
||||
results = result;
|
||||
const resObject = {
|
||||
success: true,
|
||||
payload: results,
|
||||
schema: tableName && tableSchema ? tableSchema : undefined,
|
||||
};
|
||||
return resObject;
|
||||
}
|
||||
catch (error) {
|
||||
serverError({
|
||||
component: "/api/query/get/lines-85-94",
|
||||
message: error.message,
|
||||
});
|
||||
(_b = global.ERROR_CALLBACK) === null || _b === void 0 ? void 0 : _b.call(global, `API Get Error`, error);
|
||||
if (debug && global.DSQL_USE_LOCAL) {
|
||||
console.log("apiGet:error", error.message);
|
||||
console.log("queryAndValues", queryAndValues);
|
||||
}
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
error: error.message,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
+73
-93
@@ -1,100 +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 = apiPost;
|
||||
const lodash_1 = __importDefault(require("lodash"));
|
||||
const serverError_1 = __importDefault(require("../../backend/serverError"));
|
||||
const runQuery_1 = __importDefault(require("../../backend/db/runQuery"));
|
||||
const debug_log_1 = __importDefault(require("../../../utils/logging/debug-log"));
|
||||
import _ from "lodash";
|
||||
import serverError from "../../backend/serverError";
|
||||
import runQuery from "../../backend/db/runQuery";
|
||||
import debugLog from "../../../utils/logging/debug-log";
|
||||
/**
|
||||
* # Post Function For API
|
||||
*/
|
||||
function apiPost(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ query, dbFullName, queryValues, tableName, dbSchema, dbContext, forceLocal, debug, }) {
|
||||
var _b, _c;
|
||||
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" };
|
||||
}
|
||||
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,
|
||||
dbContext,
|
||||
forceLocal,
|
||||
debug,
|
||||
export default async function apiPost({ query, dbFullName, queryValues, tableName, dbSchema, dbContext, forceLocal, debug, }) {
|
||||
var _a, _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" &&
|
||||
((_a = query === null || query === void 0 ? void 0 : query.action) === null || _a === void 0 ? void 0 : _a.match(/^create |^alter |^drop /i))) {
|
||||
return { success: false, msg: "Wrong Input" };
|
||||
}
|
||||
let results;
|
||||
/**
|
||||
* Create new user folder and file
|
||||
*
|
||||
* @description Create new user folder and file
|
||||
*/
|
||||
try {
|
||||
let { result, error } = await runQuery({
|
||||
dbFullName,
|
||||
query,
|
||||
dbSchema,
|
||||
queryValuesArray: queryValues,
|
||||
tableName,
|
||||
dbContext,
|
||||
forceLocal,
|
||||
debug,
|
||||
});
|
||||
if (debug) {
|
||||
debugLog({
|
||||
log: result,
|
||||
addTime: true,
|
||||
label: "result",
|
||||
});
|
||||
if (debug) {
|
||||
(0, debug_log_1.default)({
|
||||
log: result,
|
||||
addTime: true,
|
||||
label: "result",
|
||||
});
|
||||
(0, debug_log_1.default)({
|
||||
log: query,
|
||||
addTime: true,
|
||||
label: "query",
|
||||
});
|
||||
}
|
||||
results = result;
|
||||
if (error)
|
||||
throw new Error(error);
|
||||
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,
|
||||
debugLog({
|
||||
log: query,
|
||||
addTime: true,
|
||||
label: "query",
|
||||
});
|
||||
(_c = global.ERROR_CALLBACK) === null || _c === void 0 ? void 0 : _c.call(global, `API Post Error`, error);
|
||||
return {
|
||||
success: false,
|
||||
payload: results,
|
||||
error: error.message,
|
||||
};
|
||||
}
|
||||
});
|
||||
results = result;
|
||||
if (error)
|
||||
throw new Error(error);
|
||||
let tableSchema;
|
||||
if (dbSchema) {
|
||||
const targetTable = dbSchema.tables.find((table) => table.tableName === tableName);
|
||||
if (targetTable) {
|
||||
const clonedTargetTable = _.cloneDeep(targetTable);
|
||||
delete clonedTargetTable.childTable;
|
||||
delete clonedTargetTable.childrenTables;
|
||||
delete clonedTargetTable.updateData;
|
||||
delete clonedTargetTable.indexes;
|
||||
tableSchema = clonedTargetTable;
|
||||
}
|
||||
}
|
||||
return {
|
||||
success: true,
|
||||
payload: results,
|
||||
error: error,
|
||||
schema: tableName && tableSchema ? tableSchema : undefined,
|
||||
};
|
||||
}
|
||||
catch (error) {
|
||||
serverError({
|
||||
component: "/api/query/post/lines-132-142",
|
||||
message: error.message,
|
||||
});
|
||||
(_b = global.ERROR_CALLBACK) === null || _b === void 0 ? void 0 : _b.call(global, `API Post Error`, error);
|
||||
return {
|
||||
success: false,
|
||||
payload: results,
|
||||
error: error.message,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
+27
-44
@@ -1,35 +1,19 @@
|
||||
"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"));
|
||||
import DB_HANDLER from "../../../utils/backend/global-db/DB_HANDLER";
|
||||
import serverError from "../../backend/serverError";
|
||||
import hashPassword from "../../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} (
|
||||
export default async function facebookLogin({ usertype, body, }) {
|
||||
try {
|
||||
const foundUser = await DB_HANDLER(`SELECT * FROM users WHERE email='${body.facebookUserEmail}' AND social_login='1'`);
|
||||
if (foundUser && foundUser[0]) {
|
||||
return foundUser[0];
|
||||
}
|
||||
let socialHashedPassword = hashPassword({
|
||||
password: body.facebookUserId,
|
||||
});
|
||||
let newUser = await DB_HANDLER(`INSERT INTO ${usertype} (
|
||||
first_name,
|
||||
last_name,
|
||||
social_platform,
|
||||
@@ -49,8 +33,8 @@ function facebookLogin(_a) {
|
||||
'${body.facebookUserLastName}',
|
||||
'facebook',
|
||||
'facebook_${body.facebookUserEmail
|
||||
? body.facebookUserEmail.replace(/@.*/, "")
|
||||
: body.facebookUserFirstName.toLowerCase()}',
|
||||
? body.facebookUserEmail.replace(/@.*/, "")
|
||||
: body.facebookUserFirstName.toLowerCase()}',
|
||||
'${body.facebookUserEmail}',
|
||||
'${body.facebookUserImage}',
|
||||
'${body.facebookUserImage}',
|
||||
@@ -62,17 +46,16 @@ function facebookLogin(_a) {
|
||||
'${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,
|
||||
};
|
||||
});
|
||||
const newFoundUser = await DB_HANDLER(`SELECT * FROM ${usertype} WHERE id='${newUser.insertId}'`);
|
||||
}
|
||||
catch ( /** @type {any} */error) {
|
||||
serverError({
|
||||
component: "functions/backend/facebookLogin",
|
||||
message: error.message,
|
||||
});
|
||||
}
|
||||
return {
|
||||
isFacebookAuthValid: false,
|
||||
newFoundUser: null,
|
||||
};
|
||||
}
|
||||
|
||||
+39
-56
@@ -1,62 +1,45 @@
|
||||
"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"));
|
||||
import DB_HANDLER from "../../../utils/backend/global-db/DB_HANDLER";
|
||||
import httpsRequest from "../../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;
|
||||
}
|
||||
export default async function githubLogin({ code, clientId, clientSecret, }) {
|
||||
let gitHubUser;
|
||||
try {
|
||||
const response = await httpsRequest({
|
||||
method: "POST",
|
||||
hostname: "github.com",
|
||||
path: `/login/oauth/access_token?client_id=${clientId}&client_secret=${clientSecret}&code=${code}`,
|
||||
headers: {
|
||||
Accept: "application/json",
|
||||
"User-Agent": "*",
|
||||
},
|
||||
scheme: "https",
|
||||
});
|
||||
const accessTokenObject = JSON.parse(response);
|
||||
if (!(accessTokenObject === null || accessTokenObject === void 0 ? void 0 : accessTokenObject.access_token)) {
|
||||
return gitHubUser;
|
||||
}
|
||||
const userDataResponse = await httpsRequest({
|
||||
method: "GET",
|
||||
hostname: "api.github.com",
|
||||
path: "/user",
|
||||
headers: {
|
||||
Authorization: `Bearer ${accessTokenObject.access_token}`,
|
||||
"User-Agent": "*",
|
||||
},
|
||||
scheme: "https",
|
||||
});
|
||||
gitHubUser = JSON.parse(userDataResponse);
|
||||
if (!(gitHubUser === null || gitHubUser === void 0 ? void 0 : gitHubUser.email) && gitHubUser) {
|
||||
const existingGithubUser = await DB_HANDLER(`SELECT email FROM users WHERE social_login='1' AND social_platform='github' AND social_id='${gitHubUser.id}'`);
|
||||
if (existingGithubUser && existingGithubUser[0]) {
|
||||
gitHubUser.email = existingGithubUser[0].email;
|
||||
}
|
||||
}
|
||||
catch ( /** @type {any} */error) {
|
||||
console.log("ERROR in githubLogin.ts backend function =>", error.message);
|
||||
}
|
||||
return gitHubUser;
|
||||
});
|
||||
}
|
||||
catch ( /** @type {any} */error) {
|
||||
console.log("ERROR in githubLogin.ts backend function =>", error.message);
|
||||
}
|
||||
return gitHubUser;
|
||||
}
|
||||
|
||||
+71
-88
@@ -1,82 +1,66 @@
|
||||
"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"));
|
||||
import { OAuth2Client } from "google-auth-library";
|
||||
import serverError from "../../backend/serverError";
|
||||
import DB_HANDLER from "../../../utils/backend/global-db/DB_HANDLER";
|
||||
import hashPassword from "../../dsql/hashPassword";
|
||||
/**
|
||||
* # Google Login
|
||||
*/
|
||||
function googleLogin(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ usertype, foundUser, isSocialValidated, isUserValid, reqBody, serverRes, loginFailureReason, }) {
|
||||
var _b, _c;
|
||||
const client = new google_auth_library_1.OAuth2Client(process.env.DSQL_GOOGLE_CLIENT_ID);
|
||||
let isGoogleAuthValid = false;
|
||||
let newFoundUser = null;
|
||||
export default async function googleLogin({ usertype, foundUser, isSocialValidated, isUserValid, reqBody, serverRes, loginFailureReason, }) {
|
||||
var _a, _b;
|
||||
const client = new OAuth2Client(process.env.DSQL_GOOGLE_CLIENT_ID);
|
||||
let isGoogleAuthValid = false;
|
||||
let newFoundUser = null;
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
try {
|
||||
const ticket = await client.verifyIdToken({
|
||||
idToken: reqBody.token,
|
||||
audience: process.env.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 = hashPassword({
|
||||
password: payload.at_hash || "",
|
||||
});
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
try {
|
||||
const ticket = yield client.verifyIdToken({
|
||||
idToken: reqBody.token,
|
||||
audience: process.env.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} (
|
||||
let existinEmail = await DB_HANDLER(`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 = await DB_HANDLER(`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 = await DB_HANDLER(`INSERT INTO ${usertype} (
|
||||
first_name,
|
||||
last_name,
|
||||
social_platform,
|
||||
@@ -95,7 +79,7 @@ function googleLogin(_a) {
|
||||
'${payload.given_name}',
|
||||
'${payload.family_name}',
|
||||
'google',
|
||||
'google_${(_b = payload.email) === null || _b === void 0 ? void 0 : _b.replace(/@.*/, "")}',
|
||||
'google_${(_a = payload.email) === null || _a === void 0 ? void 0 : _a.replace(/@.*/, "")}',
|
||||
'${payload.sub}',
|
||||
'${payload.email}',
|
||||
'${payload.picture}',
|
||||
@@ -107,18 +91,17 @@ function googleLogin(_a) {
|
||||
'${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,
|
||||
});
|
||||
(_c = global.ERROR_CALLBACK) === null || _c === void 0 ? void 0 : _c.call(global, `Google Login Error`, error);
|
||||
loginFailureReason = error;
|
||||
isUserValid = false;
|
||||
isSocialValidated = false;
|
||||
}
|
||||
return { isGoogleAuthValid: isGoogleAuthValid, newFoundUser: newFoundUser };
|
||||
});
|
||||
newFoundUser = await DB_HANDLER(`SELECT * FROM ${usertype} WHERE id='${newUser.insertId}'`);
|
||||
}
|
||||
catch (error) {
|
||||
serverError({
|
||||
component: "googleLogin",
|
||||
message: error.message,
|
||||
});
|
||||
(_b = global.ERROR_CALLBACK) === null || _b === void 0 ? void 0 : _b.call(global, `Google Login Error`, error);
|
||||
loginFailureReason = error;
|
||||
isUserValid = false;
|
||||
isSocialValidated = false;
|
||||
}
|
||||
return { isGoogleAuthValid: isGoogleAuthValid, newFoundUser: newFoundUser };
|
||||
}
|
||||
|
||||
+191
-207
@@ -1,217 +1,201 @@
|
||||
"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"));
|
||||
import fs from "fs";
|
||||
import handleNodemailer from "../../backend/handleNodemailer";
|
||||
import path from "path";
|
||||
import addMariadbUser from "../../backend/addMariadbUser";
|
||||
import varDatabaseDbHandler from "../../backend/varDatabaseDbHandler";
|
||||
import encrypt from "../../dsql/encrypt";
|
||||
import addDbEntry from "../../backend/db/addDbEntry";
|
||||
import loginSocialUser from "./loginSocialUser";
|
||||
import grabDirNames from "../../../utils/backend/names/grab-dir-names";
|
||||
/**
|
||||
* # Handle Social DB
|
||||
*/
|
||||
function handleSocialDb(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ database, email, social_platform, payload, invitation, supEmail, additionalFields, debug, loginOnly, }) {
|
||||
var _b;
|
||||
try {
|
||||
const finalDbName = global.DSQL_USE_LOCAL
|
||||
? undefined
|
||||
: database
|
||||
? database
|
||||
: "datasquirel";
|
||||
const dbAppend = global.DSQL_USE_LOCAL ? "" : `${finalDbName}.`;
|
||||
const existingSocialUserQUery = `SELECT * FROM ${dbAppend}users WHERE email = ? AND social_login='1' AND social_platform = ? `;
|
||||
const existingSocialUserValues = [email, social_platform];
|
||||
if (debug) {
|
||||
console.log("handleSocialDb:existingSocialUserQUery", existingSocialUserQUery);
|
||||
console.log("handleSocialDb:existingSocialUserValues", existingSocialUserValues);
|
||||
}
|
||||
let existingSocialUser = yield (0, varDatabaseDbHandler_1.default)({
|
||||
database: finalDbName,
|
||||
queryString: existingSocialUserQUery,
|
||||
queryValuesArray: existingSocialUserValues,
|
||||
debug,
|
||||
});
|
||||
if (debug) {
|
||||
console.log("handleSocialDb:existingSocialUser", existingSocialUser);
|
||||
}
|
||||
if (existingSocialUser === null || existingSocialUser === void 0 ? void 0 : existingSocialUser[0]) {
|
||||
return yield (0, loginSocialUser_1.default)({
|
||||
user: existingSocialUser[0],
|
||||
social_platform,
|
||||
invitation,
|
||||
database: finalDbName,
|
||||
additionalFields,
|
||||
debug,
|
||||
});
|
||||
}
|
||||
else if (loginOnly) {
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: "User Does not Exist",
|
||||
};
|
||||
}
|
||||
const finalEmail = email ? email : supEmail ? supEmail : null;
|
||||
if (!finalEmail) {
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: "No Email Present",
|
||||
};
|
||||
}
|
||||
const existingEmailOnlyQuery = `SELECT * FROM ${dbAppend}users WHERE email='${finalEmail}'`;
|
||||
if (debug) {
|
||||
console.log("handleSocialDb:existingEmailOnlyQuery", existingEmailOnlyQuery);
|
||||
}
|
||||
let existingEmailOnly = yield (0, varDatabaseDbHandler_1.default)({
|
||||
database: finalDbName,
|
||||
queryString: existingEmailOnlyQuery,
|
||||
debug,
|
||||
});
|
||||
if (debug) {
|
||||
console.log("handleSocialDb:existingEmailOnly", existingEmailOnly);
|
||||
}
|
||||
if (existingEmailOnly === null || existingEmailOnly === void 0 ? void 0 : existingEmailOnly[0]) {
|
||||
return yield (0, loginSocialUser_1.default)({
|
||||
user: existingEmailOnly[0],
|
||||
social_platform,
|
||||
invitation,
|
||||
database: finalDbName,
|
||||
additionalFields,
|
||||
debug,
|
||||
});
|
||||
}
|
||||
else if (loginOnly) {
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: "Social Account Creation Not allowed",
|
||||
};
|
||||
}
|
||||
const socialHashedPassword = (0, encrypt_1.default)({
|
||||
data: email,
|
||||
});
|
||||
const data = {
|
||||
social_login: "1",
|
||||
verification_status: supEmail ? "0" : "1",
|
||||
password: socialHashedPassword,
|
||||
};
|
||||
Object.keys(payload).forEach((key) => {
|
||||
data[key] = payload[key];
|
||||
});
|
||||
const newUser = yield (0, addDbEntry_1.default)({
|
||||
dbContext: finalDbName ? "Dsql User" : undefined,
|
||||
paradigm: finalDbName ? "Full Access" : undefined,
|
||||
dbFullName: finalDbName,
|
||||
tableName: "users",
|
||||
duplicateColumnName: "email",
|
||||
duplicateColumnValue: finalEmail,
|
||||
data: Object.assign(Object.assign({}, data), { email: finalEmail }),
|
||||
});
|
||||
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 });
|
||||
}
|
||||
const newUserQueriedQuery = `SELECT * FROM ${dbAppend}users WHERE id='${newUser.insertId}'`;
|
||||
const newUserQueried = yield (0, varDatabaseDbHandler_1.default)({
|
||||
database: finalDbName,
|
||||
queryString: newUserQueriedQuery,
|
||||
debug,
|
||||
});
|
||||
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: finalDbName,
|
||||
additionalFields,
|
||||
debug,
|
||||
});
|
||||
}
|
||||
else {
|
||||
console.log("Social User Failed to insert in 'handleSocialDb.ts' backend function =>", newUser);
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: "Social User Failed to insert in 'handleSocialDb.ts' backend function",
|
||||
};
|
||||
}
|
||||
export default async function handleSocialDb({ database, email, social_platform, payload, invitation, supEmail, additionalFields, debug, loginOnly, }) {
|
||||
var _a, _b;
|
||||
try {
|
||||
const finalDbName = global.DSQL_USE_LOCAL
|
||||
? undefined
|
||||
: database
|
||||
? database
|
||||
: "datasquirel";
|
||||
const dbAppend = global.DSQL_USE_LOCAL ? "" : `${finalDbName}.`;
|
||||
const existingSocialUserQUery = `SELECT * FROM ${dbAppend}users WHERE email = ? AND social_login='1' AND social_platform = ? `;
|
||||
const existingSocialUserValues = [email, social_platform];
|
||||
if (debug) {
|
||||
console.log("handleSocialDb:existingSocialUserQUery", existingSocialUserQUery);
|
||||
console.log("handleSocialDb:existingSocialUserValues", existingSocialUserValues);
|
||||
}
|
||||
catch (error) {
|
||||
console.log("ERROR in 'handleSocialDb.ts' backend function =>", error.message);
|
||||
(_b = global.ERROR_CALLBACK) === null || _b === void 0 ? void 0 : _b.call(global, `Handle Social DB Error`, error);
|
||||
let existingSocialUser = await varDatabaseDbHandler({
|
||||
database: finalDbName,
|
||||
queryString: existingSocialUserQUery,
|
||||
queryValuesArray: existingSocialUserValues,
|
||||
debug,
|
||||
});
|
||||
if (debug) {
|
||||
console.log("handleSocialDb:existingSocialUser", existingSocialUser);
|
||||
}
|
||||
if (existingSocialUser === null || existingSocialUser === void 0 ? void 0 : existingSocialUser[0]) {
|
||||
return await loginSocialUser({
|
||||
user: existingSocialUser[0],
|
||||
social_platform,
|
||||
invitation,
|
||||
database: finalDbName,
|
||||
additionalFields,
|
||||
debug,
|
||||
});
|
||||
}
|
||||
else if (loginOnly) {
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: error.message,
|
||||
msg: "User Does not Exist",
|
||||
};
|
||||
}
|
||||
});
|
||||
const finalEmail = email ? email : supEmail ? supEmail : null;
|
||||
if (!finalEmail) {
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: "No Email Present",
|
||||
};
|
||||
}
|
||||
const existingEmailOnlyQuery = `SELECT * FROM ${dbAppend}users WHERE email='${finalEmail}'`;
|
||||
if (debug) {
|
||||
console.log("handleSocialDb:existingEmailOnlyQuery", existingEmailOnlyQuery);
|
||||
}
|
||||
let existingEmailOnly = await varDatabaseDbHandler({
|
||||
database: finalDbName,
|
||||
queryString: existingEmailOnlyQuery,
|
||||
debug,
|
||||
});
|
||||
if (debug) {
|
||||
console.log("handleSocialDb:existingEmailOnly", existingEmailOnly);
|
||||
}
|
||||
if (existingEmailOnly === null || existingEmailOnly === void 0 ? void 0 : existingEmailOnly[0]) {
|
||||
return await loginSocialUser({
|
||||
user: existingEmailOnly[0],
|
||||
social_platform,
|
||||
invitation,
|
||||
database: finalDbName,
|
||||
additionalFields,
|
||||
debug,
|
||||
});
|
||||
}
|
||||
else if (loginOnly) {
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: "Social Account Creation Not allowed",
|
||||
};
|
||||
}
|
||||
const socialHashedPassword = encrypt({
|
||||
data: email,
|
||||
});
|
||||
const data = {
|
||||
social_login: "1",
|
||||
verification_status: supEmail ? "0" : "1",
|
||||
password: socialHashedPassword,
|
||||
};
|
||||
Object.keys(payload).forEach((key) => {
|
||||
data[key] = payload[key];
|
||||
});
|
||||
const newUser = await addDbEntry({
|
||||
dbContext: finalDbName ? "Dsql User" : undefined,
|
||||
paradigm: finalDbName ? "Full Access" : undefined,
|
||||
dbFullName: finalDbName,
|
||||
tableName: "users",
|
||||
duplicateColumnName: "email",
|
||||
duplicateColumnValue: finalEmail,
|
||||
data: Object.assign(Object.assign({}, data), { email: finalEmail }),
|
||||
});
|
||||
if ((_a = newUser === null || newUser === void 0 ? void 0 : newUser.payload) === null || _a === void 0 ? void 0 : _a.insertId) {
|
||||
if (!database) {
|
||||
/**
|
||||
* Add a Mariadb User for this User
|
||||
*/
|
||||
await addMariadbUser({ userId: newUser.payload.insertId });
|
||||
}
|
||||
const newUserQueriedQuery = `SELECT * FROM ${dbAppend}users WHERE id='${newUser.payload.insertId}'`;
|
||||
const newUserQueried = await varDatabaseDbHandler({
|
||||
database: finalDbName,
|
||||
queryString: newUserQueriedQuery,
|
||||
debug,
|
||||
});
|
||||
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 = encrypt({
|
||||
data: JSON.stringify({
|
||||
id: newUser.payload.insertId,
|
||||
email: supEmail,
|
||||
dateCode: Date.now(),
|
||||
}),
|
||||
});
|
||||
handleNodemailer({
|
||||
to: supEmail,
|
||||
subject: "Verify Email Address",
|
||||
text: "Please click the link to verify your email address",
|
||||
html: fs
|
||||
.readFileSync("./email/send-email-verification-link.html", "utf8")
|
||||
.replace(/{{host}}/, process.env.DSQL_HOST || "")
|
||||
.replace(/{{token}}/, generatedToken || ""),
|
||||
}).then(() => { });
|
||||
}
|
||||
const { STATIC_ROOT } = grabDirNames();
|
||||
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.payload.insertId}`;
|
||||
let newUserMediaFolderPath = path.join(STATIC_ROOT, `images/user-images/user-${newUser.payload.insertId}`);
|
||||
fs.mkdirSync(newUserSchemaFolderPath);
|
||||
fs.mkdirSync(newUserMediaFolderPath);
|
||||
fs.writeFileSync(`${newUserSchemaFolderPath}/main.json`, JSON.stringify([]), "utf8");
|
||||
}
|
||||
return await loginSocialUser({
|
||||
user: newUserQueried[0],
|
||||
social_platform,
|
||||
invitation,
|
||||
database: finalDbName,
|
||||
additionalFields,
|
||||
debug,
|
||||
});
|
||||
}
|
||||
else {
|
||||
console.log("Social User Failed to insert in 'handleSocialDb.ts' backend function =>", newUser);
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: "Social User Failed to insert in 'handleSocialDb.ts' backend function",
|
||||
};
|
||||
}
|
||||
}
|
||||
catch (error) {
|
||||
console.log("ERROR in 'handleSocialDb.ts' backend function =>", error.message);
|
||||
(_b = global.ERROR_CALLBACK) === null || _b === void 0 ? void 0 : _b.call(global, `Handle Social DB Error`, error);
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: error.message,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,81 +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 = loginSocialUser;
|
||||
const addAdminUserOnLogin_1 = __importDefault(require("../../backend/addAdminUserOnLogin"));
|
||||
const varDatabaseDbHandler_1 = __importDefault(require("../../backend/varDatabaseDbHandler"));
|
||||
import addAdminUserOnLogin from "../../backend/addAdminUserOnLogin";
|
||||
import varDatabaseDbHandler from "../../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, 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, varDatabaseDbHandler_1.default)({
|
||||
database: finalDbName,
|
||||
queryString: foundUserQuery,
|
||||
queryValuesArray: foundUserValues,
|
||||
debug,
|
||||
});
|
||||
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;
|
||||
export default async function loginSocialUser({ 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 = await varDatabaseDbHandler({
|
||||
database: finalDbName,
|
||||
queryString: foundUserQuery,
|
||||
queryValuesArray: foundUserValues,
|
||||
debug,
|
||||
});
|
||||
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$/)))) {
|
||||
addAdminUserOnLogin({
|
||||
query: invitation,
|
||||
user: userPayload,
|
||||
});
|
||||
}
|
||||
let result = {
|
||||
success: true,
|
||||
payload: userPayload,
|
||||
csrf: csrfKey,
|
||||
};
|
||||
return result;
|
||||
}
|
||||
|
||||
@@ -20,6 +20,6 @@ export default function apiCreateUser({ encryptionKey, payload, database, userId
|
||||
} | {
|
||||
success: boolean;
|
||||
msg: string;
|
||||
sqlResult: import("../../../types").PostInsertReturn | null;
|
||||
sqlResult: import("../../../types").APIResponseObject<import("../../../types").PostInsertReturn>;
|
||||
payload: null;
|
||||
}>;
|
||||
|
||||
+126
-129
@@ -1,143 +1,140 @@
|
||||
"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"));
|
||||
const validate_email_1 = __importDefault(require("../../email/fns/validate-email"));
|
||||
import { findDbNameInSchemaDir } from "../../../shell/createDbFromSchema/grab-required-database-schemas";
|
||||
import addUsersTableToDb from "../../backend/addUsersTableToDb";
|
||||
import addDbEntry from "../../backend/db/addDbEntry";
|
||||
import updateUsersTableSchema from "../../backend/updateUsersTableSchema";
|
||||
import varDatabaseDbHandler from "../../backend/varDatabaseDbHandler";
|
||||
import hashPassword from "../../dsql/hashPassword";
|
||||
import validateEmail from "../../email/fns/validate-email";
|
||||
/**
|
||||
* # API Create User
|
||||
*/
|
||||
function apiCreateUser(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ encryptionKey, payload, database, userId, }) {
|
||||
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),
|
||||
export default async function apiCreateUser({ encryptionKey, payload, database, userId, }) {
|
||||
var _a;
|
||||
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 targetDbSchema = findDbNameInSchemaDir({
|
||||
dbName: dbFullName,
|
||||
userId,
|
||||
});
|
||||
if (!(targetDbSchema === null || targetDbSchema === void 0 ? void 0 : targetDbSchema.id)) {
|
||||
return {
|
||||
success: false,
|
||||
msg: "targetDbSchema not found",
|
||||
payload: null,
|
||||
};
|
||||
}
|
||||
const hashedPassword = hashPassword({
|
||||
encryptionKey: finalEncryptionKey,
|
||||
password: String(payload.password),
|
||||
});
|
||||
payload.password = hashedPassword;
|
||||
const fieldsQuery = `SHOW COLUMNS FROM ${dbFullName}.users`;
|
||||
let fields = await varDatabaseDbHandler({
|
||||
queryString: fieldsQuery,
|
||||
database: dbFullName,
|
||||
});
|
||||
if (!(fields === null || fields === void 0 ? void 0 : fields[0])) {
|
||||
const newTable = await addUsersTableToDb({
|
||||
userId: Number(API_USER_ID),
|
||||
database: dbFullName,
|
||||
payload: payload,
|
||||
dbId: targetDbSchema.id,
|
||||
});
|
||||
payload.password = hashedPassword;
|
||||
const fieldsQuery = `SHOW COLUMNS FROM ${dbFullName}.users`;
|
||||
let fields = yield (0, varDatabaseDbHandler_1.default)({
|
||||
fields = await varDatabaseDbHandler({
|
||||
queryString: fieldsQuery,
|
||||
database: dbFullName,
|
||||
});
|
||||
if (!(fields === null || fields === void 0 ? void 0 : fields[0])) {
|
||||
const newTable = yield (0, addUsersTableToDb_1.default)({
|
||||
}
|
||||
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)) {
|
||||
await updateUsersTableSchema({
|
||||
userId: Number(API_USER_ID),
|
||||
database: dbFullName,
|
||||
payload: payload,
|
||||
});
|
||||
fields = yield (0, varDatabaseDbHandler_1.default)({
|
||||
queryString: fieldsQuery,
|
||||
database: dbFullName,
|
||||
newPayload: {
|
||||
[key]: payload[key],
|
||||
},
|
||||
dbId: targetDbSchema.id,
|
||||
});
|
||||
}
|
||||
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 ${dbFullName}.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,
|
||||
}
|
||||
if (invalidField) {
|
||||
return {
|
||||
success: false,
|
||||
msg: `${invalidField} is not a valid field!`,
|
||||
};
|
||||
}
|
||||
const existingUserQuery = `SELECT * FROM ${dbFullName}.users WHERE email = ?${payload.username ? " OR username = ?" : ""}`;
|
||||
const existingUserValues = payload.username
|
||||
? [payload.email, payload.username]
|
||||
: [payload.email];
|
||||
const existingUser = await varDatabaseDbHandler({
|
||||
queryString: existingUserQuery,
|
||||
queryValuesArray: existingUserValues,
|
||||
database: dbFullName,
|
||||
});
|
||||
if (existingUser === null || existingUser === void 0 ? void 0 : existingUser[0]) {
|
||||
return {
|
||||
success: false,
|
||||
msg: "User Already Exists",
|
||||
payload: null,
|
||||
};
|
||||
}
|
||||
const isEmailValid = await validateEmail({ email: payload.email });
|
||||
if (!isEmailValid.isValid) {
|
||||
return {
|
||||
success: false,
|
||||
msg: isEmailValid.message,
|
||||
payload: null,
|
||||
};
|
||||
}
|
||||
const addUser = await addDbEntry({
|
||||
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" }),
|
||||
});
|
||||
if ((_a = addUser === null || addUser === void 0 ? void 0 : addUser.payload) === null || _a === void 0 ? void 0 : _a.insertId) {
|
||||
const newlyAddedUserQuery = `SELECT id,uuid,first_name,last_name,email,username,image,image_thumbnail,verification_status FROM ${dbFullName}.users WHERE id='${addUser.payload.insertId}'`;
|
||||
const newlyAddedUser = await varDatabaseDbHandler({
|
||||
queryString: newlyAddedUserQuery,
|
||||
database: dbFullName,
|
||||
});
|
||||
if (existingUser === null || existingUser === void 0 ? void 0 : existingUser[0]) {
|
||||
return {
|
||||
success: false,
|
||||
msg: "User Already Exists",
|
||||
payload: null,
|
||||
};
|
||||
}
|
||||
const isEmailValid = yield (0, validate_email_1.default)({ email: payload.email });
|
||||
if (!isEmailValid.isValid) {
|
||||
return {
|
||||
success: false,
|
||||
msg: isEmailValid.message,
|
||||
payload: null,
|
||||
};
|
||||
}
|
||||
const addUser = yield (0, addDbEntry_1.default)({
|
||||
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" }),
|
||||
});
|
||||
if (addUser === null || addUser === void 0 ? void 0 : addUser.insertId) {
|
||||
const newlyAddedUserQuery = `SELECT id,uuid,first_name,last_name,email,username,image,image_thumbnail,verification_status FROM ${dbFullName}.users WHERE id='${addUser.insertId}'`;
|
||||
const newlyAddedUser = yield (0, varDatabaseDbHandler_1.default)({
|
||||
queryString: newlyAddedUserQuery,
|
||||
database: dbFullName,
|
||||
});
|
||||
return {
|
||||
success: true,
|
||||
payload: newlyAddedUser[0],
|
||||
};
|
||||
}
|
||||
else {
|
||||
return {
|
||||
success: false,
|
||||
msg: "Could not create user",
|
||||
sqlResult: addUser,
|
||||
payload: null,
|
||||
};
|
||||
}
|
||||
});
|
||||
return {
|
||||
success: true,
|
||||
payload: newlyAddedUser[0],
|
||||
};
|
||||
}
|
||||
else {
|
||||
return {
|
||||
success: false,
|
||||
msg: "Could not create user",
|
||||
sqlResult: addUser,
|
||||
payload: null,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
+26
-43
@@ -1,48 +1,31 @@
|
||||
"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"));
|
||||
import deleteDbEntry from "../../backend/db/deleteDbEntry";
|
||||
import varDatabaseDbHandler from "../../backend/varDatabaseDbHandler";
|
||||
/**
|
||||
* # Update API User Function
|
||||
*/
|
||||
function apiDeleteUser(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ dbFullName, deletedUserId, }) {
|
||||
const existingUserQuery = `SELECT * FROM ${dbFullName}.users WHERE id = ?`;
|
||||
const existingUserValues = [deletedUserId];
|
||||
const existingUser = yield (0, varDatabaseDbHandler_1.default)({
|
||||
queryString: existingUserQuery,
|
||||
queryValuesArray: existingUserValues,
|
||||
database: dbFullName,
|
||||
});
|
||||
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",
|
||||
dbFullName,
|
||||
tableName: "users",
|
||||
identifierColumnName: "id",
|
||||
identifierValue: deletedUserId,
|
||||
});
|
||||
return {
|
||||
success: true,
|
||||
result: deleteUser,
|
||||
};
|
||||
export default async function apiDeleteUser({ dbFullName, deletedUserId, }) {
|
||||
const existingUserQuery = `SELECT * FROM ${dbFullName}.users WHERE id = ?`;
|
||||
const existingUserValues = [deletedUserId];
|
||||
const existingUser = await varDatabaseDbHandler({
|
||||
queryString: existingUserQuery,
|
||||
queryValuesArray: existingUserValues,
|
||||
database: dbFullName,
|
||||
});
|
||||
if (!(existingUser === null || existingUser === void 0 ? void 0 : existingUser[0])) {
|
||||
return {
|
||||
success: false,
|
||||
msg: "User not found",
|
||||
};
|
||||
}
|
||||
const deleteUser = await deleteDbEntry({
|
||||
dbContext: "Dsql User",
|
||||
dbFullName,
|
||||
tableName: "users",
|
||||
identifierColumnName: "id",
|
||||
identifierValue: deletedUserId,
|
||||
});
|
||||
return {
|
||||
success: true,
|
||||
result: deleteUser,
|
||||
};
|
||||
}
|
||||
|
||||
+19
-36
@@ -1,41 +1,24 @@
|
||||
"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"));
|
||||
import varDatabaseDbHandler from "../../backend/varDatabaseDbHandler";
|
||||
/**
|
||||
* # API Get User
|
||||
*/
|
||||
function apiGetUser(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ fields, dbFullName, userId, }) {
|
||||
const finalDbName = dbFullName.replace(/[^a-z0-9_]/g, "");
|
||||
const query = `SELECT ${fields.join(",")} FROM ${finalDbName}.users WHERE id=?`;
|
||||
const API_USER_ID = userId || process.env.DSQL_API_USER_ID;
|
||||
let foundUser = yield (0, varDatabaseDbHandler_1.default)({
|
||||
queryString: query,
|
||||
queryValuesArray: [API_USER_ID],
|
||||
database: finalDbName,
|
||||
});
|
||||
if (!foundUser || !foundUser[0]) {
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
};
|
||||
}
|
||||
return {
|
||||
success: true,
|
||||
payload: foundUser[0],
|
||||
};
|
||||
export default async function apiGetUser({ fields, dbFullName, userId, }) {
|
||||
const finalDbName = dbFullName.replace(/[^a-z0-9_]/g, "");
|
||||
const query = `SELECT ${fields.join(",")} FROM ${finalDbName}.users WHERE id=?`;
|
||||
const API_USER_ID = userId || process.env.DSQL_API_USER_ID;
|
||||
let foundUser = await varDatabaseDbHandler({
|
||||
queryString: query,
|
||||
queryValuesArray: [API_USER_ID],
|
||||
database: finalDbName,
|
||||
});
|
||||
if (!foundUser || !foundUser[0]) {
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
};
|
||||
}
|
||||
return {
|
||||
success: true,
|
||||
payload: foundUser[0],
|
||||
};
|
||||
}
|
||||
|
||||
+145
-153
@@ -1,162 +1,154 @@
|
||||
"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 grab_db_full_name_1 = __importDefault(require("../../../utils/grab-db-full-name"));
|
||||
const varDatabaseDbHandler_1 = __importDefault(require("../../backend/varDatabaseDbHandler"));
|
||||
const hashPassword_1 = __importDefault(require("../../dsql/hashPassword"));
|
||||
import grabDbFullName from "../../../utils/grab-db-full-name";
|
||||
import varDatabaseDbHandler from "../../backend/varDatabaseDbHandler";
|
||||
import hashPassword from "../../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, skipPassword, social, dbUserId, debug, }) {
|
||||
const dbFullName = (0, grab_db_full_name_1.default)({ dbName: database, userId: dbUserId });
|
||||
const dbAppend = global.DSQL_USE_LOCAL ? "" : `${dbFullName}.`;
|
||||
/**
|
||||
* 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;
|
||||
export default async function apiLoginUser({ encryptionKey, email, username, password, database, additionalFields, email_login, email_login_code, email_login_field, skipPassword, social, dbUserId, debug, }) {
|
||||
const dbFullName = grabDbFullName({ dbName: database, userId: dbUserId });
|
||||
if (!dbFullName) {
|
||||
console.log(`Database Full Name couldn't be grabbed`);
|
||||
return {
|
||||
success: false,
|
||||
msg: `Database Full Name couldn't be grabbed`,
|
||||
};
|
||||
}
|
||||
const dbAppend = global.DSQL_USE_LOCAL ? "" : `${dbFullName}.`;
|
||||
/**
|
||||
* 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
|
||||
? hashPassword({
|
||||
encryptionKey: encryptionKey,
|
||||
password: password,
|
||||
})
|
||||
: null;
|
||||
if (debug) {
|
||||
console.log("apiLoginUser:database:", dbFullName);
|
||||
console.log("apiLoginUser:Finding User ...");
|
||||
}
|
||||
let foundUser = await varDatabaseDbHandler({
|
||||
queryString: `SELECT * FROM ${dbAppend}users WHERE email = ? OR username = ?`,
|
||||
queryValuesArray: [email, username],
|
||||
database: dbFullName,
|
||||
debug,
|
||||
});
|
||||
if (debug) {
|
||||
console.log("apiLoginUser:foundUser:", foundUser);
|
||||
}
|
||||
if ((!foundUser || !foundUser[0]) && !social)
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: "No user found",
|
||||
};
|
||||
let isPasswordCorrect = false;
|
||||
if (debug) {
|
||||
console.log("apiLoginUser:isPasswordCorrect:", isPasswordCorrect);
|
||||
}
|
||||
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) {
|
||||
if (debug) {
|
||||
console.log("apiLoginUser:database:", dbFullName);
|
||||
console.log("apiLoginUser:Finding User ...");
|
||||
console.log("apiLoginUser:hashedPassword:", hashedPassword);
|
||||
console.log("apiLoginUser:foundUser[0].password:", foundUser[0].password);
|
||||
}
|
||||
let foundUser = yield (0, varDatabaseDbHandler_1.default)({
|
||||
queryString: `SELECT * FROM ${dbAppend}users WHERE email = ? OR username = ?`,
|
||||
isPasswordCorrect = hashedPassword === foundUser[0].password;
|
||||
}
|
||||
else if (foundUser &&
|
||||
foundUser[0] &&
|
||||
email_login &&
|
||||
email_login_code &&
|
||||
email_login_field) {
|
||||
const tempCode = foundUser[0][email_login_field];
|
||||
if (debug) {
|
||||
console.log("apiLoginUser:tempCode:", tempCode);
|
||||
}
|
||||
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 (debug) {
|
||||
console.log("apiLoginUser:isPasswordCorrect:", isPasswordCorrect);
|
||||
console.log("apiLoginUser:email_login:", email_login);
|
||||
}
|
||||
if (isPasswordCorrect && email_login) {
|
||||
const resetTempCode = await varDatabaseDbHandler({
|
||||
queryString: `UPDATE ${dbAppend}users SET ${email_login_field} = '' WHERE email = ? OR username = ?`,
|
||||
queryValuesArray: [email, username],
|
||||
database: dbFullName,
|
||||
debug,
|
||||
});
|
||||
if (debug) {
|
||||
console.log("apiLoginUser:foundUser:", foundUser);
|
||||
}
|
||||
if ((!foundUser || !foundUser[0]) && !social)
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: "No user found",
|
||||
};
|
||||
let isPasswordCorrect = false;
|
||||
if (debug) {
|
||||
console.log("apiLoginUser:isPasswordCorrect:", isPasswordCorrect);
|
||||
}
|
||||
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) {
|
||||
if (debug) {
|
||||
console.log("apiLoginUser:hashedPassword:", hashedPassword);
|
||||
console.log("apiLoginUser:foundUser[0].password:", foundUser[0].password);
|
||||
}
|
||||
isPasswordCorrect = hashedPassword === foundUser[0].password;
|
||||
}
|
||||
else if (foundUser &&
|
||||
foundUser[0] &&
|
||||
email_login &&
|
||||
email_login_code &&
|
||||
email_login_field) {
|
||||
const tempCode = foundUser[0][email_login_field];
|
||||
if (debug) {
|
||||
console.log("apiLoginUser:tempCode:", tempCode);
|
||||
}
|
||||
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 (debug) {
|
||||
console.log("apiLoginUser:isPasswordCorrect:", isPasswordCorrect);
|
||||
console.log("apiLoginUser:email_login:", email_login);
|
||||
}
|
||||
if (isPasswordCorrect && email_login) {
|
||||
const resetTempCode = yield (0, varDatabaseDbHandler_1.default)({
|
||||
queryString: `UPDATE ${dbAppend}users SET ${email_login_field} = '' WHERE email = ? OR username = ?`,
|
||||
queryValuesArray: [email, username],
|
||||
database: dbFullName,
|
||||
});
|
||||
}
|
||||
let csrfKey = Math.random().toString(36).substring(2) +
|
||||
"-" +
|
||||
Math.random().toString(36).substring(2);
|
||||
let userPayload = {
|
||||
id: foundUser[0].id,
|
||||
first_name: foundUser[0].first_name,
|
||||
last_name: foundUser[0].last_name,
|
||||
username: foundUser[0].username,
|
||||
email: foundUser[0].email,
|
||||
phone: foundUser[0].phone,
|
||||
social_id: foundUser[0].social_id,
|
||||
image: foundUser[0].image,
|
||||
image_thumbnail: foundUser[0].image_thumbnail,
|
||||
verification_status: foundUser[0].verification_status,
|
||||
social_login: foundUser[0].social_login,
|
||||
social_platform: foundUser[0].social_platform,
|
||||
csrf_k: csrfKey,
|
||||
more_data: foundUser[0].more_user_data,
|
||||
logged_in_status: true,
|
||||
date: Date.now(),
|
||||
};
|
||||
if (debug) {
|
||||
console.log("apiLoginUser:userPayload:", userPayload);
|
||||
console.log("apiLoginUser:Sending Response Object ...");
|
||||
}
|
||||
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;
|
||||
});
|
||||
}
|
||||
let csrfKey = Math.random().toString(36).substring(2) +
|
||||
"-" +
|
||||
Math.random().toString(36).substring(2);
|
||||
let userPayload = {
|
||||
id: foundUser[0].id,
|
||||
uid: foundUser[0].uid,
|
||||
uuid: foundUser[0].uuid,
|
||||
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 (debug) {
|
||||
console.log("apiLoginUser:userPayload:", userPayload);
|
||||
console.log("apiLoginUser:Sending Response Object ...");
|
||||
}
|
||||
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;
|
||||
}
|
||||
|
||||
+52
-69
@@ -1,75 +1,58 @@
|
||||
"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"));
|
||||
import varDatabaseDbHandler from "../../backend/varDatabaseDbHandler";
|
||||
/**
|
||||
* # Re-authenticate API user
|
||||
*/
|
||||
function apiReauthUser(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ existingUser, database, additionalFields, }) {
|
||||
const dbAppend = global.DSQL_USE_LOCAL
|
||||
? ""
|
||||
: database
|
||||
? `${database}.`
|
||||
: "";
|
||||
let foundUser = (existingUser === null || existingUser === void 0 ? void 0 : existingUser.id) && existingUser.id.toString().match(/./)
|
||||
? yield (0, varDatabaseDbHandler_1.default)({
|
||||
queryString: `SELECT * FROM ${dbAppend}users WHERE id=?`,
|
||||
queryValuesArray: [existingUser.id.toString()],
|
||||
database,
|
||||
})
|
||||
: null;
|
||||
if (!foundUser || !foundUser[0])
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: "No user found",
|
||||
};
|
||||
let csrfKey = Math.random().toString(36).substring(2) +
|
||||
"-" +
|
||||
Math.random().toString(36).substring(2);
|
||||
let userPayload = {
|
||||
id: foundUser[0].id,
|
||||
first_name: foundUser[0].first_name,
|
||||
last_name: foundUser[0].last_name,
|
||||
username: foundUser[0].username,
|
||||
email: foundUser[0].email,
|
||||
phone: foundUser[0].phone,
|
||||
social_id: foundUser[0].social_id,
|
||||
image: foundUser[0].image,
|
||||
image_thumbnail: foundUser[0].image_thumbnail,
|
||||
verification_status: foundUser[0].verification_status,
|
||||
social_login: foundUser[0].social_login,
|
||||
social_platform: foundUser[0].social_platform,
|
||||
csrf_k: csrfKey,
|
||||
more_data: foundUser[0].more_user_data,
|
||||
logged_in_status: true,
|
||||
date: Date.now(),
|
||||
};
|
||||
if (additionalFields &&
|
||||
Array.isArray(additionalFields) &&
|
||||
additionalFields.length > 0) {
|
||||
additionalFields.forEach((key) => {
|
||||
userPayload[key] = foundUser[0][key];
|
||||
});
|
||||
}
|
||||
export default async function apiReauthUser({ existingUser, database, additionalFields, }) {
|
||||
const dbAppend = global.DSQL_USE_LOCAL
|
||||
? ""
|
||||
: database
|
||||
? `${database}.`
|
||||
: "";
|
||||
let foundUser = (existingUser === null || existingUser === void 0 ? void 0 : existingUser.id) && existingUser.id.toString().match(/./)
|
||||
? await varDatabaseDbHandler({
|
||||
queryString: `SELECT * FROM ${dbAppend}users WHERE id=?`,
|
||||
queryValuesArray: [existingUser.id.toString()],
|
||||
database,
|
||||
})
|
||||
: null;
|
||||
if (!foundUser || !foundUser[0])
|
||||
return {
|
||||
success: true,
|
||||
msg: "Login Successful",
|
||||
payload: userPayload,
|
||||
csrf: csrfKey,
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: "No user found",
|
||||
};
|
||||
});
|
||||
let csrfKey = Math.random().toString(36).substring(2) +
|
||||
"-" +
|
||||
Math.random().toString(36).substring(2);
|
||||
let userPayload = {
|
||||
id: foundUser[0].id,
|
||||
first_name: foundUser[0].first_name,
|
||||
last_name: foundUser[0].last_name,
|
||||
username: foundUser[0].username,
|
||||
email: foundUser[0].email,
|
||||
phone: foundUser[0].phone,
|
||||
social_id: foundUser[0].social_id,
|
||||
image: foundUser[0].image,
|
||||
image_thumbnail: foundUser[0].image_thumbnail,
|
||||
verification_status: foundUser[0].verification_status,
|
||||
social_login: foundUser[0].social_login,
|
||||
social_platform: foundUser[0].social_platform,
|
||||
csrf_k: csrfKey,
|
||||
more_data: foundUser[0].more_user_data,
|
||||
logged_in_status: true,
|
||||
date: Date.now(),
|
||||
};
|
||||
if (additionalFields &&
|
||||
Array.isArray(additionalFields) &&
|
||||
additionalFields.length > 0) {
|
||||
additionalFields.forEach((key) => {
|
||||
userPayload[key] = foundUser[0][key];
|
||||
});
|
||||
}
|
||||
return {
|
||||
success: true,
|
||||
msg: "Login Successful",
|
||||
payload: userPayload,
|
||||
csrf: csrfKey,
|
||||
};
|
||||
}
|
||||
|
||||
+104
-121
@@ -1,132 +1,115 @@
|
||||
"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"));
|
||||
import varDatabaseDbHandler from "../../backend/varDatabaseDbHandler";
|
||||
import nodemailer from "nodemailer";
|
||||
import getAuthCookieNames from "../../backend/cookies/get-auth-cookie-names";
|
||||
import encrypt from "../../dsql/encrypt";
|
||||
import serializeCookies from "../../../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, response, extraCookies, }) {
|
||||
if (email === null || email === void 0 ? void 0 : email.match(/ /)) {
|
||||
return {
|
||||
success: false,
|
||||
msg: "Invalid Email/Password format",
|
||||
};
|
||||
export default async function apiSendEmailCode({ email, database, email_login_field, mail_domain, mail_port, sender, mail_username, mail_password, html, 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 ${database}.users WHERE email = ?`;
|
||||
const foundUserValues = [email];
|
||||
let foundUser = await varDatabaseDbHandler({
|
||||
queryString: foundUserQuery,
|
||||
queryValuesArray: foundUserValues,
|
||||
database,
|
||||
});
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
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)];
|
||||
}
|
||||
const createdAt = Date.now();
|
||||
const foundUserQuery = `SELECT * FROM ${database}.users WHERE email = ?`;
|
||||
const foundUserValues = [email];
|
||||
let foundUser = yield (0, varDatabaseDbHandler_1.default)({
|
||||
queryString: foundUserQuery,
|
||||
queryValuesArray: foundUserValues,
|
||||
return code;
|
||||
}
|
||||
if ((foundUser === null || foundUser === void 0 ? void 0 : foundUser[0]) && email_login_field) {
|
||||
const tempCode = generateCode();
|
||||
let transporter = nodemailer.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 = await transporter.sendMail(mailObject);
|
||||
if (!(info === null || info === void 0 ? void 0 : info.accepted))
|
||||
throw new Error("Mail not Sent!");
|
||||
const setTempCodeQuery = `UPDATE ${database}.users SET ${email_login_field} = ? WHERE email = ?`;
|
||||
const setTempCodeValues = [tempCode + `-${createdAt}`, email];
|
||||
let setTempCode = await varDatabaseDbHandler({
|
||||
queryString: setTempCodeQuery,
|
||||
queryValuesArray: setTempCodeValues,
|
||||
database,
|
||||
});
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
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)];
|
||||
/** @type {import("../../../types").SendOneTimeCodeEmailResponse} */
|
||||
const resObject = {
|
||||
success: true,
|
||||
code: tempCode,
|
||||
email: email,
|
||||
createdAt,
|
||||
msg: "Success",
|
||||
};
|
||||
if (response) {
|
||||
const cookieKeyNames = getAuthCookieNames();
|
||||
const oneTimeCodeCookieName = cookieKeyNames.oneTimeCodeName;
|
||||
const encryptedPayload = encrypt({
|
||||
data: JSON.stringify(resObject),
|
||||
});
|
||||
if (!encryptedPayload) {
|
||||
throw new Error("apiSendEmailCode Error: Failed to encrypt payload");
|
||||
}
|
||||
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,
|
||||
/** @type {import("../../../../package-shared/types").CookieObject} */
|
||||
const oneTimeCookieObject = {
|
||||
name: oneTimeCodeCookieName,
|
||||
value: encryptedPayload,
|
||||
sameSite: "Strict",
|
||||
path: "/",
|
||||
httpOnly: true,
|
||||
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 ${database}.users SET ${email_login_field} = ? WHERE email = ?`;
|
||||
const setTempCodeValues = [tempCode + `-${createdAt}`, email];
|
||||
let setTempCode = yield (0, varDatabaseDbHandler_1.default)({
|
||||
queryString: setTempCodeQuery,
|
||||
queryValuesArray: setTempCodeValues,
|
||||
database,
|
||||
});
|
||||
/** @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;
|
||||
/** @type {import("../../../../package-shared/types").CookieObject[]} */
|
||||
const cookiesObjectArray = extraCookies
|
||||
? [...extraCookies, oneTimeCookieObject]
|
||||
: [oneTimeCookieObject];
|
||||
const serializedCookies = serializeCookies({
|
||||
cookies: cookiesObjectArray,
|
||||
});
|
||||
response.setHeader("Set-Cookie", serializedCookies);
|
||||
}
|
||||
else {
|
||||
return {
|
||||
success: false,
|
||||
msg: "Invalid Email/Password format",
|
||||
};
|
||||
}
|
||||
});
|
||||
return resObject;
|
||||
}
|
||||
else {
|
||||
return {
|
||||
success: false,
|
||||
msg: "Invalid Email/Password format",
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
+58
-75
@@ -1,81 +1,64 @@
|
||||
"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"));
|
||||
import updateDbEntry from "../../backend/db/updateDbEntry";
|
||||
import encrypt from "../../dsql/encrypt";
|
||||
import hashPassword from "../../dsql/hashPassword";
|
||||
import varDatabaseDbHandler from "../../backend/varDatabaseDbHandler";
|
||||
/**
|
||||
* # Update API User Function
|
||||
*/
|
||||
function apiUpdateUser(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ payload, dbFullName, updatedUserId, dbSchema, }) {
|
||||
const existingUserQuery = `SELECT * FROM ${dbFullName}.users WHERE id = ?`;
|
||||
const existingUserValues = [updatedUserId];
|
||||
const existingUser = yield (0, varDatabaseDbHandler_1.default)({
|
||||
queryString: existingUserQuery,
|
||||
queryValuesArray: existingUserValues,
|
||||
database: dbFullName,
|
||||
});
|
||||
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)({
|
||||
dbFullName,
|
||||
tableName: "users",
|
||||
identifierColumnName: "id",
|
||||
identifierValue: updatedUserId,
|
||||
data: data,
|
||||
});
|
||||
return {
|
||||
success: true,
|
||||
payload: updateUser,
|
||||
};
|
||||
export default async function apiUpdateUser({ payload, dbFullName, updatedUserId, dbSchema, }) {
|
||||
const existingUserQuery = `SELECT * FROM ${dbFullName}.users WHERE id = ?`;
|
||||
const existingUserValues = [updatedUserId];
|
||||
const existingUser = await varDatabaseDbHandler({
|
||||
queryString: existingUserQuery,
|
||||
queryValuesArray: existingUserValues,
|
||||
database: dbFullName,
|
||||
});
|
||||
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 = encrypt({ data: value });
|
||||
}
|
||||
finalData[key] = value;
|
||||
});
|
||||
if (finalData.password && typeof finalData.password == "string") {
|
||||
finalData.password = hashPassword({ password: finalData.password });
|
||||
}
|
||||
return finalData;
|
||||
})();
|
||||
const updateUser = await updateDbEntry({
|
||||
dbFullName,
|
||||
tableName: "users",
|
||||
identifierColumnName: "id",
|
||||
identifierValue: updatedUserId,
|
||||
data: data,
|
||||
});
|
||||
return {
|
||||
success: true,
|
||||
payload: updateUser,
|
||||
};
|
||||
}
|
||||
|
||||
+5
-11
@@ -1,18 +1,12 @@
|
||||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = encryptReserPasswordUrl;
|
||||
const ejson_1 = __importDefault(require("../../../../../utils/ejson"));
|
||||
const encrypt_1 = __importDefault(require("../../../../dsql/encrypt"));
|
||||
function encryptReserPasswordUrl({ email, encryptionKey, encryptionSalt, }) {
|
||||
import EJSON from "../../../../../utils/ejson";
|
||||
import encrypt from "../../../../dsql/encrypt";
|
||||
export default function encryptReserPasswordUrl({ email, encryptionKey, encryptionSalt, }) {
|
||||
const encryptObject = {
|
||||
email,
|
||||
createdAt: Date.now(),
|
||||
};
|
||||
const encryptStr = (0, encrypt_1.default)({
|
||||
data: ejson_1.default.stringify(encryptObject),
|
||||
const encryptStr = encrypt({
|
||||
data: EJSON.stringify(encryptObject),
|
||||
encryptionKey,
|
||||
encryptionSalt,
|
||||
});
|
||||
|
||||
+31
-47
@@ -1,52 +1,36 @@
|
||||
"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 = apiSendResetPasswordLink;
|
||||
const grab_db_full_name_1 = __importDefault(require("../../../../utils/grab-db-full-name"));
|
||||
const varDatabaseDbHandler_1 = __importDefault(require("../../../backend/varDatabaseDbHandler"));
|
||||
import grabDbFullName from "../../../../utils/grab-db-full-name";
|
||||
import varDatabaseDbHandler from "../../../backend/varDatabaseDbHandler";
|
||||
/**
|
||||
* # API Login
|
||||
*/
|
||||
function apiSendResetPasswordLink(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ database, email, dbUserId, debug, }) {
|
||||
const dbFullName = (0, grab_db_full_name_1.default)({ dbName: database, userId: dbUserId });
|
||||
/**
|
||||
* Check input validity
|
||||
*
|
||||
* @description Check input validity
|
||||
*/
|
||||
if (email === null || email === void 0 ? void 0 : email.match(/ /)) {
|
||||
return {
|
||||
success: false,
|
||||
msg: "Invalid Email/Password format",
|
||||
};
|
||||
}
|
||||
let foundUser = yield (0, varDatabaseDbHandler_1.default)({
|
||||
queryString: `SELECT * FROM ${dbFullName}.users WHERE email = ? OR username = ?`,
|
||||
queryValuesArray: [email, email],
|
||||
database: dbFullName,
|
||||
debug,
|
||||
});
|
||||
if (debug) {
|
||||
console.log("apiSendResetPassword:foundUser:", foundUser);
|
||||
}
|
||||
const targetUser = foundUser === null || foundUser === void 0 ? void 0 : foundUser[0];
|
||||
if (!targetUser)
|
||||
return {
|
||||
success: false,
|
||||
msg: "No user found",
|
||||
};
|
||||
return { success: true };
|
||||
export default async function apiSendResetPasswordLink({ database, email, dbUserId, debug, }) {
|
||||
const dbFullName = grabDbFullName({ dbName: database, userId: dbUserId });
|
||||
if (!dbFullName) {
|
||||
return {
|
||||
success: false,
|
||||
msg: `Couldn't get database full name`,
|
||||
};
|
||||
}
|
||||
if (email === null || email === void 0 ? void 0 : email.match(/ /)) {
|
||||
return {
|
||||
success: false,
|
||||
msg: "Invalid Email/Password format",
|
||||
};
|
||||
}
|
||||
let foundUser = await varDatabaseDbHandler({
|
||||
queryString: `SELECT * FROM ${dbFullName}.users WHERE email = ? OR username = ?`,
|
||||
queryValuesArray: [email, email],
|
||||
database: dbFullName,
|
||||
debug,
|
||||
});
|
||||
if (debug) {
|
||||
console.log("apiSendResetPassword:foundUser:", foundUser);
|
||||
}
|
||||
const targetUser = foundUser === null || foundUser === void 0 ? void 0 : foundUser[0];
|
||||
if (!targetUser)
|
||||
return {
|
||||
success: false,
|
||||
msg: "No user found",
|
||||
};
|
||||
return { success: true };
|
||||
}
|
||||
|
||||
@@ -1,88 +1,71 @@
|
||||
"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"));
|
||||
import handleSocialDb from "../../social-login/handleSocialDb";
|
||||
import githubLogin from "../../social-login/githubLogin";
|
||||
import camelJoinedtoCamelSpace from "../../../../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,
|
||||
export default async function apiGithubLogin({ code, clientId, clientSecret, database, additionalFields, email, additionalData, }) {
|
||||
if (!code || !clientId || !clientSecret || !database) {
|
||||
return {
|
||||
success: false,
|
||||
msg: "Missing query params",
|
||||
};
|
||||
if (additionalData) {
|
||||
payload = Object.assign(Object.assign({}, payload), additionalData);
|
||||
}
|
||||
const loggedInGithubUser = yield (0, handleSocialDb_1.default)({
|
||||
database,
|
||||
email: gitHubUser.email,
|
||||
payload,
|
||||
social_platform: "github",
|
||||
supEmail: email,
|
||||
additionalFields,
|
||||
});
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
return Object.assign({}, loggedInGithubUser);
|
||||
}
|
||||
if (typeof code !== "string" ||
|
||||
typeof clientId !== "string" ||
|
||||
typeof clientSecret !== "string" ||
|
||||
typeof database !== "string") {
|
||||
return {
|
||||
success: false,
|
||||
msg: "Wrong Parameters",
|
||||
};
|
||||
}
|
||||
/**
|
||||
* Create new user folder and file
|
||||
*
|
||||
* @description Create new user folder and file
|
||||
*/
|
||||
const gitHubUser = await githubLogin({
|
||||
code: code,
|
||||
clientId: clientId,
|
||||
clientSecret: clientSecret,
|
||||
});
|
||||
if (!gitHubUser) {
|
||||
return {
|
||||
success: false,
|
||||
msg: "No github user returned",
|
||||
};
|
||||
}
|
||||
const 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: camelJoinedtoCamelSpace(nameArray[0]),
|
||||
last_name: camelJoinedtoCamelSpace(nameArray[1]),
|
||||
social_id: socialId,
|
||||
social_platform: "github",
|
||||
image: gitHubUser.avatar_url,
|
||||
image_thumbnail: gitHubUser.avatar_url,
|
||||
username: "github-user-" + socialId,
|
||||
};
|
||||
if (additionalData) {
|
||||
payload = Object.assign(Object.assign({}, payload), additionalData);
|
||||
}
|
||||
const loggedInGithubUser = await handleSocialDb({
|
||||
database,
|
||||
email: gitHubUser.email,
|
||||
payload,
|
||||
social_platform: "github",
|
||||
supEmail: email,
|
||||
additionalFields,
|
||||
});
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
return Object.assign({}, loggedInGithubUser);
|
||||
}
|
||||
|
||||
@@ -1,89 +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 = apiGoogleLogin;
|
||||
const https_1 = __importDefault(require("https"));
|
||||
const handleSocialDb_1 = __importDefault(require("../../social-login/handleSocialDb"));
|
||||
const ejson_1 = __importDefault(require("../../../../utils/ejson"));
|
||||
import https from "https";
|
||||
import handleSocialDb from "../../social-login/handleSocialDb";
|
||||
import EJSON from "../../../../utils/ejson";
|
||||
/**
|
||||
* # API google login
|
||||
*/
|
||||
function apiGoogleLogin(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ token, database, additionalFields, additionalData, debug, loginOnly, }) {
|
||||
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.");
|
||||
/**
|
||||
* Create new user folder and file
|
||||
*
|
||||
* @description Create new user folder and file
|
||||
*/
|
||||
const { given_name, family_name, email, sub, picture } = gUser;
|
||||
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",
|
||||
additionalFields,
|
||||
debug,
|
||||
loginOnly,
|
||||
});
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
return Object.assign({}, loggedInGoogleUser);
|
||||
export default async function apiGoogleLogin({ token, database, additionalFields, additionalData, debug, loginOnly, }) {
|
||||
try {
|
||||
const gUser = await new Promise((resolve, reject) => {
|
||||
https
|
||||
.request({
|
||||
method: "GET",
|
||||
hostname: "www.googleapis.com",
|
||||
path: "/oauth2/v3/userinfo",
|
||||
headers: {
|
||||
Authorization: `Bearer ${token}`,
|
||||
},
|
||||
}, (res) => {
|
||||
let data = "";
|
||||
res.on("data", (chunk) => {
|
||||
data += chunk;
|
||||
});
|
||||
res.on("end", () => {
|
||||
resolve(EJSON.parse(data));
|
||||
});
|
||||
})
|
||||
.end();
|
||||
});
|
||||
if (!(gUser === null || gUser === void 0 ? void 0 : gUser.email_verified))
|
||||
throw new Error("No Google User.");
|
||||
/**
|
||||
* Create new user folder and file
|
||||
*
|
||||
* @description Create new user folder and file
|
||||
*/
|
||||
const { given_name, family_name, email, sub, picture } = gUser;
|
||||
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);
|
||||
}
|
||||
catch ( /** @type {any} */error) {
|
||||
console.log(`api-google-login.ts ERROR: ${error.message}`);
|
||||
return {
|
||||
success: false,
|
||||
payload: undefined,
|
||||
msg: error.message,
|
||||
};
|
||||
}
|
||||
});
|
||||
const loggedInGoogleUser = await handleSocialDb({
|
||||
database,
|
||||
email: email || "",
|
||||
payload: payloadObject,
|
||||
social_platform: "google",
|
||||
additionalFields,
|
||||
debug,
|
||||
loginOnly,
|
||||
});
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
return Object.assign({}, loggedInGoogleUser);
|
||||
}
|
||||
catch ( /** @type {any} */error) {
|
||||
console.log(`api-google-login.ts ERROR: ${error.message}`);
|
||||
return {
|
||||
success: false,
|
||||
payload: undefined,
|
||||
msg: error.message,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
+81
-98
@@ -1,22 +1,7 @@
|
||||
"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"));
|
||||
import serverError from "./serverError";
|
||||
import DB_HANDLER from "../../utils/backend/global-db/DB_HANDLER";
|
||||
import addDbEntry from "./db/addDbEntry";
|
||||
import LOCAL_DB_HANDLER from "../../utils/backend/global-db/LOCAL_DB_HANDLER";
|
||||
/**
|
||||
* Add Admin User on Login
|
||||
* ==============================================================================
|
||||
@@ -25,88 +10,86 @@ const LOCAL_DB_HANDLER_1 = __importDefault(require("../../utils/backend/global-d
|
||||
* 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, }) {
|
||||
var _b;
|
||||
try {
|
||||
const finalDbHandler = global.DSQL_USE_LOCAL
|
||||
? 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");
|
||||
export default async function addAdminUserOnLogin({ query, user, }) {
|
||||
var _a;
|
||||
try {
|
||||
const finalDbHandler = global.DSQL_USE_LOCAL
|
||||
? LOCAL_DB_HANDLER
|
||||
: DB_HANDLER;
|
||||
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 = await 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 = await finalDbHandler(invitingUserDbQuery, invitingUserDbValues);
|
||||
if (invitingUserDb === null || invitingUserDb === void 0 ? void 0 : invitingUserDb[0]) {
|
||||
const existingUserUser = await 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");
|
||||
}
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
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,
|
||||
},
|
||||
});
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
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,
|
||||
},
|
||||
});
|
||||
}
|
||||
else {
|
||||
addDbEntry({
|
||||
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,
|
||||
},
|
||||
});
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
const dbTableData = await finalDbHandler(`SELECT db_tables_data FROM invitations WHERE inviting_user_id=? AND invited_user_email=?`, [invite, email]);
|
||||
const clearEntries = await 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 = await addDbEntry({
|
||||
dbFullName: "datasquirel",
|
||||
tableName: "delegated_user_tables",
|
||||
data: {
|
||||
delegated_user_id: user.id,
|
||||
root_user_id: invite,
|
||||
database: db_slug,
|
||||
table: table_slug,
|
||||
priviledge: priviledge,
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
const inviteAccepted = yield finalDbHandler(`UPDATE invitations SET invitation_status='Accepted' WHERE inviting_user_id=? AND invited_user_email=?`, [invite, email]);
|
||||
}
|
||||
const inviteAccepted = await finalDbHandler(`UPDATE invitations SET invitation_status='Accepted' WHERE inviting_user_id=? AND invited_user_email=?`, [invite, email]);
|
||||
}
|
||||
catch (error) {
|
||||
(_b = global.ERROR_CALLBACK) === null || _b === void 0 ? void 0 : _b.call(global, `Add Admin User On Login Error`, error);
|
||||
(0, serverError_1.default)({
|
||||
component: "addAdminUserOnLogin",
|
||||
message: error.message,
|
||||
user: user,
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
catch (error) {
|
||||
(_a = global.ERROR_CALLBACK) === null || _a === void 0 ? void 0 : _a.call(global, `Add Admin User On Login Error`, error);
|
||||
serverError({
|
||||
component: "addAdminUserOnLogin",
|
||||
message: error.message,
|
||||
user: user,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
+46
-62
@@ -1,70 +1,54 @@
|
||||
"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"));
|
||||
import generator from "generate-password";
|
||||
import DB_HANDLER from "../../utils/backend/global-db/DB_HANDLER";
|
||||
import NO_DB_HANDLER from "../../utils/backend/global-db/NO_DB_HANDLER";
|
||||
import addDbEntry from "./db/addDbEntry";
|
||||
import encrypt from "../dsql/encrypt";
|
||||
import LOCAL_DB_HANDLER from "../../utils/backend/global-db/LOCAL_DB_HANDLER";
|
||||
import grabSQLKeyName from "../../utils/grab-sql-key-name";
|
||||
/**
|
||||
* # Add Mariadb User
|
||||
*/
|
||||
function addMariadbUser(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ userId }) {
|
||||
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 (global.DSQL_USE_LOCAL) {
|
||||
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 = global.DSQL_USE_LOCAL
|
||||
? 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",
|
||||
});
|
||||
console.log(`User ${userId} SQL credentials successfully added.`);
|
||||
export default async function addMariadbUser({ userId }) {
|
||||
try {
|
||||
const defaultMariadbUserHost = process.env.DSQL_DB_HOST || "127.0.0.1";
|
||||
const username = grabSQLKeyName({ type: "user", userId });
|
||||
const password = generator.generate({
|
||||
length: 16,
|
||||
numbers: true,
|
||||
symbols: true,
|
||||
uppercase: true,
|
||||
exclude: "*#.'`\"",
|
||||
});
|
||||
const encryptedPassword = encrypt({ data: password });
|
||||
const createMariadbUsersQuery = `CREATE USER IF NOT EXISTS '${username}'@'127.0.0.1' IDENTIFIED BY '${password}'`;
|
||||
if (global.DSQL_USE_LOCAL) {
|
||||
await LOCAL_DB_HANDLER(createMariadbUsersQuery);
|
||||
}
|
||||
catch ( /** @type {any} */error) {
|
||||
console.log(`Error in adding SQL user in 'addMariadbUser' function =>`, error.message);
|
||||
else {
|
||||
await NO_DB_HANDLER(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 = global.DSQL_USE_LOCAL
|
||||
? await LOCAL_DB_HANDLER(updateUserQuery, updateUserValues)
|
||||
: await DB_HANDLER(updateUserQuery, updateUserValues);
|
||||
const addMariadbUser = await addDbEntry({
|
||||
tableName: "mariadb_users",
|
||||
data: {
|
||||
user_id: userId,
|
||||
username,
|
||||
host: defaultMariadbUserHost,
|
||||
password: encryptedPassword,
|
||||
primary: "1",
|
||||
grants: '[{"database":"*","table":"*","privileges":["ALL"]}]',
|
||||
},
|
||||
dbContext: "Master",
|
||||
});
|
||||
console.log(`User ${userId} SQL credentials successfully added.`);
|
||||
}
|
||||
catch ( /** @type {any} */error) {
|
||||
console.log(`Error in adding SQL user in 'addMariadbUser' function =>`, error.message);
|
||||
}
|
||||
}
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
|
||||
@@ -4,9 +4,10 @@ type Param = {
|
||||
payload?: {
|
||||
[s: string]: any;
|
||||
};
|
||||
dbId: string | number;
|
||||
};
|
||||
/**
|
||||
* # Add User Table to Database
|
||||
*/
|
||||
export default function addUsersTableToDb({ userId, database, payload, }: Param): Promise<any>;
|
||||
export default function addUsersTableToDb({ userId, database, payload, dbId, }: Param): Promise<any>;
|
||||
export {};
|
||||
|
||||
+57
-75
@@ -1,81 +1,63 @@
|
||||
"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"));
|
||||
import serverError from "./serverError";
|
||||
import DB_HANDLER from "../../utils/backend/global-db/DB_HANDLER";
|
||||
import addDbEntry from "./db/addDbEntry";
|
||||
import createDbFromSchema from "../../shell/createDbFromSchema";
|
||||
import LOCAL_DB_HANDLER from "../../utils/backend/global-db/LOCAL_DB_HANDLER";
|
||||
import grabNewUsersTableSchema from "./grabNewUsersTableSchema";
|
||||
import { grabPrimaryRequiredDbSchema, writeUpdatedDbSchema, } from "../../shell/createDbFromSchema/grab-required-database-schemas";
|
||||
/**
|
||||
* # Add User Table to Database
|
||||
*/
|
||||
function addUsersTableToDb(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ userId, database, 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 });
|
||||
const targetDb = global.DSQL_USE_LOCAL
|
||||
? 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",
|
||||
},
|
||||
});
|
||||
}
|
||||
const dbShellUpdate = yield (0, createDbFromSchema_1.default)({
|
||||
userId,
|
||||
targetDatabase: dbFullName,
|
||||
});
|
||||
return `Done!`;
|
||||
export default async function addUsersTableToDb({ userId, database, payload, dbId, }) {
|
||||
try {
|
||||
const dbFullName = database;
|
||||
const userPreset = grabNewUsersTableSchema({ payload });
|
||||
if (!userPreset)
|
||||
throw new Error("Couldn't Get User Preset!");
|
||||
let targetDatabase = grabPrimaryRequiredDbSchema({
|
||||
dbId,
|
||||
userId,
|
||||
});
|
||||
if (!targetDatabase) {
|
||||
throw new Error("Couldn't Find Target Database!");
|
||||
}
|
||||
catch ( /** @type {any} */error) {
|
||||
console.log(`addUsersTableToDb.ts ERROR: ${error.message}`);
|
||||
(0, serverError_1.default)({
|
||||
component: "addUsersTableToDb",
|
||||
message: error.message,
|
||||
user: { id: userId },
|
||||
});
|
||||
return error.message;
|
||||
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);
|
||||
}
|
||||
writeUpdatedDbSchema({ dbSchema: targetDatabase, userId });
|
||||
const targetDb = global.DSQL_USE_LOCAL
|
||||
? await LOCAL_DB_HANDLER(`SELECT id FROM user_databases WHERE user_id=? AND db_slug=?`, [userId, database])
|
||||
: await DB_HANDLER(`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 = await addDbEntry({
|
||||
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",
|
||||
},
|
||||
});
|
||||
}
|
||||
const dbShellUpdate = await createDbFromSchema({
|
||||
userId,
|
||||
targetDatabase: dbFullName,
|
||||
});
|
||||
return `Done!`;
|
||||
}
|
||||
catch ( /** @type {any} */error) {
|
||||
console.log(`addUsersTableToDb.ts ERROR: ${error.message}`);
|
||||
serverError({
|
||||
component: "addUsersTableToDb",
|
||||
message: error.message,
|
||||
user: { id: userId },
|
||||
});
|
||||
return error.message;
|
||||
}
|
||||
}
|
||||
|
||||
+1
-3
@@ -1,6 +1,4 @@
|
||||
import { CheckApiCredentialsFn } from "../../types";
|
||||
export {};
|
||||
/**
|
||||
* # Grap API Credentials
|
||||
*/
|
||||
declare const grabApiCred: CheckApiCredentialsFn;
|
||||
export default grabApiCred;
|
||||
|
||||
+44
-46
@@ -1,49 +1,47 @@
|
||||
"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"));
|
||||
export {};
|
||||
/**
|
||||
* # 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 });
|
||||
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 (error) {
|
||||
console.log(`api-cred ERROR: ${error.message}`);
|
||||
return { error: `api-cred ERROR: ${error.message}` };
|
||||
}
|
||||
};
|
||||
exports.default = grabApiCred;
|
||||
// const grabApiCred: CheckApiCredentialsFn = ({
|
||||
// key,
|
||||
// database,
|
||||
// table,
|
||||
// user_id,
|
||||
// media,
|
||||
// }) => {
|
||||
// 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 = decrypt({ encryptedString: key });
|
||||
// const ApiObject: import("../../types").ApiKeyObject = JSON.parse(
|
||||
// ApiJSON || ""
|
||||
// );
|
||||
// const isApiKeyValid = fs.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 = ApiObject.target_database
|
||||
// ?.split(",")
|
||||
// .includes(String(database));
|
||||
// if (isDatabaseAllowed && !ApiObject.target_table) return ApiObject;
|
||||
// if (isDatabaseAllowed && !table && ApiObject.target_table) return null;
|
||||
// const isTableAllowed = ApiObject.target_table
|
||||
// ?.split(",")
|
||||
// .includes(String(table));
|
||||
// if (isTableAllowed) return ApiObject;
|
||||
// return null;
|
||||
// } catch (error: any) {
|
||||
// console.log(`api-cred ERROR: ${error.message}`);
|
||||
// return { error: `api-cred ERROR: ${error.message}` };
|
||||
// }
|
||||
// };
|
||||
// export default grabApiCred;
|
||||
|
||||
+33
-46
@@ -1,33 +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.checkAuthFile = exports.deleteAuthFile = exports.getAuthFile = exports.cleanupUserAuthFiles = exports.writeAuthFile = exports.initAuthFiles = exports.grabAuthDirs = void 0;
|
||||
const fs_1 = __importDefault(require("fs"));
|
||||
const path_1 = __importDefault(require("path"));
|
||||
const ejson_1 = __importDefault(require("../../../utils/ejson"));
|
||||
const debug_log_1 = __importDefault(require("../../../utils/logging/debug-log"));
|
||||
import fs from "fs";
|
||||
import path from "path";
|
||||
import EJSON from "../../../utils/ejson";
|
||||
import debugLog from "../../../utils/logging/debug-log";
|
||||
function debugFn(log, label) {
|
||||
(0, debug_log_1.default)({ log, addTime: true, title: "write-auth-files", label });
|
||||
debugLog({ log, addTime: true, title: "write-auth-files", label });
|
||||
}
|
||||
const grabAuthDirs = () => {
|
||||
export 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");
|
||||
: path.resolve(process.cwd(), "./.tmp");
|
||||
const AUTH_DIR = path.join(ROOT_DIR, "logins");
|
||||
return { root: ROOT_DIR, auth: AUTH_DIR };
|
||||
};
|
||||
exports.grabAuthDirs = grabAuthDirs;
|
||||
const initAuthFiles = () => {
|
||||
export const initAuthFiles = () => {
|
||||
var _a;
|
||||
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 });
|
||||
const authDirs = grabAuthDirs();
|
||||
if (!fs.existsSync(authDirs.root))
|
||||
fs.mkdirSync(authDirs.root, { recursive: true });
|
||||
if (!fs.existsSync(authDirs.auth))
|
||||
fs.mkdirSync(authDirs.auth, { recursive: true });
|
||||
return true;
|
||||
}
|
||||
catch (error) {
|
||||
@@ -36,18 +29,17 @@ const initAuthFiles = () => {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
exports.initAuthFiles = initAuthFiles;
|
||||
/**
|
||||
* # Write Auth Files
|
||||
*/
|
||||
const writeAuthFile = (name, data, cleanup) => {
|
||||
(0, exports.initAuthFiles)();
|
||||
export const writeAuthFile = (name, data, cleanup) => {
|
||||
initAuthFiles();
|
||||
try {
|
||||
const { auth } = (0, exports.grabAuthDirs)();
|
||||
const { auth } = grabAuthDirs();
|
||||
if (cleanup) {
|
||||
(0, exports.cleanupUserAuthFiles)(cleanup.userId);
|
||||
cleanupUserAuthFiles(cleanup.userId);
|
||||
}
|
||||
fs_1.default.writeFileSync(path_1.default.join(auth, name), data);
|
||||
fs.writeFileSync(path.join(auth, name), data);
|
||||
return true;
|
||||
}
|
||||
catch (error) {
|
||||
@@ -55,22 +47,21 @@ const writeAuthFile = (name, data, cleanup) => {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
exports.writeAuthFile = writeAuthFile;
|
||||
/**
|
||||
* # Clean up User Auth Files
|
||||
*/
|
||||
const cleanupUserAuthFiles = (userId) => {
|
||||
(0, exports.initAuthFiles)();
|
||||
export const cleanupUserAuthFiles = (userId) => {
|
||||
initAuthFiles();
|
||||
try {
|
||||
const { auth } = (0, exports.grabAuthDirs)();
|
||||
const loginFiles = fs_1.default.readdirSync(auth);
|
||||
const { auth } = grabAuthDirs();
|
||||
const loginFiles = fs.readdirSync(auth);
|
||||
for (let i = 0; i < loginFiles.length; i++) {
|
||||
const loginFile = loginFiles[i];
|
||||
const loginFilePath = path_1.default.join(auth, loginFile);
|
||||
const loginFilePath = path.join(auth, loginFile);
|
||||
try {
|
||||
const authPayload = ejson_1.default.parse(fs_1.default.readFileSync(loginFilePath, "utf-8"));
|
||||
const authPayload = EJSON.parse(fs.readFileSync(loginFilePath, "utf-8"));
|
||||
if (authPayload.id == userId) {
|
||||
fs_1.default.unlinkSync(loginFilePath);
|
||||
fs.unlinkSync(loginFilePath);
|
||||
}
|
||||
}
|
||||
catch (error) { }
|
||||
@@ -82,42 +73,39 @@ const cleanupUserAuthFiles = (userId) => {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
exports.cleanupUserAuthFiles = cleanupUserAuthFiles;
|
||||
/**
|
||||
* # Get Auth Files
|
||||
*/
|
||||
const getAuthFile = (name) => {
|
||||
export const getAuthFile = (name) => {
|
||||
try {
|
||||
const authFilePath = path_1.default.join((0, exports.grabAuthDirs)().auth, name);
|
||||
return fs_1.default.readFileSync(authFilePath, "utf-8");
|
||||
const authFilePath = path.join(grabAuthDirs().auth, name);
|
||||
return fs.readFileSync(authFilePath, "utf-8");
|
||||
}
|
||||
catch (error) {
|
||||
console.log(`Error getting Auth File: ${error.message}`);
|
||||
return null;
|
||||
}
|
||||
};
|
||||
exports.getAuthFile = getAuthFile;
|
||||
/**
|
||||
* # Delete Auth Files
|
||||
* @param {string} name
|
||||
*/
|
||||
const deleteAuthFile = (name) => {
|
||||
export const deleteAuthFile = (name) => {
|
||||
try {
|
||||
return fs_1.default.rmSync(path_1.default.join((0, exports.grabAuthDirs)().auth, name));
|
||||
return fs.rmSync(path.join(grabAuthDirs().auth, name));
|
||||
}
|
||||
catch (error) {
|
||||
console.log(`Error deleting Auth File: ${error.message}`);
|
||||
return null;
|
||||
}
|
||||
};
|
||||
exports.deleteAuthFile = deleteAuthFile;
|
||||
/**
|
||||
* # Delete Auth Files
|
||||
* @param {string} name
|
||||
*/
|
||||
const checkAuthFile = (name) => {
|
||||
export const checkAuthFile = (name) => {
|
||||
try {
|
||||
return fs_1.default.existsSync(path_1.default.join((0, exports.grabAuthDirs)().auth, name));
|
||||
return fs.existsSync(path.join(grabAuthDirs().auth, name));
|
||||
return true;
|
||||
}
|
||||
catch (error) {
|
||||
@@ -125,4 +113,3 @@ const checkAuthFile = (name) => {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
exports.checkAuthFile = checkAuthFile;
|
||||
|
||||
@@ -1,21 +1,16 @@
|
||||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = getAuthCookieNames;
|
||||
const get_csrf_header_name_1 = __importDefault(require("../../../actions/get-csrf-header-name"));
|
||||
import getCsrfHeaderName from "../../../actions/get-csrf-header-name";
|
||||
import { AppNames } from "../../../dict/app-names";
|
||||
/**
|
||||
* # Grab Auth Cookie Names
|
||||
*/
|
||||
function getAuthCookieNames(params) {
|
||||
export default 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 = (0, get_csrf_header_name_1.default)();
|
||||
const cookiesCSRFName = getCsrfHeaderName();
|
||||
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+_/, ""));
|
||||
const targetDatabase = ((_a = params === null || params === void 0 ? void 0 : params.database) === null || _a === void 0 ? void 0 : _a.replace(new RegExp(`^${AppNames["DsqlDbPrefix"]}\\d+_`), "")) ||
|
||||
((_b = process.env.DSQL_DB_NAME) === null || _b === void 0 ? void 0 : _b.replace(new RegExp(`^${AppNames["DsqlDbPrefix"]}\\d+_`), ""));
|
||||
let keyCookieName = cookiesPrefix;
|
||||
if (params === null || params === void 0 ? void 0 : params.userId)
|
||||
keyCookieName += `user_${params.userId}_`;
|
||||
|
||||
@@ -2,6 +2,7 @@ import { DSQL_DATASQUIREL_USER_DATABASES } from "../../types/dsql";
|
||||
type Params = {
|
||||
userId: number | string;
|
||||
database: DSQL_DATASQUIREL_USER_DATABASES;
|
||||
dbId?: string | number;
|
||||
};
|
||||
export default function createDbSchemaFromDb({ userId, database, }: Params): Promise<boolean | undefined>;
|
||||
export default function createDbSchemaFromDb({ userId, database, dbId, }: Params): Promise<boolean | undefined>;
|
||||
export {};
|
||||
|
||||
+110
-122
@@ -1,132 +1,120 @@
|
||||
"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 = createDbSchemaFromDb;
|
||||
const varDatabaseDbHandler_1 = __importDefault(require("../../functions/backend/varDatabaseDbHandler"));
|
||||
const grabUserSchemaData_1 = __importDefault(require("../../functions/backend/grabUserSchemaData"));
|
||||
const setUserSchemaData_1 = __importDefault(require("../../functions/backend/setUserSchemaData"));
|
||||
const addDbEntry_1 = __importDefault(require("../../functions/backend/db/addDbEntry"));
|
||||
const slugToCamelTitle_1 = __importDefault(require("../../shell/utils/slugToCamelTitle"));
|
||||
function createDbSchemaFromDb(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ userId, database, }) {
|
||||
var _b, _c, _d, _e, _f, _g;
|
||||
try {
|
||||
if (!userId) {
|
||||
console.log("No user Id provided");
|
||||
return;
|
||||
}
|
||||
const userSchemaData = (0, grabUserSchemaData_1.default)({ userId });
|
||||
if (!userSchemaData)
|
||||
throw new Error("User schema data not found!");
|
||||
const targetDb = userSchemaData.filter((dbObject) => dbObject.dbFullName === database.db_full_name)[0];
|
||||
const existingTables = yield (0, varDatabaseDbHandler_1.default)({
|
||||
database: database.db_full_name,
|
||||
queryString: `SHOW TABLES FROM ${database.db_full_name}`,
|
||||
import varDatabaseDbHandler from "../../functions/backend/varDatabaseDbHandler";
|
||||
import addDbEntry from "../../functions/backend/db/addDbEntry";
|
||||
import slugToCamelTitle from "../../shell/utils/slugToCamelTitle";
|
||||
import grabDSQLSchemaIndexComment from "../../shell/utils/grab-dsql-schema-index-comment";
|
||||
import { grabPrimaryRequiredDbSchema, writeUpdatedDbSchema, } from "../../shell/createDbFromSchema/grab-required-database-schemas";
|
||||
import _n from "../../utils/numberfy";
|
||||
import dataTypeParser from "../../utils/db/schema/data-type-parser";
|
||||
import dataTypeConstructor from "../../utils/db/schema/data-type-constructor";
|
||||
export default async function createDbSchemaFromDb({ userId, database, dbId, }) {
|
||||
var _a, _b, _c, _d, _e, _f;
|
||||
try {
|
||||
if (!userId) {
|
||||
console.log("No user Id provided");
|
||||
return;
|
||||
}
|
||||
const targetDb = grabPrimaryRequiredDbSchema({
|
||||
userId,
|
||||
dbId: database.db_schema_id || dbId,
|
||||
});
|
||||
if (!targetDb)
|
||||
throw new Error(`Target Db not found!`);
|
||||
const existingTables = await varDatabaseDbHandler({
|
||||
database: database.db_full_name,
|
||||
queryString: `SHOW TABLES FROM ${database.db_full_name}`,
|
||||
});
|
||||
if (!existingTables)
|
||||
throw new Error("No Existing Tables");
|
||||
for (let i = 0; i < existingTables.length; i++) {
|
||||
const table = existingTables[i];
|
||||
const tableName = Object.values(table)[0];
|
||||
const tableInsert = await addDbEntry({
|
||||
dbFullName: "datasquirel",
|
||||
tableName: "user_database_tables",
|
||||
data: {
|
||||
user_id: _n(userId),
|
||||
db_id: database.id,
|
||||
db_slug: database.db_slug,
|
||||
table_name: slugToCamelTitle(tableName) || undefined,
|
||||
table_slug: tableName,
|
||||
},
|
||||
});
|
||||
if (!existingTables)
|
||||
throw new Error("No Existing Tables");
|
||||
for (let i = 0; i < existingTables.length; i++) {
|
||||
const table = existingTables[i];
|
||||
const tableName = Object.values(table)[0];
|
||||
const tableInsert = yield (0, addDbEntry_1.default)({
|
||||
dbFullName: "datasquirel",
|
||||
tableName: "user_database_tables",
|
||||
data: {
|
||||
user_id: userId,
|
||||
db_id: database.id,
|
||||
db_slug: database.db_slug,
|
||||
table_name: (0, slugToCamelTitle_1.default)(tableName),
|
||||
table_slug: tableName,
|
||||
},
|
||||
});
|
||||
const tableObject = {
|
||||
tableName: tableName,
|
||||
tableFullName: (0, slugToCamelTitle_1.default)(tableName) || "",
|
||||
fields: [],
|
||||
indexes: [],
|
||||
};
|
||||
const tableColumns = yield (0, varDatabaseDbHandler_1.default)({
|
||||
database: database.db_full_name,
|
||||
queryString: `SHOW COLUMNS FROM ${database.db_full_name}.${tableName}`,
|
||||
});
|
||||
if (tableColumns) {
|
||||
for (let k = 0; k < tableColumns.length; k++) {
|
||||
const tableColumn = tableColumns[k];
|
||||
const { Field, Type, Null, Key, Default, Extra } = tableColumn;
|
||||
const fieldObject = {
|
||||
fieldName: Field,
|
||||
dataType: Type.toUpperCase(),
|
||||
};
|
||||
if (Null === null || Null === void 0 ? void 0 : Null.match(/^no$/i))
|
||||
fieldObject.notNullValue = true;
|
||||
if (Key === null || Key === void 0 ? void 0 : Key.match(/^pri$/i))
|
||||
fieldObject.primaryKey = true;
|
||||
if ((_b = Default === null || Default === void 0 ? void 0 : Default.toString()) === null || _b === void 0 ? void 0 : _b.match(/./))
|
||||
fieldObject.defaultValue = Default;
|
||||
if ((_c = Default === null || Default === void 0 ? void 0 : Default.toString()) === null || _c === void 0 ? void 0 : _c.match(/timestamp/i)) {
|
||||
delete fieldObject.defaultValue;
|
||||
fieldObject.defaultValueLiteral = Default;
|
||||
}
|
||||
if ((_d = Extra === null || Extra === void 0 ? void 0 : Extra.toString()) === null || _d === void 0 ? void 0 : _d.match(/auto_increment/i))
|
||||
fieldObject.autoIncrement = true;
|
||||
tableObject.fields.push(fieldObject);
|
||||
const tableObject = {
|
||||
tableName: tableName,
|
||||
fields: [],
|
||||
indexes: [],
|
||||
};
|
||||
const tableColumns = await varDatabaseDbHandler({
|
||||
database: database.db_full_name,
|
||||
queryString: `SHOW COLUMNS FROM ${database.db_full_name}.${tableName}`,
|
||||
});
|
||||
if (tableColumns) {
|
||||
for (let k = 0; k < tableColumns.length; k++) {
|
||||
const tableColumn = tableColumns[k];
|
||||
const { Field, Type, Null, Key, Default, Extra } = tableColumn;
|
||||
const parsedDataType = dataTypeParser(Type.toUpperCase());
|
||||
const fieldObject = {
|
||||
fieldName: Field,
|
||||
dataType: dataTypeConstructor(parsedDataType.type, parsedDataType.limit, parsedDataType.decimal),
|
||||
};
|
||||
if (Null === null || Null === void 0 ? void 0 : Null.match(/^no$/i))
|
||||
fieldObject.notNullValue = true;
|
||||
if (Key === null || Key === void 0 ? void 0 : Key.match(/^pri$/i))
|
||||
fieldObject.primaryKey = true;
|
||||
if ((_a = Default === null || Default === void 0 ? void 0 : Default.toString()) === null || _a === void 0 ? void 0 : _a.match(/./))
|
||||
fieldObject.defaultValue = Default;
|
||||
if ((_b = Default === null || Default === void 0 ? void 0 : Default.toString()) === null || _b === void 0 ? void 0 : _b.match(/timestamp/i)) {
|
||||
delete fieldObject.defaultValue;
|
||||
fieldObject.defaultValueLiteral = Default;
|
||||
}
|
||||
if ((_c = Extra === null || Extra === void 0 ? void 0 : Extra.toString()) === null || _c === void 0 ? void 0 : _c.match(/auto_increment/i))
|
||||
fieldObject.autoIncrement = true;
|
||||
tableObject.fields.push(fieldObject);
|
||||
}
|
||||
const tableIndexes = yield (0, varDatabaseDbHandler_1.default)({
|
||||
database: database.db_full_name,
|
||||
queryString: `SHOW INDEXES FROM ${database.db_full_name}.${tableName}`,
|
||||
});
|
||||
if (tableIndexes) {
|
||||
for (let m = 0; m < tableIndexes.length; m++) {
|
||||
const indexObject = tableIndexes[m];
|
||||
const { Table, Key_name, Column_name, Null, Index_type, Index_comment, } = indexObject;
|
||||
if (!(Index_comment === null || Index_comment === void 0 ? void 0 : Index_comment.match(/^schema_index$/)))
|
||||
continue;
|
||||
const indexNewObject = {
|
||||
indexType: (Index_type === null || Index_type === void 0 ? void 0 : Index_type.match(/fulltext/i))
|
||||
? "fullText"
|
||||
: "regular",
|
||||
indexName: Key_name,
|
||||
indexTableFields: [],
|
||||
};
|
||||
const targetTableFieldObject = tableColumns === null || tableColumns === void 0 ? void 0 : tableColumns.filter((col) => col.Field === Column_name)[0];
|
||||
const existingIndexField = (_e = tableObject.indexes) === null || _e === void 0 ? void 0 : _e.filter((indx) => indx.indexName == Key_name);
|
||||
if (existingIndexField && existingIndexField[0]) {
|
||||
(_f = existingIndexField[0].indexTableFields) === null || _f === void 0 ? void 0 : _f.push({
|
||||
}
|
||||
const tableIndexes = await varDatabaseDbHandler({
|
||||
database: database.db_full_name,
|
||||
queryString: `SHOW INDEXES FROM ${database.db_full_name}.${tableName}`,
|
||||
});
|
||||
if (tableIndexes) {
|
||||
for (let m = 0; m < tableIndexes.length; m++) {
|
||||
const indexObject = tableIndexes[m];
|
||||
const { Table, Key_name, Column_name, Null, Index_type, Index_comment, } = indexObject;
|
||||
if (!(Index_comment === null || Index_comment === void 0 ? void 0 : Index_comment.match(new RegExp(grabDSQLSchemaIndexComment()))))
|
||||
continue;
|
||||
const indexNewObject = {
|
||||
indexType: (Index_type === null || Index_type === void 0 ? void 0 : Index_type.match(/fulltext/i))
|
||||
? "full_text"
|
||||
: "regular",
|
||||
indexName: Key_name,
|
||||
indexTableFields: [],
|
||||
};
|
||||
const targetTableFieldObject = tableColumns === null || tableColumns === void 0 ? void 0 : tableColumns.filter((col) => col.Field === Column_name)[0];
|
||||
const existingIndexField = (_d = tableObject.indexes) === null || _d === void 0 ? void 0 : _d.filter((indx) => indx.indexName == Key_name);
|
||||
if (existingIndexField && existingIndexField[0]) {
|
||||
(_e = existingIndexField[0].indexTableFields) === null || _e === void 0 ? void 0 : _e.push({
|
||||
value: Column_name,
|
||||
dataType: targetTableFieldObject.Type.toUpperCase(),
|
||||
});
|
||||
}
|
||||
else {
|
||||
indexNewObject.indexTableFields = [
|
||||
{
|
||||
value: Column_name,
|
||||
dataType: targetTableFieldObject.Type.toUpperCase(),
|
||||
});
|
||||
}
|
||||
else {
|
||||
indexNewObject.indexTableFields = [
|
||||
{
|
||||
value: Column_name,
|
||||
dataType: targetTableFieldObject.Type.toUpperCase(),
|
||||
},
|
||||
];
|
||||
(_g = tableObject.indexes) === null || _g === void 0 ? void 0 : _g.push(indexNewObject);
|
||||
}
|
||||
},
|
||||
];
|
||||
(_f = tableObject.indexes) === null || _f === void 0 ? void 0 : _f.push(indexNewObject);
|
||||
}
|
||||
}
|
||||
targetDb.tables.push(tableObject);
|
||||
}
|
||||
(0, setUserSchemaData_1.default)({ schemaData: userSchemaData, userId });
|
||||
return true;
|
||||
targetDb.tables.push(tableObject);
|
||||
}
|
||||
catch (error) {
|
||||
console.log(error);
|
||||
return false;
|
||||
}
|
||||
});
|
||||
writeUpdatedDbSchema({ dbSchema: targetDb, userId });
|
||||
return true;
|
||||
}
|
||||
catch (error) {
|
||||
console.log(error);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
+14
-10
@@ -1,16 +1,21 @@
|
||||
import { DbContextsArray } from "./runQuery";
|
||||
import { PostInsertReturn } from "../../../types";
|
||||
type Param<T extends {
|
||||
import { APIResponseObject, DSQL_TableSchemaType, PostInsertReturn } from "../../../types";
|
||||
export type AddDbEntryParam<T extends {
|
||||
[k: string]: any;
|
||||
} = any> = {
|
||||
} = any, K extends string = string> = {
|
||||
dbContext?: (typeof DbContextsArray)[number];
|
||||
paradigm?: "Read Only" | "Full Access";
|
||||
dbFullName?: string;
|
||||
tableName: string;
|
||||
data: T;
|
||||
tableSchema?: import("../../../types").DSQL_TableSchemaType;
|
||||
duplicateColumnName?: string;
|
||||
duplicateColumnValue?: string;
|
||||
tableName: K;
|
||||
data?: T;
|
||||
batchData?: T[];
|
||||
tableSchema?: DSQL_TableSchemaType;
|
||||
duplicateColumnName?: keyof T;
|
||||
duplicateColumnValue?: string | number;
|
||||
/**
|
||||
* Update Entry if a duplicate is found.
|
||||
* Requires `duplicateColumnName` and `duplicateColumnValue` parameters
|
||||
*/
|
||||
update?: boolean;
|
||||
encryptionKey?: string;
|
||||
encryptionSalt?: string;
|
||||
@@ -22,5 +27,4 @@ type Param<T extends {
|
||||
*/
|
||||
export default function addDbEntry<T extends {
|
||||
[k: string]: any;
|
||||
} = any>({ dbContext, paradigm, dbFullName, tableName, data, tableSchema, duplicateColumnName, duplicateColumnValue, update, encryptionKey, encryptionSalt, forceLocal, debug, }: Param<T>): Promise<PostInsertReturn | null>;
|
||||
export {};
|
||||
} = any, K extends string = string>({ dbContext, paradigm, dbFullName, tableName, data, batchData, tableSchema, duplicateColumnName, duplicateColumnValue, update, encryptionKey, encryptionSalt, forceLocal, debug, }: AddDbEntryParam<T, K>): Promise<APIResponseObject<PostInsertReturn>>;
|
||||
|
||||
+126
-117
@@ -1,100 +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 = addDbEntry;
|
||||
const sanitize_html_1 = __importDefault(require("sanitize-html"));
|
||||
const sanitizeHtmlOptions_1 = __importDefault(require("../html/sanitizeHtmlOptions"));
|
||||
const updateDbEntry_1 = __importDefault(require("./updateDbEntry"));
|
||||
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"));
|
||||
import sanitizeHtml from "sanitize-html";
|
||||
import sanitizeHtmlOptions from "../html/sanitizeHtmlOptions";
|
||||
import updateDbEntry from "./updateDbEntry";
|
||||
import _ from "lodash";
|
||||
import encrypt from "../../dsql/encrypt";
|
||||
import connDbHandler from "../../../utils/db/conn-db-handler";
|
||||
import checkIfIsMaster from "../../../utils/check-if-is-master";
|
||||
import debugLog from "../../../utils/logging/debug-log";
|
||||
import purgeDefaultFields from "../../../utils/purge-default-fields";
|
||||
/**
|
||||
* Add a db Entry Function
|
||||
*/
|
||||
function addDbEntry(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ dbContext, paradigm, dbFullName, tableName, data, tableSchema, duplicateColumnName, duplicateColumnValue, update, encryptionKey, encryptionSalt, forceLocal, debug, }) {
|
||||
var _b, _c, _d;
|
||||
const isMaster = forceLocal
|
||||
? true
|
||||
: (0, check_if_is_master_1.default)({ dbContext, dbFullName });
|
||||
if (debug) {
|
||||
(0, debug_log_1.default)({
|
||||
log: isMaster,
|
||||
addTime: true,
|
||||
label: "isMaster",
|
||||
export default async function addDbEntry({ dbContext, paradigm, dbFullName, tableName, data, batchData, tableSchema, duplicateColumnName, duplicateColumnValue, update, encryptionKey, encryptionSalt, forceLocal, debug, }) {
|
||||
const isMaster = forceLocal
|
||||
? true
|
||||
: checkIfIsMaster({ dbContext, dbFullName });
|
||||
if (debug) {
|
||||
debugLog({
|
||||
log: isMaster,
|
||||
addTime: true,
|
||||
label: "isMaster",
|
||||
});
|
||||
}
|
||||
const DB_CONN = isMaster
|
||||
? global.DSQL_DB_CONN
|
||||
: global.DSQL_FULL_ACCESS_DB_CONN || global.DSQL_DB_CONN;
|
||||
const DB_RO_CONN = isMaster
|
||||
? global.DSQL_DB_CONN
|
||||
: global.DSQL_READ_ONLY_DB_CONN || global.DSQL_DB_CONN;
|
||||
let newData = _.cloneDeep(data);
|
||||
if (newData) {
|
||||
newData = purgeDefaultFields(newData);
|
||||
}
|
||||
let newBatchData = _.cloneDeep(batchData);
|
||||
if (newBatchData) {
|
||||
newBatchData = purgeDefaultFields(newBatchData);
|
||||
}
|
||||
if (duplicateColumnName &&
|
||||
typeof duplicateColumnName === "string" &&
|
||||
newData) {
|
||||
const checkDuplicateQuery = `SELECT * FROM ${isMaster ? "" : `\`${dbFullName}\`.`}\`${tableName}\` WHERE \`${duplicateColumnName}\`=?`;
|
||||
const duplicateValue = await connDbHandler(DB_RO_CONN, checkDuplicateQuery, [duplicateColumnValue]);
|
||||
if ((duplicateValue === null || duplicateValue === void 0 ? void 0 : duplicateValue[0]) && !update) {
|
||||
return {
|
||||
success: false,
|
||||
payload: undefined,
|
||||
msg: "Duplicate entry found",
|
||||
};
|
||||
}
|
||||
else if ((duplicateValue === null || duplicateValue === void 0 ? void 0 : duplicateValue[0]) && update) {
|
||||
return await updateDbEntry({
|
||||
dbContext,
|
||||
dbFullName,
|
||||
tableName,
|
||||
data: newData,
|
||||
tableSchema,
|
||||
encryptionKey,
|
||||
encryptionSalt,
|
||||
identifierColumnName: duplicateColumnName,
|
||||
identifierValue: duplicateColumnValue || "",
|
||||
});
|
||||
}
|
||||
const DB_CONN = isMaster
|
||||
? global.DSQL_DB_CONN
|
||||
: global.DSQL_FULL_ACCESS_DB_CONN || global.DSQL_DB_CONN;
|
||||
const DB_RO_CONN = isMaster
|
||||
? global.DSQL_DB_CONN
|
||||
: global.DSQL_READ_ONLY_DB_CONN || global.DSQL_DB_CONN;
|
||||
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"];
|
||||
if (duplicateColumnName && typeof duplicateColumnName === "string") {
|
||||
const checkDuplicateQuery = `SELECT * FROM ${isMaster ? "" : `\`${dbFullName}\`.`}\`${tableName}\` WHERE \`${duplicateColumnName}\`=?`;
|
||||
const duplicateValue = yield (0, conn_db_handler_1.default)(DB_RO_CONN, checkDuplicateQuery, [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,
|
||||
dbFullName,
|
||||
tableName,
|
||||
data,
|
||||
tableSchema,
|
||||
encryptionKey,
|
||||
encryptionSalt,
|
||||
identifierColumnName: duplicateColumnName,
|
||||
identifierValue: duplicateColumnValue || "",
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
function generateQuery(data) {
|
||||
var _a, _b, _c;
|
||||
const dataKeys = Object.keys(data);
|
||||
let insertKeysArray = [];
|
||||
let insertValuesArray = [];
|
||||
for (let i = 0; i < dataKeys.length; i++) {
|
||||
try {
|
||||
const dataKey = dataKeys[i];
|
||||
let value = data === null || data === void 0 ? void 0 : data[dataKey];
|
||||
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)
|
||||
? (_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)
|
||||
continue;
|
||||
if (((_c = targetFieldSchema === null || targetFieldSchema === void 0 ? void 0 : targetFieldSchema.dataType) === null || _c === void 0 ? void 0 : _c.match(/int$/i)) &&
|
||||
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)({
|
||||
value = encrypt({
|
||||
data: value,
|
||||
encryptionKey,
|
||||
encryptionSalt,
|
||||
@@ -102,8 +91,9 @@ function addDbEntry(_a) {
|
||||
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.richText) ||
|
||||
String(value).match(htmlRegex)) {
|
||||
value = sanitizeHtml(value, sanitizeHtmlOptions);
|
||||
}
|
||||
if (targetFieldSchema === null || targetFieldSchema === void 0 ? void 0 : targetFieldSchema.pattern) {
|
||||
const pattern = new RegExp(targetFieldSchema.pattern, targetFieldSchema.patternFlags || "");
|
||||
@@ -125,55 +115,74 @@ function addDbEntry(_a) {
|
||||
}
|
||||
catch (error) {
|
||||
console.log("DSQL: Error in parsing data keys =>", error.message);
|
||||
(_d = global.ERROR_CALLBACK) === null || _d === void 0 ? void 0 : _d.call(global, `Error parsing Data Keys`, error);
|
||||
(_c = global.ERROR_CALLBACK) === null || _c === void 0 ? void 0 : _c.call(global, `Error parsing Data Keys`, error);
|
||||
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 ${isMaster ? "" : `\`${dbFullName}\`.`}\`${tableName}\` (${insertKeysArray.join(",")}) VALUES (${insertValuesArray
|
||||
.map(() => "?")
|
||||
.join(",")})`;
|
||||
insertKeysArray.push("`date_created`");
|
||||
insertValuesArray.push(Date());
|
||||
insertKeysArray.push("`date_created_code`");
|
||||
insertValuesArray.push(Date.now());
|
||||
insertKeysArray.push("`date_updated`");
|
||||
insertValuesArray.push(Date());
|
||||
insertKeysArray.push("`date_updated_code`");
|
||||
insertValuesArray.push(Date.now());
|
||||
const queryValuesArray = insertValuesArray;
|
||||
if (debug) {
|
||||
(0, debug_log_1.default)({
|
||||
log: DB_CONN === null || DB_CONN === void 0 ? void 0 : DB_CONN.getConfig(),
|
||||
addTime: true,
|
||||
label: "DB_CONN Config",
|
||||
});
|
||||
(0, debug_log_1.default)({
|
||||
log: query,
|
||||
addTime: true,
|
||||
label: "query",
|
||||
});
|
||||
(0, debug_log_1.default)({
|
||||
log: queryValuesArray,
|
||||
addTime: true,
|
||||
label: "queryValuesArray",
|
||||
});
|
||||
return { queryValuesArray, insertValuesArray, insertKeysArray };
|
||||
}
|
||||
if (newData) {
|
||||
const { insertKeysArray, insertValuesArray, queryValuesArray } = generateQuery(newData);
|
||||
const query = `INSERT INTO ${isMaster && !dbFullName ? "" : `\`${dbFullName}\`.`}\`${tableName}\` (${insertKeysArray.join(",")}) VALUES (${insertValuesArray.map(() => "?").join(",")})`;
|
||||
const newInsert = await connDbHandler(DB_CONN, query, queryValuesArray, debug);
|
||||
return {
|
||||
success: Boolean(newInsert === null || newInsert === void 0 ? void 0 : newInsert.insertId),
|
||||
payload: newInsert,
|
||||
queryObject: {
|
||||
sql: query,
|
||||
params: queryValuesArray,
|
||||
},
|
||||
};
|
||||
}
|
||||
else if (newBatchData) {
|
||||
let batchInsertKeysArray;
|
||||
let batchInsertValuesArray = [];
|
||||
let batchQueryValuesArray = [];
|
||||
for (let i = 0; i < newBatchData.length; i++) {
|
||||
const singleBatchData = newBatchData[i];
|
||||
const { insertKeysArray, insertValuesArray, queryValuesArray } = generateQuery(singleBatchData);
|
||||
if (!batchInsertKeysArray) {
|
||||
batchInsertKeysArray = insertKeysArray;
|
||||
}
|
||||
batchInsertValuesArray.push(insertValuesArray);
|
||||
batchQueryValuesArray.push(queryValuesArray);
|
||||
}
|
||||
const newInsert = yield (0, conn_db_handler_1.default)(DB_CONN, query, queryValuesArray, debug);
|
||||
const query = `INSERT INTO ${isMaster && !dbFullName ? "" : `\`${dbFullName}\`.`}\`${tableName}\` (${batchInsertKeysArray === null || batchInsertKeysArray === void 0 ? void 0 : batchInsertKeysArray.join(",")}) VALUES ${batchInsertValuesArray
|
||||
.map((vl) => `(${vl.map(() => "?").join(",")})`)
|
||||
.join(",")}`;
|
||||
console.log("query", query);
|
||||
console.log("batchQueryValuesArray", batchQueryValuesArray);
|
||||
const newInsert = await connDbHandler(DB_CONN, query, batchQueryValuesArray.flat(), debug);
|
||||
if (debug) {
|
||||
(0, debug_log_1.default)({
|
||||
debugLog({
|
||||
log: newInsert,
|
||||
addTime: true,
|
||||
label: "newInsert",
|
||||
});
|
||||
}
|
||||
return newInsert;
|
||||
});
|
||||
return {
|
||||
success: Boolean(newInsert === null || newInsert === void 0 ? void 0 : newInsert.insertId),
|
||||
payload: newInsert,
|
||||
queryObject: {
|
||||
sql: query,
|
||||
params: batchQueryValuesArray.flat(),
|
||||
},
|
||||
};
|
||||
}
|
||||
else {
|
||||
return {
|
||||
success: false,
|
||||
payload: undefined,
|
||||
msg: "No data provided",
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
+11
-6
@@ -1,10 +1,13 @@
|
||||
import { DSQL_TableSchemaType, PostInsertReturn } from "../../../types";
|
||||
import { DbContextsArray } from "./runQuery";
|
||||
type Param = {
|
||||
type Param<T extends {
|
||||
[k: string]: any;
|
||||
} = any, K extends string = string> = {
|
||||
dbContext?: (typeof DbContextsArray)[number];
|
||||
dbFullName: string;
|
||||
tableName: string;
|
||||
tableSchema?: import("../../../types").DSQL_TableSchemaType;
|
||||
identifierColumnName: string;
|
||||
dbFullName?: string;
|
||||
tableName: K;
|
||||
tableSchema?: DSQL_TableSchemaType;
|
||||
identifierColumnName: keyof T;
|
||||
identifierValue: string | number;
|
||||
forceLocal?: boolean;
|
||||
};
|
||||
@@ -12,5 +15,7 @@ type Param = {
|
||||
* # Delete DB Entry Function
|
||||
* @description
|
||||
*/
|
||||
export default function deleteDbEntry({ dbContext, dbFullName, tableName, identifierColumnName, identifierValue, forceLocal, }: Param): Promise<object | null>;
|
||||
export default function deleteDbEntry<T extends {
|
||||
[k: string]: any;
|
||||
} = any, K extends string = string>({ dbContext, dbFullName, tableName, identifierColumnName, identifierValue, forceLocal, }: Param<T, K>): Promise<PostInsertReturn | null>;
|
||||
export {};
|
||||
|
||||
+29
-49
@@ -1,54 +1,34 @@
|
||||
"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 check_if_is_master_1 = __importDefault(require("../../../utils/check-if-is-master"));
|
||||
const conn_db_handler_1 = __importDefault(require("../../../utils/db/conn-db-handler"));
|
||||
import checkIfIsMaster from "../../../utils/check-if-is-master";
|
||||
import connDbHandler from "../../../utils/db/conn-db-handler";
|
||||
/**
|
||||
* # Delete DB Entry Function
|
||||
* @description
|
||||
*/
|
||||
function deleteDbEntry(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ dbContext, dbFullName, tableName, identifierColumnName, identifierValue, forceLocal, }) {
|
||||
var _b;
|
||||
try {
|
||||
const isMaster = forceLocal
|
||||
? true
|
||||
: (0, check_if_is_master_1.default)({ dbContext, dbFullName });
|
||||
const DB_CONN = isMaster
|
||||
? global.DSQL_DB_CONN
|
||||
: global.DSQL_FULL_ACCESS_DB_CONN || global.DSQL_DB_CONN;
|
||||
const DB_RO_CONN = isMaster
|
||||
? global.DSQL_DB_CONN
|
||||
: global.DSQL_READ_ONLY_DB_CONN || global.DSQL_DB_CONN;
|
||||
/**
|
||||
* Execution
|
||||
*
|
||||
* @description
|
||||
*/
|
||||
const query = `DELETE FROM ${isMaster ? "" : `\`${dbFullName}\`.`}\`${tableName}\` WHERE \`${identifierColumnName}\`=?`;
|
||||
const deletedEntry = yield (0, conn_db_handler_1.default)(DB_CONN, query, [
|
||||
identifierValue,
|
||||
]);
|
||||
/**
|
||||
* Return statement
|
||||
*/
|
||||
return deletedEntry;
|
||||
}
|
||||
catch (error) {
|
||||
(_b = global.ERROR_CALLBACK) === null || _b === void 0 ? void 0 : _b.call(global, `Error Deleting Entry`, error);
|
||||
return null;
|
||||
}
|
||||
});
|
||||
export default async function deleteDbEntry({ dbContext, dbFullName, tableName, identifierColumnName, identifierValue, forceLocal, }) {
|
||||
var _a;
|
||||
try {
|
||||
const isMaster = forceLocal
|
||||
? true
|
||||
: checkIfIsMaster({ dbContext, dbFullName });
|
||||
const DB_CONN = isMaster
|
||||
? global.DSQL_DB_CONN
|
||||
: global.DSQL_FULL_ACCESS_DB_CONN || global.DSQL_DB_CONN;
|
||||
/**
|
||||
* Execution
|
||||
*
|
||||
* @description
|
||||
*/
|
||||
const query = `DELETE FROM ${isMaster && !dbFullName ? "" : `\`${dbFullName}\`.`}\`${tableName}\` WHERE \`${identifierColumnName.toString()}\`=?`;
|
||||
const deletedEntry = await connDbHandler(DB_CONN, query, [
|
||||
identifierValue,
|
||||
]);
|
||||
/**
|
||||
* Return statement
|
||||
*/
|
||||
return deletedEntry;
|
||||
}
|
||||
catch (error) {
|
||||
(_a = global.ERROR_CALLBACK) === null || _a === void 0 ? void 0 : _a.call(global, `Error Deleting Entry`, error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,10 +1,7 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = pathTraversalCheck;
|
||||
/**
|
||||
* # Path Traversal Check
|
||||
* @returns {string}
|
||||
*/
|
||||
function pathTraversalCheck(text) {
|
||||
export default function pathTraversalCheck(text) {
|
||||
return text.toString().replace(/\//g, "");
|
||||
}
|
||||
|
||||
+128
-146
@@ -1,155 +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.DbContextsArray = void 0;
|
||||
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"));
|
||||
exports.DbContextsArray = ["Master", "Dsql User"];
|
||||
import fullAccessDbHandler from "../fullAccessDbHandler";
|
||||
import varReadOnlyDatabaseDbHandler from "../varReadOnlyDatabaseDbHandler";
|
||||
import serverError from "../serverError";
|
||||
import addDbEntry from "./addDbEntry";
|
||||
import updateDbEntry from "./updateDbEntry";
|
||||
import deleteDbEntry from "./deleteDbEntry";
|
||||
import trimSql from "../../../utils/trim-sql";
|
||||
export const DbContextsArray = ["Master", "Dsql User"];
|
||||
/**
|
||||
* # Run DSQL users queries
|
||||
*/
|
||||
function runQuery(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ dbFullName, query, readOnly, dbSchema, queryValuesArray, tableName, debug, dbContext, forceLocal, }) {
|
||||
/**
|
||||
* 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
|
||||
*/
|
||||
export default async function runQuery({ dbFullName, query, readOnly, dbSchema, queryValuesArray, tableName, debug, dbContext, forceLocal, }) {
|
||||
/**
|
||||
* Declare variables
|
||||
*
|
||||
* @description Declare "results" variable
|
||||
*/
|
||||
let result;
|
||||
let error;
|
||||
let tableSchema;
|
||||
if (dbSchema) {
|
||||
try {
|
||||
if (typeof query === "string") {
|
||||
const formattedQuery = (0, trim_sql_1.default)(query);
|
||||
if (debug && global.DSQL_USE_LOCAL) {
|
||||
console.log("runQuery:formattedQuery", formattedQuery);
|
||||
}
|
||||
/**
|
||||
* Input Validation
|
||||
*
|
||||
* @description Input Validation
|
||||
*/
|
||||
if (readOnly && formattedQuery.match(/^alter|^delete|^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)),
|
||||
tableSchema,
|
||||
forceLocal,
|
||||
});
|
||||
}
|
||||
else {
|
||||
result = yield (0, fullAccessDbHandler_1.default)({
|
||||
queryString: formattedQuery,
|
||||
queryValuesArray: queryValuesArray === null || queryValuesArray === void 0 ? void 0 : queryValuesArray.map((vl) => String(vl)),
|
||||
tableSchema,
|
||||
forceLocal,
|
||||
});
|
||||
}
|
||||
}
|
||||
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,
|
||||
dbFullName: dbFullName,
|
||||
tableName: table,
|
||||
data: data,
|
||||
update,
|
||||
duplicateColumnName,
|
||||
duplicateColumnValue,
|
||||
tableSchema,
|
||||
debug,
|
||||
});
|
||||
if (!(result === null || result === void 0 ? void 0 : result.insertId)) {
|
||||
error = "Couldn't insert data";
|
||||
}
|
||||
break;
|
||||
case "update":
|
||||
result = yield (0, updateDbEntry_1.default)({
|
||||
dbContext,
|
||||
dbFullName: dbFullName,
|
||||
tableName: table,
|
||||
data: data,
|
||||
identifierColumnName,
|
||||
identifierValue,
|
||||
tableSchema,
|
||||
});
|
||||
break;
|
||||
case "delete":
|
||||
result = yield (0, deleteDbEntry_1.default)({
|
||||
dbContext,
|
||||
dbFullName: dbFullName,
|
||||
tableName: table,
|
||||
identifierColumnName,
|
||||
identifierValue,
|
||||
tableSchema,
|
||||
});
|
||||
break;
|
||||
default:
|
||||
result = null;
|
||||
break;
|
||||
}
|
||||
}
|
||||
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) {
|
||||
(0, serverError_1.default)({
|
||||
component: "functions/backend/runQuery",
|
||||
message: err.message,
|
||||
});
|
||||
catch (_err) {
|
||||
// console.log("ERROR getting tableSchema: ", _err.message);
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Declare variables
|
||||
*
|
||||
* @description Declare "results" variable
|
||||
*/
|
||||
try {
|
||||
if (typeof query === "string") {
|
||||
const formattedQuery = trimSql(query);
|
||||
if (debug && global.DSQL_USE_LOCAL) {
|
||||
console.log("runQuery:error", err.message);
|
||||
console.log("runQuery:formattedQuery", formattedQuery);
|
||||
}
|
||||
/**
|
||||
* Input Validation
|
||||
*
|
||||
* @description Input Validation
|
||||
*/
|
||||
if (readOnly && formattedQuery.match(/^alter|^delete|^create/i)) {
|
||||
throw new Error("Wrong Input!");
|
||||
}
|
||||
if (readOnly) {
|
||||
result = await varReadOnlyDatabaseDbHandler({
|
||||
queryString: formattedQuery,
|
||||
queryValuesArray: queryValuesArray === null || queryValuesArray === void 0 ? void 0 : queryValuesArray.map((vl) => String(vl)),
|
||||
tableSchema,
|
||||
forceLocal,
|
||||
});
|
||||
}
|
||||
else {
|
||||
result = await fullAccessDbHandler({
|
||||
queryString: formattedQuery,
|
||||
queryValuesArray: queryValuesArray === null || queryValuesArray === void 0 ? void 0 : queryValuesArray.map((vl) => String(vl)),
|
||||
tableSchema,
|
||||
forceLocal,
|
||||
});
|
||||
}
|
||||
result = null;
|
||||
error = err.message;
|
||||
}
|
||||
return { result, error };
|
||||
});
|
||||
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 = await addDbEntry({
|
||||
dbContext,
|
||||
dbFullName,
|
||||
tableName: table,
|
||||
data: data,
|
||||
update,
|
||||
duplicateColumnName,
|
||||
duplicateColumnValue,
|
||||
tableSchema,
|
||||
debug,
|
||||
});
|
||||
if (!(result === null || result === void 0 ? void 0 : result.insertId)) {
|
||||
error = "Couldn't insert data";
|
||||
}
|
||||
break;
|
||||
case "update":
|
||||
result = await updateDbEntry({
|
||||
dbContext,
|
||||
dbFullName,
|
||||
tableName: table,
|
||||
data: data,
|
||||
identifierColumnName,
|
||||
identifierValue,
|
||||
tableSchema,
|
||||
});
|
||||
break;
|
||||
case "delete":
|
||||
result = await deleteDbEntry({
|
||||
dbContext,
|
||||
dbFullName,
|
||||
tableName: table,
|
||||
identifierColumnName,
|
||||
identifierValue,
|
||||
tableSchema,
|
||||
});
|
||||
break;
|
||||
default:
|
||||
result = null;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (err) {
|
||||
serverError({
|
||||
component: "functions/backend/runQuery",
|
||||
message: err.message,
|
||||
});
|
||||
if (debug && global.DSQL_USE_LOCAL) {
|
||||
console.log("runQuery:error", err.message);
|
||||
}
|
||||
result = null;
|
||||
error = err.message;
|
||||
}
|
||||
return { result, error };
|
||||
}
|
||||
|
||||
+3
-8
@@ -1,9 +1,4 @@
|
||||
"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"));
|
||||
import _ from "lodash";
|
||||
/**
|
||||
* Sanitize SQL function
|
||||
* ==============================================================================
|
||||
@@ -89,7 +84,7 @@ function sanitizeObjects(object, spaces) {
|
||||
* @returns {string[]|number[]|object[]}
|
||||
*/
|
||||
function sanitizeArrays(array, spaces) {
|
||||
let arrayUpdated = lodash_1.default.cloneDeep(array);
|
||||
let arrayUpdated = _.cloneDeep(array);
|
||||
arrayUpdated.forEach((item, index) => {
|
||||
const value = item;
|
||||
if (!value) {
|
||||
@@ -108,4 +103,4 @@ function sanitizeArrays(array, spaces) {
|
||||
});
|
||||
return arrayUpdated;
|
||||
}
|
||||
exports.default = sanitizeSql;
|
||||
export default sanitizeSql;
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { DbContextsArray } from "./runQuery";
|
||||
import { PostInsertReturn } from "../../../types";
|
||||
import { APIResponseObject, DSQL_TableSchemaType, PostInsertReturn } from "../../../types";
|
||||
type Param<T extends {
|
||||
[k: string]: any;
|
||||
} = any> = {
|
||||
@@ -8,8 +8,8 @@ type Param<T extends {
|
||||
tableName: string;
|
||||
encryptionKey?: string;
|
||||
encryptionSalt?: string;
|
||||
data: any;
|
||||
tableSchema?: import("../../../types").DSQL_TableSchemaType;
|
||||
data?: T;
|
||||
tableSchema?: DSQL_TableSchemaType;
|
||||
identifierColumnName: keyof T;
|
||||
identifierValue: string | number;
|
||||
forceLocal?: boolean;
|
||||
@@ -20,5 +20,5 @@ type Param<T extends {
|
||||
*/
|
||||
export default function updateDbEntry<T extends {
|
||||
[k: string]: any;
|
||||
} = any>({ dbContext, dbFullName, tableName, data, tableSchema, identifierColumnName, identifierValue, encryptionKey, encryptionSalt, forceLocal, }: Param<T>): Promise<PostInsertReturn | null>;
|
||||
} = any>({ dbContext, dbFullName, tableName, data, tableSchema, identifierColumnName, identifierValue, encryptionKey, encryptionSalt, forceLocal, }: Param<T>): Promise<APIResponseObject<PostInsertReturn>>;
|
||||
export {};
|
||||
|
||||
+119
-121
@@ -1,129 +1,127 @@
|
||||
"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 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"));
|
||||
import sanitizeHtml from "sanitize-html";
|
||||
import sanitizeHtmlOptions from "../html/sanitizeHtmlOptions";
|
||||
import encrypt from "../../dsql/encrypt";
|
||||
import checkIfIsMaster from "../../../utils/check-if-is-master";
|
||||
import connDbHandler from "../../../utils/db/conn-db-handler";
|
||||
import _ from "lodash";
|
||||
import purgeDefaultFields from "../../../utils/purge-default-fields";
|
||||
/**
|
||||
* # Update DB Function
|
||||
* @description
|
||||
*/
|
||||
function updateDbEntry(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ dbContext, dbFullName, tableName, data, tableSchema, identifierColumnName, identifierValue, encryptionKey, encryptionSalt, forceLocal, }) {
|
||||
var _b;
|
||||
/**
|
||||
* Check if data is valid
|
||||
*/
|
||||
if (!data || !Object.keys(data).length)
|
||||
return null;
|
||||
const isMaster = forceLocal
|
||||
? true
|
||||
: (0, check_if_is_master_1.default)({ dbContext, dbFullName });
|
||||
const DB_CONN = isMaster
|
||||
? global.DSQL_DB_CONN
|
||||
: global.DSQL_FULL_ACCESS_DB_CONN || global.DSQL_DB_CONN;
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
/**
|
||||
* 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);
|
||||
export default async function updateDbEntry({ dbContext, dbFullName, tableName, data, tableSchema, identifierColumnName, identifierValue, encryptionKey, encryptionSalt, forceLocal, }) {
|
||||
var _a;
|
||||
/**
|
||||
* Check if data is valid
|
||||
*/
|
||||
if (!data || !Object.keys(data).length) {
|
||||
return {
|
||||
success: false,
|
||||
payload: undefined,
|
||||
msg: "No data provided",
|
||||
};
|
||||
}
|
||||
const isMaster = forceLocal
|
||||
? true
|
||||
: checkIfIsMaster({ dbContext, dbFullName });
|
||||
const DB_CONN = isMaster
|
||||
? global.DSQL_DB_CONN
|
||||
: global.DSQL_FULL_ACCESS_DB_CONN || global.DSQL_DB_CONN;
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
let newData = _.cloneDeep(data);
|
||||
newData = purgeDefaultFields(newData);
|
||||
/**
|
||||
* Declare variables
|
||||
*
|
||||
* @description Declare "results" variable
|
||||
*/
|
||||
const dataKeys = Object.keys(newData);
|
||||
let updateKeyValueArray = [];
|
||||
let updateValues = [];
|
||||
for (let i = 0; i < dataKeys.length; i++) {
|
||||
try {
|
||||
const dataKey = dataKeys[i];
|
||||
let value = newData[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)
|
||||
continue;
|
||||
const htmlRegex = /<[^>]+>/g;
|
||||
if ((targetFieldSchema === null || targetFieldSchema === void 0 ? void 0 : targetFieldSchema.richText) || String(value).match(htmlRegex)) {
|
||||
value = sanitizeHtml(value, sanitizeHtmlOptions);
|
||||
}
|
||||
if (targetFieldSchema === null || targetFieldSchema === void 0 ? void 0 : targetFieldSchema.encrypted) {
|
||||
value = encrypt({
|
||||
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);
|
||||
}
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
}
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
updateKeyValueArray.push(`date_updated='${Date()}'`);
|
||||
updateKeyValueArray.push(`date_updated_code='${Date.now()}'`);
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
const query = `UPDATE ${isMaster ? "" : `\`${dbFullName}\`.`}\`${tableName}\` SET ${updateKeyValueArray.join(",")} WHERE \`${identifierColumnName}\`=?`;
|
||||
updateValues.push(identifierValue);
|
||||
const updatedEntry = yield (0, conn_db_handler_1.default)(DB_CONN, query, updateValues);
|
||||
/**
|
||||
* Return statement
|
||||
*/
|
||||
return updatedEntry;
|
||||
});
|
||||
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 ${isMaster && !dbFullName ? "" : `\`${dbFullName}\`.`}\`${tableName}\` SET ${updateKeyValueArray.join(",")} WHERE \`${identifierColumnName}\`=?`;
|
||||
updateValues.push(identifierValue);
|
||||
const updatedEntry = await connDbHandler(DB_CONN, query, updateValues);
|
||||
/**
|
||||
* Return statement
|
||||
*/
|
||||
return {
|
||||
success: Boolean(updatedEntry === null || updatedEntry === void 0 ? void 0 : updatedEntry.affectedRows),
|
||||
payload: updatedEntry,
|
||||
queryObject: {
|
||||
sql: query,
|
||||
params: updateValues,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
+8
-1
@@ -1,4 +1,11 @@
|
||||
type Param = {
|
||||
query: string;
|
||||
values?: string[] | object;
|
||||
noErrorLogs?: boolean;
|
||||
};
|
||||
/**
|
||||
* # Main DB Handler Function
|
||||
* @requires DSQL_DB_CONN - Gobal Variable for Datasquirel Database
|
||||
*/
|
||||
export default function dbHandler(...args: any[]): Promise<any>;
|
||||
export default function dbHandler({ query, values, noErrorLogs, }: Param): Promise<any[] | object | null>;
|
||||
export {};
|
||||
|
||||
+39
-66
@@ -1,74 +1,47 @@
|
||||
"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 grab_dsql_connection_1 = __importDefault(require("../../utils/grab-dsql-connection"));
|
||||
const path_1 = __importDefault(require("path"));
|
||||
import fs from "fs";
|
||||
import path from "path";
|
||||
import grabDSQLConnection from "../../utils/grab-dsql-connection";
|
||||
/**
|
||||
* # Main DB Handler Function
|
||||
* @requires DSQL_DB_CONN - Gobal Variable for Datasquirel Database
|
||||
*/
|
||||
function dbHandler(...args) {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
var _a, _b;
|
||||
((_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");
|
||||
const CONNECTION = (0, grab_dsql_connection_1.default)();
|
||||
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);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
catch (error) {
|
||||
const tmpFolder = path_1.default.resolve(process.cwd(), "./.tmp");
|
||||
if (!fs_1.default.existsSync(tmpFolder))
|
||||
fs_1.default.mkdirSync(tmpFolder, { recursive: true });
|
||||
fs_1.default.appendFileSync(path_1.default.resolve(tmpFolder, "./dbErrorLogs.txt"), JSON.stringify(error, null, 4) + "\n" + Date() + "\n\n\n", "utf8");
|
||||
results = null;
|
||||
(_b = global.ERROR_CALLBACK) === null || _b === void 0 ? void 0 : _b.call(global, `DB Handler Error`, error);
|
||||
(0, serverError_1.default)({
|
||||
component: "dbHandler",
|
||||
message: error.message,
|
||||
});
|
||||
}
|
||||
finally {
|
||||
yield (CONNECTION === null || CONNECTION === void 0 ? void 0 : CONNECTION.end());
|
||||
}
|
||||
/**
|
||||
* Return results
|
||||
*
|
||||
* @description Return results add to cache if "req" param is passed
|
||||
*/
|
||||
if (results) {
|
||||
return JSON.parse(JSON.stringify(results));
|
||||
export default async function dbHandler({ query, values, noErrorLogs, }) {
|
||||
var _a;
|
||||
const CONNECTION = grabDSQLConnection();
|
||||
let results;
|
||||
try {
|
||||
if (query && values) {
|
||||
results = await CONNECTION.query(query, values);
|
||||
}
|
||||
else {
|
||||
results = await CONNECTION.query(query);
|
||||
}
|
||||
}
|
||||
catch (error) {
|
||||
if (!noErrorLogs) {
|
||||
(_a = global.ERROR_CALLBACK) === null || _a === void 0 ? void 0 : _a.call(global, `DB Handler Error...`, error);
|
||||
}
|
||||
if (process.env.FIRST_RUN) {
|
||||
return null;
|
||||
}
|
||||
});
|
||||
if (!noErrorLogs) {
|
||||
console.log("ERROR in dbHandler =>", error.message);
|
||||
console.log(error);
|
||||
console.log(CONNECTION.config());
|
||||
const tmpFolder = path.resolve(process.cwd(), "./.tmp");
|
||||
if (!fs.existsSync(tmpFolder))
|
||||
fs.mkdirSync(tmpFolder, { recursive: true });
|
||||
fs.appendFileSync(path.resolve(tmpFolder, "./dbErrorLogs.txt"), JSON.stringify(error, null, 4) + "\n" + Date() + "\n\n\n", "utf8");
|
||||
}
|
||||
results = null;
|
||||
}
|
||||
finally {
|
||||
await (CONNECTION === null || CONNECTION === void 0 ? void 0 : CONNECTION.end());
|
||||
}
|
||||
if (results) {
|
||||
return JSON.parse(JSON.stringify(results));
|
||||
}
|
||||
else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +0,0 @@
|
||||
/**
|
||||
* Regular expression to match default fields
|
||||
*
|
||||
* @description Regular expression to match default fields
|
||||
*/
|
||||
declare const defaultFieldsRegexp: RegExp;
|
||||
export default defaultFieldsRegexp;
|
||||
@@ -1,9 +0,0 @@
|
||||
"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;
|
||||
+55
-72
@@ -1,78 +1,61 @@
|
||||
"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 = fullAccessDbHandler;
|
||||
const conn_db_handler_1 = __importDefault(require("../../utils/db/conn-db-handler"));
|
||||
const parseDbResults_1 = __importDefault(require("./parseDbResults"));
|
||||
const serverError_1 = __importDefault(require("./serverError"));
|
||||
import connDbHandler from "../../utils/db/conn-db-handler";
|
||||
import parseDbResults from "./parseDbResults";
|
||||
import serverError from "./serverError";
|
||||
/**
|
||||
* # Full Access Db Handler
|
||||
*/
|
||||
function fullAccessDbHandler(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ queryString, tableSchema, queryValuesArray, forceLocal, }) {
|
||||
var _b;
|
||||
export default async function fullAccessDbHandler({ queryString, tableSchema, queryValuesArray, forceLocal, }) {
|
||||
var _a;
|
||||
/**
|
||||
* Declare variables
|
||||
*
|
||||
* @description Declare "results" variable
|
||||
*/
|
||||
let results;
|
||||
const DB_CONN = forceLocal
|
||||
? global.DSQL_DB_CONN
|
||||
: global.DSQL_FULL_ACCESS_DB_CONN || global.DSQL_DB_CONN;
|
||||
/**
|
||||
* Fetch from db
|
||||
*
|
||||
* @description Fetch data from db if no cache
|
||||
*/
|
||||
try {
|
||||
results = await connDbHandler(DB_CONN, queryString, queryValuesArray);
|
||||
////////////////////////////////////////
|
||||
}
|
||||
catch (error) {
|
||||
////////////////////////////////////////
|
||||
(_a = global.ERROR_CALLBACK) === null || _a === void 0 ? void 0 : _a.call(global, `Full Access DB Handler Error`, error);
|
||||
serverError({
|
||||
component: "fullAccessDbHandler",
|
||||
message: error.message,
|
||||
});
|
||||
/**
|
||||
* Declare variables
|
||||
*
|
||||
* @description Declare "results" variable
|
||||
* Return error
|
||||
*/
|
||||
let results;
|
||||
const DB_CONN = forceLocal
|
||||
? global.DSQL_DB_CONN
|
||||
: global.DSQL_FULL_ACCESS_DB_CONN || global.DSQL_DB_CONN;
|
||||
/**
|
||||
* Fetch from db
|
||||
*
|
||||
* @description Fetch data from db if no cache
|
||||
*/
|
||||
try {
|
||||
results = yield (0, conn_db_handler_1.default)(DB_CONN, queryString, queryValuesArray);
|
||||
////////////////////////////////////////
|
||||
}
|
||||
catch (error) {
|
||||
////////////////////////////////////////
|
||||
(_b = global.ERROR_CALLBACK) === null || _b === void 0 ? void 0 : _b.call(global, `Full Access DB Handler Error`, error);
|
||||
(0, serverError_1.default)({
|
||||
component: "fullAccessDbHandler",
|
||||
message: error.message,
|
||||
});
|
||||
/**
|
||||
* Return error
|
||||
*/
|
||||
return error.message;
|
||||
}
|
||||
finally {
|
||||
DB_CONN === null || DB_CONN === void 0 ? void 0 : DB_CONN.end();
|
||||
}
|
||||
/**
|
||||
* 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;
|
||||
}
|
||||
});
|
||||
return error.message;
|
||||
}
|
||||
finally {
|
||||
DB_CONN === null || DB_CONN === void 0 ? void 0 : DB_CONN.end();
|
||||
}
|
||||
/**
|
||||
* Return results
|
||||
*
|
||||
* @description Return results add to cache if "req" param is passed
|
||||
*/
|
||||
if (results && tableSchema) {
|
||||
const unparsedResults = results;
|
||||
const parsedResults = await parseDbResults({
|
||||
unparsedResults: unparsedResults,
|
||||
tableSchema: tableSchema,
|
||||
});
|
||||
return parsedResults;
|
||||
}
|
||||
else if (results) {
|
||||
return results;
|
||||
}
|
||||
else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user