Updates
This commit is contained in:
+18
@@ -0,0 +1,18 @@
|
||||
interface Return {
|
||||
success: boolean;
|
||||
payload: {
|
||||
urlPath: string;
|
||||
urlThumbnailPath: string;
|
||||
} | null;
|
||||
msg?: string;
|
||||
}
|
||||
type Param = {
|
||||
key: string;
|
||||
url: string;
|
||||
user_id?: string | number;
|
||||
};
|
||||
/**
|
||||
* # Delete File via API
|
||||
*/
|
||||
export default function deleteFile({ key, url, user_id, }: Param): Promise<Return>;
|
||||
export {};
|
||||
+76
@@ -0,0 +1,76 @@
|
||||
"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"));
|
||||
/**
|
||||
* # 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 {
|
||||
/**
|
||||
* Make https request
|
||||
*
|
||||
* @description make a request to datasquirel.com
|
||||
*/
|
||||
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);
|
||||
});
|
||||
});
|
||||
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,
|
||||
};
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
export default function getCsrfHeaderName(): string;
|
||||
@@ -0,0 +1,6 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = getCsrfHeaderName;
|
||||
function getCsrfHeaderName() {
|
||||
return "x-csrf-key";
|
||||
}
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
import { DSQL_DatabaseSchemaType, DSQL_FieldSchemaType, DSQL_TableSchemaType, GetSchemaAPIParam } from "../types";
|
||||
type GetSchemaReturn = {
|
||||
success: boolean;
|
||||
payload?: DSQL_DatabaseSchemaType | DSQL_TableSchemaType | DSQL_FieldSchemaType | null;
|
||||
};
|
||||
/**
|
||||
* # Get Schema for Database, table, or field *
|
||||
*/
|
||||
export default function getSchema({ key, database, field, table, user_id, }: GetSchemaAPIParam): Promise<GetSchemaReturn>;
|
||||
export {};
|
||||
+69
@@ -0,0 +1,69 @@
|
||||
"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"));
|
||||
/**
|
||||
* # Get Schema for Database, table, or field *
|
||||
*/
|
||||
function getSchema(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ key, database, field, table, user_id, }) {
|
||||
const grabedHostNames = (0, grab_host_names_1.default)();
|
||||
const { host, port, scheme } = grabedHostNames;
|
||||
/**
|
||||
* Make https request
|
||||
*
|
||||
* @description make a request to datasquirel.com
|
||||
*/
|
||||
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;
|
||||
});
|
||||
}
|
||||
Vendored
+24
@@ -0,0 +1,24 @@
|
||||
import { ApiGetQueryObject, GetReturn } from "../types";
|
||||
type Param<T extends {
|
||||
[k: string]: any;
|
||||
} = {
|
||||
[k: string]: any;
|
||||
}> = {
|
||||
key?: string;
|
||||
db?: string;
|
||||
query: string | ApiGetQueryObject<T>;
|
||||
queryValues?: string[];
|
||||
tableName?: string;
|
||||
user_id?: string | number;
|
||||
debug?: boolean;
|
||||
};
|
||||
export type ApiGetParams = Param;
|
||||
/**
|
||||
* # Make a get request to Datasquirel API
|
||||
*/
|
||||
export default function get<T extends {
|
||||
[k: string]: any;
|
||||
} = {
|
||||
[k: string]: any;
|
||||
}>({ key, db, query, queryValues, tableName, user_id, debug, }: Param<T>): Promise<GetReturn>;
|
||||
export {};
|
||||
Vendored
+131
@@ -0,0 +1,131 @@
|
||||
"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"));
|
||||
/**
|
||||
* # 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, }) {
|
||||
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) {
|
||||
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) {
|
||||
console.log("apiGet:Running Locally ...");
|
||||
}
|
||||
return yield (0, get_1.default)({
|
||||
dbFullName: DSQL_DB_NAME,
|
||||
query,
|
||||
queryValues,
|
||||
tableName,
|
||||
dbSchema,
|
||||
debug,
|
||||
});
|
||||
}
|
||||
/**
|
||||
* 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) {
|
||||
console.log("apiGet:queryObject", queryObject);
|
||||
}
|
||||
const queryString = (0, serialize_query_1.default)(Object.assign({}, queryObject));
|
||||
if (debug) {
|
||||
console.log("apiGet:queryString", queryString);
|
||||
}
|
||||
let path = `/api/query/${user_id || grabedHostNames.user_id}/get${queryString}`;
|
||||
if (debug) {
|
||||
console.log("apiGet: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;
|
||||
});
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
import { PostDataPayload, PostReturn } from "../types";
|
||||
type Param = {
|
||||
key?: string;
|
||||
database?: string;
|
||||
query: string | PostDataPayload;
|
||||
queryValues?: any[];
|
||||
tableName?: string;
|
||||
user_id?: boolean;
|
||||
};
|
||||
/**
|
||||
* # Make a post request to Datasquirel API
|
||||
*/
|
||||
export default function post({ key, query, queryValues, database, tableName, user_id, }: Param): Promise<PostReturn>;
|
||||
export {};
|
||||
Vendored
+133
@@ -0,0 +1,133 @@
|
||||
"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"));
|
||||
/**
|
||||
* # Make a post request to Datasquirel API
|
||||
*/
|
||||
function post(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ key, query, queryValues, database, tableName, user_id, }) {
|
||||
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, post_1.default)({
|
||||
dbFullName: DSQL_DB_NAME,
|
||||
query,
|
||||
dbSchema,
|
||||
queryValues,
|
||||
tableName,
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Make https request
|
||||
*
|
||||
* @description make a request to datasquirel.com
|
||||
*/
|
||||
const httpResponse = yield new Promise((resolve, reject) => {
|
||||
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) {
|
||||
console.log(error);
|
||||
console.log(reqPayloadString);
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
error: "Query object is invalid. Please Check query data values",
|
||||
};
|
||||
}
|
||||
const reqPayload = reqPayloadString;
|
||||
const 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 ( /** @type {any} */error) {
|
||||
console.log("Route ERROR:", error.message);
|
||||
resolve({
|
||||
success: false,
|
||||
payload: null,
|
||||
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;
|
||||
});
|
||||
}
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
interface Return {
|
||||
success: boolean;
|
||||
payload: {
|
||||
urlPath: string;
|
||||
} | null;
|
||||
msg?: string;
|
||||
}
|
||||
type Param = {
|
||||
key: string;
|
||||
payload: {
|
||||
fileData: string;
|
||||
fileName: string;
|
||||
mimeType?: string;
|
||||
folder?: string;
|
||||
isPrivate?: boolean;
|
||||
};
|
||||
user_id?: boolean;
|
||||
};
|
||||
/**
|
||||
* # Upload File via API
|
||||
*/
|
||||
export default function uploadImage({ key, payload, user_id, }: Param): Promise<Return>;
|
||||
export {};
|
||||
+76
@@ -0,0 +1,76 @@
|
||||
"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"));
|
||||
/**
|
||||
* # Upload File via API
|
||||
*/
|
||||
function uploadImage(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ key, payload, user_id, }) {
|
||||
const grabedHostNames = (0, grab_host_names_1.default)();
|
||||
const { host, port, scheme } = grabedHostNames;
|
||||
try {
|
||||
/**
|
||||
* Make https request
|
||||
*
|
||||
* @description make a request to datasquirel.com
|
||||
*/
|
||||
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);
|
||||
});
|
||||
});
|
||||
httpsRequest.write(reqPayload);
|
||||
httpsRequest.end();
|
||||
});
|
||||
return httpResponse;
|
||||
}
|
||||
catch (error) {
|
||||
console.log("Error in uploading file: ", error.message);
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: error.message,
|
||||
};
|
||||
}
|
||||
});
|
||||
}
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
interface FunctionReturn {
|
||||
success: boolean;
|
||||
payload: {
|
||||
urlPath: string;
|
||||
urlThumbnailPath: string;
|
||||
} | null;
|
||||
msg?: string;
|
||||
}
|
||||
type Param = {
|
||||
key?: string;
|
||||
payload: {
|
||||
imageData: string;
|
||||
imageName: string;
|
||||
mimeType?: string;
|
||||
thumbnailSize?: number;
|
||||
folder?: string;
|
||||
isPrivate?: boolean;
|
||||
};
|
||||
user_id?: boolean;
|
||||
};
|
||||
/**
|
||||
* # Upload Image via API
|
||||
*/
|
||||
export default function uploadImage({ key, payload, user_id, }: Param): Promise<FunctionReturn>;
|
||||
export {};
|
||||
+77
@@ -0,0 +1,77 @@
|
||||
"use strict";
|
||||
// @ts-check
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = uploadImage;
|
||||
const grab_host_names_1 = __importDefault(require("../utils/grab-host-names"));
|
||||
/**
|
||||
* # Upload Image via API
|
||||
*/
|
||||
function uploadImage(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ key, payload, user_id, }) {
|
||||
const grabedHostNames = (0, grab_host_names_1.default)();
|
||||
const { host, port, scheme } = grabedHostNames;
|
||||
try {
|
||||
/**
|
||||
* Make https request
|
||||
*
|
||||
* @description make a request to datasquirel.com
|
||||
*/
|
||||
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);
|
||||
});
|
||||
});
|
||||
httpsRequest.write(reqPayload);
|
||||
httpsRequest.end();
|
||||
});
|
||||
return httpResponse;
|
||||
}
|
||||
catch (error) {
|
||||
console.log("Error in uploading image: ", error.message);
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: error.message,
|
||||
};
|
||||
}
|
||||
});
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
import { AddUserFunctionReturn, UserDataPayload } from "../../types";
|
||||
type Param = {
|
||||
key?: string;
|
||||
database?: string;
|
||||
payload: UserDataPayload;
|
||||
encryptionKey?: string;
|
||||
encryptionSalt?: string;
|
||||
user_id?: string | number;
|
||||
apiUserId?: string | number;
|
||||
};
|
||||
/**
|
||||
* # Add User to Database
|
||||
*/
|
||||
export default function addUser({ key, payload, database, encryptionKey, user_id, apiUserId, }: Param): Promise<AddUserFunctionReturn>;
|
||||
export {};
|
||||
+98
@@ -0,0 +1,98 @@
|
||||
"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"));
|
||||
/**
|
||||
* # 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,
|
||||
});
|
||||
}
|
||||
/**
|
||||
* 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();
|
||||
});
|
||||
return httpResponse;
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import { UpdateUserFunctionReturn } from "../../types";
|
||||
type Param = {
|
||||
key?: string;
|
||||
database?: string;
|
||||
deletedUserId: string | number;
|
||||
user_id?: boolean;
|
||||
};
|
||||
/**
|
||||
* # Update User
|
||||
*/
|
||||
export default function deleteUser({ key, database, user_id, deletedUserId, }: Param): Promise<UpdateUserFunctionReturn>;
|
||||
export {};
|
||||
@@ -0,0 +1,95 @@
|
||||
"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"));
|
||||
/**
|
||||
* # 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,
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Make https request
|
||||
*
|
||||
* @description make a request to datasquirel.com
|
||||
*/
|
||||
const httpResponse = (yield 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`,
|
||||
},
|
||||
/**
|
||||
* 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;
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import http from "http";
|
||||
type Param = {
|
||||
request?: http.IncomingMessage;
|
||||
cookieString?: string;
|
||||
encryptionKey: string;
|
||||
encryptionSalt: string;
|
||||
database: string;
|
||||
};
|
||||
type Return = {
|
||||
key: string | undefined;
|
||||
csrf: string | undefined;
|
||||
};
|
||||
/**
|
||||
* 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
|
||||
*/
|
||||
export default function getToken({ request, encryptionKey, encryptionSalt, cookieString, }: Param): Return;
|
||||
export {};
|
||||
+74
@@ -0,0 +1,74 @@
|
||||
"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"));
|
||||
/**
|
||||
* 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, }) {
|
||||
try {
|
||||
/**
|
||||
* Grab the payload
|
||||
*
|
||||
* @description Grab the payload
|
||||
*/
|
||||
const cookies = (0, parseCookies_1.default)({ request, cookieString });
|
||||
const keynames = (0, get_auth_cookie_names_1.default)();
|
||||
const authKeyName = keynames.keyCookieName;
|
||||
const csrfName = keynames.csrfCookieName;
|
||||
const key = cookies[authKeyName];
|
||||
const csrf = cookies[csrfName];
|
||||
/**
|
||||
* Grab the payload
|
||||
*
|
||||
* @description Grab the payload
|
||||
*/
|
||||
let userPayload = (0, decrypt_1.default)({
|
||||
encryptedString: key,
|
||||
encryptionKey,
|
||||
encryptionSalt,
|
||||
});
|
||||
/**
|
||||
* Grab the payload
|
||||
*
|
||||
* @description Grab the payload
|
||||
*/
|
||||
if (!userPayload) {
|
||||
return { key: undefined, csrf: undefined };
|
||||
}
|
||||
/**
|
||||
* Grab the payload
|
||||
*
|
||||
* @description Grab the payload
|
||||
*/
|
||||
let userObject = JSON.parse(userPayload);
|
||||
if (!userObject.csrf_k) {
|
||||
return { key: undefined, csrf: undefined };
|
||||
}
|
||||
/**
|
||||
* Return User Object
|
||||
*
|
||||
* @description Return User Object
|
||||
*/
|
||||
return { key, csrf };
|
||||
}
|
||||
catch (error) {
|
||||
/**
|
||||
* Return User Object
|
||||
*
|
||||
* @description Return User Object
|
||||
*/
|
||||
return {
|
||||
key: undefined,
|
||||
csrf: undefined,
|
||||
};
|
||||
}
|
||||
}
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
import { GetUserFunctionReturn } from "../../types";
|
||||
type Param = {
|
||||
key: string;
|
||||
database: string;
|
||||
userId: number;
|
||||
fields?: string[];
|
||||
apiUserId?: boolean;
|
||||
};
|
||||
/**
|
||||
* # Get User
|
||||
*/
|
||||
export default function getUser({ key, userId, database, fields, apiUserId, }: Param): Promise<GetUserFunctionReturn>;
|
||||
export {};
|
||||
+120
@@ -0,0 +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 = 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"));
|
||||
/**
|
||||
* # 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;
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import http from "http";
|
||||
import { APILoginFunctionReturn } from "../../types";
|
||||
type Param = {
|
||||
key?: string;
|
||||
database: string;
|
||||
payload: {
|
||||
email?: string;
|
||||
username?: string;
|
||||
password?: string;
|
||||
};
|
||||
additionalFields?: string[];
|
||||
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;
|
||||
};
|
||||
/**
|
||||
* # 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, }: Param): Promise<APILoginFunctionReturn>;
|
||||
export {};
|
||||
+190
@@ -0,0 +1,190 @@
|
||||
"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");
|
||||
/**
|
||||
* # 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, }) {
|
||||
var _b;
|
||||
const grabedHostNames = (0, grab_host_names_1.default)({ userId: user_id || apiUserID });
|
||||
const { host, port, scheme } = grabedHostNames;
|
||||
const defaultTempLoginFieldName = "temp_login_code";
|
||||
const emailLoginTempCodeFieldName = email_login
|
||||
? temp_code_field
|
||||
? temp_code_field
|
||||
: defaultTempLoginFieldName
|
||||
: undefined;
|
||||
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 required fields
|
||||
*
|
||||
* @description Check required fields
|
||||
*/
|
||||
if (!payload.email) {
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: "Email Required",
|
||||
};
|
||||
}
|
||||
/**
|
||||
* Initialize HTTP response variable
|
||||
*/
|
||||
/** @type {import("../../types").APILoginFunctionReturn} */
|
||||
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_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,
|
||||
encryptionKey: finalEncryptionKey,
|
||||
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);
|
||||
});
|
||||
});
|
||||
httpsRequest.write(reqPayloadJSON);
|
||||
httpsRequest.end();
|
||||
});
|
||||
}
|
||||
if (debug) {
|
||||
console.log(`loginUser:httpResponse:`, httpResponse);
|
||||
}
|
||||
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) { }
|
||||
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));
|
||||
}
|
||||
httpResponse["cookieNames"] = cookieNames;
|
||||
httpResponse["key"] = String(encryptedPayload);
|
||||
const authKeyName = cookieNames.keyCookieName;
|
||||
const csrfName = cookieNames.csrfCookieName;
|
||||
if (debug) {
|
||||
console.log(`loginUser:authKeyName:`, authKeyName);
|
||||
console.log(`loginUser:csrfName:`, csrfName);
|
||||
console.log(`loginUser:encryptedPayload:`, encryptedPayload);
|
||||
}
|
||||
response === null || response === void 0 ? void 0 : response.setHeader("Set-Cookie", [
|
||||
`${authKeyName}=${encryptedPayload};samesite=strict;path=/;HttpOnly=true;Secure=true`,
|
||||
`${csrfName}=${(_b = httpResponse.payload) === null || _b === void 0 ? void 0 : _b.csrf_k};samesite=strict;path=/;HttpOnly=true`,
|
||||
]);
|
||||
if (debug) {
|
||||
console.log(`loginUser:Response Sent!`);
|
||||
}
|
||||
}
|
||||
return httpResponse;
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import http from "http";
|
||||
type Param = {
|
||||
encryptedUserString?: string;
|
||||
request?: http.IncomingMessage & {
|
||||
[s: string]: any;
|
||||
};
|
||||
response?: http.ServerResponse & {
|
||||
[s: string]: any;
|
||||
};
|
||||
cookieString?: string;
|
||||
database?: string;
|
||||
dsqlUserId?: string | number;
|
||||
debug?: boolean;
|
||||
};
|
||||
type Return = {
|
||||
success: boolean;
|
||||
msg: string;
|
||||
cookieNames?: any;
|
||||
};
|
||||
/**
|
||||
* # Logout user
|
||||
*/
|
||||
export default function logoutUser({ response, database, dsqlUserId, encryptedUserString, request, cookieString, debug, }: Param): Return;
|
||||
export {};
|
||||
@@ -0,0 +1,87 @@
|
||||
"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"));
|
||||
/**
|
||||
* # Logout user
|
||||
*/
|
||||
function logoutUser({ response, database, dsqlUserId, encryptedUserString, request, cookieString, debug, }) {
|
||||
/**
|
||||
* Check Encryption Keys
|
||||
*
|
||||
* @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)({
|
||||
database,
|
||||
userId: user_id,
|
||||
});
|
||||
if (debug) {
|
||||
console.log("logoutUser:cookieNames", cookieNames);
|
||||
}
|
||||
const authKeyName = cookieNames.keyCookieName;
|
||||
const csrfName = cookieNames.csrfCookieName;
|
||||
const oneTimeCodeName = cookieNames.oneTimeCodeName;
|
||||
const decryptedUserJSON = (() => {
|
||||
try {
|
||||
if (request) {
|
||||
const cookiesObject = (0, parseCookies_1.default)({
|
||||
request,
|
||||
cookieString,
|
||||
});
|
||||
return (0, decrypt_1.default)({
|
||||
encryptedString: cookiesObject[authKeyName],
|
||||
});
|
||||
}
|
||||
else if (encryptedUserString) {
|
||||
return (0, decrypt_1.default)({
|
||||
encryptedString: encryptedUserString,
|
||||
});
|
||||
}
|
||||
else {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
catch ( /** @type {any} */error) {
|
||||
console.log("Error getting decrypted User JSON to logout:", error.message);
|
||||
return undefined;
|
||||
}
|
||||
})();
|
||||
if (debug) {
|
||||
console.log("logoutUser:decryptedUserJSON", decryptedUserJSON);
|
||||
}
|
||||
if (!decryptedUserJSON)
|
||||
throw new Error("Invalid User");
|
||||
const userObject = ejson_1.default.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", [
|
||||
`${authKeyName}=null;max-age=0`,
|
||||
`${csrfName}=null;max-age=0`,
|
||||
`${oneTimeCodeName}=null;max-age=0`,
|
||||
]);
|
||||
const csrf = userObject.csrf_k;
|
||||
(0, write_auth_files_1.deleteAuthFile)(csrf);
|
||||
return {
|
||||
success: true,
|
||||
msg: "User Logged Out",
|
||||
cookieNames,
|
||||
};
|
||||
}
|
||||
catch (error) {
|
||||
console.log("Logout Error:", error.message);
|
||||
return {
|
||||
success: false,
|
||||
msg: "Logout Failed",
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import http from "http";
|
||||
import { APILoginFunctionReturn } from "../../types";
|
||||
type Param = {
|
||||
key?: string;
|
||||
database?: string;
|
||||
response?: http.ServerResponse;
|
||||
request?: http.IncomingMessage;
|
||||
level?: "deep" | "normal";
|
||||
encryptionKey?: string;
|
||||
encryptionSalt?: string;
|
||||
additionalFields?: string[];
|
||||
encryptedUserString?: string;
|
||||
user_id?: string | number;
|
||||
};
|
||||
/**
|
||||
* # Reauthorize User
|
||||
*/
|
||||
export default function reauthUser({ key, database, response, request, level, encryptionKey, encryptionSalt, additionalFields, encryptedUserString, user_id, }: Param): Promise<APILoginFunctionReturn>;
|
||||
export {};
|
||||
+157
@@ -0,0 +1,157 @@
|
||||
"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 fs_1 = __importDefault(require("fs"));
|
||||
const path_1 = __importDefault(require("path"));
|
||||
const encrypt_1 = __importDefault(require("../../functions/dsql/encrypt"));
|
||||
const user_auth_1 = __importDefault(require("./user-auth"));
|
||||
const grab_host_names_1 = __importDefault(require("../../utils/grab-host-names"));
|
||||
const api_reauth_user_1 = __importDefault(require("../../functions/api/users/api-reauth-user"));
|
||||
const write_auth_files_1 = require("../../functions/backend/auth/write-auth-files");
|
||||
const get_auth_cookie_names_1 = __importDefault(require("../../functions/backend/cookies/get-auth-cookie-names"));
|
||||
/**
|
||||
* # Reauthorize User
|
||||
*/
|
||||
function reauthUser(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ key, database, response, request, level, encryptionKey, encryptionSalt, additionalFields, encryptedUserString, user_id, }) {
|
||||
var _b, _c;
|
||||
/**
|
||||
* Check Encryption Keys
|
||||
*
|
||||
* @description Check Encryption Keys
|
||||
*/
|
||||
const grabedHostNames = (0, grab_host_names_1.default)();
|
||||
const { host, port, scheme } = grabedHostNames;
|
||||
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",
|
||||
};
|
||||
}
|
||||
/**
|
||||
* 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 === 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) { }
|
||||
httpResponse = yield (0, api_reauth_user_1.default)({
|
||||
existingUser: existingUser.payload,
|
||||
additionalFields,
|
||||
});
|
||||
}
|
||||
else {
|
||||
/**
|
||||
* Make https request
|
||||
*
|
||||
* @description make a request to datasquirel.com
|
||||
*/
|
||||
httpResponse = (yield 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();
|
||||
}));
|
||||
}
|
||||
/**
|
||||
* Make https request
|
||||
*
|
||||
* @description make a request to datasquirel.com
|
||||
*/
|
||||
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,
|
||||
});
|
||||
const cookieNames = (0, get_auth_cookie_names_1.default)({
|
||||
database,
|
||||
userId: user_id || grabedHostNames.user_id,
|
||||
});
|
||||
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;Secure=true`,
|
||||
`${csrfName}=${(_c = httpResponse.payload) === null || _c === void 0 ? void 0 : _c.csrf_k};samesite=strict;path=/;HttpOnly=true`,
|
||||
]);
|
||||
if (httpResponse.csrf) {
|
||||
(0, write_auth_files_1.deleteAuthFile)(String(existingUser.payload.csrf_k));
|
||||
(0, write_auth_files_1.writeAuthFile)(httpResponse.csrf, JSON.stringify(httpResponse.payload));
|
||||
}
|
||||
}
|
||||
return httpResponse;
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import http from "http";
|
||||
import { SendOneTimeCodeEmailResponse } from "../../types";
|
||||
type Param = {
|
||||
key?: string;
|
||||
database?: string;
|
||||
email: string;
|
||||
temp_code_field_name?: string;
|
||||
response?: http.ServerResponse & {
|
||||
[s: string]: any;
|
||||
};
|
||||
mail_domain?: string;
|
||||
mail_username?: string;
|
||||
mail_password?: string;
|
||||
mail_port?: number;
|
||||
sender?: string;
|
||||
user_id?: boolean;
|
||||
extraCookies?: import("../../types").CookieObject[];
|
||||
};
|
||||
/**
|
||||
* # 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 {};
|
||||
@@ -0,0 +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 = 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"));
|
||||
/**
|
||||
* # 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>`;
|
||||
/**
|
||||
* 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_send_email_code_1.default)({
|
||||
database: DSQL_DB_NAME,
|
||||
email,
|
||||
email_login_field: emailLoginTempCodeFieldName,
|
||||
html: emailHtml,
|
||||
mail_domain,
|
||||
mail_password,
|
||||
mail_port,
|
||||
mail_username,
|
||||
sender,
|
||||
response,
|
||||
extraCookies,
|
||||
});
|
||||
}
|
||||
else {
|
||||
/**
|
||||
* Make https request
|
||||
*
|
||||
* @description make a request to datasquirel.com
|
||||
*
|
||||
* @type {import("../../types").SendOneTimeCodeEmailResponse}
|
||||
*/
|
||||
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,
|
||||
});
|
||||
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);
|
||||
});
|
||||
});
|
||||
httpsRequest.write(reqPayload);
|
||||
httpsRequest.end();
|
||||
});
|
||||
return httpResponse;
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
import http from "http";
|
||||
interface FunctionReturn {
|
||||
success: boolean;
|
||||
user: {
|
||||
id: number;
|
||||
first_name: string;
|
||||
last_name: string;
|
||||
csrf_k: string;
|
||||
social_id: string;
|
||||
} | null;
|
||||
dsqlUserId?: number;
|
||||
msg?: string;
|
||||
}
|
||||
type Param = {
|
||||
key: string;
|
||||
code: string;
|
||||
email: string | null;
|
||||
database: string;
|
||||
clientId: string;
|
||||
clientSecret: string;
|
||||
response: http.ServerResponse;
|
||||
encryptionKey: string;
|
||||
encryptionSalt: string;
|
||||
additionalFields?: string[];
|
||||
additionalData?: {
|
||||
[s: string]: string | number;
|
||||
};
|
||||
user_id?: boolean;
|
||||
};
|
||||
/**
|
||||
* # SERVER FUNCTION: Login with google Function
|
||||
*/
|
||||
export default function githubAuth({ key, code, email, database, clientId, clientSecret, response, encryptionKey, encryptionSalt, additionalFields, user_id, additionalData, }: Param): Promise<FunctionReturn | undefined>;
|
||||
export {};
|
||||
@@ -0,0 +1,172 @@
|
||||
"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"));
|
||||
/**
|
||||
* # 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, }) {
|
||||
/**
|
||||
* Check inputs
|
||||
*
|
||||
* @description Check inputs
|
||||
*/
|
||||
const grabedHostNames = (0, grab_host_names_1.default)();
|
||||
const { host, port, scheme } = grabedHostNames;
|
||||
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_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 () {
|
||||
try {
|
||||
resolve(JSON.parse(str));
|
||||
}
|
||||
catch (error) {
|
||||
console.log(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 = (0, encrypt_1.default)({
|
||||
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;Secure=true`,
|
||||
`${csrfName}=${user.csrf_k};samesite=strict;path=/;HttpOnly=true`,
|
||||
`dsqluid=${dsqlUserId};samesite=strict;path=/;HttpOnly=true`,
|
||||
`datasquirel_social_id=${user.social_id};samesite=strict;path=/`,
|
||||
]);
|
||||
}
|
||||
return httpResponse;
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import http from "http";
|
||||
import { APILoginFunctionReturn } from "../../../types";
|
||||
type Param = {
|
||||
key?: string;
|
||||
token: string;
|
||||
database?: string;
|
||||
response?: http.ServerResponse;
|
||||
encryptionKey?: string;
|
||||
encryptionSalt?: string;
|
||||
additionalFields?: string[];
|
||||
additionalData?: {
|
||||
[s: string]: string | number;
|
||||
};
|
||||
apiUserID?: string | number;
|
||||
debug?: boolean;
|
||||
};
|
||||
/**
|
||||
* # SERVER FUNCTION: Login with google Function
|
||||
*/
|
||||
export default function googleAuth({ key, token, database, response, encryptionKey, encryptionSalt, additionalFields, additionalData, apiUserID, debug, }: Param): Promise<APILoginFunctionReturn>;
|
||||
export {};
|
||||
@@ -0,0 +1,163 @@
|
||||
"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");
|
||||
/**
|
||||
* # 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, }) {
|
||||
var _b;
|
||||
const grabedHostNames = (0, grab_host_names_1.default)();
|
||||
const { host, port, scheme } = grabedHostNames;
|
||||
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 = {
|
||||
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 = yield (0, api_google_login_1.default)({
|
||||
token,
|
||||
additionalFields,
|
||||
additionalData,
|
||||
debug,
|
||||
});
|
||||
}
|
||||
else {
|
||||
/**
|
||||
* Make https request
|
||||
*
|
||||
* @description make a request to datasquirel.com
|
||||
* @type {{ success: boolean, user: import("../../../types").DATASQUIREL_LoggedInUser | null, msg?: string, dsqlUserId?: number } | null } - Https response object
|
||||
*/
|
||||
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;
|
||||
});
|
||||
response.on("end", function () {
|
||||
resolve(JSON.parse(str));
|
||||
});
|
||||
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.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: apiUserID || process.env.DSQL_API_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;Secure=true`,
|
||||
`${csrfName}=${(_b = httpResponse.payload) === null || _b === void 0 ? void 0 : _b.csrf_k};samesite=strict;path=/;HttpOnly=true`,
|
||||
]);
|
||||
}
|
||||
return httpResponse;
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import { UpdateUserFunctionReturn } from "../../types";
|
||||
type Param = {
|
||||
key?: string;
|
||||
database?: string;
|
||||
updatedUserId: string | number;
|
||||
payload: {
|
||||
[s: string]: any;
|
||||
};
|
||||
user_id?: boolean;
|
||||
};
|
||||
/**
|
||||
* # Update User
|
||||
*/
|
||||
export default function updateUser({ key, payload, database, user_id, updatedUserId, }: Param): Promise<UpdateUserFunctionReturn>;
|
||||
export {};
|
||||
@@ -0,0 +1,98 @@
|
||||
"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"));
|
||||
/**
|
||||
* # 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,
|
||||
});
|
||||
}
|
||||
/**
|
||||
* 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();
|
||||
});
|
||||
return httpResponse;
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import http from "http";
|
||||
import { AuthenticatedUser } from "../../types";
|
||||
type Param = {
|
||||
request?: http.IncomingMessage & {
|
||||
[s: string]: any;
|
||||
};
|
||||
req?: http.IncomingMessage & {
|
||||
[s: string]: any;
|
||||
};
|
||||
cookieString?: string;
|
||||
encryptedUserString?: string;
|
||||
encryptionKey?: string;
|
||||
encryptionSalt?: string;
|
||||
level?: "deep" | "normal";
|
||||
database?: string;
|
||||
dsqlUserId?: string | number;
|
||||
expiry?: number;
|
||||
csrfHeaderName?: string;
|
||||
debug?: boolean;
|
||||
};
|
||||
/**
|
||||
* Authenticate User from request
|
||||
* ==============================================================================
|
||||
* @description This Function takes in a request object and returns a user object
|
||||
* with the user's data
|
||||
*/
|
||||
export default function userAuth({ request, req, encryptionKey, encryptionSalt, level, database, dsqlUserId, encryptedUserString, expiry, cookieString, csrfHeaderName, debug, }: Param): AuthenticatedUser;
|
||||
export {};
|
||||
+155
@@ -0,0 +1,155 @@
|
||||
"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 minuteInMilliseconds = 60000;
|
||||
const hourInMilliseconds = minuteInMilliseconds * 60;
|
||||
const dayInMilliseconds = hourInMilliseconds * 24;
|
||||
const weekInMilliseconds = dayInMilliseconds * 7;
|
||||
const monthInMilliseconds = dayInMilliseconds * 30;
|
||||
const yearInMilliseconds = dayInMilliseconds * 365;
|
||||
/**
|
||||
* Authenticate User from request
|
||||
* ==============================================================================
|
||||
* @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, }) {
|
||||
try {
|
||||
const finalRequest = req || request;
|
||||
const { user_id } = (0, grab_host_names_1.default)({ userId: dsqlUserId });
|
||||
const cookies = (0, parseCookies_1.default)({
|
||||
request: finalRequest,
|
||||
cookieString,
|
||||
});
|
||||
if (debug) {
|
||||
console.log("userAuth:cookies:", cookies);
|
||||
}
|
||||
const keyNames = (0, get_auth_cookie_names_1.default)({
|
||||
userId: user_id,
|
||||
database: database || process.env.DSQL_DB_NAME,
|
||||
});
|
||||
if (debug) {
|
||||
console.log("userAuth:keyNames:", keyNames);
|
||||
}
|
||||
const key = encryptedUserString
|
||||
? encryptedUserString
|
||||
: cookies[keyNames.keyCookieName];
|
||||
if (debug) {
|
||||
console.log("userAuth:key:", key);
|
||||
}
|
||||
/**
|
||||
* Grab the payload
|
||||
*
|
||||
* @description Grab the payload
|
||||
*/
|
||||
let userPayloadJSON = (0, decrypt_1.default)({
|
||||
encryptedString: key,
|
||||
encryptionKey,
|
||||
encryptionSalt,
|
||||
});
|
||||
if (debug) {
|
||||
console.log("userAuth:userPayloadJSON:", userPayloadJSON);
|
||||
}
|
||||
/**
|
||||
* Grab the payload
|
||||
*
|
||||
* @description Grab the payload
|
||||
*/
|
||||
if (!userPayloadJSON) {
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: "Couldn't Decrypt cookie",
|
||||
};
|
||||
}
|
||||
/**
|
||||
* Grab the payload
|
||||
*
|
||||
* @description Grab the payload
|
||||
*/
|
||||
/** @type {import("../../types").DATASQUIREL_LoggedInUser} */
|
||||
let userObject = JSON.parse(userPayloadJSON);
|
||||
if (debug) {
|
||||
console.log("userAuth:userObject:", userObject);
|
||||
}
|
||||
if (!userObject.csrf_k) {
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: "No CSRF_K in decrypted payload",
|
||||
};
|
||||
}
|
||||
if (!(0, write_auth_files_1.checkAuthFile)(userObject.csrf_k)) {
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: "Auth file doesn't exist",
|
||||
};
|
||||
}
|
||||
/**
|
||||
* Grab the payload
|
||||
*
|
||||
* @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)();
|
||||
if (finalRequest.headers[finalCsrfHeaderName] !== userObject.csrf_k) {
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: "CSRF_K mismatch",
|
||||
};
|
||||
}
|
||||
}
|
||||
const payloadCreationDate = Number(userObject.date);
|
||||
if (Number.isNaN(payloadCreationDate) ||
|
||||
typeof payloadCreationDate !== "number") {
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: "Payload Creation Date is not a number",
|
||||
};
|
||||
}
|
||||
const timeElapsed = Date.now() - payloadCreationDate;
|
||||
const finalExpiry = process.env.DSQL_SESSION_EXPIRY_TIME
|
||||
? Number(process.env.DSQL_SESSION_EXPIRY_TIME)
|
||||
: expiry;
|
||||
if (timeElapsed > finalExpiry) {
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: "Session has expired",
|
||||
};
|
||||
}
|
||||
/**
|
||||
* Return User Object
|
||||
*
|
||||
* @description Return User Object
|
||||
*/
|
||||
return {
|
||||
success: true,
|
||||
payload: userObject,
|
||||
};
|
||||
}
|
||||
catch (error) {
|
||||
/**
|
||||
* Return User Object
|
||||
*
|
||||
* @description Return User Object
|
||||
*/
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: error.message,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import http from "http";
|
||||
import { SendOneTimeCodeEmailResponse } from "../../types";
|
||||
type Param = {
|
||||
request?: http.IncomingMessage & {
|
||||
[s: string]: any;
|
||||
};
|
||||
cookieString?: string;
|
||||
email?: string;
|
||||
};
|
||||
/**
|
||||
* # Verify the temp email code sent to the user's email address
|
||||
*/
|
||||
export default function validateTempEmailCode({ request, email, cookieString, }: Param): Promise<SendOneTimeCodeEmailResponse | null>;
|
||||
export {};
|
||||
@@ -0,0 +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 = 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"));
|
||||
/**
|
||||
* # 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, }) {
|
||||
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;
|
||||
}
|
||||
catch (error) {
|
||||
console.log("validateTempEmailCode error:", error.message);
|
||||
return null;
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import { DATASQUIREL_LoggedInUser } from "../../types";
|
||||
type Param = {
|
||||
token: string;
|
||||
encryptionKey: string;
|
||||
encryptionSalt: string;
|
||||
level?: ("deep" | "normal") | null;
|
||||
database: string;
|
||||
};
|
||||
/**
|
||||
* Validate Token
|
||||
* ======================================
|
||||
* @description This Function takes in a encrypted token and returns a user object
|
||||
*/
|
||||
export default function validateToken({ token, encryptionKey, encryptionSalt, }: Param): DATASQUIREL_LoggedInUser | null;
|
||||
export {};
|
||||
@@ -0,0 +1,63 @@
|
||||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = validateToken;
|
||||
const decrypt_1 = __importDefault(require("../../functions/dsql/decrypt"));
|
||||
/**
|
||||
* Validate Token
|
||||
* ======================================
|
||||
* @description This Function takes in a encrypted token and returns a user object
|
||||
*/
|
||||
function validateToken({ token, encryptionKey, encryptionSalt, }) {
|
||||
try {
|
||||
/**
|
||||
* Grab the payload
|
||||
*
|
||||
* @description Grab the payload
|
||||
*/
|
||||
const key = token;
|
||||
/**
|
||||
* Grab the payload
|
||||
*
|
||||
* @description Grab the payload
|
||||
*/
|
||||
let userPayload = (0, decrypt_1.default)({
|
||||
encryptedString: key,
|
||||
encryptionKey,
|
||||
encryptionSalt,
|
||||
});
|
||||
/**
|
||||
* Grab the payload
|
||||
*
|
||||
* @description Grab the payload
|
||||
*/
|
||||
if (!userPayload) {
|
||||
return null;
|
||||
}
|
||||
/**
|
||||
* Grab the payload
|
||||
*
|
||||
* @description Grab the payload
|
||||
*/
|
||||
let userObject = JSON.parse(userPayload);
|
||||
if (!userObject.csrf_k) {
|
||||
return null;
|
||||
}
|
||||
/**
|
||||
* Return User Object
|
||||
*
|
||||
* @description Return User Object
|
||||
*/
|
||||
return userObject;
|
||||
}
|
||||
catch (error) {
|
||||
/**
|
||||
* Return User Object
|
||||
*
|
||||
* @description Return User Object
|
||||
*/
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -29,7 +29,6 @@ function apiPost(_a) {
|
||||
((_b = query === null || query === void 0 ? void 0 : query.action) === null || _b === void 0 ? void 0 : _b.match(/^create |^alter |^drop /i))) {
|
||||
return { success: false, msg: "Wrong Input" };
|
||||
}
|
||||
/** @type {any} */
|
||||
let results;
|
||||
/**
|
||||
* Create new user folder and file
|
||||
|
||||
@@ -35,7 +35,6 @@ function apiDeleteUser(_a) {
|
||||
}
|
||||
const deleteUser = yield (0, deleteDbEntry_1.default)({
|
||||
dbContext: "Dsql User",
|
||||
paradigm: "Full Access",
|
||||
dbFullName,
|
||||
tableName: "users",
|
||||
identifierColumnName: "id",
|
||||
|
||||
@@ -68,7 +68,6 @@ function apiUpdateUser(_a) {
|
||||
})();
|
||||
const updateUser = yield (0, updateDbEntry_1.default)({
|
||||
dbContext: "Dsql User",
|
||||
paradigm: "Full Access",
|
||||
dbFullName,
|
||||
tableName: "users",
|
||||
identifierColumnName: "id",
|
||||
|
||||
+5
-1
@@ -16,6 +16,7 @@ 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"));
|
||||
/**
|
||||
* # Main DB Handler Function
|
||||
*/
|
||||
@@ -44,7 +45,10 @@ function dbHandler(...args) {
|
||||
});
|
||||
}
|
||||
catch (error) {
|
||||
fs_1.default.appendFileSync("./.tmp/dbErrorLogs.txt", JSON.stringify(error, null, 4) + "\n" + Date() + "\n\n\n", "utf8");
|
||||
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;
|
||||
(0, serverError_1.default)({
|
||||
component: "dbHandler",
|
||||
|
||||
+4
-1
@@ -39,7 +39,10 @@ function dbHandler(_a) {
|
||||
console.log("ERROR in dbHandler =>", error.message);
|
||||
console.log(error);
|
||||
console.log(CONNECTION.config());
|
||||
fs_1.default.appendFileSync(path_1.default.resolve(__dirname, "../.tmp/dbErrorLogs.txt"), JSON.stringify(error, null, 4) + "\n" + Date() + "\n\n\n", "utf8");
|
||||
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;
|
||||
}
|
||||
finally {
|
||||
|
||||
Vendored
+29
-9
@@ -34,7 +34,29 @@ export interface DSQL_ChildrenTablesType {
|
||||
tableName: string;
|
||||
tableNameFull?: string;
|
||||
}
|
||||
export interface DSQL_FieldSchemaType {
|
||||
export declare const TextFieldTypesArray: readonly [{
|
||||
readonly title: "Plain Text";
|
||||
readonly value: "plain";
|
||||
}, {
|
||||
readonly title: "Rich Text";
|
||||
readonly value: "richText";
|
||||
}, {
|
||||
readonly title: "JSON";
|
||||
readonly value: "json";
|
||||
}, {
|
||||
readonly title: "YAML";
|
||||
readonly value: "yaml";
|
||||
}, {
|
||||
readonly title: "HTML";
|
||||
readonly value: "html";
|
||||
}, {
|
||||
readonly title: "CSS";
|
||||
readonly value: "css";
|
||||
}, {
|
||||
readonly title: "Javascript";
|
||||
readonly value: "javascript";
|
||||
}];
|
||||
export type DSQL_FieldSchemaType = {
|
||||
fieldName?: string;
|
||||
originName?: string;
|
||||
updatedField?: boolean;
|
||||
@@ -47,13 +69,6 @@ export interface DSQL_FieldSchemaType {
|
||||
defaultValue?: string | number;
|
||||
defaultValueLiteral?: string;
|
||||
foreignKey?: DSQL_ForeignKeyType;
|
||||
richText?: boolean;
|
||||
json?: boolean;
|
||||
yaml?: boolean;
|
||||
html?: boolean;
|
||||
css?: boolean;
|
||||
javascript?: boolean;
|
||||
shell?: boolean;
|
||||
newTempField?: boolean;
|
||||
defaultField?: boolean;
|
||||
plainText?: boolean;
|
||||
@@ -65,7 +80,11 @@ export interface DSQL_FieldSchemaType {
|
||||
onDelete?: string;
|
||||
onDeleteLiteral?: string;
|
||||
cssFiles?: string[];
|
||||
}
|
||||
integerLength?: string | number;
|
||||
decimals?: string | number;
|
||||
} & {
|
||||
[key in (typeof TextFieldTypesArray)[number]["value"]]?: boolean;
|
||||
};
|
||||
export interface DSQL_ForeignKeyType {
|
||||
foreignKeyName?: string;
|
||||
destinationTableName?: string;
|
||||
@@ -784,6 +803,7 @@ export interface MYSQL_user_database_tables_table_def {
|
||||
table_slug?: string;
|
||||
table_description?: string;
|
||||
child_table?: number;
|
||||
active_data?: 0 | 1;
|
||||
child_table_parent_database?: string;
|
||||
child_table_parent_table?: string;
|
||||
date_created?: string;
|
||||
|
||||
Vendored
+10
-1
@@ -1,5 +1,14 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.ServerQueryEqualities = exports.ServerQueryOperators = void 0;
|
||||
exports.ServerQueryEqualities = exports.ServerQueryOperators = exports.TextFieldTypesArray = void 0;
|
||||
exports.TextFieldTypesArray = [
|
||||
{ title: "Plain Text", value: "plain" },
|
||||
{ title: "Rich Text", value: "richText" },
|
||||
{ title: "JSON", value: "json" },
|
||||
{ title: "YAML", value: "yaml" },
|
||||
{ title: "HTML", value: "html" },
|
||||
{ title: "CSS", value: "css" },
|
||||
{ title: "Javascript", value: "javascript" },
|
||||
];
|
||||
exports.ServerQueryOperators = ["AND", "OR"];
|
||||
exports.ServerQueryEqualities = ["EQUAL", "LIKE", "NOT EQUAL"];
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
import sqlGenerator from "../../functions/dsql/sql/sql-generator";
|
||||
import { PostReturn, ServerQueryParam, ServerQueryQueryObject } from "../../types";
|
||||
export declare const DsqlCrudActions: readonly ["insert", "update", "delete", "get"];
|
||||
export type CrudQueryObject<T extends object = {
|
||||
[key: string]: any;
|
||||
}> = ServerQueryParam & {
|
||||
query: ServerQueryQueryObject<T>;
|
||||
};
|
||||
export type CrudParam<T extends object = {
|
||||
[key: string]: any;
|
||||
}> = {
|
||||
action: (typeof DsqlCrudActions)[number];
|
||||
table: string;
|
||||
data?: T;
|
||||
targetId?: string | number;
|
||||
query?: CrudQueryObject<T>;
|
||||
sanitize?: (data?: T) => T;
|
||||
};
|
||||
export default function dsqlCrud<T extends {
|
||||
[key: string]: any;
|
||||
} = {
|
||||
[key: string]: any;
|
||||
}>({ action, data, table, targetId, query, sanitize, }: CrudParam<T>): Promise<(PostReturn & {
|
||||
queryObject?: ReturnType<Awaited<typeof sqlGenerator>>;
|
||||
}) | null>;
|
||||
+69
@@ -0,0 +1,69 @@
|
||||
"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.DsqlCrudActions = void 0;
|
||||
exports.default = dsqlCrud;
|
||||
const get_1 = __importDefault(require("../../actions/get"));
|
||||
const post_1 = __importDefault(require("../../actions/post"));
|
||||
const sql_generator_1 = __importDefault(require("../../functions/dsql/sql/sql-generator"));
|
||||
exports.DsqlCrudActions = ["insert", "update", "delete", "get"];
|
||||
function dsqlCrud(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ action, data, table, targetId, query, sanitize, }) {
|
||||
const finalData = sanitize ? sanitize(data) : data;
|
||||
const finalId = targetId;
|
||||
let queryObject;
|
||||
switch (action) {
|
||||
case "get":
|
||||
queryObject = (0, sql_generator_1.default)({
|
||||
tableName: table,
|
||||
genObject: query,
|
||||
});
|
||||
const GET_RES = yield (0, get_1.default)({
|
||||
query: (queryObject === null || queryObject === void 0 ? void 0 : queryObject.string) || "",
|
||||
queryValues: (queryObject === null || queryObject === void 0 ? void 0 : queryObject.values) || [],
|
||||
});
|
||||
return Object.assign(Object.assign({}, GET_RES), { queryObject });
|
||||
case "insert":
|
||||
return yield (0, post_1.default)({
|
||||
query: {
|
||||
action: "insert",
|
||||
table,
|
||||
data: finalData,
|
||||
},
|
||||
});
|
||||
case "update":
|
||||
data === null || data === void 0 ? true : delete data.id;
|
||||
return yield (0, post_1.default)({
|
||||
query: {
|
||||
action: "update",
|
||||
table,
|
||||
identifierColumnName: "id",
|
||||
identifierValue: String(finalId),
|
||||
data: finalData,
|
||||
},
|
||||
});
|
||||
case "delete":
|
||||
return yield (0, post_1.default)({
|
||||
query: {
|
||||
action: "delete",
|
||||
table,
|
||||
identifierColumnName: "id",
|
||||
identifierValue: String(finalId),
|
||||
},
|
||||
});
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
import { DATASQUIREL_LoggedInUser, ServerQueryParam } from "../../types";
|
||||
export declare const DataCrudRequestMethods: readonly ["GET", "POST", "PUT", "DELETE"];
|
||||
export type APIDataCrudQuery = ServerQueryParam & {
|
||||
page?: number;
|
||||
};
|
||||
export type CRUDResponseObject<P extends any = any> = {
|
||||
success: boolean;
|
||||
payload?: P;
|
||||
msg?: string;
|
||||
error?: string;
|
||||
};
|
||||
export type ApiDataCrudParam<T extends {
|
||||
[key: string]: any;
|
||||
} = {
|
||||
[key: string]: any;
|
||||
}> = {
|
||||
method: (typeof DataCrudRequestMethods)[number];
|
||||
body?: T;
|
||||
query?: string | T;
|
||||
tableName: string;
|
||||
addUser?: {
|
||||
field: string;
|
||||
};
|
||||
user?: DATASQUIREL_LoggedInUser;
|
||||
extraData?: T;
|
||||
transform?: ({ data, existingData, user, }: {
|
||||
user?: DATASQUIREL_LoggedInUser;
|
||||
data: T;
|
||||
existingData?: T;
|
||||
reqMethod: (typeof DataCrudRequestMethods)[number];
|
||||
}) => Promise<T>;
|
||||
existingData?: T;
|
||||
};
|
||||
export default function dsqlMethodCrud<T extends {
|
||||
[key: string]: any;
|
||||
} = {
|
||||
[key: string]: any;
|
||||
}, P extends {
|
||||
[key: string]: any;
|
||||
} = {
|
||||
[key: string]: any;
|
||||
}>({ method, tableName, addUser, user, extraData, transform, existingData, body, query, }: ApiDataCrudParam<T>): Promise<CRUDResponseObject<P>>;
|
||||
@@ -0,0 +1,122 @@
|
||||
"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.DataCrudRequestMethods = void 0;
|
||||
exports.default = dsqlMethodCrud;
|
||||
const ejson_1 = __importDefault(require("../ejson"));
|
||||
const crud_1 = __importDefault(require("./crud"));
|
||||
exports.DataCrudRequestMethods = ["GET", "POST", "PUT", "DELETE"];
|
||||
function dsqlMethodCrud(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ method, tableName, addUser, user, extraData, transform, existingData, body, query, }) {
|
||||
let result = {
|
||||
success: false,
|
||||
};
|
||||
try {
|
||||
let finalBody = body;
|
||||
let finalQuery = query;
|
||||
Object.keys(finalQuery).forEach((key) => {
|
||||
const value = finalQuery[key];
|
||||
if (typeof value == "string" && value.match(/^\{|^\[/)) {
|
||||
finalQuery[key] = ejson_1.default.stringify(value);
|
||||
}
|
||||
if (value == "true") {
|
||||
finalQuery[key] = true;
|
||||
}
|
||||
if (value == "false") {
|
||||
finalQuery[key] = false;
|
||||
}
|
||||
});
|
||||
const LIMIT = finalQuery.limit || 10;
|
||||
const PAGE = finalQuery.page || 1;
|
||||
const OFFSET = (PAGE - 1) * LIMIT;
|
||||
let finalData = Object.assign(Object.assign({}, finalBody.data), extraData);
|
||||
if (user && addUser) {
|
||||
finalData = Object.assign(Object.assign({}, finalData), { [addUser.field]: String(user.id) });
|
||||
}
|
||||
if (transform) {
|
||||
finalData = yield transform({
|
||||
data: finalData,
|
||||
existingData: existingData,
|
||||
user,
|
||||
reqMethod: method,
|
||||
});
|
||||
}
|
||||
switch (method) {
|
||||
case "GET":
|
||||
const GET_RESULT = yield (0, crud_1.default)({
|
||||
action: "get",
|
||||
table: tableName,
|
||||
query: Object.assign(Object.assign({}, finalQuery), { query: Object.assign(Object.assign({}, finalQuery.query), { user_id: user
|
||||
? {
|
||||
value: String(user.id),
|
||||
}
|
||||
: undefined }), limit: LIMIT, offset: OFFSET || undefined }),
|
||||
});
|
||||
result = {
|
||||
success: Boolean(GET_RESULT === null || GET_RESULT === void 0 ? void 0 : GET_RESULT.success),
|
||||
payload: GET_RESULT === null || GET_RESULT === void 0 ? void 0 : GET_RESULT.payload,
|
||||
msg: GET_RESULT === null || GET_RESULT === void 0 ? void 0 : GET_RESULT.msg,
|
||||
error: GET_RESULT === null || GET_RESULT === void 0 ? void 0 : GET_RESULT.error,
|
||||
};
|
||||
break;
|
||||
case "POST":
|
||||
const POST_RESULT = yield (0, crud_1.default)({
|
||||
action: "insert",
|
||||
table: tableName,
|
||||
data: finalData,
|
||||
});
|
||||
result = {
|
||||
success: Boolean(POST_RESULT === null || POST_RESULT === void 0 ? void 0 : POST_RESULT.success),
|
||||
payload: POST_RESULT === null || POST_RESULT === void 0 ? void 0 : POST_RESULT.payload,
|
||||
msg: POST_RESULT === null || POST_RESULT === void 0 ? void 0 : POST_RESULT.msg,
|
||||
error: POST_RESULT === null || POST_RESULT === void 0 ? void 0 : POST_RESULT.error,
|
||||
};
|
||||
break;
|
||||
case "PUT":
|
||||
const PUT_RESULT = yield (0, crud_1.default)({
|
||||
action: "update",
|
||||
table: tableName,
|
||||
data: finalData,
|
||||
targetId: finalBody.data.id,
|
||||
});
|
||||
result = {
|
||||
success: Boolean(PUT_RESULT === null || PUT_RESULT === void 0 ? void 0 : PUT_RESULT.success),
|
||||
payload: PUT_RESULT === null || PUT_RESULT === void 0 ? void 0 : PUT_RESULT.payload,
|
||||
msg: PUT_RESULT === null || PUT_RESULT === void 0 ? void 0 : PUT_RESULT.msg,
|
||||
error: PUT_RESULT === null || PUT_RESULT === void 0 ? void 0 : PUT_RESULT.error,
|
||||
};
|
||||
break;
|
||||
case "DELETE":
|
||||
const DELETE_RESULT = yield (0, crud_1.default)({
|
||||
action: "delete",
|
||||
table: tableName,
|
||||
targetId: finalBody.data.id,
|
||||
});
|
||||
result = {
|
||||
success: Boolean(DELETE_RESULT === null || DELETE_RESULT === void 0 ? void 0 : DELETE_RESULT.success),
|
||||
payload: DELETE_RESULT === null || DELETE_RESULT === void 0 ? void 0 : DELETE_RESULT.payload,
|
||||
msg: DELETE_RESULT === null || DELETE_RESULT === void 0 ? void 0 : DELETE_RESULT.msg,
|
||||
error: DELETE_RESULT === null || DELETE_RESULT === void 0 ? void 0 : DELETE_RESULT.error,
|
||||
};
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
catch (error) {
|
||||
return result;
|
||||
}
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user