Updates
This commit is contained in:
parent
6e334c2525
commit
7e8bb37c09
@ -1,7 +1,6 @@
|
|||||||
import _ from "lodash";
|
import _ from "lodash";
|
||||||
import getCsrfHeaderName from "../../package-shared/actions/get-csrf-header-name";
|
|
||||||
|
|
||||||
type FetchApiOptions = {
|
type FetchApiOptions<T extends { [k: string]: any } = { [k: string]: any }> = {
|
||||||
method:
|
method:
|
||||||
| "POST"
|
| "POST"
|
||||||
| "GET"
|
| "GET"
|
||||||
@ -13,7 +12,7 @@ type FetchApiOptions = {
|
|||||||
| "delete"
|
| "delete"
|
||||||
| "put"
|
| "put"
|
||||||
| "patch";
|
| "patch";
|
||||||
body?: object | string;
|
body?: T | string;
|
||||||
headers?: FetchHeader;
|
headers?: FetchHeader;
|
||||||
};
|
};
|
||||||
|
|
||||||
@ -31,25 +30,34 @@ export type FetchApiReturn = {
|
|||||||
/**
|
/**
|
||||||
* # Fetch API
|
* # Fetch API
|
||||||
*/
|
*/
|
||||||
export default async function fetchApi(
|
export default async function fetchApi<
|
||||||
|
T extends { [k: string]: any } = { [k: string]: any },
|
||||||
|
R extends any = any
|
||||||
|
>(
|
||||||
url: string,
|
url: string,
|
||||||
options?: FetchApiOptions,
|
options?: FetchApiOptions<T>,
|
||||||
csrf?: boolean,
|
csrf?: boolean,
|
||||||
/** Key to use to grab local Storage csrf value. */
|
/**
|
||||||
localStorageCSRFKey?: string
|
* Key to use to grab local Storage csrf value.
|
||||||
): Promise<any> {
|
*/
|
||||||
|
localStorageCSRFKey?: string,
|
||||||
|
/**
|
||||||
|
* Key with which to set the request header csrf
|
||||||
|
* value
|
||||||
|
*/
|
||||||
|
csrfHeaderKey?: string
|
||||||
|
): Promise<R> {
|
||||||
let data;
|
let data;
|
||||||
|
|
||||||
const csrfValue = localStorage.getItem(
|
const csrfKey = "x-dsql-csrf-key";
|
||||||
localStorageCSRFKey || getCsrfHeaderName()
|
const csrfValue = localStorage.getItem(localStorageCSRFKey || csrfKey);
|
||||||
);
|
|
||||||
|
|
||||||
let finalHeaders = {
|
let finalHeaders = {
|
||||||
"Content-Type": "application/json",
|
"Content-Type": "application/json",
|
||||||
} as FetchHeader;
|
} as FetchHeader;
|
||||||
|
|
||||||
if (csrf && csrfValue) {
|
if (csrf && csrfValue) {
|
||||||
finalHeaders[getCsrfHeaderName()] = csrfValue;
|
finalHeaders[localStorageCSRFKey || csrfKey] = csrfValue;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (typeof options === "string") {
|
if (typeof options === "string") {
|
||||||
|
5
dist/client/auth/github/getAccessToken.js
vendored
5
dist/client/auth/github/getAccessToken.js
vendored
@ -1,12 +1,9 @@
|
|||||||
"use strict";
|
|
||||||
Object.defineProperty(exports, "__esModule", { value: true });
|
|
||||||
exports.default = getAccessToken;
|
|
||||||
/**
|
/**
|
||||||
* Login with Github Function
|
* Login with Github Function
|
||||||
* ===============================================================================
|
* ===============================================================================
|
||||||
* @description This function uses github api to login a user with datasquirel
|
* @description This function uses github api to login a user with datasquirel
|
||||||
*/
|
*/
|
||||||
function getAccessToken({ clientId, redirectUrl, setLoading, scopes, }) {
|
export default function getAccessToken({ clientId, redirectUrl, setLoading, scopes, }) {
|
||||||
if (setLoading)
|
if (setLoading)
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
const scopeString = scopes ? scopes.join("%20") : "read:user";
|
const scopeString = scopes ? scopes.join("%20") : "read:user";
|
||||||
|
21
dist/client/auth/google/getAccessToken.js
vendored
21
dist/client/auth/google/getAccessToken.js
vendored
@ -1,27 +1,13 @@
|
|||||||
"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());
|
|
||||||
});
|
|
||||||
};
|
|
||||||
Object.defineProperty(exports, "__esModule", { value: true });
|
|
||||||
exports.default = getAccessToken;
|
|
||||||
exports.googleLogin = googleLogin;
|
|
||||||
let interval;
|
let interval;
|
||||||
/**
|
/**
|
||||||
* Login with Google Function
|
* Login with Google Function
|
||||||
* ===============================================================================
|
* ===============================================================================
|
||||||
* @description This function uses google identity api to login a user with datasquirel
|
* @description This function uses google identity api to login a user with datasquirel
|
||||||
*/
|
*/
|
||||||
function getAccessToken(params) {
|
export default async function getAccessToken(params) {
|
||||||
return __awaiter(this, void 0, void 0, function* () {
|
|
||||||
var _a, _b;
|
var _a, _b;
|
||||||
(_a = params.setLoading) === null || _a === void 0 ? void 0 : _a.call(params, true);
|
(_a = params.setLoading) === null || _a === void 0 ? void 0 : _a.call(params, true);
|
||||||
const response = (yield new Promise((resolve, reject) => {
|
const response = (await new Promise((resolve, reject) => {
|
||||||
interval = setInterval(() => {
|
interval = setInterval(() => {
|
||||||
// @ts-ignore
|
// @ts-ignore
|
||||||
let google = window.google;
|
let google = window.google;
|
||||||
@ -33,12 +19,11 @@ function getAccessToken(params) {
|
|||||||
}));
|
}));
|
||||||
(_b = params.setLoading) === null || _b === void 0 ? void 0 : _b.call(params, false);
|
(_b = params.setLoading) === null || _b === void 0 ? void 0 : _b.call(params, false);
|
||||||
return response;
|
return response;
|
||||||
});
|
|
||||||
}
|
}
|
||||||
/**
|
/**
|
||||||
* # Google Login Function
|
* # Google Login Function
|
||||||
*/
|
*/
|
||||||
function googleLogin({ google, clientId, setLoading, triggerPrompt, }) {
|
export function googleLogin({ google, clientId, setLoading, triggerPrompt, }) {
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
setLoading === null || setLoading === void 0 ? void 0 : setLoading(false);
|
setLoading === null || setLoading === void 0 ? void 0 : setLoading(false);
|
||||||
}, 3000);
|
}, 3000);
|
||||||
|
29
dist/client/auth/logout.js
vendored
29
dist/client/auth/logout.js
vendored
@ -1,27 +1,11 @@
|
|||||||
"use strict";
|
import getCsrfHeaderName from "../../package-shared/actions/get-csrf-header-name";
|
||||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
import parseClientCookies from "../utils/parseClientCookies";
|
||||||
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 = logout;
|
|
||||||
const get_csrf_header_name_1 = __importDefault(require("../../package-shared/actions/get-csrf-header-name"));
|
|
||||||
const parseClientCookies_1 = __importDefault(require("../utils/parseClientCookies"));
|
|
||||||
/**
|
/**
|
||||||
* Login with Google Function
|
* Login with Google Function
|
||||||
* ===============================================================================
|
* ===============================================================================
|
||||||
* @description This function uses google identity api to login a user with datasquirel
|
* @description This function uses google identity api to login a user with datasquirel
|
||||||
*/
|
*/
|
||||||
function logout(params) {
|
export default async function logout(params) {
|
||||||
return __awaiter(this, void 0, void 0, function* () {
|
|
||||||
try {
|
try {
|
||||||
const localUser = localStorage.getItem("user");
|
const localUser = localStorage.getItem("user");
|
||||||
let targetUser;
|
let targetUser;
|
||||||
@ -37,7 +21,7 @@ function logout(params) {
|
|||||||
////////////////////////////////////////
|
////////////////////////////////////////
|
||||||
////////////////////////////////////////
|
////////////////////////////////////////
|
||||||
////////////////////////////////////////
|
////////////////////////////////////////
|
||||||
const cookies = (0, parseClientCookies_1.default)();
|
const cookies = parseClientCookies();
|
||||||
const socialId = (cookies === null || cookies === void 0 ? void 0 : cookies.datasquirel_social_id) &&
|
const socialId = (cookies === null || cookies === void 0 ? void 0 : cookies.datasquirel_social_id) &&
|
||||||
typeof cookies.datasquirel_social_id == "string" &&
|
typeof cookies.datasquirel_social_id == "string" &&
|
||||||
!cookies.datasquirel_social_id.match(/^null$/i)
|
!cookies.datasquirel_social_id.match(/^null$/i)
|
||||||
@ -47,12 +31,12 @@ function logout(params) {
|
|||||||
////////////////////////////////////////
|
////////////////////////////////////////
|
||||||
////////////////////////////////////////
|
////////////////////////////////////////
|
||||||
localStorage.setItem("user", "{}");
|
localStorage.setItem("user", "{}");
|
||||||
localStorage.removeItem((0, get_csrf_header_name_1.default)());
|
localStorage.removeItem(getCsrfHeaderName());
|
||||||
document.cookie = `datasquirel_social_id=null;samesite=strict;path=/`;
|
document.cookie = `datasquirel_social_id=null;samesite=strict;path=/`;
|
||||||
////////////////////////////////////////
|
////////////////////////////////////////
|
||||||
////////////////////////////////////////
|
////////////////////////////////////////
|
||||||
////////////////////////////////////////
|
////////////////////////////////////////
|
||||||
const response = yield new Promise((resolve, reject) => {
|
const response = await new Promise((resolve, reject) => {
|
||||||
if (socialId && !(socialId === null || socialId === void 0 ? void 0 : socialId.match(/^null$/i))) {
|
if (socialId && !(socialId === null || socialId === void 0 ? void 0 : socialId.match(/^null$/i))) {
|
||||||
const googleClientId = params === null || params === void 0 ? void 0 : params.googleClientId;
|
const googleClientId = params === null || params === void 0 ? void 0 : params.googleClientId;
|
||||||
if (googleClientId) {
|
if (googleClientId) {
|
||||||
@ -99,5 +83,4 @@ function logout(params) {
|
|||||||
catch (error) {
|
catch (error) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
12
dist/client/auth/post-login.js
vendored
12
dist/client/auth/post-login.js
vendored
@ -1,10 +1,4 @@
|
|||||||
"use strict";
|
import getCsrfHeaderName from "../../package-shared/actions/get-csrf-header-name";
|
||||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
||||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
||||||
};
|
|
||||||
Object.defineProperty(exports, "__esModule", { value: true });
|
|
||||||
exports.default = postLogin;
|
|
||||||
const get_csrf_header_name_1 = __importDefault(require("../../package-shared/actions/get-csrf-header-name"));
|
|
||||||
/**
|
/**
|
||||||
* Client Setup After Login
|
* Client Setup After Login
|
||||||
* ===============================================================================
|
* ===============================================================================
|
||||||
@ -12,13 +6,13 @@ const get_csrf_header_name_1 = __importDefault(require("../../package-shared/act
|
|||||||
* is logged in. Use this in conjunction with the `datasquirel.user.loginUser`
|
* is logged in. Use this in conjunction with the `datasquirel.user.loginUser`
|
||||||
* function
|
* function
|
||||||
*/
|
*/
|
||||||
function postLogin(res) {
|
export default function postLogin(res) {
|
||||||
try {
|
try {
|
||||||
if (!res.payload)
|
if (!res.payload)
|
||||||
return false;
|
return false;
|
||||||
if (!res.payload.csrf_k)
|
if (!res.payload.csrf_k)
|
||||||
return false;
|
return false;
|
||||||
localStorage.setItem((0, get_csrf_header_name_1.default)(), res.payload.csrf_k);
|
localStorage.setItem(getCsrfHeaderName(), res.payload.csrf_k);
|
||||||
localStorage.setItem("user", JSON.stringify(res.payload));
|
localStorage.setItem("user", JSON.stringify(res.payload));
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
25
dist/client/fetch/index.d.ts
vendored
25
dist/client/fetch/index.d.ts
vendored
@ -1,6 +1,10 @@
|
|||||||
type FetchApiOptions = {
|
type FetchApiOptions<T extends {
|
||||||
|
[k: string]: any;
|
||||||
|
} = {
|
||||||
|
[k: string]: any;
|
||||||
|
}> = {
|
||||||
method: "POST" | "GET" | "DELETE" | "PUT" | "PATCH" | "post" | "get" | "delete" | "put" | "patch";
|
method: "POST" | "GET" | "DELETE" | "PUT" | "PATCH" | "post" | "get" | "delete" | "put" | "patch";
|
||||||
body?: object | string;
|
body?: T | string;
|
||||||
headers?: FetchHeader;
|
headers?: FetchHeader;
|
||||||
};
|
};
|
||||||
type FetchHeader = HeadersInit & {
|
type FetchHeader = HeadersInit & {
|
||||||
@ -15,7 +19,18 @@ export type FetchApiReturn = {
|
|||||||
/**
|
/**
|
||||||
* # Fetch API
|
* # Fetch API
|
||||||
*/
|
*/
|
||||||
export default function fetchApi(url: string, options?: FetchApiOptions, csrf?: boolean,
|
export default function fetchApi<T extends {
|
||||||
/** Key to use to grab local Storage csrf value. */
|
[k: string]: any;
|
||||||
localStorageCSRFKey?: string): Promise<any>;
|
} = {
|
||||||
|
[k: string]: any;
|
||||||
|
}, R extends any = any>(url: string, options?: FetchApiOptions<T>, csrf?: boolean,
|
||||||
|
/**
|
||||||
|
* Key to use to grab local Storage csrf value.
|
||||||
|
*/
|
||||||
|
localStorageCSRFKey?: string,
|
||||||
|
/**
|
||||||
|
* Key with which to set the request header csrf
|
||||||
|
* value
|
||||||
|
*/
|
||||||
|
csrfHeaderKey?: string): Promise<R>;
|
||||||
export {};
|
export {};
|
||||||
|
54
dist/client/fetch/index.js
vendored
54
dist/client/fetch/index.js
vendored
@ -1,48 +1,39 @@
|
|||||||
"use strict";
|
import _ from "lodash";
|
||||||
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 = fetchApi;
|
|
||||||
const lodash_1 = __importDefault(require("lodash"));
|
|
||||||
const get_csrf_header_name_1 = __importDefault(require("../../package-shared/actions/get-csrf-header-name"));
|
|
||||||
/**
|
/**
|
||||||
* # Fetch API
|
* # Fetch API
|
||||||
*/
|
*/
|
||||||
function fetchApi(url, options, csrf,
|
export default async function fetchApi(url, options, csrf,
|
||||||
/** Key to use to grab local Storage csrf value. */
|
/**
|
||||||
localStorageCSRFKey) {
|
* Key to use to grab local Storage csrf value.
|
||||||
return __awaiter(this, void 0, void 0, function* () {
|
*/
|
||||||
|
localStorageCSRFKey,
|
||||||
|
/**
|
||||||
|
* Key with which to set the request header csrf
|
||||||
|
* value
|
||||||
|
*/
|
||||||
|
csrfHeaderKey) {
|
||||||
let data;
|
let data;
|
||||||
const csrfValue = localStorage.getItem(localStorageCSRFKey || (0, get_csrf_header_name_1.default)());
|
const csrfKey = "x-dsql-csrf-key";
|
||||||
|
const csrfValue = localStorage.getItem(localStorageCSRFKey || csrfKey);
|
||||||
let finalHeaders = {
|
let finalHeaders = {
|
||||||
"Content-Type": "application/json",
|
"Content-Type": "application/json",
|
||||||
};
|
};
|
||||||
if (csrf && csrfValue) {
|
if (csrf && csrfValue) {
|
||||||
finalHeaders[(0, get_csrf_header_name_1.default)()] = csrfValue;
|
finalHeaders[localStorageCSRFKey || csrfKey] = csrfValue;
|
||||||
}
|
}
|
||||||
if (typeof options === "string") {
|
if (typeof options === "string") {
|
||||||
try {
|
try {
|
||||||
let fetchData;
|
let fetchData;
|
||||||
switch (options) {
|
switch (options) {
|
||||||
case "post":
|
case "post":
|
||||||
fetchData = yield fetch(url, {
|
fetchData = await fetch(url, {
|
||||||
method: options,
|
method: options,
|
||||||
headers: finalHeaders,
|
headers: finalHeaders,
|
||||||
});
|
});
|
||||||
data = fetchData.json();
|
data = fetchData.json();
|
||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
fetchData = yield fetch(url);
|
fetchData = await fetch(url);
|
||||||
data = fetchData.json();
|
data = fetchData.json();
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
@ -56,17 +47,17 @@ localStorageCSRFKey) {
|
|||||||
try {
|
try {
|
||||||
let fetchData;
|
let fetchData;
|
||||||
if (options.body && typeof options.body === "object") {
|
if (options.body && typeof options.body === "object") {
|
||||||
let oldOptionsBody = lodash_1.default.cloneDeep(options.body);
|
let oldOptionsBody = _.cloneDeep(options.body);
|
||||||
options.body = JSON.stringify(oldOptionsBody);
|
options.body = JSON.stringify(oldOptionsBody);
|
||||||
}
|
}
|
||||||
if (options.headers) {
|
if (options.headers) {
|
||||||
options.headers = lodash_1.default.merge(options.headers, finalHeaders);
|
options.headers = _.merge(options.headers, finalHeaders);
|
||||||
const finalOptions = Object.assign({}, options);
|
const finalOptions = Object.assign({}, options);
|
||||||
fetchData = yield fetch(url, finalOptions);
|
fetchData = await fetch(url, finalOptions);
|
||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
const finalOptions = Object.assign(Object.assign({}, options), { headers: finalHeaders });
|
const finalOptions = Object.assign(Object.assign({}, options), { headers: finalHeaders });
|
||||||
fetchData = yield fetch(url, finalOptions);
|
fetchData = await fetch(url, finalOptions);
|
||||||
}
|
}
|
||||||
data = fetchData.json();
|
data = fetchData.json();
|
||||||
}
|
}
|
||||||
@ -77,8 +68,8 @@ localStorageCSRFKey) {
|
|||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
try {
|
try {
|
||||||
let fetchData = yield fetch(url);
|
let fetchData = await fetch(url);
|
||||||
data = yield fetchData.json();
|
data = await fetchData.json();
|
||||||
}
|
}
|
||||||
catch (error) {
|
catch (error) {
|
||||||
console.log("FetchAPI error #3:", error.message);
|
console.log("FetchAPI error #3:", error.message);
|
||||||
@ -86,5 +77,4 @@ localStorageCSRFKey) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
return data;
|
return data;
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
71
dist/client/index.js
vendored
71
dist/client/index.js
vendored
@ -1,60 +1,55 @@
|
|||||||
"use strict";
|
import imageInputFileToBase64 from "./media/imageInputFileToBase64";
|
||||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
import imageInputToBase64 from "./media/imageInputToBase64";
|
||||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
import inputFileToBase64 from "./media/inputFileToBase64";
|
||||||
};
|
import getAccessToken from "./auth/google/getAccessToken";
|
||||||
Object.defineProperty(exports, "__esModule", { value: true });
|
import getGithubAccessToken from "./auth/github/getAccessToken";
|
||||||
const imageInputFileToBase64_1 = __importDefault(require("./media/imageInputFileToBase64"));
|
import logout from "./auth/logout";
|
||||||
const imageInputToBase64_1 = __importDefault(require("./media/imageInputToBase64"));
|
import fetchApi from "./fetch";
|
||||||
const inputFileToBase64_1 = __importDefault(require("./media/inputFileToBase64"));
|
import clientFetch from "./fetch";
|
||||||
const getAccessToken_1 = __importDefault(require("./auth/google/getAccessToken"));
|
import serializeQuery from "../package-shared/utils/serialize-query";
|
||||||
const getAccessToken_2 = __importDefault(require("./auth/github/getAccessToken"));
|
import serializeCookies from "../package-shared/utils/serialize-cookies";
|
||||||
const logout_1 = __importDefault(require("./auth/logout"));
|
import EJSON from "../package-shared/utils/ejson";
|
||||||
const fetch_1 = __importDefault(require("./fetch"));
|
import numberfy from "../package-shared/utils/numberfy";
|
||||||
const fetch_2 = __importDefault(require("./fetch"));
|
import slugify from "../package-shared/utils/slugify";
|
||||||
const serialize_query_1 = __importDefault(require("../package-shared/utils/serialize-query"));
|
import postLogin from "./auth/post-login";
|
||||||
const serialize_cookies_1 = __importDefault(require("../package-shared/utils/serialize-cookies"));
|
import deserializeQuery from "../package-shared/utils/deserialize-query";
|
||||||
const ejson_1 = __importDefault(require("../package-shared/utils/ejson"));
|
import debugLog from "../package-shared/utils/logging/debug-log";
|
||||||
const numberfy_1 = __importDefault(require("../package-shared/utils/numberfy"));
|
|
||||||
const slugify_1 = __importDefault(require("../package-shared/utils/slugify"));
|
|
||||||
const post_login_1 = __importDefault(require("./auth/post-login"));
|
|
||||||
const deserialize_query_1 = __importDefault(require("../package-shared/utils/deserialize-query"));
|
|
||||||
const debug_log_1 = __importDefault(require("../package-shared/utils/logging/debug-log"));
|
|
||||||
const media = {
|
const media = {
|
||||||
imageInputToBase64: imageInputToBase64_1.default,
|
imageInputToBase64: imageInputToBase64,
|
||||||
imageInputFileToBase64: imageInputFileToBase64_1.default,
|
imageInputFileToBase64: imageInputFileToBase64,
|
||||||
inputFileToBase64: inputFileToBase64_1.default,
|
inputFileToBase64: inputFileToBase64,
|
||||||
};
|
};
|
||||||
/**
|
/**
|
||||||
* User Auth Object
|
* User Auth Object
|
||||||
*/
|
*/
|
||||||
const auth = {
|
const auth = {
|
||||||
google: {
|
google: {
|
||||||
getAccessToken: getAccessToken_1.default,
|
getAccessToken: getAccessToken,
|
||||||
},
|
},
|
||||||
github: {
|
github: {
|
||||||
getAccessToken: getAccessToken_2.default,
|
getAccessToken: getGithubAccessToken,
|
||||||
},
|
},
|
||||||
logout: logout_1.default,
|
logout,
|
||||||
postLogin: post_login_1.default,
|
postLogin,
|
||||||
};
|
};
|
||||||
const utils = {
|
const utils = {
|
||||||
deserializeQuery: deserialize_query_1.default,
|
deserializeQuery,
|
||||||
serializeQuery: serialize_query_1.default,
|
serializeQuery,
|
||||||
serializeCookies: serialize_cookies_1.default,
|
serializeCookies,
|
||||||
EJSON: ejson_1.default,
|
EJSON,
|
||||||
numberfy: numberfy_1.default,
|
numberfy,
|
||||||
slugify: slugify_1.default,
|
slugify,
|
||||||
debugLog: debug_log_1.default,
|
debugLog,
|
||||||
};
|
};
|
||||||
/**
|
/**
|
||||||
* Fetch
|
* Fetch
|
||||||
*/
|
*/
|
||||||
const fetch = {
|
const fetch = {
|
||||||
fetchApi: fetch_1.default,
|
fetchApi,
|
||||||
clientFetch: fetch_2.default,
|
clientFetch,
|
||||||
};
|
};
|
||||||
/**
|
/**
|
||||||
* Main Export
|
* Main Export
|
||||||
*/
|
*/
|
||||||
const datasquirelClient = { media, auth, fetch, utils };
|
const datasquirelClient = { media, auth, fetch, utils };
|
||||||
exports.default = datasquirelClient;
|
export default datasquirelClient;
|
||||||
|
19
dist/client/media/client.js
vendored
19
dist/client/media/client.js
vendored
@ -1,18 +1,13 @@
|
|||||||
"use strict";
|
import imageInputFileToBase64 from "./imageInputFileToBase64";
|
||||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
import imageInputToBase64 from "./imageInputToBase64";
|
||||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
||||||
};
|
|
||||||
Object.defineProperty(exports, "__esModule", { value: true });
|
|
||||||
const imageInputFileToBase64_1 = __importDefault(require("./imageInputFileToBase64"));
|
|
||||||
const imageInputToBase64_1 = __importDefault(require("./imageInputToBase64"));
|
|
||||||
/**
|
/**
|
||||||
* ==========================
|
* ==========================
|
||||||
* Media Functions Object
|
* Media Functions Object
|
||||||
* ==========================
|
* ==========================
|
||||||
*/
|
*/
|
||||||
const media = {
|
const media = {
|
||||||
imageInputToBase64: imageInputToBase64_1.default,
|
imageInputToBase64: imageInputToBase64,
|
||||||
imageInputFileToBase64: imageInputFileToBase64_1.default,
|
imageInputFileToBase64: imageInputFileToBase64,
|
||||||
};
|
};
|
||||||
/**
|
/**
|
||||||
* ==========================
|
* ==========================
|
||||||
@ -20,8 +15,8 @@ const media = {
|
|||||||
* ==========================
|
* ==========================
|
||||||
*/
|
*/
|
||||||
const auth = {
|
const auth = {
|
||||||
imageInputToBase64: imageInputToBase64_1.default,
|
imageInputToBase64: imageInputToBase64,
|
||||||
imageInputFileToBase64: imageInputFileToBase64_1.default,
|
imageInputFileToBase64: imageInputFileToBase64,
|
||||||
};
|
};
|
||||||
/**
|
/**
|
||||||
* ==========================
|
* ==========================
|
||||||
@ -31,4 +26,4 @@ const auth = {
|
|||||||
const datasquirelClient = {
|
const datasquirelClient = {
|
||||||
media: media,
|
media: media,
|
||||||
};
|
};
|
||||||
exports.default = datasquirelClient;
|
export default datasquirelClient;
|
||||||
|
20
dist/client/media/imageInputFileToBase64.js
vendored
20
dist/client/media/imageInputFileToBase64.js
vendored
@ -1,20 +1,7 @@
|
|||||||
"use strict";
|
|
||||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
|
||||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
|
||||||
return new (P || (P = Promise))(function (resolve, reject) {
|
|
||||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
|
||||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
||||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
||||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
||||||
});
|
|
||||||
};
|
|
||||||
Object.defineProperty(exports, "__esModule", { value: true });
|
|
||||||
exports.default = imageInputFileToBase64;
|
|
||||||
/**
|
/**
|
||||||
* # Image input File top Base64
|
* # Image input File top Base64
|
||||||
*/
|
*/
|
||||||
function imageInputFileToBase64(_a) {
|
export default async function imageInputFileToBase64({ imageInputFile, maxWidth, imagePreviewNode, }) {
|
||||||
return __awaiter(this, arguments, void 0, function* ({ imageInputFile, maxWidth, imagePreviewNode, }) {
|
|
||||||
/**
|
/**
|
||||||
* Make https request
|
* Make https request
|
||||||
*
|
*
|
||||||
@ -33,7 +20,7 @@ function imageInputFileToBase64(_a) {
|
|||||||
const img = new Image();
|
const img = new Image();
|
||||||
/** ********************* Add source to new image */
|
/** ********************* Add source to new image */
|
||||||
img.src = blobURL;
|
img.src = blobURL;
|
||||||
imageDataBase64 = yield new Promise((res, rej) => {
|
imageDataBase64 = await new Promise((res, rej) => {
|
||||||
/** ********************* Handle Errors in loading image */
|
/** ********************* Handle Errors in loading image */
|
||||||
img.onerror = function () {
|
img.onerror = function () {
|
||||||
URL.revokeObjectURL(this.src);
|
URL.revokeObjectURL(this.src);
|
||||||
@ -67,7 +54,7 @@ function imageInputFileToBase64(_a) {
|
|||||||
res(srcEncoded);
|
res(srcEncoded);
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
imageSize = yield new Promise((res, rej) => {
|
imageSize = await new Promise((res, rej) => {
|
||||||
canvas.toBlob((blob) => {
|
canvas.toBlob((blob) => {
|
||||||
res(blob === null || blob === void 0 ? void 0 : blob.size);
|
res(blob === null || blob === void 0 ? void 0 : blob.size);
|
||||||
}, MIME_TYPE, QUALITY);
|
}, MIME_TYPE, QUALITY);
|
||||||
@ -88,5 +75,4 @@ function imageInputFileToBase64(_a) {
|
|||||||
imageSize: undefined,
|
imageSize: undefined,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
24
dist/client/media/imageInputToBase64.js
vendored
24
dist/client/media/imageInputToBase64.js
vendored
@ -1,21 +1,8 @@
|
|||||||
"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());
|
|
||||||
});
|
|
||||||
};
|
|
||||||
Object.defineProperty(exports, "__esModule", { value: true });
|
|
||||||
exports.default = imageInputToBase64;
|
|
||||||
/**
|
/**
|
||||||
* # Image Input Element to Base 64
|
* # Image Input Element to Base 64
|
||||||
*/
|
*/
|
||||||
function imageInputToBase64(_a) {
|
export default async function imageInputToBase64({ imageInput, maxWidth, mimeType, }) {
|
||||||
return __awaiter(this, arguments, void 0, function* ({ imageInput, maxWidth, mimeType, }) {
|
var _a, _b;
|
||||||
var _b, _c;
|
|
||||||
/**
|
/**
|
||||||
* Make https request
|
* Make https request
|
||||||
*
|
*
|
||||||
@ -23,17 +10,17 @@ function imageInputToBase64(_a) {
|
|||||||
*/
|
*/
|
||||||
try {
|
try {
|
||||||
let imagePreviewNode = document.querySelector(`[data-imagepreview='image']`);
|
let imagePreviewNode = document.querySelector(`[data-imagepreview='image']`);
|
||||||
let imageName = (_b = imageInput.files) === null || _b === void 0 ? void 0 : _b[0].name.replace(/\..*/, "");
|
let imageName = (_a = imageInput.files) === null || _a === void 0 ? void 0 : _a[0].name.replace(/\..*/, "");
|
||||||
let imageDataBase64;
|
let imageDataBase64;
|
||||||
const MIME_TYPE = mimeType ? mimeType : "image/jpeg";
|
const MIME_TYPE = mimeType ? mimeType : "image/jpeg";
|
||||||
const QUALITY = 0.95;
|
const QUALITY = 0.95;
|
||||||
const MAX_WIDTH = maxWidth ? maxWidth : null;
|
const MAX_WIDTH = maxWidth ? maxWidth : null;
|
||||||
const file = (_c = imageInput.files) === null || _c === void 0 ? void 0 : _c[0];
|
const file = (_b = imageInput.files) === null || _b === void 0 ? void 0 : _b[0];
|
||||||
const blobURL = file ? URL.createObjectURL(file) : undefined;
|
const blobURL = file ? URL.createObjectURL(file) : undefined;
|
||||||
const img = new Image();
|
const img = new Image();
|
||||||
if (blobURL) {
|
if (blobURL) {
|
||||||
img.src = blobURL;
|
img.src = blobURL;
|
||||||
imageDataBase64 = yield new Promise((res, rej) => {
|
imageDataBase64 = await new Promise((res, rej) => {
|
||||||
/** ********************* Handle Errors in loading image */
|
/** ********************* Handle Errors in loading image */
|
||||||
img.onerror = function () {
|
img.onerror = function () {
|
||||||
URL.revokeObjectURL(this.src);
|
URL.revokeObjectURL(this.src);
|
||||||
@ -86,5 +73,4 @@ function imageInputToBase64(_a) {
|
|||||||
console.log("Image Processing Error! =>", error.message);
|
console.log("Image Processing Error! =>", error.message);
|
||||||
return {};
|
return {};
|
||||||
}
|
}
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
22
dist/client/media/inputFileToBase64.js
vendored
22
dist/client/media/inputFileToBase64.js
vendored
@ -1,15 +1,3 @@
|
|||||||
"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());
|
|
||||||
});
|
|
||||||
};
|
|
||||||
Object.defineProperty(exports, "__esModule", { value: true });
|
|
||||||
exports.default = inputFileToBase64;
|
|
||||||
/**
|
/**
|
||||||
* Input File to base64
|
* Input File to base64
|
||||||
* ==============================================================================
|
* ==============================================================================
|
||||||
@ -18,11 +6,10 @@ exports.default = inputFileToBase64;
|
|||||||
* HTML file input elements usually return an array of input objects, so be sure to select the target
|
* HTML file input elements usually return an array of input objects, so be sure to select the target
|
||||||
* file from the array.
|
* file from the array.
|
||||||
*/
|
*/
|
||||||
function inputFileToBase64(_a) {
|
export default async function inputFileToBase64({ inputFile, allowedRegex, }) {
|
||||||
return __awaiter(this, arguments, void 0, function* ({ inputFile, allowedRegex, }) {
|
var _a;
|
||||||
var _b;
|
|
||||||
const allowedTypesRegex = allowedRegex ? allowedRegex : /image\/*|\/pdf/;
|
const allowedTypesRegex = allowedRegex ? allowedRegex : /image\/*|\/pdf/;
|
||||||
if (!((_b = inputFile === null || inputFile === void 0 ? void 0 : inputFile.type) === null || _b === void 0 ? void 0 : _b.match(allowedTypesRegex))) {
|
if (!((_a = inputFile === null || inputFile === void 0 ? void 0 : inputFile.type) === null || _a === void 0 ? void 0 : _a.match(allowedTypesRegex))) {
|
||||||
window.alert(`We currently don't support ${inputFile.type} file types. Support is coming soon. For now we support only images and PDFs.`);
|
window.alert(`We currently don't support ${inputFile.type} file types. Support is coming soon. For now we support only images and PDFs.`);
|
||||||
return {
|
return {
|
||||||
fileName: inputFile.name,
|
fileName: inputFile.name,
|
||||||
@ -30,7 +17,7 @@ function inputFileToBase64(_a) {
|
|||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
let fileName = inputFile.name.replace(/\..*/, "");
|
let fileName = inputFile.name.replace(/\..*/, "");
|
||||||
const fileData = yield new Promise((resolve, reject) => {
|
const fileData = await new Promise((resolve, reject) => {
|
||||||
var reader = new FileReader();
|
var reader = new FileReader();
|
||||||
reader.readAsDataURL(inputFile);
|
reader.readAsDataURL(inputFile);
|
||||||
reader.onload = function () {
|
reader.onload = function () {
|
||||||
@ -55,5 +42,4 @@ function inputFileToBase64(_a) {
|
|||||||
fileName: inputFile.name,
|
fileName: inputFile.name,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
5
dist/client/utils/parseClientCookies.js
vendored
5
dist/client/utils/parseClientCookies.js
vendored
@ -1,12 +1,9 @@
|
|||||||
"use strict";
|
|
||||||
Object.defineProperty(exports, "__esModule", { value: true });
|
|
||||||
exports.default = default_1;
|
|
||||||
/**
|
/**
|
||||||
* Parse request cookies
|
* Parse request cookies
|
||||||
* ============================================================================== *
|
* ============================================================================== *
|
||||||
* @description This function takes in a request object and returns the cookies as a JS object
|
* @description This function takes in a request object and returns the cookies as a JS object
|
||||||
*/
|
*/
|
||||||
function default_1() {
|
export default function () {
|
||||||
/**
|
/**
|
||||||
* Check inputs
|
* Check inputs
|
||||||
*
|
*
|
||||||
|
4
dist/console-colors.js
vendored
4
dist/console-colors.js
vendored
@ -1,5 +1,3 @@
|
|||||||
"use strict";
|
|
||||||
Object.defineProperty(exports, "__esModule", { value: true });
|
|
||||||
const colors = {
|
const colors = {
|
||||||
Reset: "\x1b[0m",
|
Reset: "\x1b[0m",
|
||||||
Bright: "\x1b[1m",
|
Bright: "\x1b[1m",
|
||||||
@ -27,4 +25,4 @@ const colors = {
|
|||||||
BgWhite: "\x1b[47m",
|
BgWhite: "\x1b[47m",
|
||||||
BgGray: "\x1b[100m",
|
BgGray: "\x1b[100m",
|
||||||
};
|
};
|
||||||
exports.default = colors;
|
export default colors;
|
||||||
|
59
dist/engine/dsql.js
vendored
59
dist/engine/dsql.js
vendored
@ -1,28 +1,13 @@
|
|||||||
#! /usr/bin/env node
|
#! /usr/bin/env node
|
||||||
"use strict";
|
import fs from "fs";
|
||||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
import path from "path";
|
||||||
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 = run;
|
|
||||||
const fs_1 = __importDefault(require("fs"));
|
|
||||||
const path_1 = __importDefault(require("path"));
|
|
||||||
require("dotenv").config({
|
require("dotenv").config({
|
||||||
path: path_1.default.resolve(process.cwd(), ".env"),
|
path: path.resolve(process.cwd(), ".env"),
|
||||||
});
|
});
|
||||||
const index_1 = __importDefault(require("../index"));
|
import datasquirel from "../index";
|
||||||
const console_colors_1 = __importDefault(require("../console-colors"));
|
import colors from "../console-colors";
|
||||||
const createDbFromSchema_1 = __importDefault(require("../package-shared/shell/createDbFromSchema"));
|
import createDbFromSchema from "../package-shared/shell/createDbFromSchema";
|
||||||
if (!fs_1.default.existsSync(path_1.default.resolve(process.cwd(), ".env"))) {
|
if (!fs.existsSync(path.resolve(process.cwd(), ".env"))) {
|
||||||
console.log(".env file not found");
|
console.log(".env file not found");
|
||||||
process.exit();
|
process.exit();
|
||||||
}
|
}
|
||||||
@ -39,12 +24,11 @@ if (!(DSQL_PASS === null || DSQL_PASS === void 0 ? void 0 : DSQL_PASS.match(/./)
|
|||||||
console.log("DSQL_PASS is required in your `.env` file");
|
console.log("DSQL_PASS is required in your `.env` file");
|
||||||
process.exit();
|
process.exit();
|
||||||
}
|
}
|
||||||
const dbSchemaLocalFilePath = path_1.default.resolve(process.cwd(), "dsql.schema.json");
|
const dbSchemaLocalFilePath = path.resolve(process.cwd(), "dsql.schema.json");
|
||||||
function run() {
|
export default async function run() {
|
||||||
return __awaiter(this, void 0, void 0, function* () {
|
|
||||||
let schemaData;
|
let schemaData;
|
||||||
if (DSQL_KEY && (DSQL_REF_DB_NAME === null || DSQL_REF_DB_NAME === void 0 ? void 0 : DSQL_REF_DB_NAME.match(/./))) {
|
if (DSQL_KEY && (DSQL_REF_DB_NAME === null || DSQL_REF_DB_NAME === void 0 ? void 0 : DSQL_REF_DB_NAME.match(/./))) {
|
||||||
const dbSchemaDataResponse = yield index_1.default.getSchema({
|
const dbSchemaDataResponse = await datasquirel.getSchema({
|
||||||
key: DSQL_KEY,
|
key: DSQL_KEY,
|
||||||
database: DSQL_REF_DB_NAME || undefined,
|
database: DSQL_REF_DB_NAME || undefined,
|
||||||
});
|
});
|
||||||
@ -60,7 +44,7 @@ function run() {
|
|||||||
schemaData = [fetchedDbSchemaObject];
|
schemaData = [fetchedDbSchemaObject];
|
||||||
}
|
}
|
||||||
else if (DSQL_KEY) {
|
else if (DSQL_KEY) {
|
||||||
const dbSchemaDataResponse = yield index_1.default.getSchema({
|
const dbSchemaDataResponse = await datasquirel.getSchema({
|
||||||
key: DSQL_KEY,
|
key: DSQL_KEY,
|
||||||
database: DSQL_REF_DB_NAME || undefined,
|
database: DSQL_REF_DB_NAME || undefined,
|
||||||
});
|
});
|
||||||
@ -76,9 +60,9 @@ function run() {
|
|||||||
// });
|
// });
|
||||||
schemaData = fetchedDbSchemaObject;
|
schemaData = fetchedDbSchemaObject;
|
||||||
}
|
}
|
||||||
else if (fs_1.default.existsSync(dbSchemaLocalFilePath)) {
|
else if (fs.existsSync(dbSchemaLocalFilePath)) {
|
||||||
schemaData = [
|
schemaData = [
|
||||||
JSON.parse(fs_1.default.readFileSync(dbSchemaLocalFilePath, "utf8")),
|
JSON.parse(fs.readFileSync(dbSchemaLocalFilePath, "utf8")),
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
@ -90,25 +74,24 @@ function run() {
|
|||||||
process.exit();
|
process.exit();
|
||||||
}
|
}
|
||||||
if (DSQL_FULL_SYNC === null || DSQL_FULL_SYNC === void 0 ? void 0 : DSQL_FULL_SYNC.match(/true/i)) {
|
if (DSQL_FULL_SYNC === null || DSQL_FULL_SYNC === void 0 ? void 0 : DSQL_FULL_SYNC.match(/true/i)) {
|
||||||
fs_1.default.writeFileSync(dbSchemaLocalFilePath, JSON.stringify(schemaData[0], null, 4), "utf8");
|
fs.writeFileSync(dbSchemaLocalFilePath, JSON.stringify(schemaData[0], null, 4), "utf8");
|
||||||
}
|
}
|
||||||
console.log(` - ${console_colors_1.default.FgBlue}Info:${console_colors_1.default.Reset} Now generating and mapping databases ...`);
|
console.log(` - ${colors.FgBlue}Info:${colors.Reset} Now generating and mapping databases ...`);
|
||||||
yield (0, createDbFromSchema_1.default)({
|
await createDbFromSchema({
|
||||||
dbSchemaData: schemaData,
|
dbSchemaData: schemaData,
|
||||||
});
|
});
|
||||||
console.log(` - ${console_colors_1.default.FgGreen}Success:${console_colors_1.default.Reset} Databases created Successfully!`);
|
console.log(` - ${colors.FgGreen}Success:${colors.Reset} Databases created Successfully!`);
|
||||||
});
|
|
||||||
}
|
}
|
||||||
let interval;
|
let interval;
|
||||||
if (fs_1.default.existsSync(dbSchemaLocalFilePath) && !(DSQL_KEY === null || DSQL_KEY === void 0 ? void 0 : DSQL_KEY.match(/....../))) {
|
if (fs.existsSync(dbSchemaLocalFilePath) && !(DSQL_KEY === null || DSQL_KEY === void 0 ? void 0 : DSQL_KEY.match(/....../))) {
|
||||||
fs_1.default.watchFile(dbSchemaLocalFilePath, { interval: 1000 }, (curr, prev) => {
|
fs.watchFile(dbSchemaLocalFilePath, { interval: 1000 }, (curr, prev) => {
|
||||||
console.log(` - ${console_colors_1.default.FgBlue}Info:${console_colors_1.default.Reset} Syncing Databases Locally ...`);
|
console.log(` - ${colors.FgBlue}Info:${colors.Reset} Syncing Databases Locally ...`);
|
||||||
run();
|
run();
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
else if (DSQL_KEY === null || DSQL_KEY === void 0 ? void 0 : DSQL_KEY.match(/....../)) {
|
else if (DSQL_KEY === null || DSQL_KEY === void 0 ? void 0 : DSQL_KEY.match(/....../)) {
|
||||||
interval = setInterval(() => {
|
interval = setInterval(() => {
|
||||||
console.log(` - ${console_colors_1.default.FgMagenta}Info:${console_colors_1.default.Reset} Syncing Databases from the cloud ...`);
|
console.log(` - ${colors.FgMagenta}Info:${colors.Reset} Syncing Databases from the cloud ...`);
|
||||||
run();
|
run();
|
||||||
}, 20000);
|
}, 20000);
|
||||||
}
|
}
|
||||||
|
13
dist/engine/dump.js
vendored
13
dist/engine/dump.js
vendored
@ -1,14 +1,9 @@
|
|||||||
#! /usr/bin/env node
|
#! /usr/bin/env node
|
||||||
"use strict";
|
|
||||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
||||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
||||||
};
|
|
||||||
var _a, _b, _c;
|
var _a, _b, _c;
|
||||||
Object.defineProperty(exports, "__esModule", { value: true });
|
import path from "path";
|
||||||
const path_1 = __importDefault(require("path"));
|
import { execSync } from "child_process";
|
||||||
const child_process_1 = require("child_process");
|
|
||||||
require("dotenv").config({
|
require("dotenv").config({
|
||||||
path: path_1.default.resolve(process.cwd(), ".env"),
|
path: path.resolve(process.cwd(), ".env"),
|
||||||
});
|
});
|
||||||
const mysqlPath = ((_a = process.platform) === null || _a === void 0 ? void 0 : _a.match(/win/i))
|
const mysqlPath = ((_a = process.platform) === null || _a === void 0 ? void 0 : _a.match(/win/i))
|
||||||
? "'" + "C:\\Program Files\\MySQL\\MySQL Server 8.0\\bin\\mysql.exe" + "'"
|
? "'" + "C:\\Program Files\\MySQL\\MySQL Server 8.0\\bin\\mysql.exe" + "'"
|
||||||
@ -39,7 +34,7 @@ try {
|
|||||||
cwd: process.cwd(),
|
cwd: process.cwd(),
|
||||||
};
|
};
|
||||||
// if (process.platform.match(/win/i)) execSyncOptions.shell = "bash.exe";
|
// if (process.platform.match(/win/i)) execSyncOptions.shell = "bash.exe";
|
||||||
const dump = (0, child_process_1.execSync)(`${mysqlPath} -u ${DSQL_USER} -p${DSQL_PASS} ${dbName} < ${dumpFilePath}`, execSyncOptions);
|
const dump = execSync(`${mysqlPath} -u ${DSQL_USER} -p${DSQL_PASS} ${dbName} < ${dumpFilePath}`, execSyncOptions);
|
||||||
console.log("Dumped successfully", dump.toString());
|
console.log("Dumped successfully", dump.toString());
|
||||||
////////////////////////////////////////
|
////////////////////////////////////////
|
||||||
////////////////////////////////////////
|
////////////////////////////////////////
|
||||||
|
68
dist/engine/schema-to-typedef.js
vendored
68
dist/engine/schema-to-typedef.js
vendored
@ -1,26 +1,12 @@
|
|||||||
#! /usr/bin/env node
|
#! /usr/bin/env node
|
||||||
"use strict";
|
import fs from "fs";
|
||||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
import datasquirel from "..";
|
||||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
import { parseArgs } from "util";
|
||||||
return new (P || (P = Promise))(function (resolve, reject) {
|
import dbSchemaToType from "../package-shared/functions/dsql/db-schema-to-type";
|
||||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
import path from "path";
|
||||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
import debugLog from "../package-shared/utils/logging/debug-log";
|
||||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
import parseEnv from "../package-shared/utils/parse-env";
|
||||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
const args = parseArgs({
|
||||||
});
|
|
||||||
};
|
|
||||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
||||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
||||||
};
|
|
||||||
Object.defineProperty(exports, "__esModule", { value: true });
|
|
||||||
const fs_1 = __importDefault(require("fs"));
|
|
||||||
const __1 = __importDefault(require(".."));
|
|
||||||
const util_1 = require("util");
|
|
||||||
const db_schema_to_type_1 = __importDefault(require("../package-shared/functions/dsql/db-schema-to-type"));
|
|
||||||
const path_1 = __importDefault(require("path"));
|
|
||||||
const debug_log_1 = __importDefault(require("../package-shared/utils/logging/debug-log"));
|
|
||||||
const parse_env_1 = __importDefault(require("../package-shared/utils/parse-env"));
|
|
||||||
const args = (0, util_1.parseArgs)({
|
|
||||||
args: process.argv,
|
args: process.argv,
|
||||||
options: {
|
options: {
|
||||||
apiKey: {
|
apiKey: {
|
||||||
@ -55,12 +41,12 @@ const args = (0, util_1.parseArgs)({
|
|||||||
});
|
});
|
||||||
let appendedEnv = {};
|
let appendedEnv = {};
|
||||||
if (args.values.envfile && typeof args.values.envfile == "string") {
|
if (args.values.envfile && typeof args.values.envfile == "string") {
|
||||||
const finalEnvPath = path_1.default.resolve(process.cwd(), args.values.envfile);
|
const finalEnvPath = path.resolve(process.cwd(), args.values.envfile);
|
||||||
if (fs_1.default.existsSync(finalEnvPath)) {
|
if (fs.existsSync(finalEnvPath)) {
|
||||||
const parsedEnv = (0, parse_env_1.default)(finalEnvPath);
|
const parsedEnv = parseEnv(finalEnvPath);
|
||||||
appendedEnv = parsedEnv || {};
|
appendedEnv = (parsedEnv || {});
|
||||||
if (args.values.debug) {
|
if (args.values.debug) {
|
||||||
(0, debug_log_1.default)({
|
debugLog({
|
||||||
log: appendedEnv,
|
log: appendedEnv,
|
||||||
label: "Appended env",
|
label: "Appended env",
|
||||||
title: "Schema to Typedef",
|
title: "Schema to Typedef",
|
||||||
@ -71,25 +57,25 @@ if (args.values.envfile && typeof args.values.envfile == "string") {
|
|||||||
}
|
}
|
||||||
const finalEnv = Object.assign(Object.assign({}, process.env), appendedEnv);
|
const finalEnv = Object.assign(Object.assign({}, process.env), appendedEnv);
|
||||||
process.env = Object.assign(Object.assign({}, process.env), appendedEnv);
|
process.env = Object.assign(Object.assign({}, process.env), appendedEnv);
|
||||||
(() => __awaiter(void 0, void 0, void 0, function* () {
|
(async () => {
|
||||||
try {
|
try {
|
||||||
const key = args.values.apiKey || finalEnv["DSQL_FULL_ACCESS_API_KEY"];
|
const key = args.values.apiKey || finalEnv["DSQL_FULL_ACCESS_API_KEY"];
|
||||||
const database = args.values.database || finalEnv["DSQL_DB_NAME"];
|
const database = args.values.database || finalEnv["DSQL_DB_NAME"];
|
||||||
const user_id = args.values.userid || finalEnv["DSQL_API_USER_ID"] || "1";
|
const user_id = args.values.userid || finalEnv["DSQL_API_USER_ID"] || "1";
|
||||||
if (args.values.debug) {
|
if (args.values.debug) {
|
||||||
(0, debug_log_1.default)({
|
debugLog({
|
||||||
log: args.values,
|
log: args.values,
|
||||||
label: "Arguments",
|
label: "Arguments",
|
||||||
title: "Schema to Typedef",
|
title: "Schema to Typedef",
|
||||||
addTime: true,
|
addTime: true,
|
||||||
});
|
});
|
||||||
(0, debug_log_1.default)({
|
debugLog({
|
||||||
log: process.env.DSQL_FULL_ACCESS_API_KEY,
|
log: process.env.DSQL_FULL_ACCESS_API_KEY,
|
||||||
label: "process.env.DSQL_FULL_ACCESS_API_KEY",
|
label: "process.env.DSQL_FULL_ACCESS_API_KEY",
|
||||||
title: "Schema to Typedef",
|
title: "Schema to Typedef",
|
||||||
addTime: true,
|
addTime: true,
|
||||||
});
|
});
|
||||||
(0, debug_log_1.default)({
|
debugLog({
|
||||||
log: process.env.DSQL_DB_NAME,
|
log: process.env.DSQL_DB_NAME,
|
||||||
label: "process.env.DSQL_DB_NAME",
|
label: "process.env.DSQL_DB_NAME",
|
||||||
title: "Schema to Typedef",
|
title: "Schema to Typedef",
|
||||||
@ -104,7 +90,7 @@ process.env = Object.assign(Object.assign({}, process.env), appendedEnv);
|
|||||||
throw new Error("Outfile are required");
|
throw new Error("Outfile are required");
|
||||||
if (!user_id || typeof user_id !== "string")
|
if (!user_id || typeof user_id !== "string")
|
||||||
throw new Error("Outfile are required");
|
throw new Error("Outfile are required");
|
||||||
const schema = yield __1.default.getSchema({
|
const schema = await datasquirel.getSchema({
|
||||||
key,
|
key,
|
||||||
database,
|
database,
|
||||||
user_id,
|
user_id,
|
||||||
@ -112,7 +98,7 @@ process.env = Object.assign(Object.assign({}, process.env), appendedEnv);
|
|||||||
});
|
});
|
||||||
const dbSchema = schema.payload;
|
const dbSchema = schema.payload;
|
||||||
if (args.values.debug) {
|
if (args.values.debug) {
|
||||||
(0, debug_log_1.default)({
|
debugLog({
|
||||||
log: schema,
|
log: schema,
|
||||||
label: "schema",
|
label: "schema",
|
||||||
title: "Schema to Typedef",
|
title: "Schema to Typedef",
|
||||||
@ -121,16 +107,16 @@ process.env = Object.assign(Object.assign({}, process.env), appendedEnv);
|
|||||||
}
|
}
|
||||||
if (!dbSchema)
|
if (!dbSchema)
|
||||||
throw new Error("No schema found");
|
throw new Error("No schema found");
|
||||||
const definitions = (0, db_schema_to_type_1.default)({ dbSchema });
|
const definitions = dbSchemaToType({ dbSchema });
|
||||||
const finalOutfile = path_1.default.resolve(process.cwd(), args.values.outfile);
|
const finalOutfile = path.resolve(process.cwd(), args.values.outfile);
|
||||||
const ourfileDir = path_1.default.dirname(finalOutfile);
|
const ourfileDir = path.dirname(finalOutfile);
|
||||||
if (!fs_1.default.existsSync(ourfileDir)) {
|
if (!fs.existsSync(ourfileDir)) {
|
||||||
fs_1.default.mkdirSync(ourfileDir, { recursive: true });
|
fs.mkdirSync(ourfileDir, { recursive: true });
|
||||||
}
|
}
|
||||||
fs_1.default.writeFileSync(finalOutfile, (definitions === null || definitions === void 0 ? void 0 : definitions.join("\n\n")) || "", "utf-8");
|
fs.writeFileSync(finalOutfile, (definitions === null || definitions === void 0 ? void 0 : definitions.join("\n\n")) || "", "utf-8");
|
||||||
}
|
}
|
||||||
catch (error) {
|
catch (error) {
|
||||||
(0, debug_log_1.default)({
|
debugLog({
|
||||||
log: error.message,
|
log: error.message,
|
||||||
label: "Error",
|
label: "Error",
|
||||||
title: "Schema to Typedef",
|
title: "Schema to Typedef",
|
||||||
@ -139,4 +125,4 @@ process.env = Object.assign(Object.assign({}, process.env), appendedEnv);
|
|||||||
});
|
});
|
||||||
process.exit(1);
|
process.exit(1);
|
||||||
}
|
}
|
||||||
}))();
|
})();
|
||||||
|
25
dist/index.d.ts
vendored
25
dist/index.d.ts
vendored
@ -9,9 +9,6 @@ declare global {
|
|||||||
import get from "./package-shared/actions/get";
|
import get from "./package-shared/actions/get";
|
||||||
import post from "./package-shared/actions/post";
|
import post from "./package-shared/actions/post";
|
||||||
import getSchema from "./package-shared/actions/get-schema";
|
import getSchema from "./package-shared/actions/get-schema";
|
||||||
import uploadImage from "./package-shared/actions/upload-image";
|
|
||||||
import uploadFile from "./package-shared/actions/upload-file";
|
|
||||||
import deleteFile from "./package-shared/actions/delete-file";
|
|
||||||
import createUser from "./package-shared/actions/users/add-user";
|
import createUser from "./package-shared/actions/users/add-user";
|
||||||
import updateUser from "./package-shared/actions/users/update-user";
|
import updateUser from "./package-shared/actions/users/update-user";
|
||||||
import loginUser from "./package-shared/actions/users/login-user";
|
import loginUser from "./package-shared/actions/users/login-user";
|
||||||
@ -44,6 +41,23 @@ import parseEnv from "./package-shared/utils/parse-env";
|
|||||||
* Main Export
|
* Main Export
|
||||||
*/
|
*/
|
||||||
declare const datasquirel: {
|
declare const datasquirel: {
|
||||||
|
/**
|
||||||
|
* API Actions
|
||||||
|
*/
|
||||||
|
api: {
|
||||||
|
crud: {
|
||||||
|
get: typeof import("./package-shared/api/crud/get").default;
|
||||||
|
insert: typeof import("./package-shared/api/crud/post").default;
|
||||||
|
update: typeof import("./package-shared/api/crud/put").default;
|
||||||
|
delete: typeof import("./package-shared/api/crud/delete").default;
|
||||||
|
options: () => Promise<void>;
|
||||||
|
};
|
||||||
|
media: {
|
||||||
|
get: typeof import("./package-shared/api/media/get").default;
|
||||||
|
add: typeof import("./package-shared/api/media/post").default;
|
||||||
|
delete: typeof import("./package-shared/api/media/delete").default;
|
||||||
|
};
|
||||||
|
};
|
||||||
/**
|
/**
|
||||||
* Get Action
|
* Get Action
|
||||||
*/
|
*/
|
||||||
@ -52,11 +66,6 @@ declare const datasquirel: {
|
|||||||
* Post Action
|
* Post Action
|
||||||
*/
|
*/
|
||||||
post: typeof post;
|
post: typeof post;
|
||||||
media: {
|
|
||||||
uploadImage: typeof uploadImage;
|
|
||||||
uploadFile: typeof uploadFile;
|
|
||||||
deleteFile: typeof deleteFile;
|
|
||||||
};
|
|
||||||
user: {
|
user: {
|
||||||
createUser: typeof createUser;
|
createUser: typeof createUser;
|
||||||
deleteUser: typeof deleteUser;
|
deleteUser: typeof deleteUser;
|
||||||
|
150
dist/index.js
vendored
150
dist/index.js
vendored
@ -1,117 +1,113 @@
|
|||||||
"use strict";
|
import get from "./package-shared/actions/get";
|
||||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
import post from "./package-shared/actions/post";
|
||||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
import getSchema from "./package-shared/actions/get-schema";
|
||||||
};
|
import createUser from "./package-shared/actions/users/add-user";
|
||||||
Object.defineProperty(exports, "__esModule", { value: true });
|
import updateUser from "./package-shared/actions/users/update-user";
|
||||||
const get_1 = __importDefault(require("./package-shared/actions/get"));
|
import loginUser from "./package-shared/actions/users/login-user";
|
||||||
const post_1 = __importDefault(require("./package-shared/actions/post"));
|
import sendEmailCode from "./package-shared/actions/users/send-email-code";
|
||||||
const get_schema_1 = __importDefault(require("./package-shared/actions/get-schema"));
|
import logoutUser from "./package-shared/actions/users/logout-user";
|
||||||
const upload_image_1 = __importDefault(require("./package-shared/actions/upload-image"));
|
import userAuth from "./package-shared/actions/users/user-auth";
|
||||||
const upload_file_1 = __importDefault(require("./package-shared/actions/upload-file"));
|
import reAuthUser from "./package-shared/actions/users/reauth-user";
|
||||||
const delete_file_1 = __importDefault(require("./package-shared/actions/delete-file"));
|
import getUser from "./package-shared/actions/users/get-user";
|
||||||
const add_user_1 = __importDefault(require("./package-shared/actions/users/add-user"));
|
import loginWithGoogle from "./package-shared/actions/users/social/google-auth";
|
||||||
const update_user_1 = __importDefault(require("./package-shared/actions/users/update-user"));
|
import loginWithGithub from "./package-shared/actions/users/social/github-auth";
|
||||||
const login_user_1 = __importDefault(require("./package-shared/actions/users/login-user"));
|
import getToken from "./package-shared/actions/users/get-token";
|
||||||
const send_email_code_1 = __importDefault(require("./package-shared/actions/users/send-email-code"));
|
import validateToken from "./package-shared/actions/users/validate-token";
|
||||||
const logout_user_1 = __importDefault(require("./package-shared/actions/users/logout-user"));
|
import datasquirelClient from "./client";
|
||||||
const user_auth_1 = __importDefault(require("./package-shared/actions/users/user-auth"));
|
import sqlGenerator from "./package-shared/functions/dsql/sql/sql-generator";
|
||||||
const reauth_user_1 = __importDefault(require("./package-shared/actions/users/reauth-user"));
|
import sqlInsertGenerator from "./package-shared/functions/dsql/sql/sql-insert-generator";
|
||||||
const get_user_1 = __importDefault(require("./package-shared/actions/users/get-user"));
|
import sqlDeleteGenerator from "./package-shared/functions/dsql/sql/sql-delete-generator";
|
||||||
const google_auth_1 = __importDefault(require("./package-shared/actions/users/social/google-auth"));
|
import trimSql from "./package-shared/utils/trim-sql";
|
||||||
const github_auth_1 = __importDefault(require("./package-shared/actions/users/social/github-auth"));
|
import parseCookies from "./package-shared/utils/backend/parseCookies";
|
||||||
const get_token_1 = __importDefault(require("./package-shared/actions/users/get-token"));
|
import connDbHandler from "./package-shared/utils/db/conn-db-handler";
|
||||||
const validate_token_1 = __importDefault(require("./package-shared/actions/users/validate-token"));
|
import encrypt from "./package-shared/functions/dsql/encrypt";
|
||||||
const client_1 = __importDefault(require("./client"));
|
import decrypt from "./package-shared/functions/dsql/decrypt";
|
||||||
const sql_generator_1 = __importDefault(require("./package-shared/functions/dsql/sql/sql-generator"));
|
import hashPassword from "./package-shared/functions/dsql/hashPassword";
|
||||||
const sql_insert_generator_1 = __importDefault(require("./package-shared/functions/dsql/sql/sql-insert-generator"));
|
import validateTempEmailCode from "./package-shared/actions/users/validate-temp-email-code";
|
||||||
const sql_delete_generator_1 = __importDefault(require("./package-shared/functions/dsql/sql/sql-delete-generator"));
|
import deleteUser from "./package-shared/actions/users/delete-user";
|
||||||
const trim_sql_1 = __importDefault(require("./package-shared/utils/trim-sql"));
|
import dsqlCrud from "./package-shared/utils/data-fetching/crud";
|
||||||
const parseCookies_1 = __importDefault(require("./package-shared/utils/backend/parseCookies"));
|
import dsqlMethodCrud from "./package-shared/utils/data-fetching/method-crud";
|
||||||
const conn_db_handler_1 = __importDefault(require("./package-shared/utils/db/conn-db-handler"));
|
import debugLog from "./package-shared/utils/logging/debug-log";
|
||||||
const encrypt_1 = __importDefault(require("./package-shared/functions/dsql/encrypt"));
|
import parseEnv from "./package-shared/utils/parse-env";
|
||||||
const decrypt_1 = __importDefault(require("./package-shared/functions/dsql/decrypt"));
|
import crud from "./package-shared/api/crud";
|
||||||
const hashPassword_1 = __importDefault(require("./package-shared/functions/dsql/hashPassword"));
|
import media from "./package-shared/api/media";
|
||||||
const validate_temp_email_code_1 = __importDefault(require("./package-shared/actions/users/validate-temp-email-code"));
|
|
||||||
const delete_user_1 = __importDefault(require("./package-shared/actions/users/delete-user"));
|
|
||||||
const crud_1 = __importDefault(require("./package-shared/utils/data-fetching/crud"));
|
|
||||||
const method_crud_1 = __importDefault(require("./package-shared/utils/data-fetching/method-crud"));
|
|
||||||
const debug_log_1 = __importDefault(require("./package-shared/utils/logging/debug-log"));
|
|
||||||
const parse_env_1 = __importDefault(require("./package-shared/utils/parse-env"));
|
|
||||||
/**
|
/**
|
||||||
* User Functions Object
|
* User Functions Object
|
||||||
*/
|
*/
|
||||||
const user = {
|
const user = {
|
||||||
createUser: add_user_1.default,
|
createUser: createUser,
|
||||||
deleteUser: delete_user_1.default,
|
deleteUser,
|
||||||
loginUser: login_user_1.default,
|
loginUser: loginUser,
|
||||||
sendEmailCode: send_email_code_1.default,
|
sendEmailCode: sendEmailCode,
|
||||||
logoutUser: logout_user_1.default,
|
logoutUser: logoutUser,
|
||||||
userAuth: user_auth_1.default,
|
userAuth: userAuth,
|
||||||
reAuthUser: reauth_user_1.default,
|
reAuthUser: reAuthUser,
|
||||||
updateUser: update_user_1.default,
|
updateUser: updateUser,
|
||||||
getUser: get_user_1.default,
|
getUser: getUser,
|
||||||
getToken: get_token_1.default,
|
getToken: getToken,
|
||||||
validateToken: validate_token_1.default,
|
validateToken: validateToken,
|
||||||
validateTempEmailCode: validate_temp_email_code_1.default,
|
validateTempEmailCode,
|
||||||
social: {
|
social: {
|
||||||
loginWithGoogle: google_auth_1.default,
|
loginWithGoogle: loginWithGoogle,
|
||||||
loginWithGithub: github_auth_1.default,
|
loginWithGithub: loginWithGithub,
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
/**
|
/**
|
||||||
* Media Functions Object
|
* API Functions Object
|
||||||
*/
|
*/
|
||||||
const media = {
|
const api = {
|
||||||
uploadImage: upload_image_1.default,
|
crud,
|
||||||
uploadFile: upload_file_1.default,
|
media,
|
||||||
deleteFile: delete_file_1.default,
|
|
||||||
};
|
};
|
||||||
/**
|
/**
|
||||||
* SQL Utils
|
* SQL Utils
|
||||||
*/
|
*/
|
||||||
const sql = {
|
const sql = {
|
||||||
sqlGenerator: sql_generator_1.default,
|
sqlGenerator,
|
||||||
sqlInsertGenerator: sql_insert_generator_1.default,
|
sqlInsertGenerator,
|
||||||
sqlDeleteGenerator: sql_delete_generator_1.default,
|
sqlDeleteGenerator,
|
||||||
trim: trim_sql_1.default,
|
trim: trimSql,
|
||||||
};
|
};
|
||||||
/**
|
/**
|
||||||
* Main Export
|
* Main Export
|
||||||
*/
|
*/
|
||||||
const datasquirel = {
|
const datasquirel = {
|
||||||
|
/**
|
||||||
|
* API Actions
|
||||||
|
*/
|
||||||
|
api,
|
||||||
/**
|
/**
|
||||||
* Get Action
|
* Get Action
|
||||||
*/
|
*/
|
||||||
get: get_1.default,
|
get,
|
||||||
/**
|
/**
|
||||||
* Post Action
|
* Post Action
|
||||||
*/
|
*/
|
||||||
post: post_1.default,
|
post,
|
||||||
media,
|
|
||||||
user,
|
user,
|
||||||
getSchema: get_schema_1.default,
|
getSchema,
|
||||||
client: client_1.default,
|
client: datasquirelClient,
|
||||||
sql,
|
sql,
|
||||||
utils: {
|
utils: {
|
||||||
crypto: {
|
crypto: {
|
||||||
encrypt: encrypt_1.default,
|
encrypt,
|
||||||
decrypt: decrypt_1.default,
|
decrypt,
|
||||||
hashPassword: hashPassword_1.default,
|
hashPassword,
|
||||||
},
|
},
|
||||||
parseCookies: parseCookies_1.default,
|
parseCookies,
|
||||||
connDbHandler: conn_db_handler_1.default,
|
connDbHandler,
|
||||||
debugLog: debug_log_1.default,
|
debugLog,
|
||||||
parseEnv: parse_env_1.default,
|
parseEnv,
|
||||||
},
|
},
|
||||||
/**
|
/**
|
||||||
* Run Crud actions `get`, `insert`, `update`, `delete`
|
* Run Crud actions `get`, `insert`, `update`, `delete`
|
||||||
* @note *Requires global variables `DSQL_USE_LOCAL` and `DSQL_DB_CONN`
|
* @note *Requires global variables `DSQL_USE_LOCAL` and `DSQL_DB_CONN`
|
||||||
*/
|
*/
|
||||||
crud: crud_1.default,
|
crud: dsqlCrud,
|
||||||
/**
|
/**
|
||||||
* Run Crud based on request Methods `GET`, `POST`, `PUT`, `PATCH`
|
* Run Crud based on request Methods `GET`, `POST`, `PUT`, `PATCH`
|
||||||
* @note *Requires global variables `DSQL_USE_LOCAL` and `DSQL_DB_CONN`
|
* @note *Requires global variables `DSQL_USE_LOCAL` and `DSQL_DB_CONN`
|
||||||
*/
|
*/
|
||||||
methodCrud: method_crud_1.default,
|
methodCrud: dsqlMethodCrud,
|
||||||
};
|
};
|
||||||
exports.default = datasquirel;
|
export default datasquirel;
|
||||||
|
25
dist/package-shared/actions/delete-file.js
vendored
25
dist/package-shared/actions/delete-file.js
vendored
@ -1,25 +1,9 @@
|
|||||||
"use strict";
|
import grabHostNames from "../utils/grab-host-names";
|
||||||
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
|
* # Delete File via API
|
||||||
*/
|
*/
|
||||||
function deleteFile(_a) {
|
export default async function deleteFile({ key, url, user_id, }) {
|
||||||
return __awaiter(this, arguments, void 0, function* ({ key, url, user_id, }) {
|
const grabedHostNames = grabHostNames();
|
||||||
const grabedHostNames = (0, grab_host_names_1.default)();
|
|
||||||
const { host, port, scheme } = grabedHostNames;
|
const { host, port, scheme } = grabedHostNames;
|
||||||
try {
|
try {
|
||||||
/**
|
/**
|
||||||
@ -27,7 +11,7 @@ function deleteFile(_a) {
|
|||||||
*
|
*
|
||||||
* @description make a request to datasquirel.com
|
* @description make a request to datasquirel.com
|
||||||
*/
|
*/
|
||||||
const httpResponse = yield new Promise((resolve, reject) => {
|
const httpResponse = await new Promise((resolve, reject) => {
|
||||||
const reqPayload = JSON.stringify({ url: url });
|
const reqPayload = JSON.stringify({ url: url });
|
||||||
const httpsRequest = scheme.request({
|
const httpsRequest = scheme.request({
|
||||||
method: "POST",
|
method: "POST",
|
||||||
@ -72,5 +56,4 @@ function deleteFile(_a) {
|
|||||||
msg: error.message,
|
msg: error.message,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
@ -1,6 +1,3 @@
|
|||||||
"use strict";
|
export default function getCsrfHeaderName() {
|
||||||
Object.defineProperty(exports, "__esModule", { value: true });
|
|
||||||
exports.default = getCsrfHeaderName;
|
|
||||||
function getCsrfHeaderName() {
|
|
||||||
return "x-dsql-csrf-key";
|
return "x-dsql-csrf-key";
|
||||||
}
|
}
|
||||||
|
25
dist/package-shared/actions/get-schema.js
vendored
25
dist/package-shared/actions/get-schema.js
vendored
@ -1,32 +1,16 @@
|
|||||||
"use strict";
|
import grabHostNames from "../utils/grab-host-names";
|
||||||
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 *
|
* # Get Schema for Database, table, or field *
|
||||||
*/
|
*/
|
||||||
function getSchema(_a) {
|
export default async function getSchema({ key, database, field, table, user_id, env, }) {
|
||||||
return __awaiter(this, arguments, void 0, function* ({ key, database, field, table, user_id, env, }) {
|
const grabedHostNames = grabHostNames({ env });
|
||||||
const grabedHostNames = (0, grab_host_names_1.default)({ env });
|
|
||||||
const { host, port, scheme } = grabedHostNames;
|
const { host, port, scheme } = grabedHostNames;
|
||||||
/**
|
/**
|
||||||
* Make https request
|
* Make https request
|
||||||
*
|
*
|
||||||
* @description make a request to datasquirel.com
|
* @description make a request to datasquirel.com
|
||||||
*/
|
*/
|
||||||
const httpResponse = yield new Promise((resolve, reject) => {
|
const httpResponse = await new Promise((resolve, reject) => {
|
||||||
const queryObject = { database, field, table };
|
const queryObject = { database, field, table };
|
||||||
let query = Object.keys(queryObject)
|
let query = Object.keys(queryObject)
|
||||||
.filter((k) => queryObject[k])
|
.filter((k) => queryObject[k])
|
||||||
@ -65,5 +49,4 @@ function getSchema(_a) {
|
|||||||
.end();
|
.end();
|
||||||
});
|
});
|
||||||
return httpResponse;
|
return httpResponse;
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
49
dist/package-shared/actions/get.js
vendored
49
dist/package-shared/actions/get.js
vendored
@ -1,34 +1,18 @@
|
|||||||
"use strict";
|
import path from "path";
|
||||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
import fs from "fs";
|
||||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
import grabHostNames from "../utils/grab-host-names";
|
||||||
return new (P || (P = Promise))(function (resolve, reject) {
|
import apiGet from "../functions/api/query/get";
|
||||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
import serializeQuery from "../utils/serialize-query";
|
||||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
import apiGetGrabQueryAndValues from "../utils/grab-query-and-values";
|
||||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
import debugLog from "../utils/logging/debug-log";
|
||||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
||||||
});
|
|
||||||
};
|
|
||||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
||||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
||||||
};
|
|
||||||
Object.defineProperty(exports, "__esModule", { value: true });
|
|
||||||
exports.default = get;
|
|
||||||
const path_1 = __importDefault(require("path"));
|
|
||||||
const fs_1 = __importDefault(require("fs"));
|
|
||||||
const grab_host_names_1 = __importDefault(require("../utils/grab-host-names"));
|
|
||||||
const get_1 = __importDefault(require("../functions/api/query/get"));
|
|
||||||
const serialize_query_1 = __importDefault(require("../utils/serialize-query"));
|
|
||||||
const grab_query_and_values_1 = __importDefault(require("../utils/grab-query-and-values"));
|
|
||||||
const debug_log_1 = __importDefault(require("../utils/logging/debug-log"));
|
|
||||||
/**
|
/**
|
||||||
* # Make a get request to Datasquirel API
|
* # Make a get request to Datasquirel API
|
||||||
*/
|
*/
|
||||||
function get(_a) {
|
export default async function get({ key, db, query, queryValues, tableName, user_id, debug, forceLocal, }) {
|
||||||
return __awaiter(this, arguments, void 0, function* ({ key, db, query, queryValues, tableName, user_id, debug, forceLocal, }) {
|
const grabedHostNames = grabHostNames();
|
||||||
const grabedHostNames = (0, grab_host_names_1.default)();
|
|
||||||
const { host, port, scheme } = grabedHostNames;
|
const { host, port, scheme } = grabedHostNames;
|
||||||
function debugFn(log, label) {
|
function debugFn(log, label) {
|
||||||
(0, debug_log_1.default)({ log, addTime: true, title: "apiGet", label });
|
debugLog({ log, addTime: true, title: "apiGet", label });
|
||||||
}
|
}
|
||||||
/**
|
/**
|
||||||
* Check for local DB settings
|
* Check for local DB settings
|
||||||
@ -39,14 +23,14 @@ function get(_a) {
|
|||||||
if ((DSQL_DB_NAME === null || DSQL_DB_NAME === void 0 ? void 0 : DSQL_DB_NAME.match(/./)) && global.DSQL_USE_LOCAL) {
|
if ((DSQL_DB_NAME === null || DSQL_DB_NAME === void 0 ? void 0 : DSQL_DB_NAME.match(/./)) && global.DSQL_USE_LOCAL) {
|
||||||
let dbSchema;
|
let dbSchema;
|
||||||
try {
|
try {
|
||||||
const localDbSchemaPath = path_1.default.resolve(process.cwd(), "dsql.schema.json");
|
const localDbSchemaPath = path.resolve(process.cwd(), "dsql.schema.json");
|
||||||
dbSchema = JSON.parse(fs_1.default.readFileSync(localDbSchemaPath, "utf8"));
|
dbSchema = JSON.parse(fs.readFileSync(localDbSchemaPath, "utf8"));
|
||||||
}
|
}
|
||||||
catch (error) { }
|
catch (error) { }
|
||||||
if (debug) {
|
if (debug) {
|
||||||
debugFn("Running Locally ...");
|
debugFn("Running Locally ...");
|
||||||
}
|
}
|
||||||
return yield (0, get_1.default)({
|
return await apiGet({
|
||||||
dbFullName: DSQL_DB_NAME,
|
dbFullName: DSQL_DB_NAME,
|
||||||
query,
|
query,
|
||||||
queryValues,
|
queryValues,
|
||||||
@ -61,8 +45,8 @@ function get(_a) {
|
|||||||
*
|
*
|
||||||
* @description make a request to datasquirel.com
|
* @description make a request to datasquirel.com
|
||||||
*/
|
*/
|
||||||
const httpResponse = yield new Promise((resolve, reject) => {
|
const httpResponse = await new Promise((resolve, reject) => {
|
||||||
const queryAndValues = (0, grab_query_and_values_1.default)({
|
const queryAndValues = apiGetGrabQueryAndValues({
|
||||||
query,
|
query,
|
||||||
values: queryValues,
|
values: queryValues,
|
||||||
});
|
});
|
||||||
@ -76,7 +60,7 @@ function get(_a) {
|
|||||||
if (debug) {
|
if (debug) {
|
||||||
debugFn(queryObject, "queryObject");
|
debugFn(queryObject, "queryObject");
|
||||||
}
|
}
|
||||||
const queryString = (0, serialize_query_1.default)(Object.assign({}, queryObject));
|
const queryString = serializeQuery(Object.assign({}, queryObject));
|
||||||
if (debug) {
|
if (debug) {
|
||||||
debugFn(queryString, "queryString");
|
debugFn(queryString, "queryString");
|
||||||
}
|
}
|
||||||
@ -128,5 +112,4 @@ function get(_a) {
|
|||||||
.end();
|
.end();
|
||||||
});
|
});
|
||||||
return httpResponse;
|
return httpResponse;
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
45
dist/package-shared/actions/post.js
vendored
45
dist/package-shared/actions/post.js
vendored
@ -1,33 +1,17 @@
|
|||||||
"use strict";
|
|
||||||
// @ts-check
|
// @ts-check
|
||||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
import path from "path";
|
||||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
import fs from "fs";
|
||||||
return new (P || (P = Promise))(function (resolve, reject) {
|
import grabHostNames from "../utils/grab-host-names";
|
||||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
import apiPost from "../functions/api/query/post";
|
||||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
import debugLog from "../utils/logging/debug-log";
|
||||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
||||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
||||||
});
|
|
||||||
};
|
|
||||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
||||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
||||||
};
|
|
||||||
Object.defineProperty(exports, "__esModule", { value: true });
|
|
||||||
exports.default = post;
|
|
||||||
const path_1 = __importDefault(require("path"));
|
|
||||||
const fs_1 = __importDefault(require("fs"));
|
|
||||||
const grab_host_names_1 = __importDefault(require("../utils/grab-host-names"));
|
|
||||||
const post_1 = __importDefault(require("../functions/api/query/post"));
|
|
||||||
const debug_log_1 = __importDefault(require("../utils/logging/debug-log"));
|
|
||||||
/**
|
/**
|
||||||
* # Make a post request to Datasquirel API
|
* # Make a post request to Datasquirel API
|
||||||
*/
|
*/
|
||||||
function post(_a) {
|
export default async function post({ key, query, queryValues, database, tableName, user_id, forceLocal, debug, }) {
|
||||||
return __awaiter(this, arguments, void 0, function* ({ key, query, queryValues, database, tableName, user_id, forceLocal, debug, }) {
|
const grabedHostNames = grabHostNames();
|
||||||
const grabedHostNames = (0, grab_host_names_1.default)();
|
|
||||||
const { host, port, scheme } = grabedHostNames;
|
const { host, port, scheme } = grabedHostNames;
|
||||||
if (debug) {
|
if (debug) {
|
||||||
(0, debug_log_1.default)({
|
debugLog({
|
||||||
log: grabedHostNames,
|
log: grabedHostNames,
|
||||||
addTime: true,
|
addTime: true,
|
||||||
label: "grabedHostNames",
|
label: "grabedHostNames",
|
||||||
@ -47,18 +31,18 @@ function post(_a) {
|
|||||||
/** @type {import("../types").DSQL_DatabaseSchemaType | undefined} */
|
/** @type {import("../types").DSQL_DatabaseSchemaType | undefined} */
|
||||||
let dbSchema;
|
let dbSchema;
|
||||||
try {
|
try {
|
||||||
const localDbSchemaPath = path_1.default.resolve(process.cwd(), "dsql.schema.json");
|
const localDbSchemaPath = path.resolve(process.cwd(), "dsql.schema.json");
|
||||||
dbSchema = JSON.parse(fs_1.default.readFileSync(localDbSchemaPath, "utf8"));
|
dbSchema = JSON.parse(fs.readFileSync(localDbSchemaPath, "utf8"));
|
||||||
}
|
}
|
||||||
catch (error) { }
|
catch (error) { }
|
||||||
if (debug) {
|
if (debug) {
|
||||||
(0, debug_log_1.default)({
|
debugLog({
|
||||||
log: "Using Local DB ...",
|
log: "Using Local DB ...",
|
||||||
addTime: true,
|
addTime: true,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
return yield (0, post_1.default)({
|
return await apiPost({
|
||||||
dbFullName: DSQL_DB_NAME,
|
dbFullName: database || DSQL_DB_NAME,
|
||||||
query,
|
query,
|
||||||
dbSchema,
|
dbSchema,
|
||||||
queryValues,
|
queryValues,
|
||||||
@ -72,7 +56,7 @@ function post(_a) {
|
|||||||
*
|
*
|
||||||
* @description make a request to datasquirel.com
|
* @description make a request to datasquirel.com
|
||||||
*/
|
*/
|
||||||
const httpResponse = yield new Promise((resolve, reject) => {
|
const httpResponse = await new Promise((resolve, reject) => {
|
||||||
var _a;
|
var _a;
|
||||||
const reqPayloadString = JSON.stringify({
|
const reqPayloadString = JSON.stringify({
|
||||||
query,
|
query,
|
||||||
@ -145,5 +129,4 @@ function post(_a) {
|
|||||||
httpsRequest.end();
|
httpsRequest.end();
|
||||||
});
|
});
|
||||||
return httpResponse;
|
return httpResponse;
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
29
dist/package-shared/actions/upload-file.js
vendored
29
dist/package-shared/actions/upload-file.js
vendored
@ -1,26 +1,10 @@
|
|||||||
"use strict";
|
import grabHostNames from "../utils/grab-host-names";
|
||||||
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
|
* # Upload File via API
|
||||||
*/
|
*/
|
||||||
function uploadImage(_a) {
|
export default async function uploadImage({ key, payload, user_id, useDefault, }) {
|
||||||
return __awaiter(this, arguments, void 0, function* ({ key, payload, user_id, useDefault, }) {
|
var _a;
|
||||||
var _b;
|
const grabedHostNames = grabHostNames({ useDefault });
|
||||||
const grabedHostNames = (0, grab_host_names_1.default)({ useDefault });
|
|
||||||
const { host, port, scheme } = grabedHostNames;
|
const { host, port, scheme } = grabedHostNames;
|
||||||
try {
|
try {
|
||||||
/**
|
/**
|
||||||
@ -28,7 +12,7 @@ function uploadImage(_a) {
|
|||||||
*
|
*
|
||||||
* @description make a request to datasquirel.com
|
* @description make a request to datasquirel.com
|
||||||
*/
|
*/
|
||||||
const httpResponse = yield new Promise((resolve, reject) => {
|
const httpResponse = await new Promise((resolve, reject) => {
|
||||||
const reqPayload = JSON.stringify(payload);
|
const reqPayload = JSON.stringify(payload);
|
||||||
const httpsRequest = scheme.request({
|
const httpsRequest = scheme.request({
|
||||||
method: "POST",
|
method: "POST",
|
||||||
@ -67,12 +51,11 @@ function uploadImage(_a) {
|
|||||||
}
|
}
|
||||||
catch (error) {
|
catch (error) {
|
||||||
console.log("Error in uploading file: ", error.message);
|
console.log("Error in uploading file: ", error.message);
|
||||||
(_b = global.ERROR_CALLBACK) === null || _b === void 0 ? void 0 : _b.call(global, `Error Uploading File`, error);
|
(_a = global.ERROR_CALLBACK) === null || _a === void 0 ? void 0 : _a.call(global, `Error Uploading File`, error);
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
payload: null,
|
payload: null,
|
||||||
msg: error.message,
|
msg: error.message,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
29
dist/package-shared/actions/upload-image.js
vendored
29
dist/package-shared/actions/upload-image.js
vendored
@ -1,26 +1,10 @@
|
|||||||
"use strict";
|
import grabHostNames from "../utils/grab-host-names";
|
||||||
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
|
* # Upload Image via API
|
||||||
*/
|
*/
|
||||||
function uploadImage(_a) {
|
export default async function uploadImage({ key, payload, user_id, useDefault, }) {
|
||||||
return __awaiter(this, arguments, void 0, function* ({ key, payload, user_id, useDefault, }) {
|
var _a;
|
||||||
var _b;
|
const grabedHostNames = grabHostNames({ useDefault });
|
||||||
const grabedHostNames = (0, grab_host_names_1.default)({ useDefault });
|
|
||||||
const { host, port, scheme } = grabedHostNames;
|
const { host, port, scheme } = grabedHostNames;
|
||||||
try {
|
try {
|
||||||
/**
|
/**
|
||||||
@ -28,7 +12,7 @@ function uploadImage(_a) {
|
|||||||
*
|
*
|
||||||
* @description make a request to datasquirel.com
|
* @description make a request to datasquirel.com
|
||||||
*/
|
*/
|
||||||
const httpResponse = yield new Promise((resolve, reject) => {
|
const httpResponse = await new Promise((resolve, reject) => {
|
||||||
const reqPayload = JSON.stringify(payload);
|
const reqPayload = JSON.stringify(payload);
|
||||||
const httpsRequest = scheme.request({
|
const httpsRequest = scheme.request({
|
||||||
method: "POST",
|
method: "POST",
|
||||||
@ -67,12 +51,11 @@ function uploadImage(_a) {
|
|||||||
}
|
}
|
||||||
catch (error) {
|
catch (error) {
|
||||||
console.log("Error in uploading image: ", error.message);
|
console.log("Error in uploading image: ", error.message);
|
||||||
(_b = global.ERROR_CALLBACK) === null || _b === void 0 ? void 0 : _b.call(global, `Error Uploading Image`, error);
|
(_a = global.ERROR_CALLBACK) === null || _a === void 0 ? void 0 : _a.call(global, `Error Uploading Image`, error);
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
payload: null,
|
payload: null,
|
||||||
msg: error.message,
|
msg: error.message,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
37
dist/package-shared/actions/users/add-user.js
vendored
37
dist/package-shared/actions/users/add-user.js
vendored
@ -1,34 +1,18 @@
|
|||||||
"use strict";
|
import path from "path";
|
||||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
import fs from "fs";
|
||||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
import grabHostNames from "../../utils/grab-host-names";
|
||||||
return new (P || (P = Promise))(function (resolve, reject) {
|
import apiCreateUser from "../../functions/api/users/api-create-user";
|
||||||
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
|
* # Add User to Database
|
||||||
*/
|
*/
|
||||||
function addUser(_a) {
|
export default async function addUser({ key, payload, database, encryptionKey, user_id, apiUserId, }) {
|
||||||
return __awaiter(this, arguments, void 0, function* ({ key, payload, database, encryptionKey, user_id, apiUserId, }) {
|
|
||||||
/**
|
/**
|
||||||
* Check for local DB settings
|
* Check for local DB settings
|
||||||
*
|
*
|
||||||
* @description Look for local db settings in `.env` file and by pass the http request if available
|
* @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 { 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 grabedHostNames = grabHostNames();
|
||||||
const { host, port, scheme } = grabedHostNames;
|
const { host, port, scheme } = grabedHostNames;
|
||||||
if ((DSQL_DB_HOST === null || DSQL_DB_HOST === void 0 ? void 0 : DSQL_DB_HOST.match(/./)) &&
|
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_USERNAME === null || DSQL_DB_USERNAME === void 0 ? void 0 : DSQL_DB_USERNAME.match(/./)) &&
|
||||||
@ -38,11 +22,11 @@ function addUser(_a) {
|
|||||||
/** @type {import("../../types").DSQL_DatabaseSchemaType | undefined} */
|
/** @type {import("../../types").DSQL_DatabaseSchemaType | undefined} */
|
||||||
let dbSchema;
|
let dbSchema;
|
||||||
try {
|
try {
|
||||||
const localDbSchemaPath = path_1.default.resolve(process.cwd(), "dsql.schema.json");
|
const localDbSchemaPath = path.resolve(process.cwd(), "dsql.schema.json");
|
||||||
dbSchema = JSON.parse(fs_1.default.readFileSync(localDbSchemaPath, "utf8"));
|
dbSchema = JSON.parse(fs.readFileSync(localDbSchemaPath, "utf8"));
|
||||||
}
|
}
|
||||||
catch (error) { }
|
catch (error) { }
|
||||||
return yield (0, api_create_user_1.default)({
|
return await apiCreateUser({
|
||||||
database: DSQL_DB_NAME,
|
database: DSQL_DB_NAME,
|
||||||
encryptionKey,
|
encryptionKey,
|
||||||
payload,
|
payload,
|
||||||
@ -54,7 +38,7 @@ function addUser(_a) {
|
|||||||
*
|
*
|
||||||
* @description make a request to datasquirel.com
|
* @description make a request to datasquirel.com
|
||||||
*/
|
*/
|
||||||
const httpResponse = yield new Promise((resolve, reject) => {
|
const httpResponse = await new Promise((resolve, reject) => {
|
||||||
const reqPayload = JSON.stringify({
|
const reqPayload = JSON.stringify({
|
||||||
payload,
|
payload,
|
||||||
database,
|
database,
|
||||||
@ -94,5 +78,4 @@ function addUser(_a) {
|
|||||||
httpsRequest.end();
|
httpsRequest.end();
|
||||||
});
|
});
|
||||||
return httpResponse;
|
return httpResponse;
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
37
dist/package-shared/actions/users/delete-user.js
vendored
37
dist/package-shared/actions/users/delete-user.js
vendored
@ -1,34 +1,18 @@
|
|||||||
"use strict";
|
import path from "path";
|
||||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
import fs from "fs";
|
||||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
import grabHostNames from "../../utils/grab-host-names";
|
||||||
return new (P || (P = Promise))(function (resolve, reject) {
|
import apiDeleteUser from "../../functions/api/users/api-delete-user";
|
||||||
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
|
* # Update User
|
||||||
*/
|
*/
|
||||||
function deleteUser(_a) {
|
export default async function deleteUser({ key, database, user_id, deletedUserId, }) {
|
||||||
return __awaiter(this, arguments, void 0, function* ({ key, database, user_id, deletedUserId, }) {
|
|
||||||
/**
|
/**
|
||||||
* Check for local DB settings
|
* Check for local DB settings
|
||||||
*
|
*
|
||||||
* @description Look for local db settings in `.env` file and by pass the http request if available
|
* @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 { DSQL_DB_HOST, DSQL_DB_USERNAME, DSQL_DB_PASSWORD, DSQL_DB_NAME } = process.env;
|
||||||
const grabedHostNames = (0, grab_host_names_1.default)();
|
const grabedHostNames = grabHostNames();
|
||||||
const { host, port, scheme } = grabedHostNames;
|
const { host, port, scheme } = grabedHostNames;
|
||||||
if ((DSQL_DB_HOST === null || DSQL_DB_HOST === void 0 ? void 0 : DSQL_DB_HOST.match(/./)) &&
|
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_USERNAME === null || DSQL_DB_USERNAME === void 0 ? void 0 : DSQL_DB_USERNAME.match(/./)) &&
|
||||||
@ -38,11 +22,11 @@ function deleteUser(_a) {
|
|||||||
/** @type {import("../../types").DSQL_DatabaseSchemaType | undefined} */
|
/** @type {import("../../types").DSQL_DatabaseSchemaType | undefined} */
|
||||||
let dbSchema;
|
let dbSchema;
|
||||||
try {
|
try {
|
||||||
const localDbSchemaPath = path_1.default.resolve(process.cwd(), "dsql.schema.json");
|
const localDbSchemaPath = path.resolve(process.cwd(), "dsql.schema.json");
|
||||||
dbSchema = JSON.parse(fs_1.default.readFileSync(localDbSchemaPath, "utf8"));
|
dbSchema = JSON.parse(fs.readFileSync(localDbSchemaPath, "utf8"));
|
||||||
}
|
}
|
||||||
catch (error) { }
|
catch (error) { }
|
||||||
return yield (0, api_delete_user_1.default)({
|
return await apiDeleteUser({
|
||||||
dbFullName: DSQL_DB_NAME,
|
dbFullName: DSQL_DB_NAME,
|
||||||
deletedUserId,
|
deletedUserId,
|
||||||
});
|
});
|
||||||
@ -52,7 +36,7 @@ function deleteUser(_a) {
|
|||||||
*
|
*
|
||||||
* @description make a request to datasquirel.com
|
* @description make a request to datasquirel.com
|
||||||
*/
|
*/
|
||||||
const httpResponse = (yield new Promise((resolve, reject) => {
|
const httpResponse = (await new Promise((resolve, reject) => {
|
||||||
const reqPayload = JSON.stringify({
|
const reqPayload = JSON.stringify({
|
||||||
database,
|
database,
|
||||||
deletedUserId,
|
deletedUserId,
|
||||||
@ -91,5 +75,4 @@ function deleteUser(_a) {
|
|||||||
httpsRequest.end();
|
httpsRequest.end();
|
||||||
}));
|
}));
|
||||||
return httpResponse;
|
return httpResponse;
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
20
dist/package-shared/actions/users/get-token.js
vendored
20
dist/package-shared/actions/users/get-token.js
vendored
@ -1,19 +1,13 @@
|
|||||||
"use strict";
|
import decrypt from "../../functions/dsql/decrypt";
|
||||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
import getAuthCookieNames from "../../functions/backend/cookies/get-auth-cookie-names";
|
||||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
import parseCookies from "../../utils/backend/parseCookies";
|
||||||
};
|
|
||||||
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
|
* Get just the access token for user
|
||||||
* ==============================================================================
|
* ==============================================================================
|
||||||
* @description This Function takes in a request object and returns a user token
|
* @description This Function takes in a request object and returns a user token
|
||||||
* string and csrf token string
|
* string and csrf token string
|
||||||
*/
|
*/
|
||||||
function getToken({ request, encryptionKey, encryptionSalt, cookieString, }) {
|
export default function getToken({ request, encryptionKey, encryptionSalt, cookieString, }) {
|
||||||
var _a;
|
var _a;
|
||||||
try {
|
try {
|
||||||
/**
|
/**
|
||||||
@ -21,8 +15,8 @@ function getToken({ request, encryptionKey, encryptionSalt, cookieString, }) {
|
|||||||
*
|
*
|
||||||
* @description Grab the payload
|
* @description Grab the payload
|
||||||
*/
|
*/
|
||||||
const cookies = (0, parseCookies_1.default)({ request, cookieString });
|
const cookies = parseCookies({ request, cookieString });
|
||||||
const keynames = (0, get_auth_cookie_names_1.default)();
|
const keynames = getAuthCookieNames();
|
||||||
const authKeyName = keynames.keyCookieName;
|
const authKeyName = keynames.keyCookieName;
|
||||||
const csrfName = keynames.csrfCookieName;
|
const csrfName = keynames.csrfCookieName;
|
||||||
const key = cookies[authKeyName];
|
const key = cookies[authKeyName];
|
||||||
@ -32,7 +26,7 @@ function getToken({ request, encryptionKey, encryptionSalt, cookieString, }) {
|
|||||||
*
|
*
|
||||||
* @description Grab the payload
|
* @description Grab the payload
|
||||||
*/
|
*/
|
||||||
let userPayload = (0, decrypt_1.default)({
|
let userPayload = decrypt({
|
||||||
encryptedString: key,
|
encryptedString: key,
|
||||||
encryptionKey,
|
encryptionKey,
|
||||||
encryptionSalt,
|
encryptionSalt,
|
||||||
|
37
dist/package-shared/actions/users/get-user.js
vendored
37
dist/package-shared/actions/users/get-user.js
vendored
@ -1,27 +1,11 @@
|
|||||||
"use strict";
|
import path from "path";
|
||||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
import fs from "fs";
|
||||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
import grabHostNames from "../../utils/grab-host-names";
|
||||||
return new (P || (P = Promise))(function (resolve, reject) {
|
import apiGetUser from "../../functions/api/users/api-get-user";
|
||||||
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
|
* # Get User
|
||||||
*/
|
*/
|
||||||
function getUser(_a) {
|
export default async function getUser({ key, userId, database, fields, apiUserId, }) {
|
||||||
return __awaiter(this, arguments, void 0, function* ({ key, userId, database, fields, apiUserId, }) {
|
|
||||||
/**
|
/**
|
||||||
* Initialize
|
* Initialize
|
||||||
*/
|
*/
|
||||||
@ -47,7 +31,7 @@ function getUser(_a) {
|
|||||||
database,
|
database,
|
||||||
fields: [...new Set(updatedFields)],
|
fields: [...new Set(updatedFields)],
|
||||||
});
|
});
|
||||||
const grabedHostNames = (0, grab_host_names_1.default)();
|
const grabedHostNames = grabHostNames();
|
||||||
const { host, port, scheme } = grabedHostNames;
|
const { host, port, scheme } = grabedHostNames;
|
||||||
/**
|
/**
|
||||||
* Check for local DB settings
|
* Check for local DB settings
|
||||||
@ -63,11 +47,11 @@ function getUser(_a) {
|
|||||||
/** @type {import("../../types").DSQL_DatabaseSchemaType | undefined} */
|
/** @type {import("../../types").DSQL_DatabaseSchemaType | undefined} */
|
||||||
let dbSchema;
|
let dbSchema;
|
||||||
try {
|
try {
|
||||||
const localDbSchemaPath = path_1.default.resolve(process.cwd(), "dsql.schema.json");
|
const localDbSchemaPath = path.resolve(process.cwd(), "dsql.schema.json");
|
||||||
dbSchema = JSON.parse(fs_1.default.readFileSync(localDbSchemaPath, "utf8"));
|
dbSchema = JSON.parse(fs.readFileSync(localDbSchemaPath, "utf8"));
|
||||||
}
|
}
|
||||||
catch (error) { }
|
catch (error) { }
|
||||||
return yield (0, api_get_user_1.default)({
|
return await apiGetUser({
|
||||||
userId,
|
userId,
|
||||||
fields: [...new Set(updatedFields)],
|
fields: [...new Set(updatedFields)],
|
||||||
dbFullName: DSQL_DB_NAME,
|
dbFullName: DSQL_DB_NAME,
|
||||||
@ -78,7 +62,7 @@ function getUser(_a) {
|
|||||||
*
|
*
|
||||||
* @description make a request to datasquirel.com
|
* @description make a request to datasquirel.com
|
||||||
*/
|
*/
|
||||||
const httpResponse = yield new Promise((resolve, reject) => {
|
const httpResponse = await new Promise((resolve, reject) => {
|
||||||
const httpsRequest = scheme.request({
|
const httpsRequest = scheme.request({
|
||||||
method: "POST",
|
method: "POST",
|
||||||
headers: {
|
headers: {
|
||||||
@ -116,5 +100,4 @@ function getUser(_a) {
|
|||||||
/** ********************************************** */
|
/** ********************************************** */
|
||||||
/** ********************************************** */
|
/** ********************************************** */
|
||||||
return httpResponse;
|
return httpResponse;
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
@ -1,37 +1,5 @@
|
|||||||
import http from "http";
|
import { APILoginFunctionReturn, LoginUserParam } from "../../types";
|
||||||
import { APILoginFunctionReturn } from "../../types";
|
|
||||||
type Param = {
|
|
||||||
key?: string;
|
|
||||||
database: string;
|
|
||||||
payload: {
|
|
||||||
email?: string;
|
|
||||||
username?: string;
|
|
||||||
password?: string;
|
|
||||||
};
|
|
||||||
additionalFields?: string[];
|
|
||||||
request?: http.IncomingMessage & {
|
|
||||||
[s: string]: any;
|
|
||||||
};
|
|
||||||
response?: http.ServerResponse & {
|
|
||||||
[s: string]: any;
|
|
||||||
};
|
|
||||||
encryptionKey?: string;
|
|
||||||
encryptionSalt?: string;
|
|
||||||
email_login?: boolean;
|
|
||||||
email_login_code?: string;
|
|
||||||
temp_code_field?: string;
|
|
||||||
token?: boolean;
|
|
||||||
user_id?: string | number;
|
|
||||||
skipPassword?: boolean;
|
|
||||||
debug?: boolean;
|
|
||||||
skipWriteAuthFile?: boolean;
|
|
||||||
apiUserID?: string | number;
|
|
||||||
dbUserId?: string | number;
|
|
||||||
cleanupTokens?: boolean;
|
|
||||||
secureCookie?: boolean;
|
|
||||||
};
|
|
||||||
/**
|
/**
|
||||||
* # Login A user
|
* # Login A user
|
||||||
*/
|
*/
|
||||||
export default function loginUser({ key, payload, database, additionalFields, response, encryptionKey, encryptionSalt, email_login, email_login_code, temp_code_field, token, user_id, skipPassword, apiUserID, skipWriteAuthFile, dbUserId, debug, cleanupTokens, secureCookie, request, }: Param): Promise<APILoginFunctionReturn>;
|
export default function loginUser({ key, payload, database, additionalFields, response, encryptionKey, encryptionSalt, email_login, email_login_code, temp_code_field, token, user_id, skipPassword, apiUserID, skipWriteAuthFile, dbUserId, debug, cleanupTokens, secureCookie, request, }: LoginUserParam): Promise<APILoginFunctionReturn>;
|
||||||
export {};
|
|
||||||
|
65
dist/package-shared/actions/users/login-user.js
vendored
65
dist/package-shared/actions/users/login-user.js
vendored
@ -1,36 +1,20 @@
|
|||||||
"use strict";
|
import fs from "fs";
|
||||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
import path from "path";
|
||||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
import encrypt from "../../functions/dsql/encrypt";
|
||||||
return new (P || (P = Promise))(function (resolve, reject) {
|
import grabHostNames from "../../utils/grab-host-names";
|
||||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
import apiLoginUser from "../../functions/api/users/api-login";
|
||||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
import getAuthCookieNames from "../../functions/backend/cookies/get-auth-cookie-names";
|
||||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
import { writeAuthFile } from "../../functions/backend/auth/write-auth-files";
|
||||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
import debugLog from "../../utils/logging/debug-log";
|
||||||
});
|
import grabCookieExpiryDate from "../../utils/grab-cookie-expirt-date";
|
||||||
};
|
|
||||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
||||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
||||||
};
|
|
||||||
Object.defineProperty(exports, "__esModule", { value: true });
|
|
||||||
exports.default = loginUser;
|
|
||||||
const fs_1 = __importDefault(require("fs"));
|
|
||||||
const path_1 = __importDefault(require("path"));
|
|
||||||
const encrypt_1 = __importDefault(require("../../functions/dsql/encrypt"));
|
|
||||||
const grab_host_names_1 = __importDefault(require("../../utils/grab-host-names"));
|
|
||||||
const api_login_1 = __importDefault(require("../../functions/api/users/api-login"));
|
|
||||||
const get_auth_cookie_names_1 = __importDefault(require("../../functions/backend/cookies/get-auth-cookie-names"));
|
|
||||||
const write_auth_files_1 = require("../../functions/backend/auth/write-auth-files");
|
|
||||||
const debug_log_1 = __importDefault(require("../../utils/logging/debug-log"));
|
|
||||||
const grab_cookie_expirt_date_1 = __importDefault(require("../../utils/grab-cookie-expirt-date"));
|
|
||||||
/**
|
/**
|
||||||
* # Login A user
|
* # Login A user
|
||||||
*/
|
*/
|
||||||
function loginUser(_a) {
|
export default async function loginUser({ key, payload, database, additionalFields, response, encryptionKey, encryptionSalt, email_login, email_login_code, temp_code_field, token, user_id, skipPassword, apiUserID, skipWriteAuthFile, dbUserId, debug, cleanupTokens, secureCookie, request, }) {
|
||||||
return __awaiter(this, arguments, void 0, function* ({ key, payload, database, additionalFields, response, encryptionKey, encryptionSalt, email_login, email_login_code, temp_code_field, token, user_id, skipPassword, apiUserID, skipWriteAuthFile, dbUserId, debug, cleanupTokens, secureCookie, request, }) {
|
var _a, _b, _c;
|
||||||
var _b, _c, _d;
|
const grabedHostNames = grabHostNames({ userId: user_id || apiUserID });
|
||||||
const grabedHostNames = (0, grab_host_names_1.default)({ userId: user_id || apiUserID });
|
|
||||||
const { host, port, scheme } = grabedHostNames;
|
const { host, port, scheme } = grabedHostNames;
|
||||||
const COOKIE_EXPIRY_DATE = (0, grab_cookie_expirt_date_1.default)();
|
const COOKIE_EXPIRY_DATE = grabCookieExpiryDate();
|
||||||
const defaultTempLoginFieldName = "temp_login_code";
|
const defaultTempLoginFieldName = "temp_login_code";
|
||||||
const emailLoginTempCodeFieldName = email_login
|
const emailLoginTempCodeFieldName = email_login
|
||||||
? temp_code_field
|
? temp_code_field
|
||||||
@ -40,7 +24,7 @@ function loginUser(_a) {
|
|||||||
const finalEncryptionKey = encryptionKey || process.env.DSQL_ENCRYPTION_PASSWORD;
|
const finalEncryptionKey = encryptionKey || process.env.DSQL_ENCRYPTION_PASSWORD;
|
||||||
const finalEncryptionSalt = encryptionSalt || process.env.DSQL_ENCRYPTION_SALT;
|
const finalEncryptionSalt = encryptionSalt || process.env.DSQL_ENCRYPTION_SALT;
|
||||||
function debugFn(log, label) {
|
function debugFn(log, label) {
|
||||||
(0, debug_log_1.default)({ log, addTime: true, title: "loginUser", label });
|
debugLog({ log, addTime: true, title: "loginUser", label });
|
||||||
}
|
}
|
||||||
if (!(finalEncryptionKey === null || finalEncryptionKey === void 0 ? void 0 : finalEncryptionKey.match(/.{8,}/))) {
|
if (!(finalEncryptionKey === null || finalEncryptionKey === void 0 ? void 0 : finalEncryptionKey.match(/.{8,}/))) {
|
||||||
console.log("Encryption key is invalid");
|
console.log("Encryption key is invalid");
|
||||||
@ -90,12 +74,12 @@ function loginUser(_a) {
|
|||||||
global.DSQL_USE_LOCAL) {
|
global.DSQL_USE_LOCAL) {
|
||||||
let dbSchema;
|
let dbSchema;
|
||||||
try {
|
try {
|
||||||
const localDbSchemaPath = path_1.default.resolve(process.cwd(), "dsql.schema.json");
|
const localDbSchemaPath = path.resolve(process.cwd(), "dsql.schema.json");
|
||||||
dbSchema = JSON.parse(fs_1.default.readFileSync(localDbSchemaPath, "utf8"));
|
dbSchema = JSON.parse(fs.readFileSync(localDbSchemaPath, "utf8"));
|
||||||
}
|
}
|
||||||
catch (error) { }
|
catch (error) { }
|
||||||
httpResponse = yield (0, api_login_1.default)({
|
httpResponse = await apiLoginUser({
|
||||||
database: process.env.DSQL_DB_NAME || "",
|
database: database || process.env.DSQL_DB_NAME || "",
|
||||||
email: payload.email,
|
email: payload.email,
|
||||||
username: payload.username,
|
username: payload.username,
|
||||||
password: payload.password,
|
password: payload.password,
|
||||||
@ -111,7 +95,7 @@ function loginUser(_a) {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
httpResponse = yield new Promise((resolve, reject) => {
|
httpResponse = await new Promise((resolve, reject) => {
|
||||||
const reqPayload = {
|
const reqPayload = {
|
||||||
encryptionKey: finalEncryptionKey,
|
encryptionKey: finalEncryptionKey,
|
||||||
payload,
|
payload,
|
||||||
@ -157,7 +141,7 @@ function loginUser(_a) {
|
|||||||
debugFn(httpResponse, "httpResponse");
|
debugFn(httpResponse, "httpResponse");
|
||||||
}
|
}
|
||||||
if (httpResponse === null || httpResponse === void 0 ? void 0 : httpResponse.success) {
|
if (httpResponse === null || httpResponse === void 0 ? void 0 : httpResponse.success) {
|
||||||
let encryptedPayload = (0, encrypt_1.default)({
|
let encryptedPayload = encrypt({
|
||||||
data: JSON.stringify(httpResponse.payload),
|
data: JSON.stringify(httpResponse.payload),
|
||||||
encryptionKey: finalEncryptionKey,
|
encryptionKey: finalEncryptionKey,
|
||||||
encryptionSalt: finalEncryptionSalt,
|
encryptionSalt: finalEncryptionSalt,
|
||||||
@ -167,14 +151,14 @@ function loginUser(_a) {
|
|||||||
httpResponse["token"] = encryptedPayload;
|
httpResponse["token"] = encryptedPayload;
|
||||||
}
|
}
|
||||||
catch (error) {
|
catch (error) {
|
||||||
(_b = global.ERROR_CALLBACK) === null || _b === void 0 ? void 0 : _b.call(global, `Login User HTTP Response Error`, error);
|
(_a = global.ERROR_CALLBACK) === null || _a === void 0 ? void 0 : _a.call(global, `Login User HTTP Response Error`, error);
|
||||||
}
|
}
|
||||||
const cookieNames = (0, get_auth_cookie_names_1.default)({
|
const cookieNames = getAuthCookieNames({
|
||||||
database,
|
database,
|
||||||
userId: grabedHostNames.user_id,
|
userId: grabedHostNames.user_id,
|
||||||
});
|
});
|
||||||
if (httpResponse.csrf && !skipWriteAuthFile) {
|
if (httpResponse.csrf && !skipWriteAuthFile) {
|
||||||
(0, write_auth_files_1.writeAuthFile)(httpResponse.csrf, JSON.stringify(httpResponse.payload), cleanupTokens && ((_c = httpResponse.payload) === null || _c === void 0 ? void 0 : _c.id)
|
writeAuthFile(httpResponse.csrf, JSON.stringify(httpResponse.payload), cleanupTokens && ((_b = httpResponse.payload) === null || _b === void 0 ? void 0 : _b.id)
|
||||||
? { userId: httpResponse.payload.id }
|
? { userId: httpResponse.payload.id }
|
||||||
: undefined);
|
: undefined);
|
||||||
}
|
}
|
||||||
@ -189,12 +173,11 @@ function loginUser(_a) {
|
|||||||
}
|
}
|
||||||
response === null || response === void 0 ? void 0 : response.setHeader("Set-Cookie", [
|
response === null || response === void 0 ? void 0 : response.setHeader("Set-Cookie", [
|
||||||
`${authKeyName}=${encryptedPayload};samesite=strict;path=/;HttpOnly=true;Expires=${COOKIE_EXPIRY_DATE}${secureCookie ? ";Secure=true" : ""}`,
|
`${authKeyName}=${encryptedPayload};samesite=strict;path=/;HttpOnly=true;Expires=${COOKIE_EXPIRY_DATE}${secureCookie ? ";Secure=true" : ""}`,
|
||||||
`${csrfName}=${(_d = httpResponse.payload) === null || _d === void 0 ? void 0 : _d.csrf_k};samesite=strict;path=/;HttpOnly=true;Expires=${COOKIE_EXPIRY_DATE}`,
|
`${csrfName}=${(_c = httpResponse.payload) === null || _c === void 0 ? void 0 : _c.csrf_k};samesite=strict;path=/;HttpOnly=true;Expires=${COOKIE_EXPIRY_DATE}`,
|
||||||
]);
|
]);
|
||||||
if (debug) {
|
if (debug) {
|
||||||
debugFn("Response Sent!");
|
debugFn("Response Sent!");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return httpResponse;
|
return httpResponse;
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
38
dist/package-shared/actions/users/logout-user.js
vendored
38
dist/package-shared/actions/users/logout-user.js
vendored
@ -1,20 +1,14 @@
|
|||||||
"use strict";
|
import getAuthCookieNames from "../../functions/backend/cookies/get-auth-cookie-names";
|
||||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
import decrypt from "../../functions/dsql/decrypt";
|
||||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
import EJSON from "../../utils/ejson";
|
||||||
};
|
import { deleteAuthFile } from "../../functions/backend/auth/write-auth-files";
|
||||||
Object.defineProperty(exports, "__esModule", { value: true });
|
import parseCookies from "../../utils/backend/parseCookies";
|
||||||
exports.default = logoutUser;
|
import grabHostNames from "../../utils/grab-host-names";
|
||||||
const get_auth_cookie_names_1 = __importDefault(require("../../functions/backend/cookies/get-auth-cookie-names"));
|
import debugLog from "../../utils/logging/debug-log";
|
||||||
const decrypt_1 = __importDefault(require("../../functions/dsql/decrypt"));
|
|
||||||
const ejson_1 = __importDefault(require("../../utils/ejson"));
|
|
||||||
const write_auth_files_1 = require("../../functions/backend/auth/write-auth-files");
|
|
||||||
const parseCookies_1 = __importDefault(require("../../utils/backend/parseCookies"));
|
|
||||||
const grab_host_names_1 = __importDefault(require("../../utils/grab-host-names"));
|
|
||||||
const debug_log_1 = __importDefault(require("../../utils/logging/debug-log"));
|
|
||||||
/**
|
/**
|
||||||
* # Logout user
|
* # Logout user
|
||||||
*/
|
*/
|
||||||
function logoutUser({ response, database, dsqlUserId, encryptedUserString, request, cookieString, debug, }) {
|
export default function logoutUser({ response, database, dsqlUserId, encryptedUserString, request, cookieString, debug, }) {
|
||||||
var _a;
|
var _a;
|
||||||
/**
|
/**
|
||||||
* Check Encryption Keys
|
* Check Encryption Keys
|
||||||
@ -22,13 +16,13 @@ function logoutUser({ response, database, dsqlUserId, encryptedUserString, reque
|
|||||||
* @description Check Encryption Keys
|
* @description Check Encryption Keys
|
||||||
*/
|
*/
|
||||||
try {
|
try {
|
||||||
const { user_id } = (0, grab_host_names_1.default)({ userId: dsqlUserId });
|
const { user_id } = grabHostNames({ userId: dsqlUserId });
|
||||||
const cookieNames = (0, get_auth_cookie_names_1.default)({
|
const cookieNames = getAuthCookieNames({
|
||||||
database,
|
database,
|
||||||
userId: user_id,
|
userId: user_id,
|
||||||
});
|
});
|
||||||
function debugFn(log, label) {
|
function debugFn(log, label) {
|
||||||
(0, debug_log_1.default)({ log, addTime: true, title: "logoutUser", label });
|
debugLog({ log, addTime: true, title: "logoutUser", label });
|
||||||
}
|
}
|
||||||
if (debug) {
|
if (debug) {
|
||||||
debugFn(cookieNames, "cookieNames");
|
debugFn(cookieNames, "cookieNames");
|
||||||
@ -39,16 +33,16 @@ function logoutUser({ response, database, dsqlUserId, encryptedUserString, reque
|
|||||||
const decryptedUserJSON = (() => {
|
const decryptedUserJSON = (() => {
|
||||||
try {
|
try {
|
||||||
if (request) {
|
if (request) {
|
||||||
const cookiesObject = (0, parseCookies_1.default)({
|
const cookiesObject = parseCookies({
|
||||||
request,
|
request,
|
||||||
cookieString,
|
cookieString,
|
||||||
});
|
});
|
||||||
return (0, decrypt_1.default)({
|
return decrypt({
|
||||||
encryptedString: cookiesObject[authKeyName],
|
encryptedString: cookiesObject[authKeyName],
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
else if (encryptedUserString) {
|
else if (encryptedUserString) {
|
||||||
return (0, decrypt_1.default)({
|
return decrypt({
|
||||||
encryptedString: encryptedUserString,
|
encryptedString: encryptedUserString,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@ -66,7 +60,7 @@ function logoutUser({ response, database, dsqlUserId, encryptedUserString, reque
|
|||||||
}
|
}
|
||||||
if (!decryptedUserJSON)
|
if (!decryptedUserJSON)
|
||||||
throw new Error("Invalid User");
|
throw new Error("Invalid User");
|
||||||
const userObject = ejson_1.default.parse(decryptedUserJSON);
|
const userObject = EJSON.parse(decryptedUserJSON);
|
||||||
if (!(userObject === null || userObject === void 0 ? void 0 : userObject.csrf_k))
|
if (!(userObject === null || userObject === void 0 ? void 0 : userObject.csrf_k))
|
||||||
throw new Error("Invalid User. Please check key");
|
throw new Error("Invalid User. Please check key");
|
||||||
response === null || response === void 0 ? void 0 : response.setHeader("Set-Cookie", [
|
response === null || response === void 0 ? void 0 : response.setHeader("Set-Cookie", [
|
||||||
@ -75,7 +69,7 @@ function logoutUser({ response, database, dsqlUserId, encryptedUserString, reque
|
|||||||
`${oneTimeCodeName}=null;max-age=0`,
|
`${oneTimeCodeName}=null;max-age=0`,
|
||||||
]);
|
]);
|
||||||
const csrf = userObject.csrf_k;
|
const csrf = userObject.csrf_k;
|
||||||
(0, write_auth_files_1.deleteAuthFile)(csrf);
|
deleteAuthFile(csrf);
|
||||||
return {
|
return {
|
||||||
success: true,
|
success: true,
|
||||||
msg: "User Logged Out",
|
msg: "User Logged Out",
|
||||||
|
35
dist/package-shared/actions/users/reauth-user.js
vendored
35
dist/package-shared/actions/users/reauth-user.js
vendored
@ -1,38 +1,22 @@
|
|||||||
"use strict";
|
import userAuth from "./user-auth";
|
||||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
import grabHostNames from "../../utils/grab-host-names";
|
||||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
import loginUser from "./login-user";
|
||||||
return new (P || (P = Promise))(function (resolve, reject) {
|
|
||||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
|
||||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
||||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
||||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
||||||
});
|
|
||||||
};
|
|
||||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
||||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
||||||
};
|
|
||||||
Object.defineProperty(exports, "__esModule", { value: true });
|
|
||||||
exports.default = reauthUser;
|
|
||||||
const user_auth_1 = __importDefault(require("./user-auth"));
|
|
||||||
const grab_host_names_1 = __importDefault(require("../../utils/grab-host-names"));
|
|
||||||
const login_user_1 = __importDefault(require("./login-user"));
|
|
||||||
/**
|
/**
|
||||||
* # Reauthorize User
|
* # Reauthorize User
|
||||||
*/
|
*/
|
||||||
function reauthUser(_a) {
|
export default async function reauthUser({ key, database, response, request, level, encryptionKey, encryptionSalt, additionalFields, encryptedUserString, user_id, secureCookie, }) {
|
||||||
return __awaiter(this, arguments, void 0, function* ({ key, database, response, request, level, encryptionKey, encryptionSalt, additionalFields, encryptedUserString, user_id, secureCookie, }) {
|
var _a;
|
||||||
var _b;
|
|
||||||
/**
|
/**
|
||||||
* Check Encryption Keys
|
* Check Encryption Keys
|
||||||
*
|
*
|
||||||
* @description Check Encryption Keys
|
* @description Check Encryption Keys
|
||||||
*/
|
*/
|
||||||
const grabedHostNames = (0, grab_host_names_1.default)();
|
const grabedHostNames = grabHostNames();
|
||||||
// const { host, port, scheme } = grabedHostNames;
|
// const { host, port, scheme } = grabedHostNames;
|
||||||
// const COOKIE_EXPIRY_DATE = grabCookieExpiryDate();
|
// const COOKIE_EXPIRY_DATE = grabCookieExpiryDate();
|
||||||
const finalEncryptionKey = encryptionKey || process.env.DSQL_ENCRYPTION_PASSWORD;
|
const finalEncryptionKey = encryptionKey || process.env.DSQL_ENCRYPTION_PASSWORD;
|
||||||
const finalEncryptionSalt = encryptionSalt || process.env.DSQL_ENCRYPTION_SALT;
|
const finalEncryptionSalt = encryptionSalt || process.env.DSQL_ENCRYPTION_SALT;
|
||||||
const existingUser = (0, user_auth_1.default)({
|
const existingUser = userAuth({
|
||||||
database,
|
database,
|
||||||
encryptionKey: finalEncryptionKey,
|
encryptionKey: finalEncryptionKey,
|
||||||
encryptionSalt: finalEncryptionSalt,
|
encryptionSalt: finalEncryptionSalt,
|
||||||
@ -40,14 +24,14 @@ function reauthUser(_a) {
|
|||||||
request,
|
request,
|
||||||
encryptedUserString,
|
encryptedUserString,
|
||||||
});
|
});
|
||||||
if (!((_b = existingUser === null || existingUser === void 0 ? void 0 : existingUser.payload) === null || _b === void 0 ? void 0 : _b.id)) {
|
if (!((_a = existingUser === null || existingUser === void 0 ? void 0 : existingUser.payload) === null || _a === void 0 ? void 0 : _a.id)) {
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
payload: null,
|
payload: null,
|
||||||
msg: "Cookie Credentials Invalid",
|
msg: "Cookie Credentials Invalid",
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
return yield (0, login_user_1.default)({
|
return await loginUser({
|
||||||
database: database || "",
|
database: database || "",
|
||||||
payload: {
|
payload: {
|
||||||
email: existingUser.payload.email,
|
email: existingUser.payload.email,
|
||||||
@ -175,5 +159,4 @@ function reauthUser(_a) {
|
|||||||
// }
|
// }
|
||||||
// }
|
// }
|
||||||
// return httpResponse;
|
// return httpResponse;
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
@ -19,5 +19,5 @@ type Param = {
|
|||||||
/**
|
/**
|
||||||
* # Send Email Code to a User
|
* # Send Email Code to a User
|
||||||
*/
|
*/
|
||||||
export default function sendEmailCode({ key, email, database, temp_code_field_name, mail_domain, mail_password, mail_username, mail_port, sender, user_id, response, extraCookies, }: Param): Promise<SendOneTimeCodeEmailResponse>;
|
export default function sendEmailCode(params: Param): Promise<SendOneTimeCodeEmailResponse>;
|
||||||
export {};
|
export {};
|
||||||
|
@ -1,28 +1,13 @@
|
|||||||
"use strict";
|
import fs from "fs";
|
||||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
import path from "path";
|
||||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
import grabHostNames from "../../utils/grab-host-names";
|
||||||
return new (P || (P = Promise))(function (resolve, reject) {
|
import apiSendEmailCode from "../../functions/api/users/api-send-email-code";
|
||||||
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
|
* # Send Email Code to a User
|
||||||
*/
|
*/
|
||||||
function sendEmailCode(_a) {
|
export default async function sendEmailCode(params) {
|
||||||
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 { key, email, database, temp_code_field_name, mail_domain, mail_password, mail_username, mail_port, sender, user_id, response, extraCookies, } = params;
|
||||||
const grabedHostNames = (0, grab_host_names_1.default)();
|
const grabedHostNames = grabHostNames();
|
||||||
const { host, port, scheme } = grabedHostNames;
|
const { host, port, scheme } = grabedHostNames;
|
||||||
const defaultTempLoginFieldName = "temp_login_code";
|
const defaultTempLoginFieldName = "temp_login_code";
|
||||||
const emailLoginTempCodeFieldName = temp_code_field_name
|
const emailLoginTempCodeFieldName = temp_code_field_name
|
||||||
@ -43,11 +28,11 @@ function sendEmailCode(_a) {
|
|||||||
/** @type {import("../../types").DSQL_DatabaseSchemaType | undefined} */
|
/** @type {import("../../types").DSQL_DatabaseSchemaType | undefined} */
|
||||||
let dbSchema;
|
let dbSchema;
|
||||||
try {
|
try {
|
||||||
const localDbSchemaPath = path_1.default.resolve(process.cwd(), "dsql.schema.json");
|
const localDbSchemaPath = path.resolve(process.cwd(), "dsql.schema.json");
|
||||||
dbSchema = JSON.parse(fs_1.default.readFileSync(localDbSchemaPath, "utf8"));
|
dbSchema = JSON.parse(fs.readFileSync(localDbSchemaPath, "utf8"));
|
||||||
}
|
}
|
||||||
catch (error) { }
|
catch (error) { }
|
||||||
return yield (0, api_send_email_code_1.default)({
|
return await apiSendEmailCode({
|
||||||
database: DSQL_DB_NAME,
|
database: DSQL_DB_NAME,
|
||||||
email,
|
email,
|
||||||
email_login_field: emailLoginTempCodeFieldName,
|
email_login_field: emailLoginTempCodeFieldName,
|
||||||
@ -69,7 +54,7 @@ function sendEmailCode(_a) {
|
|||||||
*
|
*
|
||||||
* @type {import("../../types").SendOneTimeCodeEmailResponse}
|
* @type {import("../../types").SendOneTimeCodeEmailResponse}
|
||||||
*/
|
*/
|
||||||
const httpResponse = yield new Promise((resolve, reject) => {
|
const httpResponse = await new Promise((resolve, reject) => {
|
||||||
const reqPayload = JSON.stringify({
|
const reqPayload = JSON.stringify({
|
||||||
email,
|
email,
|
||||||
database,
|
database,
|
||||||
@ -116,5 +101,4 @@ function sendEmailCode(_a) {
|
|||||||
});
|
});
|
||||||
return httpResponse;
|
return httpResponse;
|
||||||
}
|
}
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
@ -1,37 +1,21 @@
|
|||||||
"use strict";
|
import fs from "fs";
|
||||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
import path from "path";
|
||||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
import encrypt from "../../../functions/dsql/encrypt";
|
||||||
return new (P || (P = Promise))(function (resolve, reject) {
|
import grabHostNames from "../../../utils/grab-host-names";
|
||||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
import apiGithubLogin from "../../../functions/api/users/social/api-github-login";
|
||||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
import grabCookieExpiryDate from "../../../utils/grab-cookie-expirt-date";
|
||||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
||||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
||||||
});
|
|
||||||
};
|
|
||||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
||||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
||||||
};
|
|
||||||
Object.defineProperty(exports, "__esModule", { value: true });
|
|
||||||
exports.default = githubAuth;
|
|
||||||
const fs_1 = __importDefault(require("fs"));
|
|
||||||
const path_1 = __importDefault(require("path"));
|
|
||||||
const encrypt_1 = __importDefault(require("../../../functions/dsql/encrypt"));
|
|
||||||
const grab_host_names_1 = __importDefault(require("../../../utils/grab-host-names"));
|
|
||||||
const api_github_login_1 = __importDefault(require("../../../functions/api/users/social/api-github-login"));
|
|
||||||
const grab_cookie_expirt_date_1 = __importDefault(require("../../../utils/grab-cookie-expirt-date"));
|
|
||||||
/**
|
/**
|
||||||
* # SERVER FUNCTION: Login with google Function
|
* # SERVER FUNCTION: Login with google Function
|
||||||
*/
|
*/
|
||||||
function githubAuth(_a) {
|
export default async function githubAuth({ key, code, email, database, clientId, clientSecret, response, encryptionKey, encryptionSalt, additionalFields, user_id, additionalData, secureCookie, }) {
|
||||||
return __awaiter(this, arguments, void 0, function* ({ key, code, email, database, clientId, clientSecret, response, encryptionKey, encryptionSalt, additionalFields, user_id, additionalData, secureCookie, }) {
|
|
||||||
/**
|
/**
|
||||||
* Check inputs
|
* Check inputs
|
||||||
*
|
*
|
||||||
* @description Check inputs
|
* @description Check inputs
|
||||||
*/
|
*/
|
||||||
const grabedHostNames = (0, grab_host_names_1.default)();
|
const grabedHostNames = grabHostNames();
|
||||||
const { host, port, scheme } = grabedHostNames;
|
const { host, port, scheme } = grabedHostNames;
|
||||||
const COOKIE_EXPIRY_DATE = (0, grab_cookie_expirt_date_1.default)();
|
const COOKIE_EXPIRY_DATE = grabCookieExpiryDate();
|
||||||
if (!code || (code === null || code === void 0 ? void 0 : code.match(/ /))) {
|
if (!code || (code === null || code === void 0 ? void 0 : code.match(/ /))) {
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
@ -70,11 +54,11 @@ function githubAuth(_a) {
|
|||||||
/** @type {import("../../../types").DSQL_DatabaseSchemaType | undefined | undefined} */
|
/** @type {import("../../../types").DSQL_DatabaseSchemaType | undefined | undefined} */
|
||||||
let dbSchema;
|
let dbSchema;
|
||||||
try {
|
try {
|
||||||
const localDbSchemaPath = path_1.default.resolve(process.cwd(), "dsql.schema.json");
|
const localDbSchemaPath = path.resolve(process.cwd(), "dsql.schema.json");
|
||||||
dbSchema = JSON.parse(fs_1.default.readFileSync(localDbSchemaPath, "utf8"));
|
dbSchema = JSON.parse(fs.readFileSync(localDbSchemaPath, "utf8"));
|
||||||
}
|
}
|
||||||
catch (error) { }
|
catch (error) { }
|
||||||
httpResponse = yield (0, api_github_login_1.default)({
|
httpResponse = await apiGithubLogin({
|
||||||
code,
|
code,
|
||||||
email: email || undefined,
|
email: email || undefined,
|
||||||
clientId,
|
clientId,
|
||||||
@ -91,7 +75,7 @@ function githubAuth(_a) {
|
|||||||
* @description make a request to datasquirel.com
|
* @description make a request to datasquirel.com
|
||||||
* @type {FunctionReturn} - Https response object
|
* @type {FunctionReturn} - Https response object
|
||||||
*/
|
*/
|
||||||
httpResponse = (yield new Promise((resolve, reject) => {
|
httpResponse = (await new Promise((resolve, reject) => {
|
||||||
const reqPayload = JSON.stringify({
|
const reqPayload = JSON.stringify({
|
||||||
code,
|
code,
|
||||||
email,
|
email,
|
||||||
@ -155,7 +139,7 @@ function githubAuth(_a) {
|
|||||||
* @description make a request to datasquirel.com
|
* @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)) {
|
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)({
|
let encryptedPayload = encrypt({
|
||||||
data: JSON.stringify(httpResponse.user),
|
data: JSON.stringify(httpResponse.user),
|
||||||
encryptionKey,
|
encryptionKey,
|
||||||
encryptionSalt,
|
encryptionSalt,
|
||||||
@ -169,5 +153,4 @@ function githubAuth(_a) {
|
|||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
return httpResponse;
|
return httpResponse;
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
@ -1,35 +1,19 @@
|
|||||||
"use strict";
|
import encrypt from "../../../functions/dsql/encrypt";
|
||||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
import grabHostNames from "../../../utils/grab-host-names";
|
||||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
import apiGoogleLogin from "../../../functions/api/users/social/api-google-login";
|
||||||
return new (P || (P = Promise))(function (resolve, reject) {
|
import getAuthCookieNames from "../../../functions/backend/cookies/get-auth-cookie-names";
|
||||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
import { writeAuthFile } from "../../../functions/backend/auth/write-auth-files";
|
||||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
import grabCookieExpiryDate from "../../../utils/grab-cookie-expirt-date";
|
||||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
||||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
||||||
});
|
|
||||||
};
|
|
||||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
||||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
||||||
};
|
|
||||||
Object.defineProperty(exports, "__esModule", { value: true });
|
|
||||||
exports.default = googleAuth;
|
|
||||||
const encrypt_1 = __importDefault(require("../../../functions/dsql/encrypt"));
|
|
||||||
const grab_host_names_1 = __importDefault(require("../../../utils/grab-host-names"));
|
|
||||||
const api_google_login_1 = __importDefault(require("../../../functions/api/users/social/api-google-login"));
|
|
||||||
const get_auth_cookie_names_1 = __importDefault(require("../../../functions/backend/cookies/get-auth-cookie-names"));
|
|
||||||
const write_auth_files_1 = require("../../../functions/backend/auth/write-auth-files");
|
|
||||||
const grab_cookie_expirt_date_1 = __importDefault(require("../../../utils/grab-cookie-expirt-date"));
|
|
||||||
/**
|
/**
|
||||||
* # SERVER FUNCTION: Login with google Function
|
* # SERVER FUNCTION: Login with google Function
|
||||||
*/
|
*/
|
||||||
function googleAuth(_a) {
|
export default async function googleAuth({ key, token, database, response, encryptionKey, encryptionSalt, additionalFields, additionalData, apiUserID, debug, secureCookie, loginOnly, }) {
|
||||||
return __awaiter(this, arguments, void 0, function* ({ key, token, database, response, encryptionKey, encryptionSalt, additionalFields, additionalData, apiUserID, debug, secureCookie, loginOnly, }) {
|
var _a;
|
||||||
var _b;
|
const grabedHostNames = grabHostNames({
|
||||||
const grabedHostNames = (0, grab_host_names_1.default)({
|
|
||||||
userId: apiUserID || process.env.DSQL_API_USER_ID,
|
userId: apiUserID || process.env.DSQL_API_USER_ID,
|
||||||
});
|
});
|
||||||
const { host, port, scheme, user_id } = grabedHostNames;
|
const { host, port, scheme, user_id } = grabedHostNames;
|
||||||
const COOKIE_EXPIRY_DATE = (0, grab_cookie_expirt_date_1.default)();
|
const COOKIE_EXPIRY_DATE = grabCookieExpiryDate();
|
||||||
const finalEncryptionKey = encryptionKey || process.env.DSQL_ENCRYPTION_PASSWORD;
|
const finalEncryptionKey = encryptionKey || process.env.DSQL_ENCRYPTION_PASSWORD;
|
||||||
const finalEncryptionSalt = encryptionSalt || process.env.DSQL_ENCRYPTION_SALT;
|
const finalEncryptionSalt = encryptionSalt || process.env.DSQL_ENCRYPTION_SALT;
|
||||||
if (!(finalEncryptionKey === null || finalEncryptionKey === void 0 ? void 0 : finalEncryptionKey.match(/.{8,}/))) {
|
if (!(finalEncryptionKey === null || finalEncryptionKey === void 0 ? void 0 : finalEncryptionKey.match(/.{8,}/))) {
|
||||||
@ -80,7 +64,7 @@ function googleAuth(_a) {
|
|||||||
if (debug) {
|
if (debug) {
|
||||||
console.log(`Google login with Local Paradigm ...`);
|
console.log(`Google login with Local Paradigm ...`);
|
||||||
}
|
}
|
||||||
httpResponse = yield (0, api_google_login_1.default)({
|
httpResponse = await apiGoogleLogin({
|
||||||
token,
|
token,
|
||||||
additionalFields,
|
additionalFields,
|
||||||
additionalData,
|
additionalData,
|
||||||
@ -88,7 +72,7 @@ function googleAuth(_a) {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
httpResponse = yield new Promise((resolve, reject) => {
|
httpResponse = await new Promise((resolve, reject) => {
|
||||||
const reqPayload = JSON.stringify({
|
const reqPayload = JSON.stringify({
|
||||||
token,
|
token,
|
||||||
database,
|
database,
|
||||||
@ -135,17 +119,17 @@ function googleAuth(_a) {
|
|||||||
* @description make a request to datasquirel.com
|
* @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)) {
|
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)({
|
let encryptedPayload = encrypt({
|
||||||
data: JSON.stringify(httpResponse.payload),
|
data: JSON.stringify(httpResponse.payload),
|
||||||
encryptionKey: finalEncryptionKey,
|
encryptionKey: finalEncryptionKey,
|
||||||
encryptionSalt: finalEncryptionSalt,
|
encryptionSalt: finalEncryptionSalt,
|
||||||
});
|
});
|
||||||
const cookieNames = (0, get_auth_cookie_names_1.default)({
|
const cookieNames = getAuthCookieNames({
|
||||||
database,
|
database,
|
||||||
userId: user_id,
|
userId: user_id,
|
||||||
});
|
});
|
||||||
if (httpResponse.csrf) {
|
if (httpResponse.csrf) {
|
||||||
(0, write_auth_files_1.writeAuthFile)(httpResponse.csrf, JSON.stringify(httpResponse.payload));
|
writeAuthFile(httpResponse.csrf, JSON.stringify(httpResponse.payload));
|
||||||
}
|
}
|
||||||
httpResponse["cookieNames"] = cookieNames;
|
httpResponse["cookieNames"] = cookieNames;
|
||||||
httpResponse["key"] = String(encryptedPayload);
|
httpResponse["key"] = String(encryptedPayload);
|
||||||
@ -153,9 +137,8 @@ function googleAuth(_a) {
|
|||||||
const csrfName = cookieNames.csrfCookieName;
|
const csrfName = cookieNames.csrfCookieName;
|
||||||
response === null || response === void 0 ? void 0 : response.setHeader("Set-Cookie", [
|
response === null || response === void 0 ? void 0 : response.setHeader("Set-Cookie", [
|
||||||
`${authKeyName}=${encryptedPayload};samesite=strict;path=/;HttpOnly=true;;Expires=${COOKIE_EXPIRY_DATE}${secureCookie ? ";Secure=true" : ""}`,
|
`${authKeyName}=${encryptedPayload};samesite=strict;path=/;HttpOnly=true;;Expires=${COOKIE_EXPIRY_DATE}${secureCookie ? ";Secure=true" : ""}`,
|
||||||
`${csrfName}=${(_b = httpResponse.payload) === null || _b === void 0 ? void 0 : _b.csrf_k};samesite=strict;path=/;HttpOnly=true;;Expires=${COOKIE_EXPIRY_DATE}`,
|
`${csrfName}=${(_a = httpResponse.payload) === null || _a === void 0 ? void 0 : _a.csrf_k};samesite=strict;path=/;HttpOnly=true;;Expires=${COOKIE_EXPIRY_DATE}`,
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
return httpResponse;
|
return httpResponse;
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
37
dist/package-shared/actions/users/update-user.js
vendored
37
dist/package-shared/actions/users/update-user.js
vendored
@ -1,34 +1,18 @@
|
|||||||
"use strict";
|
import path from "path";
|
||||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
import fs from "fs";
|
||||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
import grabHostNames from "../../utils/grab-host-names";
|
||||||
return new (P || (P = Promise))(function (resolve, reject) {
|
import apiUpdateUser from "../../functions/api/users/api-update-user";
|
||||||
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
|
* # Update User
|
||||||
*/
|
*/
|
||||||
function updateUser(_a) {
|
export default async function updateUser({ key, payload, database, user_id, updatedUserId, }) {
|
||||||
return __awaiter(this, arguments, void 0, function* ({ key, payload, database, user_id, updatedUserId, }) {
|
|
||||||
/**
|
/**
|
||||||
* Check for local DB settings
|
* Check for local DB settings
|
||||||
*
|
*
|
||||||
* @description Look for local db settings in `.env` file and by pass the http request if available
|
* @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 { DSQL_DB_HOST, DSQL_DB_USERNAME, DSQL_DB_PASSWORD, DSQL_DB_NAME } = process.env;
|
||||||
const grabedHostNames = (0, grab_host_names_1.default)();
|
const grabedHostNames = grabHostNames();
|
||||||
const { host, port, scheme } = grabedHostNames;
|
const { host, port, scheme } = grabedHostNames;
|
||||||
if ((DSQL_DB_HOST === null || DSQL_DB_HOST === void 0 ? void 0 : DSQL_DB_HOST.match(/./)) &&
|
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_USERNAME === null || DSQL_DB_USERNAME === void 0 ? void 0 : DSQL_DB_USERNAME.match(/./)) &&
|
||||||
@ -38,11 +22,11 @@ function updateUser(_a) {
|
|||||||
/** @type {import("../../types").DSQL_DatabaseSchemaType | undefined} */
|
/** @type {import("../../types").DSQL_DatabaseSchemaType | undefined} */
|
||||||
let dbSchema;
|
let dbSchema;
|
||||||
try {
|
try {
|
||||||
const localDbSchemaPath = path_1.default.resolve(process.cwd(), "dsql.schema.json");
|
const localDbSchemaPath = path.resolve(process.cwd(), "dsql.schema.json");
|
||||||
dbSchema = JSON.parse(fs_1.default.readFileSync(localDbSchemaPath, "utf8"));
|
dbSchema = JSON.parse(fs.readFileSync(localDbSchemaPath, "utf8"));
|
||||||
}
|
}
|
||||||
catch (error) { }
|
catch (error) { }
|
||||||
return yield (0, api_update_user_1.default)({
|
return await apiUpdateUser({
|
||||||
payload: payload,
|
payload: payload,
|
||||||
dbFullName: DSQL_DB_NAME,
|
dbFullName: DSQL_DB_NAME,
|
||||||
updatedUserId,
|
updatedUserId,
|
||||||
@ -54,7 +38,7 @@ function updateUser(_a) {
|
|||||||
*
|
*
|
||||||
* @description make a request to datasquirel.com
|
* @description make a request to datasquirel.com
|
||||||
*/
|
*/
|
||||||
const httpResponse = yield new Promise((resolve, reject) => {
|
const httpResponse = await new Promise((resolve, reject) => {
|
||||||
const reqPayload = JSON.stringify({
|
const reqPayload = JSON.stringify({
|
||||||
payload,
|
payload,
|
||||||
database,
|
database,
|
||||||
@ -94,5 +78,4 @@ function updateUser(_a) {
|
|||||||
httpsRequest.end();
|
httpsRequest.end();
|
||||||
});
|
});
|
||||||
return httpResponse;
|
return httpResponse;
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
44
dist/package-shared/actions/users/user-auth.js
vendored
44
dist/package-shared/actions/users/user-auth.js
vendored
@ -1,16 +1,10 @@
|
|||||||
"use strict";
|
import decrypt from "../../functions/dsql/decrypt";
|
||||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
import getAuthCookieNames from "../../functions/backend/cookies/get-auth-cookie-names";
|
||||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
import { checkAuthFile } from "../../functions/backend/auth/write-auth-files";
|
||||||
};
|
import parseCookies from "../../utils/backend/parseCookies";
|
||||||
Object.defineProperty(exports, "__esModule", { value: true });
|
import getCsrfHeaderName from "../../actions/get-csrf-header-name";
|
||||||
exports.default = userAuth;
|
import grabHostNames from "../../utils/grab-host-names";
|
||||||
const decrypt_1 = __importDefault(require("../../functions/dsql/decrypt"));
|
import debugLog from "../../utils/logging/debug-log";
|
||||||
const get_auth_cookie_names_1 = __importDefault(require("../../functions/backend/cookies/get-auth-cookie-names"));
|
|
||||||
const write_auth_files_1 = require("../../functions/backend/auth/write-auth-files");
|
|
||||||
const parseCookies_1 = __importDefault(require("../../utils/backend/parseCookies"));
|
|
||||||
const get_csrf_header_name_1 = __importDefault(require("../../actions/get-csrf-header-name"));
|
|
||||||
const grab_host_names_1 = __importDefault(require("../../utils/grab-host-names"));
|
|
||||||
const debug_log_1 = __importDefault(require("../../utils/logging/debug-log"));
|
|
||||||
const minuteInMilliseconds = 60000;
|
const minuteInMilliseconds = 60000;
|
||||||
const hourInMilliseconds = minuteInMilliseconds * 60;
|
const hourInMilliseconds = minuteInMilliseconds * 60;
|
||||||
const dayInMilliseconds = hourInMilliseconds * 24;
|
const dayInMilliseconds = hourInMilliseconds * 24;
|
||||||
@ -23,28 +17,28 @@ const yearInMilliseconds = dayInMilliseconds * 365;
|
|||||||
* @description This Function takes in a request object and returns a user object
|
* @description This Function takes in a request object and returns a user object
|
||||||
* with the user's data
|
* with the user's data
|
||||||
*/
|
*/
|
||||||
function userAuth({ request, req, encryptionKey, encryptionSalt, level, database, dsqlUserId, encryptedUserString, expiry = weekInMilliseconds, cookieString, csrfHeaderName, debug, skipFileCheck, }) {
|
export default function userAuth({ request, req, encryptionKey, encryptionSalt, level, database, dsqlUserId, encryptedUserString, expiry = weekInMilliseconds, cookieString, csrfHeaderName, debug, skipFileCheck, }) {
|
||||||
var _a;
|
var _a;
|
||||||
try {
|
try {
|
||||||
const finalRequest = req || request;
|
const finalRequest = req || request;
|
||||||
const { user_id } = (0, grab_host_names_1.default)({ userId: dsqlUserId });
|
const { user_id } = grabHostNames({ userId: dsqlUserId });
|
||||||
const cookies = (0, parseCookies_1.default)({
|
const cookies = parseCookies({
|
||||||
request: finalRequest,
|
request: finalRequest,
|
||||||
cookieString,
|
cookieString,
|
||||||
});
|
});
|
||||||
if (debug) {
|
if (debug) {
|
||||||
(0, debug_log_1.default)({
|
debugLog({
|
||||||
log: cookies,
|
log: cookies,
|
||||||
addTime: true,
|
addTime: true,
|
||||||
label: "userAuth:cookies",
|
label: "userAuth:cookies",
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
const keyNames = (0, get_auth_cookie_names_1.default)({
|
const keyNames = getAuthCookieNames({
|
||||||
userId: user_id,
|
userId: user_id,
|
||||||
database: database || process.env.DSQL_DB_NAME,
|
database: database || process.env.DSQL_DB_NAME,
|
||||||
});
|
});
|
||||||
if (debug) {
|
if (debug) {
|
||||||
(0, debug_log_1.default)({
|
debugLog({
|
||||||
log: keyNames,
|
log: keyNames,
|
||||||
addTime: true,
|
addTime: true,
|
||||||
label: "userAuth:keyNames",
|
label: "userAuth:keyNames",
|
||||||
@ -54,7 +48,7 @@ function userAuth({ request, req, encryptionKey, encryptionSalt, level, database
|
|||||||
? encryptedUserString
|
? encryptedUserString
|
||||||
: cookies[keyNames.keyCookieName];
|
: cookies[keyNames.keyCookieName];
|
||||||
if (debug) {
|
if (debug) {
|
||||||
(0, debug_log_1.default)({
|
debugLog({
|
||||||
log: key,
|
log: key,
|
||||||
addTime: true,
|
addTime: true,
|
||||||
label: "userAuth:key",
|
label: "userAuth:key",
|
||||||
@ -65,13 +59,13 @@ function userAuth({ request, req, encryptionKey, encryptionSalt, level, database
|
|||||||
*
|
*
|
||||||
* @description Grab the payload
|
* @description Grab the payload
|
||||||
*/
|
*/
|
||||||
let userPayloadJSON = (0, decrypt_1.default)({
|
let userPayloadJSON = decrypt({
|
||||||
encryptedString: key,
|
encryptedString: key,
|
||||||
encryptionKey,
|
encryptionKey,
|
||||||
encryptionSalt,
|
encryptionSalt,
|
||||||
});
|
});
|
||||||
if (debug) {
|
if (debug) {
|
||||||
(0, debug_log_1.default)({
|
debugLog({
|
||||||
log: userPayloadJSON,
|
log: userPayloadJSON,
|
||||||
addTime: true,
|
addTime: true,
|
||||||
label: "userAuth:userPayloadJSON",
|
label: "userAuth:userPayloadJSON",
|
||||||
@ -92,7 +86,7 @@ function userAuth({ request, req, encryptionKey, encryptionSalt, level, database
|
|||||||
}
|
}
|
||||||
let userObject = JSON.parse(userPayloadJSON);
|
let userObject = JSON.parse(userPayloadJSON);
|
||||||
if (debug) {
|
if (debug) {
|
||||||
(0, debug_log_1.default)({
|
debugLog({
|
||||||
log: userObject,
|
log: userObject,
|
||||||
addTime: true,
|
addTime: true,
|
||||||
label: "userAuth:userObject",
|
label: "userAuth:userObject",
|
||||||
@ -106,7 +100,7 @@ function userAuth({ request, req, encryptionKey, encryptionSalt, level, database
|
|||||||
cookieNames: keyNames,
|
cookieNames: keyNames,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
if (!skipFileCheck && !(0, write_auth_files_1.checkAuthFile)(userObject.csrf_k)) {
|
if (!skipFileCheck && !checkAuthFile(userObject.csrf_k)) {
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
payload: null,
|
payload: null,
|
||||||
@ -120,7 +114,7 @@ function userAuth({ request, req, encryptionKey, encryptionSalt, level, database
|
|||||||
* @description Grab the payload
|
* @description Grab the payload
|
||||||
*/
|
*/
|
||||||
if ((level === null || level === void 0 ? void 0 : level.match(/deep/i)) && finalRequest) {
|
if ((level === null || level === void 0 ? void 0 : level.match(/deep/i)) && finalRequest) {
|
||||||
const finalCsrfHeaderName = csrfHeaderName || (0, get_csrf_header_name_1.default)();
|
const finalCsrfHeaderName = csrfHeaderName || getCsrfHeaderName();
|
||||||
if (finalRequest.headers[finalCsrfHeaderName] !== userObject.csrf_k) {
|
if (finalRequest.headers[finalCsrfHeaderName] !== userObject.csrf_k) {
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
|
@ -1,37 +1,21 @@
|
|||||||
"use strict";
|
import getAuthCookieNames from "../../functions/backend/cookies/get-auth-cookie-names";
|
||||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
import parseCookies from "../../utils/backend/parseCookies";
|
||||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
import decrypt from "../../functions/dsql/decrypt";
|
||||||
return new (P || (P = Promise))(function (resolve, reject) {
|
import EJSON from "../../utils/ejson";
|
||||||
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
|
* # Verify the temp email code sent to the user's email address
|
||||||
*/
|
*/
|
||||||
function validateTempEmailCode(_a) {
|
export default async function validateTempEmailCode({ request, email, cookieString, }) {
|
||||||
return __awaiter(this, arguments, void 0, function* ({ request, email, cookieString, }) {
|
var _a;
|
||||||
var _b;
|
|
||||||
try {
|
try {
|
||||||
const keyNames = (0, get_auth_cookie_names_1.default)();
|
const keyNames = getAuthCookieNames();
|
||||||
const oneTimeCodeCookieName = keyNames.oneTimeCodeName;
|
const oneTimeCodeCookieName = keyNames.oneTimeCodeName;
|
||||||
const cookies = (0, parseCookies_1.default)({ request, cookieString });
|
const cookies = parseCookies({ request, cookieString });
|
||||||
const encryptedOneTimeCode = cookies[oneTimeCodeCookieName];
|
const encryptedOneTimeCode = cookies[oneTimeCodeCookieName];
|
||||||
const encryptedPayload = (0, decrypt_1.default)({
|
const encryptedPayload = decrypt({
|
||||||
encryptedString: encryptedOneTimeCode,
|
encryptedString: encryptedOneTimeCode,
|
||||||
});
|
});
|
||||||
const payload = ejson_1.default.parse(encryptedPayload);
|
const payload = EJSON.parse(encryptedPayload);
|
||||||
if ((payload === null || payload === void 0 ? void 0 : payload.email) && !email) {
|
if ((payload === null || payload === void 0 ? void 0 : payload.email) && !email) {
|
||||||
return payload;
|
return payload;
|
||||||
}
|
}
|
||||||
@ -41,9 +25,8 @@ function validateTempEmailCode(_a) {
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
catch (error) {
|
catch (error) {
|
||||||
(_b = global.ERROR_CALLBACK) === null || _b === void 0 ? void 0 : _b.call(global, `Validate Temp Email Code Error`, error);
|
(_a = global.ERROR_CALLBACK) === null || _a === void 0 ? void 0 : _a.call(global, `Validate Temp Email Code Error`, error);
|
||||||
console.log("validateTempEmailCode error:", error.message);
|
console.log("validateTempEmailCode error:", error.message);
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
@ -1,16 +1,10 @@
|
|||||||
"use strict";
|
import decrypt from "../../functions/dsql/decrypt";
|
||||||
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
|
* Validate Token
|
||||||
* ======================================
|
* ======================================
|
||||||
* @description This Function takes in a encrypted token and returns a user object
|
* @description This Function takes in a encrypted token and returns a user object
|
||||||
*/
|
*/
|
||||||
function validateToken({ token, encryptionKey, encryptionSalt, }) {
|
export default function validateToken({ token, encryptionKey, encryptionSalt, }) {
|
||||||
var _a;
|
var _a;
|
||||||
try {
|
try {
|
||||||
/**
|
/**
|
||||||
@ -24,7 +18,7 @@ function validateToken({ token, encryptionKey, encryptionSalt, }) {
|
|||||||
*
|
*
|
||||||
* @description Grab the payload
|
* @description Grab the payload
|
||||||
*/
|
*/
|
||||||
let userPayload = (0, decrypt_1.default)({
|
let userPayload = decrypt({
|
||||||
encryptedString: key,
|
encryptedString: key,
|
||||||
encryptionKey,
|
encryptionKey,
|
||||||
encryptionSalt,
|
encryptionSalt,
|
||||||
|
21
dist/package-shared/api/crud/delete.d.ts
vendored
Normal file
21
dist/package-shared/api/crud/delete.d.ts
vendored
Normal file
@ -0,0 +1,21 @@
|
|||||||
|
import { SQLDeleteData } from "../../types";
|
||||||
|
type Params<T extends {
|
||||||
|
[key: string]: any;
|
||||||
|
} = {
|
||||||
|
[key: string]: any;
|
||||||
|
}> = {
|
||||||
|
dbName: string;
|
||||||
|
tableName: string;
|
||||||
|
deleteSpec?: T & {
|
||||||
|
deleteKeyValues?: SQLDeleteData<T>[];
|
||||||
|
};
|
||||||
|
targetID?: string | number;
|
||||||
|
};
|
||||||
|
export default function apiCrudDELETE<T extends {
|
||||||
|
[key: string]: any;
|
||||||
|
} = {
|
||||||
|
[key: string]: any;
|
||||||
|
}>({ dbName, tableName, deleteSpec, targetID }: Params<T>): Promise<import("../../types").APIResponseObject<{
|
||||||
|
[k: string]: any;
|
||||||
|
}>>;
|
||||||
|
export {};
|
14
dist/package-shared/api/crud/delete.js
vendored
Normal file
14
dist/package-shared/api/crud/delete.js
vendored
Normal file
@ -0,0 +1,14 @@
|
|||||||
|
import path from "path";
|
||||||
|
import queryDSQLAPI from "../../functions/api/query-dsql-api";
|
||||||
|
import grabAPIBasePath from "../../utils/grab-api-base-path";
|
||||||
|
export default async function apiCrudDELETE({ dbName, tableName, deleteSpec, targetID }) {
|
||||||
|
const basePath = grabAPIBasePath({ paradigm: "crud" });
|
||||||
|
const finalID = typeof targetID === "number" ? String(targetID) : targetID;
|
||||||
|
const finalPath = path.join(basePath, dbName, tableName, finalID || "");
|
||||||
|
const GET_RES = await queryDSQLAPI({
|
||||||
|
method: "DELETE",
|
||||||
|
path: finalPath,
|
||||||
|
body: deleteSpec,
|
||||||
|
});
|
||||||
|
return GET_RES;
|
||||||
|
}
|
17
dist/package-shared/api/crud/get.d.ts
vendored
Normal file
17
dist/package-shared/api/crud/get.d.ts
vendored
Normal file
@ -0,0 +1,17 @@
|
|||||||
|
import { APIResponseObject, DsqlCrudQueryObject } from "../../types";
|
||||||
|
type Params<T extends {
|
||||||
|
[key: string]: any;
|
||||||
|
} = {
|
||||||
|
[key: string]: any;
|
||||||
|
}> = {
|
||||||
|
dbName: string;
|
||||||
|
tableName: string;
|
||||||
|
query?: DsqlCrudQueryObject<T>;
|
||||||
|
targetId?: string | number;
|
||||||
|
};
|
||||||
|
export default function apiCrudGET<T extends {
|
||||||
|
[key: string]: any;
|
||||||
|
} = {
|
||||||
|
[key: string]: any;
|
||||||
|
}>({ dbName, tableName, query, targetId, }: Params<T>): Promise<APIResponseObject>;
|
||||||
|
export {};
|
14
dist/package-shared/api/crud/get.js
vendored
Normal file
14
dist/package-shared/api/crud/get.js
vendored
Normal file
@ -0,0 +1,14 @@
|
|||||||
|
import path from "path";
|
||||||
|
import queryDSQLAPI from "../../functions/api/query-dsql-api";
|
||||||
|
import grabAPIBasePath from "../../utils/grab-api-base-path";
|
||||||
|
export default async function apiCrudGET({ dbName, tableName, query, targetId, }) {
|
||||||
|
const basePath = grabAPIBasePath({ paradigm: "crud" });
|
||||||
|
const finalID = typeof targetId === "number" ? String(targetId) : targetId;
|
||||||
|
const finalPath = path.join(basePath, dbName, tableName, finalID || "");
|
||||||
|
const GET_RES = await queryDSQLAPI({
|
||||||
|
method: "GET",
|
||||||
|
path: finalPath,
|
||||||
|
query,
|
||||||
|
});
|
||||||
|
return GET_RES;
|
||||||
|
}
|
12
dist/package-shared/api/crud/index.d.ts
vendored
Normal file
12
dist/package-shared/api/crud/index.d.ts
vendored
Normal file
@ -0,0 +1,12 @@
|
|||||||
|
import apiCrudGET from "./get";
|
||||||
|
import apiCrudPOST from "./post";
|
||||||
|
import apiCrudPUT from "./put";
|
||||||
|
import apiCrudDELETE from "./delete";
|
||||||
|
declare const crud: {
|
||||||
|
get: typeof apiCrudGET;
|
||||||
|
insert: typeof apiCrudPOST;
|
||||||
|
update: typeof apiCrudPUT;
|
||||||
|
delete: typeof apiCrudDELETE;
|
||||||
|
options: () => Promise<void>;
|
||||||
|
};
|
||||||
|
export default crud;
|
12
dist/package-shared/api/crud/index.js
vendored
Normal file
12
dist/package-shared/api/crud/index.js
vendored
Normal file
@ -0,0 +1,12 @@
|
|||||||
|
import apiCrudGET from "./get";
|
||||||
|
import apiCrudPOST from "./post";
|
||||||
|
import apiCrudPUT from "./put";
|
||||||
|
import apiCrudDELETE from "./delete";
|
||||||
|
const crud = {
|
||||||
|
get: apiCrudGET,
|
||||||
|
insert: apiCrudPOST,
|
||||||
|
update: apiCrudPUT,
|
||||||
|
delete: apiCrudDELETE,
|
||||||
|
options: async () => { },
|
||||||
|
};
|
||||||
|
export default crud;
|
16
dist/package-shared/api/crud/post.d.ts
vendored
Normal file
16
dist/package-shared/api/crud/post.d.ts
vendored
Normal file
@ -0,0 +1,16 @@
|
|||||||
|
import { APIResponseObject } from "../../types";
|
||||||
|
export type APICrudPostParams<T extends {
|
||||||
|
[key: string]: any;
|
||||||
|
} = {
|
||||||
|
[key: string]: any;
|
||||||
|
}> = {
|
||||||
|
dbName: string;
|
||||||
|
tableName: string;
|
||||||
|
body: T;
|
||||||
|
update?: boolean;
|
||||||
|
};
|
||||||
|
export default function apiCrudPOST<T extends {
|
||||||
|
[key: string]: any;
|
||||||
|
} = {
|
||||||
|
[key: string]: any;
|
||||||
|
}>({ dbName, tableName, body, update, }: APICrudPostParams<T>): Promise<APIResponseObject>;
|
19
dist/package-shared/api/crud/post.js
vendored
Normal file
19
dist/package-shared/api/crud/post.js
vendored
Normal file
@ -0,0 +1,19 @@
|
|||||||
|
import path from "path";
|
||||||
|
import queryDSQLAPI from "../../functions/api/query-dsql-api";
|
||||||
|
import grabAPIBasePath from "../../utils/grab-api-base-path";
|
||||||
|
export default async function apiCrudPOST({ dbName, tableName, body, update, }) {
|
||||||
|
const basePath = grabAPIBasePath({ paradigm: "crud" });
|
||||||
|
const passedID = body.id;
|
||||||
|
const finalID = update
|
||||||
|
? typeof passedID === "number"
|
||||||
|
? String(passedID)
|
||||||
|
: passedID
|
||||||
|
: undefined;
|
||||||
|
const finalPath = path.join(basePath, dbName, tableName, finalID || "");
|
||||||
|
const GET_RES = await queryDSQLAPI({
|
||||||
|
method: update ? "PUT" : "POST",
|
||||||
|
path: finalPath,
|
||||||
|
body,
|
||||||
|
});
|
||||||
|
return GET_RES;
|
||||||
|
}
|
14
dist/package-shared/api/crud/put.d.ts
vendored
Normal file
14
dist/package-shared/api/crud/put.d.ts
vendored
Normal file
@ -0,0 +1,14 @@
|
|||||||
|
import { APICrudPostParams } from "./post";
|
||||||
|
type Params<T extends {
|
||||||
|
[key: string]: any;
|
||||||
|
} = {
|
||||||
|
[key: string]: any;
|
||||||
|
}> = Omit<APICrudPostParams<T>, "update"> & {
|
||||||
|
targetID: string | number;
|
||||||
|
};
|
||||||
|
export default function apiCrudPUT<T extends {
|
||||||
|
[key: string]: any;
|
||||||
|
} = {
|
||||||
|
[key: string]: any;
|
||||||
|
}>({ dbName, tableName, body, targetID }: Params<T>): Promise<import("../../types").APIResponseObject>;
|
||||||
|
export {};
|
13
dist/package-shared/api/crud/put.js
vendored
Normal file
13
dist/package-shared/api/crud/put.js
vendored
Normal file
@ -0,0 +1,13 @@
|
|||||||
|
import apiCrudPOST from "./post";
|
||||||
|
export default async function apiCrudPUT({ dbName, tableName, body, targetID }) {
|
||||||
|
const updatedBody = Object.assign({}, body);
|
||||||
|
if (targetID) {
|
||||||
|
updatedBody["id"] = targetID;
|
||||||
|
}
|
||||||
|
return await apiCrudPOST({
|
||||||
|
dbName,
|
||||||
|
tableName,
|
||||||
|
body: updatedBody,
|
||||||
|
update: true,
|
||||||
|
});
|
||||||
|
}
|
5
dist/package-shared/api/media/delete.d.ts
vendored
Normal file
5
dist/package-shared/api/media/delete.d.ts
vendored
Normal file
@ -0,0 +1,5 @@
|
|||||||
|
import { APIResponseObject } from "../../types";
|
||||||
|
import { DSQL_DATASQUIREL_USER_MEDIA } from "../../types/dsql";
|
||||||
|
export default function apiMediaDELETE(params: {
|
||||||
|
mediaID?: string | number;
|
||||||
|
}): Promise<APIResponseObject<DSQL_DATASQUIREL_USER_MEDIA | DSQL_DATASQUIREL_USER_MEDIA[]>>;
|
17
dist/package-shared/api/media/delete.js
vendored
Normal file
17
dist/package-shared/api/media/delete.js
vendored
Normal file
@ -0,0 +1,17 @@
|
|||||||
|
import queryDSQLAPI from "../../functions/api/query-dsql-api";
|
||||||
|
import path from "path";
|
||||||
|
import grabAPIBasePath from "../../utils/grab-api-base-path";
|
||||||
|
export default async function apiMediaDELETE(params) {
|
||||||
|
const basePath = grabAPIBasePath({ paradigm: "media" });
|
||||||
|
const mediaID = params.mediaID
|
||||||
|
? typeof params.mediaID === "number"
|
||||||
|
? String(params.mediaID)
|
||||||
|
: params.mediaID
|
||||||
|
: undefined;
|
||||||
|
const finalPath = path.join(basePath, mediaID || "");
|
||||||
|
const DELETE_MEDIA_RES = await queryDSQLAPI({
|
||||||
|
method: "DELETE",
|
||||||
|
path: finalPath,
|
||||||
|
});
|
||||||
|
return DELETE_MEDIA_RES;
|
||||||
|
}
|
3
dist/package-shared/api/media/get.d.ts
vendored
Normal file
3
dist/package-shared/api/media/get.d.ts
vendored
Normal file
@ -0,0 +1,3 @@
|
|||||||
|
import { APIGetMediaParams, APIResponseObject } from "../../types";
|
||||||
|
import { DSQL_DATASQUIREL_USER_MEDIA } from "../../types/dsql";
|
||||||
|
export default function apiMediaGET(params: APIGetMediaParams): Promise<APIResponseObject<DSQL_DATASQUIREL_USER_MEDIA | DSQL_DATASQUIREL_USER_MEDIA[]>>;
|
18
dist/package-shared/api/media/get.js
vendored
Normal file
18
dist/package-shared/api/media/get.js
vendored
Normal file
@ -0,0 +1,18 @@
|
|||||||
|
import queryDSQLAPI from "../../functions/api/query-dsql-api";
|
||||||
|
import path from "path";
|
||||||
|
import grabAPIBasePath from "../../utils/grab-api-base-path";
|
||||||
|
export default async function apiMediaGET(params) {
|
||||||
|
const basePath = grabAPIBasePath({ paradigm: "media" });
|
||||||
|
const mediaID = params.mediaID
|
||||||
|
? typeof params.mediaID === "number"
|
||||||
|
? String(params.mediaID)
|
||||||
|
: params.mediaID
|
||||||
|
: undefined;
|
||||||
|
const finalPath = path.join(basePath, mediaID || "");
|
||||||
|
const GET_MEDIA_RES = await queryDSQLAPI({
|
||||||
|
method: "GET",
|
||||||
|
path: finalPath,
|
||||||
|
query: params,
|
||||||
|
});
|
||||||
|
return GET_MEDIA_RES;
|
||||||
|
}
|
9
dist/package-shared/api/media/index.d.ts
vendored
Normal file
9
dist/package-shared/api/media/index.d.ts
vendored
Normal file
@ -0,0 +1,9 @@
|
|||||||
|
import apiMediaGET from "./get";
|
||||||
|
import apiMediaPOST from "./post";
|
||||||
|
import apiMediaDELETE from "./delete";
|
||||||
|
declare const media: {
|
||||||
|
get: typeof apiMediaGET;
|
||||||
|
add: typeof apiMediaPOST;
|
||||||
|
delete: typeof apiMediaDELETE;
|
||||||
|
};
|
||||||
|
export default media;
|
9
dist/package-shared/api/media/index.js
vendored
Normal file
9
dist/package-shared/api/media/index.js
vendored
Normal file
@ -0,0 +1,9 @@
|
|||||||
|
import apiMediaGET from "./get";
|
||||||
|
import apiMediaPOST from "./post";
|
||||||
|
import apiMediaDELETE from "./delete";
|
||||||
|
const media = {
|
||||||
|
get: apiMediaGET,
|
||||||
|
add: apiMediaPOST,
|
||||||
|
delete: apiMediaDELETE,
|
||||||
|
};
|
||||||
|
export default media;
|
3
dist/package-shared/api/media/post.d.ts
vendored
Normal file
3
dist/package-shared/api/media/post.d.ts
vendored
Normal file
@ -0,0 +1,3 @@
|
|||||||
|
import { AddMediaAPIBody, APIResponseObject } from "../../types";
|
||||||
|
import { DSQL_DATASQUIREL_USER_MEDIA } from "../../types/dsql";
|
||||||
|
export default function apiMediaPOST(params: AddMediaAPIBody): Promise<APIResponseObject<DSQL_DATASQUIREL_USER_MEDIA | DSQL_DATASQUIREL_USER_MEDIA[]>>;
|
11
dist/package-shared/api/media/post.js
vendored
Normal file
11
dist/package-shared/api/media/post.js
vendored
Normal file
@ -0,0 +1,11 @@
|
|||||||
|
import queryDSQLAPI from "../../functions/api/query-dsql-api";
|
||||||
|
import grabAPIBasePath from "../../utils/grab-api-base-path";
|
||||||
|
export default async function apiMediaPOST(params) {
|
||||||
|
const basePath = grabAPIBasePath({ paradigm: "media" });
|
||||||
|
const POST_MEDIA_RES = await queryDSQLAPI({
|
||||||
|
method: "POST",
|
||||||
|
path: basePath,
|
||||||
|
body: params,
|
||||||
|
});
|
||||||
|
return POST_MEDIA_RES;
|
||||||
|
}
|
2
dist/package-shared/api/user/index.d.ts
vendored
Normal file
2
dist/package-shared/api/user/index.d.ts
vendored
Normal file
@ -0,0 +1,2 @@
|
|||||||
|
declare const user: {};
|
||||||
|
export default user;
|
2
dist/package-shared/api/user/index.js
vendored
Normal file
2
dist/package-shared/api/user/index.js
vendored
Normal file
@ -0,0 +1,2 @@
|
|||||||
|
const user = {};
|
||||||
|
export default user;
|
87
dist/package-shared/data/data-types.d.ts
vendored
Normal file
87
dist/package-shared/data/data-types.d.ts
vendored
Normal file
@ -0,0 +1,87 @@
|
|||||||
|
declare const DataTypes: readonly [{
|
||||||
|
readonly title: "VARCHAR";
|
||||||
|
readonly name: "VARCHAR";
|
||||||
|
readonly value: "0-255";
|
||||||
|
readonly argument: true;
|
||||||
|
readonly description: "Varchar is simply letters and numbers within the range 0 - 255";
|
||||||
|
readonly maxValue: 255;
|
||||||
|
}, {
|
||||||
|
readonly title: "TINYINT";
|
||||||
|
readonly name: "TINYINT";
|
||||||
|
readonly value: "0-100";
|
||||||
|
readonly description: "TINYINT means Integers: 0 to 100";
|
||||||
|
readonly maxValue: 127;
|
||||||
|
}, {
|
||||||
|
readonly title: "SMALLINT";
|
||||||
|
readonly name: "SMALLINT";
|
||||||
|
readonly value: "0-255";
|
||||||
|
readonly description: "SMALLINT means Integers: 0 to 240933";
|
||||||
|
readonly maxValue: 32767;
|
||||||
|
}, {
|
||||||
|
readonly title: "MEDIUMINT";
|
||||||
|
readonly name: "MEDIUMINT";
|
||||||
|
readonly value: "0-255";
|
||||||
|
readonly description: "MEDIUMINT means Integers: 0 to 1245568545560";
|
||||||
|
readonly maxValue: 8388607;
|
||||||
|
}, {
|
||||||
|
readonly title: "INT";
|
||||||
|
readonly name: "INT";
|
||||||
|
readonly value: "0-255";
|
||||||
|
readonly description: "INT means Integers: 0 to 12560";
|
||||||
|
readonly maxValue: 2147483647;
|
||||||
|
}, {
|
||||||
|
readonly title: "BIGINT";
|
||||||
|
readonly name: "BIGINT";
|
||||||
|
readonly value: "0-255";
|
||||||
|
readonly description: "BIGINT means Integers: 0 to 1245569056767568545560";
|
||||||
|
readonly maxValue: 2e+63;
|
||||||
|
}, {
|
||||||
|
readonly title: "TINYTEXT";
|
||||||
|
readonly name: "TINYTEXT";
|
||||||
|
readonly value: "0-255";
|
||||||
|
readonly description: "Text with 255 max characters";
|
||||||
|
readonly maxValue: 127;
|
||||||
|
}, {
|
||||||
|
readonly title: "TEXT";
|
||||||
|
readonly name: "TEXT";
|
||||||
|
readonly value: "0-100";
|
||||||
|
readonly description: "MEDIUMTEXT is just text with max length 16,777,215";
|
||||||
|
}, {
|
||||||
|
readonly title: "MEDIUMTEXT";
|
||||||
|
readonly name: "MEDIUMTEXT";
|
||||||
|
readonly value: "0-255";
|
||||||
|
readonly description: "MEDIUMTEXT is just text with max length 16,777,215";
|
||||||
|
}, {
|
||||||
|
readonly title: "LONGTEXT";
|
||||||
|
readonly name: "LONGTEXT";
|
||||||
|
readonly value: "0-255";
|
||||||
|
readonly description: "LONGTEXT is just text with max length 4,294,967,295";
|
||||||
|
}, {
|
||||||
|
readonly title: "DECIMAL";
|
||||||
|
readonly name: "DECIMAL";
|
||||||
|
readonly description: "Numbers with decimals";
|
||||||
|
readonly integer: "1-100";
|
||||||
|
readonly decimals: "1-4";
|
||||||
|
}, {
|
||||||
|
readonly title: "FLOAT";
|
||||||
|
readonly name: "FLOAT";
|
||||||
|
readonly description: "Numbers with decimals";
|
||||||
|
readonly integer: "1-100";
|
||||||
|
readonly decimals: "1-4";
|
||||||
|
}, {
|
||||||
|
readonly title: "DOUBLE";
|
||||||
|
readonly name: "DOUBLE";
|
||||||
|
readonly description: "Numbers with decimals";
|
||||||
|
readonly integer: "1-100";
|
||||||
|
readonly decimals: "1-4";
|
||||||
|
}, {
|
||||||
|
readonly title: "UUID";
|
||||||
|
readonly name: "UUID";
|
||||||
|
readonly valueLiteral: "UUID()";
|
||||||
|
readonly description: "A Unique ID";
|
||||||
|
}, {
|
||||||
|
readonly title: "TIMESTAMP";
|
||||||
|
readonly name: "TIMESTAMP";
|
||||||
|
readonly description: "Time Stamp";
|
||||||
|
}];
|
||||||
|
export default DataTypes;
|
103
dist/package-shared/data/data-types.js
vendored
Normal file
103
dist/package-shared/data/data-types.js
vendored
Normal file
@ -0,0 +1,103 @@
|
|||||||
|
const DataTypes = [
|
||||||
|
{
|
||||||
|
title: "VARCHAR",
|
||||||
|
name: "VARCHAR",
|
||||||
|
value: "0-255",
|
||||||
|
argument: true,
|
||||||
|
description: "Varchar is simply letters and numbers within the range 0 - 255",
|
||||||
|
maxValue: 255,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: "TINYINT",
|
||||||
|
name: "TINYINT",
|
||||||
|
value: "0-100",
|
||||||
|
description: "TINYINT means Integers: 0 to 100",
|
||||||
|
maxValue: 127,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: "SMALLINT",
|
||||||
|
name: "SMALLINT",
|
||||||
|
value: "0-255",
|
||||||
|
description: "SMALLINT means Integers: 0 to 240933",
|
||||||
|
maxValue: 32767,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: "MEDIUMINT",
|
||||||
|
name: "MEDIUMINT",
|
||||||
|
value: "0-255",
|
||||||
|
description: "MEDIUMINT means Integers: 0 to 1245568545560",
|
||||||
|
maxValue: 8388607,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: "INT",
|
||||||
|
name: "INT",
|
||||||
|
value: "0-255",
|
||||||
|
description: "INT means Integers: 0 to 12560",
|
||||||
|
maxValue: 2147483647,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: "BIGINT",
|
||||||
|
name: "BIGINT",
|
||||||
|
value: "0-255",
|
||||||
|
description: "BIGINT means Integers: 0 to 1245569056767568545560",
|
||||||
|
maxValue: 2e63,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: "TINYTEXT",
|
||||||
|
name: "TINYTEXT",
|
||||||
|
value: "0-255",
|
||||||
|
description: "Text with 255 max characters",
|
||||||
|
maxValue: 127,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: "TEXT",
|
||||||
|
name: "TEXT",
|
||||||
|
value: "0-100",
|
||||||
|
description: "MEDIUMTEXT is just text with max length 16,777,215",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: "MEDIUMTEXT",
|
||||||
|
name: "MEDIUMTEXT",
|
||||||
|
value: "0-255",
|
||||||
|
description: "MEDIUMTEXT is just text with max length 16,777,215",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: "LONGTEXT",
|
||||||
|
name: "LONGTEXT",
|
||||||
|
value: "0-255",
|
||||||
|
description: "LONGTEXT is just text with max length 4,294,967,295",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: "DECIMAL",
|
||||||
|
name: "DECIMAL",
|
||||||
|
description: "Numbers with decimals",
|
||||||
|
integer: "1-100",
|
||||||
|
decimals: "1-4",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: "FLOAT",
|
||||||
|
name: "FLOAT",
|
||||||
|
description: "Numbers with decimals",
|
||||||
|
integer: "1-100",
|
||||||
|
decimals: "1-4",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: "DOUBLE",
|
||||||
|
name: "DOUBLE",
|
||||||
|
description: "Numbers with decimals",
|
||||||
|
integer: "1-100",
|
||||||
|
decimals: "1-4",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: "UUID",
|
||||||
|
name: "UUID",
|
||||||
|
valueLiteral: "UUID()",
|
||||||
|
description: "A Unique ID",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: "TIMESTAMP",
|
||||||
|
name: "TIMESTAMP",
|
||||||
|
description: "Time Stamp",
|
||||||
|
},
|
||||||
|
];
|
||||||
|
export default DataTypes;
|
105
dist/package-shared/data/data-types.ts
vendored
Normal file
105
dist/package-shared/data/data-types.ts
vendored
Normal file
@ -0,0 +1,105 @@
|
|||||||
|
const DataTypes = [
|
||||||
|
{
|
||||||
|
title: "VARCHAR",
|
||||||
|
name: "VARCHAR",
|
||||||
|
value: "0-255",
|
||||||
|
argument: true,
|
||||||
|
description:
|
||||||
|
"Varchar is simply letters and numbers within the range 0 - 255",
|
||||||
|
maxValue: 255,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: "TINYINT",
|
||||||
|
name: "TINYINT",
|
||||||
|
value: "0-100",
|
||||||
|
description: "TINYINT means Integers: 0 to 100",
|
||||||
|
maxValue: 127,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: "SMALLINT",
|
||||||
|
name: "SMALLINT",
|
||||||
|
value: "0-255",
|
||||||
|
description: "SMALLINT means Integers: 0 to 240933",
|
||||||
|
maxValue: 32767,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: "MEDIUMINT",
|
||||||
|
name: "MEDIUMINT",
|
||||||
|
value: "0-255",
|
||||||
|
description: "MEDIUMINT means Integers: 0 to 1245568545560",
|
||||||
|
maxValue: 8388607,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: "INT",
|
||||||
|
name: "INT",
|
||||||
|
value: "0-255",
|
||||||
|
description: "INT means Integers: 0 to 12560",
|
||||||
|
maxValue: 2147483647,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: "BIGINT",
|
||||||
|
name: "BIGINT",
|
||||||
|
value: "0-255",
|
||||||
|
description: "BIGINT means Integers: 0 to 1245569056767568545560",
|
||||||
|
maxValue: 2e63,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: "TINYTEXT",
|
||||||
|
name: "TINYTEXT",
|
||||||
|
value: "0-255",
|
||||||
|
description: "Text with 255 max characters",
|
||||||
|
maxValue: 127,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: "TEXT",
|
||||||
|
name: "TEXT",
|
||||||
|
value: "0-100",
|
||||||
|
description: "MEDIUMTEXT is just text with max length 16,777,215",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: "MEDIUMTEXT",
|
||||||
|
name: "MEDIUMTEXT",
|
||||||
|
value: "0-255",
|
||||||
|
description: "MEDIUMTEXT is just text with max length 16,777,215",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: "LONGTEXT",
|
||||||
|
name: "LONGTEXT",
|
||||||
|
value: "0-255",
|
||||||
|
description: "LONGTEXT is just text with max length 4,294,967,295",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: "DECIMAL",
|
||||||
|
name: "DECIMAL",
|
||||||
|
description: "Numbers with decimals",
|
||||||
|
integer: "1-100",
|
||||||
|
decimals: "1-4",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: "FLOAT",
|
||||||
|
name: "FLOAT",
|
||||||
|
description: "Numbers with decimals",
|
||||||
|
integer: "1-100",
|
||||||
|
decimals: "1-4",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: "DOUBLE",
|
||||||
|
name: "DOUBLE",
|
||||||
|
description: "Numbers with decimals",
|
||||||
|
integer: "1-100",
|
||||||
|
decimals: "1-4",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: "UUID",
|
||||||
|
name: "UUID",
|
||||||
|
valueLiteral: "UUID()",
|
||||||
|
description: "A Unique ID",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: "TIMESTAMP",
|
||||||
|
name: "TIMESTAMP",
|
||||||
|
description: "Time Stamp",
|
||||||
|
},
|
||||||
|
] as const;
|
||||||
|
|
||||||
|
export default DataTypes;
|
8
dist/package-shared/data/dataTypes.json
vendored
8
dist/package-shared/data/dataTypes.json
vendored
@ -88,6 +88,14 @@
|
|||||||
"integer": "1-100",
|
"integer": "1-100",
|
||||||
"decimals": "1-4"
|
"decimals": "1-4"
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
"title": "OPTIONS",
|
||||||
|
"name": "VARCHAR",
|
||||||
|
"value": "250",
|
||||||
|
"argument": true,
|
||||||
|
"description": "This is a custom field which is a varchar under the hood",
|
||||||
|
"maxValue": 255
|
||||||
|
},
|
||||||
{
|
{
|
||||||
"title": "UUID",
|
"title": "UUID",
|
||||||
"name": "UUID",
|
"name": "UUID",
|
||||||
|
8
dist/package-shared/dict/app-names.d.ts
vendored
Normal file
8
dist/package-shared/dict/app-names.d.ts
vendored
Normal file
@ -0,0 +1,8 @@
|
|||||||
|
export declare const AppNames: {
|
||||||
|
readonly MaxScaleUserName: "dsql_maxscale_user";
|
||||||
|
readonly ReplicaUserName: "dsql_replication_user";
|
||||||
|
readonly DsqlDbPrefix: "datasquirel_user_";
|
||||||
|
readonly PrivateMediaProceedureName: "dsql_UpdateUserMedia";
|
||||||
|
readonly PrivateMediaInsertTriggerName: "dsql_trg_user_private_folders_insert";
|
||||||
|
readonly PrivateMediaDeleteTriggerName: "dsql_trg_user_private_folders_delete";
|
||||||
|
};
|
8
dist/package-shared/dict/app-names.js
vendored
Normal file
8
dist/package-shared/dict/app-names.js
vendored
Normal file
@ -0,0 +1,8 @@
|
|||||||
|
export const AppNames = {
|
||||||
|
MaxScaleUserName: "dsql_maxscale_user",
|
||||||
|
ReplicaUserName: "dsql_replication_user",
|
||||||
|
DsqlDbPrefix: "datasquirel_user_",
|
||||||
|
PrivateMediaProceedureName: "dsql_UpdateUserMedia",
|
||||||
|
PrivateMediaInsertTriggerName: "dsql_trg_user_private_folders_insert",
|
||||||
|
PrivateMediaDeleteTriggerName: "dsql_trg_user_private_folders_delete",
|
||||||
|
};
|
5
dist/package-shared/dict/cookie-names.d.ts
vendored
Normal file
5
dist/package-shared/dict/cookie-names.d.ts
vendored
Normal file
@ -0,0 +1,5 @@
|
|||||||
|
export declare const CookieNames: {
|
||||||
|
readonly OneTimeLoginEmail: "dsql-one-time-login-email";
|
||||||
|
readonly DelegatedUserId: "dsql-delegated-user-id";
|
||||||
|
readonly DelegatedDatabase: "dsql-delegated-database";
|
||||||
|
};
|
5
dist/package-shared/dict/cookie-names.js
vendored
Normal file
5
dist/package-shared/dict/cookie-names.js
vendored
Normal file
@ -0,0 +1,5 @@
|
|||||||
|
export const CookieNames = {
|
||||||
|
OneTimeLoginEmail: "dsql-one-time-login-email",
|
||||||
|
DelegatedUserId: "dsql-delegated-user-id",
|
||||||
|
DelegatedDatabase: "dsql-delegated-database",
|
||||||
|
};
|
7
dist/package-shared/dict/local-storage-dict.d.ts
vendored
Normal file
7
dist/package-shared/dict/local-storage-dict.d.ts
vendored
Normal file
@ -0,0 +1,7 @@
|
|||||||
|
export declare const LocalStorageDict: {
|
||||||
|
OneTimeEmail: string;
|
||||||
|
User: string;
|
||||||
|
CSRF: string;
|
||||||
|
CurrentQueue: string;
|
||||||
|
DiskUsage: string;
|
||||||
|
};
|
8
dist/package-shared/dict/local-storage-dict.js
vendored
Normal file
8
dist/package-shared/dict/local-storage-dict.js
vendored
Normal file
@ -0,0 +1,8 @@
|
|||||||
|
import getCsrfHeaderName from "../actions/get-csrf-header-name";
|
||||||
|
export const LocalStorageDict = {
|
||||||
|
OneTimeEmail: "dsql-one-time-login-email",
|
||||||
|
User: "user",
|
||||||
|
CSRF: getCsrfHeaderName(),
|
||||||
|
CurrentQueue: "current_queue",
|
||||||
|
DiskUsage: "disk_usage",
|
||||||
|
};
|
6
dist/package-shared/dict/resource-limits.d.ts
vendored
Normal file
6
dist/package-shared/dict/resource-limits.d.ts
vendored
Normal file
@ -0,0 +1,6 @@
|
|||||||
|
declare const ResourceLimits: {
|
||||||
|
readonly user_databases: 20;
|
||||||
|
readonly table_entries: 20;
|
||||||
|
readonly general: 20;
|
||||||
|
};
|
||||||
|
export default ResourceLimits;
|
6
dist/package-shared/dict/resource-limits.js
vendored
Normal file
6
dist/package-shared/dict/resource-limits.js
vendored
Normal file
@ -0,0 +1,6 @@
|
|||||||
|
const ResourceLimits = {
|
||||||
|
user_databases: 20,
|
||||||
|
table_entries: 20,
|
||||||
|
general: 20,
|
||||||
|
};
|
||||||
|
export default ResourceLimits;
|
20
dist/package-shared/functions/api/query-dsql-api.d.ts
vendored
Normal file
20
dist/package-shared/functions/api/query-dsql-api.d.ts
vendored
Normal file
@ -0,0 +1,20 @@
|
|||||||
|
import { APIResponseObject, DataCrudRequestMethods, DataCrudRequestMethodsLowerCase } from "../../types";
|
||||||
|
type Param<T = {
|
||||||
|
[k: string]: any;
|
||||||
|
}> = {
|
||||||
|
key?: string;
|
||||||
|
body?: T;
|
||||||
|
query?: T;
|
||||||
|
useDefault?: boolean;
|
||||||
|
path: string;
|
||||||
|
method?: (typeof DataCrudRequestMethods)[number] | (typeof DataCrudRequestMethodsLowerCase)[number];
|
||||||
|
};
|
||||||
|
/**
|
||||||
|
* # Query DSQL API
|
||||||
|
*/
|
||||||
|
export default function queryDSQLAPI<T = {
|
||||||
|
[k: string]: any;
|
||||||
|
}, P = {
|
||||||
|
[k: string]: any;
|
||||||
|
}>({ key, body, query, useDefault, path: passedPath, method, }: Param<T>): Promise<APIResponseObject<P>>;
|
||||||
|
export {};
|
73
dist/package-shared/functions/api/query-dsql-api.js
vendored
Normal file
73
dist/package-shared/functions/api/query-dsql-api.js
vendored
Normal file
@ -0,0 +1,73 @@
|
|||||||
|
import path from "path";
|
||||||
|
import grabHostNames from "../../utils/grab-host-names";
|
||||||
|
import serializeQuery from "../../utils/serialize-query";
|
||||||
|
/**
|
||||||
|
* # Query DSQL API
|
||||||
|
*/
|
||||||
|
export default async function queryDSQLAPI({ key, body, query, useDefault, path: passedPath, method, }) {
|
||||||
|
const grabedHostNames = grabHostNames({ useDefault });
|
||||||
|
const { host, port, scheme } = grabedHostNames;
|
||||||
|
try {
|
||||||
|
/**
|
||||||
|
* Make https request
|
||||||
|
*
|
||||||
|
* @description make a request to datasquirel.com
|
||||||
|
*/
|
||||||
|
const httpResponse = await new Promise((resolve, reject) => {
|
||||||
|
const reqPayload = body ? JSON.stringify(body) : undefined;
|
||||||
|
let headers = {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
Authorization: key ||
|
||||||
|
(!method || method == "GET" || method == "get"
|
||||||
|
? process.env.DSQL_READ_ONLY_API_KEY
|
||||||
|
: undefined) ||
|
||||||
|
process.env.DSQL_FULL_ACCESS_API_KEY ||
|
||||||
|
process.env.DSQL_API_KEY,
|
||||||
|
};
|
||||||
|
if (reqPayload) {
|
||||||
|
headers["Content-Length"] = Buffer.from(reqPayload).length;
|
||||||
|
}
|
||||||
|
let finalPath = path.join("/", passedPath);
|
||||||
|
if (query) {
|
||||||
|
const queryString = serializeQuery(query);
|
||||||
|
finalPath += `${queryString}`;
|
||||||
|
}
|
||||||
|
const httpsRequest = scheme.request({
|
||||||
|
method: method || "GET",
|
||||||
|
headers,
|
||||||
|
port,
|
||||||
|
hostname: host,
|
||||||
|
path: finalPath,
|
||||||
|
},
|
||||||
|
/**
|
||||||
|
* Callback Function
|
||||||
|
*
|
||||||
|
* @description https request callback
|
||||||
|
*/
|
||||||
|
(response) => {
|
||||||
|
var str = "";
|
||||||
|
response.on("data", function (chunk) {
|
||||||
|
str += chunk;
|
||||||
|
});
|
||||||
|
response.on("end", function () {
|
||||||
|
resolve(JSON.parse(str));
|
||||||
|
});
|
||||||
|
response.on("error", (err) => {
|
||||||
|
reject(err);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
if (reqPayload) {
|
||||||
|
httpsRequest.write(reqPayload);
|
||||||
|
}
|
||||||
|
httpsRequest.end();
|
||||||
|
});
|
||||||
|
return httpResponse;
|
||||||
|
}
|
||||||
|
catch (error) {
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
payload: undefined,
|
||||||
|
msg: error.message,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
44
dist/package-shared/functions/api/query/get.js
vendored
44
dist/package-shared/functions/api/query/get.js
vendored
@ -1,29 +1,13 @@
|
|||||||
"use strict";
|
import _ from "lodash";
|
||||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
import serverError from "../../backend/serverError";
|
||||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
import runQuery from "../../backend/db/runQuery";
|
||||||
return new (P || (P = Promise))(function (resolve, reject) {
|
import apiGetGrabQueryAndValues from "../../../utils/grab-query-and-values";
|
||||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
|
||||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
||||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
||||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
||||||
});
|
|
||||||
};
|
|
||||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
||||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
||||||
};
|
|
||||||
Object.defineProperty(exports, "__esModule", { value: true });
|
|
||||||
exports.default = apiGet;
|
|
||||||
const lodash_1 = __importDefault(require("lodash"));
|
|
||||||
const serverError_1 = __importDefault(require("../../backend/serverError"));
|
|
||||||
const runQuery_1 = __importDefault(require("../../backend/db/runQuery"));
|
|
||||||
const grab_query_and_values_1 = __importDefault(require("../../../utils/grab-query-and-values"));
|
|
||||||
/**
|
/**
|
||||||
* # Get Function FOr API
|
* # Get Function FOr API
|
||||||
*/
|
*/
|
||||||
function apiGet(_a) {
|
export default async function apiGet({ query, dbFullName, queryValues, tableName, dbSchema, debug, dbContext, forceLocal, }) {
|
||||||
return __awaiter(this, arguments, void 0, function* ({ query, dbFullName, queryValues, tableName, dbSchema, debug, dbContext, forceLocal, }) {
|
var _a, _b;
|
||||||
var _b, _c;
|
const queryAndValues = apiGetGrabQueryAndValues({
|
||||||
const queryAndValues = (0, grab_query_and_values_1.default)({
|
|
||||||
query,
|
query,
|
||||||
values: queryValues,
|
values: queryValues,
|
||||||
});
|
});
|
||||||
@ -32,7 +16,7 @@ function apiGet(_a) {
|
|||||||
}
|
}
|
||||||
let results;
|
let results;
|
||||||
try {
|
try {
|
||||||
let { result, error } = yield (0, runQuery_1.default)({
|
let { result, error } = await runQuery({
|
||||||
dbFullName: dbFullName,
|
dbFullName: dbFullName,
|
||||||
query: queryAndValues.query,
|
query: queryAndValues.query,
|
||||||
queryValuesArray: queryAndValues.values,
|
queryValuesArray: queryAndValues.values,
|
||||||
@ -49,15 +33,12 @@ function apiGet(_a) {
|
|||||||
}
|
}
|
||||||
let tableSchema;
|
let tableSchema;
|
||||||
if (dbSchema) {
|
if (dbSchema) {
|
||||||
const targetTable = (_b = dbSchema.tables) === null || _b === void 0 ? void 0 : _b.find((table) => table.tableName === tableName);
|
const targetTable = (_a = dbSchema.tables) === null || _a === void 0 ? void 0 : _a.find((table) => table.tableName === tableName);
|
||||||
if (targetTable) {
|
if (targetTable) {
|
||||||
const clonedTargetTable = lodash_1.default.cloneDeep(targetTable);
|
const clonedTargetTable = _.cloneDeep(targetTable);
|
||||||
delete clonedTargetTable.childTable;
|
delete clonedTargetTable.childTable;
|
||||||
delete clonedTargetTable.childTableDbFullName;
|
|
||||||
delete clonedTargetTable.childTableName;
|
|
||||||
delete clonedTargetTable.childrenTables;
|
delete clonedTargetTable.childrenTables;
|
||||||
delete clonedTargetTable.updateData;
|
delete clonedTargetTable.updateData;
|
||||||
delete clonedTargetTable.tableNameOld;
|
|
||||||
delete clonedTargetTable.indexes;
|
delete clonedTargetTable.indexes;
|
||||||
tableSchema = clonedTargetTable;
|
tableSchema = clonedTargetTable;
|
||||||
}
|
}
|
||||||
@ -75,11 +56,11 @@ function apiGet(_a) {
|
|||||||
return resObject;
|
return resObject;
|
||||||
}
|
}
|
||||||
catch (error) {
|
catch (error) {
|
||||||
(0, serverError_1.default)({
|
serverError({
|
||||||
component: "/api/query/get/lines-85-94",
|
component: "/api/query/get/lines-85-94",
|
||||||
message: error.message,
|
message: error.message,
|
||||||
});
|
});
|
||||||
(_c = global.ERROR_CALLBACK) === null || _c === void 0 ? void 0 : _c.call(global, `API Get Error`, error);
|
(_b = global.ERROR_CALLBACK) === null || _b === void 0 ? void 0 : _b.call(global, `API Get Error`, error);
|
||||||
if (debug && global.DSQL_USE_LOCAL) {
|
if (debug && global.DSQL_USE_LOCAL) {
|
||||||
console.log("apiGet:error", error.message);
|
console.log("apiGet:error", error.message);
|
||||||
console.log("queryAndValues", queryAndValues);
|
console.log("queryAndValues", queryAndValues);
|
||||||
@ -90,5 +71,4 @@ function apiGet(_a) {
|
|||||||
error: error.message,
|
error: error.message,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
52
dist/package-shared/functions/api/query/post.js
vendored
52
dist/package-shared/functions/api/query/post.js
vendored
@ -1,33 +1,17 @@
|
|||||||
"use strict";
|
import _ from "lodash";
|
||||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
import serverError from "../../backend/serverError";
|
||||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
import runQuery from "../../backend/db/runQuery";
|
||||||
return new (P || (P = Promise))(function (resolve, reject) {
|
import debugLog from "../../../utils/logging/debug-log";
|
||||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
|
||||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
||||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
||||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
||||||
});
|
|
||||||
};
|
|
||||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
||||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
||||||
};
|
|
||||||
Object.defineProperty(exports, "__esModule", { value: true });
|
|
||||||
exports.default = apiPost;
|
|
||||||
const lodash_1 = __importDefault(require("lodash"));
|
|
||||||
const serverError_1 = __importDefault(require("../../backend/serverError"));
|
|
||||||
const runQuery_1 = __importDefault(require("../../backend/db/runQuery"));
|
|
||||||
const debug_log_1 = __importDefault(require("../../../utils/logging/debug-log"));
|
|
||||||
/**
|
/**
|
||||||
* # Post Function For API
|
* # Post Function For API
|
||||||
*/
|
*/
|
||||||
function apiPost(_a) {
|
export default async function apiPost({ query, dbFullName, queryValues, tableName, dbSchema, dbContext, forceLocal, debug, }) {
|
||||||
return __awaiter(this, arguments, void 0, function* ({ query, dbFullName, queryValues, tableName, dbSchema, dbContext, forceLocal, debug, }) {
|
var _a, _b;
|
||||||
var _b, _c;
|
|
||||||
if (typeof query === "string" && (query === null || query === void 0 ? void 0 : query.match(/^create |^alter |^drop /i))) {
|
if (typeof query === "string" && (query === null || query === void 0 ? void 0 : query.match(/^create |^alter |^drop /i))) {
|
||||||
return { success: false, msg: "Wrong Input" };
|
return { success: false, msg: "Wrong Input" };
|
||||||
}
|
}
|
||||||
if (typeof query === "object" &&
|
if (typeof query === "object" &&
|
||||||
((_b = query === null || query === void 0 ? void 0 : query.action) === null || _b === void 0 ? void 0 : _b.match(/^create |^alter |^drop /i))) {
|
((_a = query === null || query === void 0 ? void 0 : query.action) === null || _a === void 0 ? void 0 : _a.match(/^create |^alter |^drop /i))) {
|
||||||
return { success: false, msg: "Wrong Input" };
|
return { success: false, msg: "Wrong Input" };
|
||||||
}
|
}
|
||||||
let results;
|
let results;
|
||||||
@ -37,10 +21,10 @@ function apiPost(_a) {
|
|||||||
* @description Create new user folder and file
|
* @description Create new user folder and file
|
||||||
*/
|
*/
|
||||||
try {
|
try {
|
||||||
let { result, error } = yield (0, runQuery_1.default)({
|
let { result, error } = await runQuery({
|
||||||
dbFullName: dbFullName,
|
dbFullName,
|
||||||
query: query,
|
query,
|
||||||
dbSchema: dbSchema,
|
dbSchema,
|
||||||
queryValuesArray: queryValues,
|
queryValuesArray: queryValues,
|
||||||
tableName,
|
tableName,
|
||||||
dbContext,
|
dbContext,
|
||||||
@ -48,12 +32,12 @@ function apiPost(_a) {
|
|||||||
debug,
|
debug,
|
||||||
});
|
});
|
||||||
if (debug) {
|
if (debug) {
|
||||||
(0, debug_log_1.default)({
|
debugLog({
|
||||||
log: result,
|
log: result,
|
||||||
addTime: true,
|
addTime: true,
|
||||||
label: "result",
|
label: "result",
|
||||||
});
|
});
|
||||||
(0, debug_log_1.default)({
|
debugLog({
|
||||||
log: query,
|
log: query,
|
||||||
addTime: true,
|
addTime: true,
|
||||||
label: "query",
|
label: "query",
|
||||||
@ -66,13 +50,10 @@ function apiPost(_a) {
|
|||||||
if (dbSchema) {
|
if (dbSchema) {
|
||||||
const targetTable = dbSchema.tables.find((table) => table.tableName === tableName);
|
const targetTable = dbSchema.tables.find((table) => table.tableName === tableName);
|
||||||
if (targetTable) {
|
if (targetTable) {
|
||||||
const clonedTargetTable = lodash_1.default.cloneDeep(targetTable);
|
const clonedTargetTable = _.cloneDeep(targetTable);
|
||||||
delete clonedTargetTable.childTable;
|
delete clonedTargetTable.childTable;
|
||||||
delete clonedTargetTable.childTableDbFullName;
|
|
||||||
delete clonedTargetTable.childTableName;
|
|
||||||
delete clonedTargetTable.childrenTables;
|
delete clonedTargetTable.childrenTables;
|
||||||
delete clonedTargetTable.updateData;
|
delete clonedTargetTable.updateData;
|
||||||
delete clonedTargetTable.tableNameOld;
|
|
||||||
delete clonedTargetTable.indexes;
|
delete clonedTargetTable.indexes;
|
||||||
tableSchema = clonedTargetTable;
|
tableSchema = clonedTargetTable;
|
||||||
}
|
}
|
||||||
@ -85,16 +66,15 @@ function apiPost(_a) {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
catch (error) {
|
catch (error) {
|
||||||
(0, serverError_1.default)({
|
serverError({
|
||||||
component: "/api/query/post/lines-132-142",
|
component: "/api/query/post/lines-132-142",
|
||||||
message: error.message,
|
message: error.message,
|
||||||
});
|
});
|
||||||
(_c = global.ERROR_CALLBACK) === null || _c === void 0 ? void 0 : _c.call(global, `API Post Error`, error);
|
(_b = global.ERROR_CALLBACK) === null || _b === void 0 ? void 0 : _b.call(global, `API Post Error`, error);
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
payload: results,
|
payload: results,
|
||||||
error: error.message,
|
error: error.message,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
@ -1,35 +1,19 @@
|
|||||||
"use strict";
|
import DB_HANDLER from "../../../utils/backend/global-db/DB_HANDLER";
|
||||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
import serverError from "../../backend/serverError";
|
||||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
import hashPassword from "../../dsql/hashPassword";
|
||||||
return new (P || (P = Promise))(function (resolve, reject) {
|
|
||||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
|
||||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
||||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
||||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
||||||
});
|
|
||||||
};
|
|
||||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
||||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
||||||
};
|
|
||||||
Object.defineProperty(exports, "__esModule", { value: true });
|
|
||||||
exports.default = facebookLogin;
|
|
||||||
const DB_HANDLER_1 = __importDefault(require("../../../utils/backend/global-db/DB_HANDLER"));
|
|
||||||
const serverError_1 = __importDefault(require("../../backend/serverError"));
|
|
||||||
const hashPassword_1 = __importDefault(require("../../dsql/hashPassword"));
|
|
||||||
/**
|
/**
|
||||||
* # Facebook Login
|
* # Facebook Login
|
||||||
*/
|
*/
|
||||||
function facebookLogin(_a) {
|
export default async function facebookLogin({ usertype, body, }) {
|
||||||
return __awaiter(this, arguments, void 0, function* ({ usertype, body, }) {
|
|
||||||
try {
|
try {
|
||||||
const foundUser = yield (0, DB_HANDLER_1.default)(`SELECT * FROM users WHERE email='${body.facebookUserEmail}' AND social_login='1'`);
|
const foundUser = await DB_HANDLER(`SELECT * FROM users WHERE email='${body.facebookUserEmail}' AND social_login='1'`);
|
||||||
if (foundUser && foundUser[0]) {
|
if (foundUser && foundUser[0]) {
|
||||||
return foundUser[0];
|
return foundUser[0];
|
||||||
}
|
}
|
||||||
let socialHashedPassword = (0, hashPassword_1.default)({
|
let socialHashedPassword = hashPassword({
|
||||||
password: body.facebookUserId,
|
password: body.facebookUserId,
|
||||||
});
|
});
|
||||||
let newUser = yield (0, DB_HANDLER_1.default)(`INSERT INTO ${usertype} (
|
let newUser = await DB_HANDLER(`INSERT INTO ${usertype} (
|
||||||
first_name,
|
first_name,
|
||||||
last_name,
|
last_name,
|
||||||
social_platform,
|
social_platform,
|
||||||
@ -62,10 +46,10 @@ function facebookLogin(_a) {
|
|||||||
'${Date()}',
|
'${Date()}',
|
||||||
'${Date.now()}'
|
'${Date.now()}'
|
||||||
)`);
|
)`);
|
||||||
const newFoundUser = yield (0, DB_HANDLER_1.default)(`SELECT * FROM ${usertype} WHERE id='${newUser.insertId}'`);
|
const newFoundUser = await DB_HANDLER(`SELECT * FROM ${usertype} WHERE id='${newUser.insertId}'`);
|
||||||
}
|
}
|
||||||
catch ( /** @type {any} */error) {
|
catch ( /** @type {any} */error) {
|
||||||
(0, serverError_1.default)({
|
serverError({
|
||||||
component: "functions/backend/facebookLogin",
|
component: "functions/backend/facebookLogin",
|
||||||
message: error.message,
|
message: error.message,
|
||||||
});
|
});
|
||||||
@ -74,5 +58,4 @@ function facebookLogin(_a) {
|
|||||||
isFacebookAuthValid: false,
|
isFacebookAuthValid: false,
|
||||||
newFoundUser: null,
|
newFoundUser: null,
|
||||||
};
|
};
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
@ -1,28 +1,12 @@
|
|||||||
"use strict";
|
import DB_HANDLER from "../../../utils/backend/global-db/DB_HANDLER";
|
||||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
import httpsRequest from "../../backend/httpsRequest";
|
||||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
|
||||||
return new (P || (P = Promise))(function (resolve, reject) {
|
|
||||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
|
||||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
||||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
||||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
||||||
});
|
|
||||||
};
|
|
||||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
||||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
||||||
};
|
|
||||||
Object.defineProperty(exports, "__esModule", { value: true });
|
|
||||||
exports.default = githubLogin;
|
|
||||||
const DB_HANDLER_1 = __importDefault(require("../../../utils/backend/global-db/DB_HANDLER"));
|
|
||||||
const httpsRequest_1 = __importDefault(require("../../backend/httpsRequest"));
|
|
||||||
/**
|
/**
|
||||||
* # Login/signup a github user
|
* # Login/signup a github user
|
||||||
*/
|
*/
|
||||||
function githubLogin(_a) {
|
export default async function githubLogin({ code, clientId, clientSecret, }) {
|
||||||
return __awaiter(this, arguments, void 0, function* ({ code, clientId, clientSecret, }) {
|
|
||||||
let gitHubUser;
|
let gitHubUser;
|
||||||
try {
|
try {
|
||||||
const response = yield (0, httpsRequest_1.default)({
|
const response = await httpsRequest({
|
||||||
method: "POST",
|
method: "POST",
|
||||||
hostname: "github.com",
|
hostname: "github.com",
|
||||||
path: `/login/oauth/access_token?client_id=${clientId}&client_secret=${clientSecret}&code=${code}`,
|
path: `/login/oauth/access_token?client_id=${clientId}&client_secret=${clientSecret}&code=${code}`,
|
||||||
@ -36,7 +20,7 @@ function githubLogin(_a) {
|
|||||||
if (!(accessTokenObject === null || accessTokenObject === void 0 ? void 0 : accessTokenObject.access_token)) {
|
if (!(accessTokenObject === null || accessTokenObject === void 0 ? void 0 : accessTokenObject.access_token)) {
|
||||||
return gitHubUser;
|
return gitHubUser;
|
||||||
}
|
}
|
||||||
const userDataResponse = yield (0, httpsRequest_1.default)({
|
const userDataResponse = await httpsRequest({
|
||||||
method: "GET",
|
method: "GET",
|
||||||
hostname: "api.github.com",
|
hostname: "api.github.com",
|
||||||
path: "/user",
|
path: "/user",
|
||||||
@ -48,7 +32,7 @@ function githubLogin(_a) {
|
|||||||
});
|
});
|
||||||
gitHubUser = JSON.parse(userDataResponse);
|
gitHubUser = JSON.parse(userDataResponse);
|
||||||
if (!(gitHubUser === null || gitHubUser === void 0 ? void 0 : gitHubUser.email) && gitHubUser) {
|
if (!(gitHubUser === null || gitHubUser === void 0 ? void 0 : gitHubUser.email) && gitHubUser) {
|
||||||
const existingGithubUser = yield (0, DB_HANDLER_1.default)(`SELECT email FROM users WHERE social_login='1' AND social_platform='github' AND social_id='${gitHubUser.id}'`);
|
const existingGithubUser = await DB_HANDLER(`SELECT email FROM users WHERE social_login='1' AND social_platform='github' AND social_id='${gitHubUser.id}'`);
|
||||||
if (existingGithubUser && existingGithubUser[0]) {
|
if (existingGithubUser && existingGithubUser[0]) {
|
||||||
gitHubUser.email = existingGithubUser[0].email;
|
gitHubUser.email = existingGithubUser[0].email;
|
||||||
}
|
}
|
||||||
@ -58,5 +42,4 @@ function githubLogin(_a) {
|
|||||||
console.log("ERROR in githubLogin.ts backend function =>", error.message);
|
console.log("ERROR in githubLogin.ts backend function =>", error.message);
|
||||||
}
|
}
|
||||||
return gitHubUser;
|
return gitHubUser;
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
@ -1,36 +1,20 @@
|
|||||||
"use strict";
|
import { OAuth2Client } from "google-auth-library";
|
||||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
import serverError from "../../backend/serverError";
|
||||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
import DB_HANDLER from "../../../utils/backend/global-db/DB_HANDLER";
|
||||||
return new (P || (P = Promise))(function (resolve, reject) {
|
import hashPassword from "../../dsql/hashPassword";
|
||||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
|
||||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
||||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
||||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
||||||
});
|
|
||||||
};
|
|
||||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
||||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
||||||
};
|
|
||||||
Object.defineProperty(exports, "__esModule", { value: true });
|
|
||||||
exports.default = googleLogin;
|
|
||||||
const google_auth_library_1 = require("google-auth-library");
|
|
||||||
const serverError_1 = __importDefault(require("../../backend/serverError"));
|
|
||||||
const DB_HANDLER_1 = __importDefault(require("../../../utils/backend/global-db/DB_HANDLER"));
|
|
||||||
const hashPassword_1 = __importDefault(require("../../dsql/hashPassword"));
|
|
||||||
/**
|
/**
|
||||||
* # Google Login
|
* # Google Login
|
||||||
*/
|
*/
|
||||||
function googleLogin(_a) {
|
export default async function googleLogin({ usertype, foundUser, isSocialValidated, isUserValid, reqBody, serverRes, loginFailureReason, }) {
|
||||||
return __awaiter(this, arguments, void 0, function* ({ usertype, foundUser, isSocialValidated, isUserValid, reqBody, serverRes, loginFailureReason, }) {
|
var _a, _b;
|
||||||
var _b, _c;
|
const client = new OAuth2Client(process.env.DSQL_GOOGLE_CLIENT_ID);
|
||||||
const client = new google_auth_library_1.OAuth2Client(process.env.DSQL_GOOGLE_CLIENT_ID);
|
|
||||||
let isGoogleAuthValid = false;
|
let isGoogleAuthValid = false;
|
||||||
let newFoundUser = null;
|
let newFoundUser = null;
|
||||||
////////////////////////////////////////////////
|
////////////////////////////////////////////////
|
||||||
////////////////////////////////////////////////
|
////////////////////////////////////////////////
|
||||||
////////////////////////////////////////////////
|
////////////////////////////////////////////////
|
||||||
try {
|
try {
|
||||||
const ticket = yield client.verifyIdToken({
|
const ticket = await client.verifyIdToken({
|
||||||
idToken: reqBody.token,
|
idToken: reqBody.token,
|
||||||
audience: process.env.DSQL_GOOGLE_CLIENT_ID, // Specify the CLIENT_ID of the app that accesses the backend
|
audience: process.env.DSQL_GOOGLE_CLIENT_ID, // Specify the CLIENT_ID of the app that accesses the backend
|
||||||
// Or, if multiple clients access the backend:
|
// Or, if multiple clients access the backend:
|
||||||
@ -48,13 +32,13 @@ function googleLogin(_a) {
|
|||||||
isGoogleAuthValid = payload.email_verified;
|
isGoogleAuthValid = payload.email_verified;
|
||||||
////// If request specified a G Suite domain:
|
////// If request specified a G Suite domain:
|
||||||
////// const domain = payload['hd'];
|
////// const domain = payload['hd'];
|
||||||
let socialHashedPassword = (0, hashPassword_1.default)({
|
let socialHashedPassword = hashPassword({
|
||||||
password: payload.at_hash || "",
|
password: payload.at_hash || "",
|
||||||
});
|
});
|
||||||
////////////////////////////////////////////////
|
////////////////////////////////////////////////
|
||||||
////////////////////////////////////////////////
|
////////////////////////////////////////////////
|
||||||
////////////////////////////////////////////////
|
////////////////////////////////////////////////
|
||||||
let existinEmail = yield (0, DB_HANDLER_1.default)(`SELECT * FROM ${usertype} WHERE email='${payload.email}' AND social_login!='1' AND social_platform!='google'`);
|
let existinEmail = await DB_HANDLER(`SELECT * FROM ${usertype} WHERE email='${payload.email}' AND social_login!='1' AND social_platform!='google'`);
|
||||||
if (existinEmail && existinEmail[0]) {
|
if (existinEmail && existinEmail[0]) {
|
||||||
loginFailureReason = "Email Exists Already";
|
loginFailureReason = "Email Exists Already";
|
||||||
isGoogleAuthValid = false;
|
isGoogleAuthValid = false;
|
||||||
@ -65,7 +49,7 @@ function googleLogin(_a) {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
////////////////////////////////////////
|
////////////////////////////////////////
|
||||||
foundUser = yield (0, DB_HANDLER_1.default)(`SELECT * FROM ${usertype} WHERE email='${payload.email}' AND social_login='1' AND social_platform='google'`);
|
foundUser = await DB_HANDLER(`SELECT * FROM ${usertype} WHERE email='${payload.email}' AND social_login='1' AND social_platform='google'`);
|
||||||
if (foundUser && foundUser[0]) {
|
if (foundUser && foundUser[0]) {
|
||||||
newFoundUser = foundUser;
|
newFoundUser = foundUser;
|
||||||
return {
|
return {
|
||||||
@ -76,7 +60,7 @@ function googleLogin(_a) {
|
|||||||
////////////////////////////////////////////////
|
////////////////////////////////////////////////
|
||||||
////////////////////////////////////////////////
|
////////////////////////////////////////////////
|
||||||
////////////////////////////////////////////////
|
////////////////////////////////////////////////
|
||||||
let newUser = yield (0, DB_HANDLER_1.default)(`INSERT INTO ${usertype} (
|
let newUser = await DB_HANDLER(`INSERT INTO ${usertype} (
|
||||||
first_name,
|
first_name,
|
||||||
last_name,
|
last_name,
|
||||||
social_platform,
|
social_platform,
|
||||||
@ -95,7 +79,7 @@ function googleLogin(_a) {
|
|||||||
'${payload.given_name}',
|
'${payload.given_name}',
|
||||||
'${payload.family_name}',
|
'${payload.family_name}',
|
||||||
'google',
|
'google',
|
||||||
'google_${(_b = payload.email) === null || _b === void 0 ? void 0 : _b.replace(/@.*/, "")}',
|
'google_${(_a = payload.email) === null || _a === void 0 ? void 0 : _a.replace(/@.*/, "")}',
|
||||||
'${payload.sub}',
|
'${payload.sub}',
|
||||||
'${payload.email}',
|
'${payload.email}',
|
||||||
'${payload.picture}',
|
'${payload.picture}',
|
||||||
@ -107,18 +91,17 @@ function googleLogin(_a) {
|
|||||||
'${Date()}',
|
'${Date()}',
|
||||||
'${Date.now()}'
|
'${Date.now()}'
|
||||||
)`);
|
)`);
|
||||||
newFoundUser = yield (0, DB_HANDLER_1.default)(`SELECT * FROM ${usertype} WHERE id='${newUser.insertId}'`);
|
newFoundUser = await DB_HANDLER(`SELECT * FROM ${usertype} WHERE id='${newUser.insertId}'`);
|
||||||
}
|
}
|
||||||
catch (error) {
|
catch (error) {
|
||||||
(0, serverError_1.default)({
|
serverError({
|
||||||
component: "googleLogin",
|
component: "googleLogin",
|
||||||
message: error.message,
|
message: error.message,
|
||||||
});
|
});
|
||||||
(_c = global.ERROR_CALLBACK) === null || _c === void 0 ? void 0 : _c.call(global, `Google Login Error`, error);
|
(_b = global.ERROR_CALLBACK) === null || _b === void 0 ? void 0 : _b.call(global, `Google Login Error`, error);
|
||||||
loginFailureReason = error;
|
loginFailureReason = error;
|
||||||
isUserValid = false;
|
isUserValid = false;
|
||||||
isSocialValidated = false;
|
isSocialValidated = false;
|
||||||
}
|
}
|
||||||
return { isGoogleAuthValid: isGoogleAuthValid, newFoundUser: newFoundUser };
|
return { isGoogleAuthValid: isGoogleAuthValid, newFoundUser: newFoundUser };
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
@ -1,32 +1,17 @@
|
|||||||
"use strict";
|
import fs from "fs";
|
||||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
import handleNodemailer from "../../backend/handleNodemailer";
|
||||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
import path from "path";
|
||||||
return new (P || (P = Promise))(function (resolve, reject) {
|
import addMariadbUser from "../../backend/addMariadbUser";
|
||||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
import varDatabaseDbHandler from "../../backend/varDatabaseDbHandler";
|
||||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
import encrypt from "../../dsql/encrypt";
|
||||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
import addDbEntry from "../../backend/db/addDbEntry";
|
||||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
import loginSocialUser from "./loginSocialUser";
|
||||||
});
|
import grabDirNames from "../../../utils/backend/names/grab-dir-names";
|
||||||
};
|
|
||||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
||||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
||||||
};
|
|
||||||
Object.defineProperty(exports, "__esModule", { value: true });
|
|
||||||
exports.default = handleSocialDb;
|
|
||||||
const fs_1 = __importDefault(require("fs"));
|
|
||||||
const handleNodemailer_1 = __importDefault(require("../../backend/handleNodemailer"));
|
|
||||||
const path_1 = __importDefault(require("path"));
|
|
||||||
const addMariadbUser_1 = __importDefault(require("../../backend/addMariadbUser"));
|
|
||||||
const varDatabaseDbHandler_1 = __importDefault(require("../../backend/varDatabaseDbHandler"));
|
|
||||||
const encrypt_1 = __importDefault(require("../../dsql/encrypt"));
|
|
||||||
const addDbEntry_1 = __importDefault(require("../../backend/db/addDbEntry"));
|
|
||||||
const loginSocialUser_1 = __importDefault(require("./loginSocialUser"));
|
|
||||||
/**
|
/**
|
||||||
* # Handle Social DB
|
* # Handle Social DB
|
||||||
*/
|
*/
|
||||||
function handleSocialDb(_a) {
|
export default async function handleSocialDb({ database, email, social_platform, payload, invitation, supEmail, additionalFields, debug, loginOnly, }) {
|
||||||
return __awaiter(this, arguments, void 0, function* ({ database, email, social_platform, payload, invitation, supEmail, additionalFields, debug, loginOnly, }) {
|
var _a, _b;
|
||||||
var _b;
|
|
||||||
try {
|
try {
|
||||||
const finalDbName = global.DSQL_USE_LOCAL
|
const finalDbName = global.DSQL_USE_LOCAL
|
||||||
? undefined
|
? undefined
|
||||||
@ -40,7 +25,7 @@ function handleSocialDb(_a) {
|
|||||||
console.log("handleSocialDb:existingSocialUserQUery", existingSocialUserQUery);
|
console.log("handleSocialDb:existingSocialUserQUery", existingSocialUserQUery);
|
||||||
console.log("handleSocialDb:existingSocialUserValues", existingSocialUserValues);
|
console.log("handleSocialDb:existingSocialUserValues", existingSocialUserValues);
|
||||||
}
|
}
|
||||||
let existingSocialUser = yield (0, varDatabaseDbHandler_1.default)({
|
let existingSocialUser = await varDatabaseDbHandler({
|
||||||
database: finalDbName,
|
database: finalDbName,
|
||||||
queryString: existingSocialUserQUery,
|
queryString: existingSocialUserQUery,
|
||||||
queryValuesArray: existingSocialUserValues,
|
queryValuesArray: existingSocialUserValues,
|
||||||
@ -50,7 +35,7 @@ function handleSocialDb(_a) {
|
|||||||
console.log("handleSocialDb:existingSocialUser", existingSocialUser);
|
console.log("handleSocialDb:existingSocialUser", existingSocialUser);
|
||||||
}
|
}
|
||||||
if (existingSocialUser === null || existingSocialUser === void 0 ? void 0 : existingSocialUser[0]) {
|
if (existingSocialUser === null || existingSocialUser === void 0 ? void 0 : existingSocialUser[0]) {
|
||||||
return yield (0, loginSocialUser_1.default)({
|
return await loginSocialUser({
|
||||||
user: existingSocialUser[0],
|
user: existingSocialUser[0],
|
||||||
social_platform,
|
social_platform,
|
||||||
invitation,
|
invitation,
|
||||||
@ -78,7 +63,7 @@ function handleSocialDb(_a) {
|
|||||||
if (debug) {
|
if (debug) {
|
||||||
console.log("handleSocialDb:existingEmailOnlyQuery", existingEmailOnlyQuery);
|
console.log("handleSocialDb:existingEmailOnlyQuery", existingEmailOnlyQuery);
|
||||||
}
|
}
|
||||||
let existingEmailOnly = yield (0, varDatabaseDbHandler_1.default)({
|
let existingEmailOnly = await varDatabaseDbHandler({
|
||||||
database: finalDbName,
|
database: finalDbName,
|
||||||
queryString: existingEmailOnlyQuery,
|
queryString: existingEmailOnlyQuery,
|
||||||
debug,
|
debug,
|
||||||
@ -87,7 +72,7 @@ function handleSocialDb(_a) {
|
|||||||
console.log("handleSocialDb:existingEmailOnly", existingEmailOnly);
|
console.log("handleSocialDb:existingEmailOnly", existingEmailOnly);
|
||||||
}
|
}
|
||||||
if (existingEmailOnly === null || existingEmailOnly === void 0 ? void 0 : existingEmailOnly[0]) {
|
if (existingEmailOnly === null || existingEmailOnly === void 0 ? void 0 : existingEmailOnly[0]) {
|
||||||
return yield (0, loginSocialUser_1.default)({
|
return await loginSocialUser({
|
||||||
user: existingEmailOnly[0],
|
user: existingEmailOnly[0],
|
||||||
social_platform,
|
social_platform,
|
||||||
invitation,
|
invitation,
|
||||||
@ -103,7 +88,7 @@ function handleSocialDb(_a) {
|
|||||||
msg: "Social Account Creation Not allowed",
|
msg: "Social Account Creation Not allowed",
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
const socialHashedPassword = (0, encrypt_1.default)({
|
const socialHashedPassword = encrypt({
|
||||||
data: email,
|
data: email,
|
||||||
});
|
});
|
||||||
const data = {
|
const data = {
|
||||||
@ -114,7 +99,7 @@ function handleSocialDb(_a) {
|
|||||||
Object.keys(payload).forEach((key) => {
|
Object.keys(payload).forEach((key) => {
|
||||||
data[key] = payload[key];
|
data[key] = payload[key];
|
||||||
});
|
});
|
||||||
const newUser = yield (0, addDbEntry_1.default)({
|
const newUser = await addDbEntry({
|
||||||
dbContext: finalDbName ? "Dsql User" : undefined,
|
dbContext: finalDbName ? "Dsql User" : undefined,
|
||||||
paradigm: finalDbName ? "Full Access" : undefined,
|
paradigm: finalDbName ? "Full Access" : undefined,
|
||||||
dbFullName: finalDbName,
|
dbFullName: finalDbName,
|
||||||
@ -123,15 +108,15 @@ function handleSocialDb(_a) {
|
|||||||
duplicateColumnValue: finalEmail,
|
duplicateColumnValue: finalEmail,
|
||||||
data: Object.assign(Object.assign({}, data), { email: finalEmail }),
|
data: Object.assign(Object.assign({}, data), { email: finalEmail }),
|
||||||
});
|
});
|
||||||
if (newUser === null || newUser === void 0 ? void 0 : newUser.insertId) {
|
if ((_a = newUser === null || newUser === void 0 ? void 0 : newUser.payload) === null || _a === void 0 ? void 0 : _a.insertId) {
|
||||||
if (!database) {
|
if (!database) {
|
||||||
/**
|
/**
|
||||||
* Add a Mariadb User for this User
|
* Add a Mariadb User for this User
|
||||||
*/
|
*/
|
||||||
yield (0, addMariadbUser_1.default)({ userId: newUser.insertId });
|
await addMariadbUser({ userId: newUser.payload.insertId });
|
||||||
}
|
}
|
||||||
const newUserQueriedQuery = `SELECT * FROM ${dbAppend}users WHERE id='${newUser.insertId}'`;
|
const newUserQueriedQuery = `SELECT * FROM ${dbAppend}users WHERE id='${newUser.payload.insertId}'`;
|
||||||
const newUserQueried = yield (0, varDatabaseDbHandler_1.default)({
|
const newUserQueried = await varDatabaseDbHandler({
|
||||||
database: finalDbName,
|
database: finalDbName,
|
||||||
queryString: newUserQueriedQuery,
|
queryString: newUserQueriedQuery,
|
||||||
debug,
|
debug,
|
||||||
@ -148,24 +133,24 @@ function handleSocialDb(_a) {
|
|||||||
*
|
*
|
||||||
* @description Send verification email to newly created agent
|
* @description Send verification email to newly created agent
|
||||||
*/
|
*/
|
||||||
let generatedToken = (0, encrypt_1.default)({
|
let generatedToken = encrypt({
|
||||||
data: JSON.stringify({
|
data: JSON.stringify({
|
||||||
id: newUser.insertId,
|
id: newUser.payload.insertId,
|
||||||
email: supEmail,
|
email: supEmail,
|
||||||
dateCode: Date.now(),
|
dateCode: Date.now(),
|
||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
(0, handleNodemailer_1.default)({
|
handleNodemailer({
|
||||||
to: supEmail,
|
to: supEmail,
|
||||||
subject: "Verify Email Address",
|
subject: "Verify Email Address",
|
||||||
text: "Please click the link to verify your email address",
|
text: "Please click the link to verify your email address",
|
||||||
html: fs_1.default
|
html: fs
|
||||||
.readFileSync("./email/send-email-verification-link.html", "utf8")
|
.readFileSync("./email/send-email-verification-link.html", "utf8")
|
||||||
.replace(/{{host}}/, process.env.DSQL_HOST || "")
|
.replace(/{{host}}/, process.env.DSQL_HOST || "")
|
||||||
.replace(/{{token}}/, generatedToken || ""),
|
.replace(/{{token}}/, generatedToken || ""),
|
||||||
}).then(() => { });
|
}).then(() => { });
|
||||||
}
|
}
|
||||||
const STATIC_ROOT = process.env.DSQL_STATIC_SERVER_DIR;
|
const { STATIC_ROOT } = grabDirNames();
|
||||||
if (!STATIC_ROOT) {
|
if (!STATIC_ROOT) {
|
||||||
console.log("Static File ENV not Found!");
|
console.log("Static File ENV not Found!");
|
||||||
return {
|
return {
|
||||||
@ -180,13 +165,13 @@ function handleSocialDb(_a) {
|
|||||||
* @description Create new user folder and file
|
* @description Create new user folder and file
|
||||||
*/
|
*/
|
||||||
if (!database || (database === null || database === void 0 ? void 0 : database.match(/^datasquirel$/))) {
|
if (!database || (database === null || database === void 0 ? void 0 : database.match(/^datasquirel$/))) {
|
||||||
let newUserSchemaFolderPath = `${process.env.DSQL_USER_DB_SCHEMA_PATH}/user-${newUser.insertId}`;
|
let newUserSchemaFolderPath = `${process.env.DSQL_USER_DB_SCHEMA_PATH}/user-${newUser.payload.insertId}`;
|
||||||
let newUserMediaFolderPath = path_1.default.join(STATIC_ROOT, `images/user-images/user-${newUser.insertId}`);
|
let newUserMediaFolderPath = path.join(STATIC_ROOT, `images/user-images/user-${newUser.payload.insertId}`);
|
||||||
fs_1.default.mkdirSync(newUserSchemaFolderPath);
|
fs.mkdirSync(newUserSchemaFolderPath);
|
||||||
fs_1.default.mkdirSync(newUserMediaFolderPath);
|
fs.mkdirSync(newUserMediaFolderPath);
|
||||||
fs_1.default.writeFileSync(`${newUserSchemaFolderPath}/main.json`, JSON.stringify([]), "utf8");
|
fs.writeFileSync(`${newUserSchemaFolderPath}/main.json`, JSON.stringify([]), "utf8");
|
||||||
}
|
}
|
||||||
return yield (0, loginSocialUser_1.default)({
|
return await loginSocialUser({
|
||||||
user: newUserQueried[0],
|
user: newUserQueried[0],
|
||||||
social_platform,
|
social_platform,
|
||||||
invitation,
|
invitation,
|
||||||
@ -213,5 +198,4 @@ function handleSocialDb(_a) {
|
|||||||
msg: error.message,
|
msg: error.message,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
@ -1,33 +1,17 @@
|
|||||||
"use strict";
|
import addAdminUserOnLogin from "../../backend/addAdminUserOnLogin";
|
||||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
import varDatabaseDbHandler from "../../backend/varDatabaseDbHandler";
|
||||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
|
||||||
return new (P || (P = Promise))(function (resolve, reject) {
|
|
||||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
|
||||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
||||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
||||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
||||||
});
|
|
||||||
};
|
|
||||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
||||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
||||||
};
|
|
||||||
Object.defineProperty(exports, "__esModule", { value: true });
|
|
||||||
exports.default = loginSocialUser;
|
|
||||||
const addAdminUserOnLogin_1 = __importDefault(require("../../backend/addAdminUserOnLogin"));
|
|
||||||
const varDatabaseDbHandler_1 = __importDefault(require("../../backend/varDatabaseDbHandler"));
|
|
||||||
/**
|
/**
|
||||||
* Function to login social user
|
* Function to login social user
|
||||||
* ==============================================================================
|
* ==============================================================================
|
||||||
* @description This function logs in the user after 'handleSocialDb' function finishes
|
* @description This function logs in the user after 'handleSocialDb' function finishes
|
||||||
* the user creation or confirmation process
|
* the user creation or confirmation process
|
||||||
*/
|
*/
|
||||||
function loginSocialUser(_a) {
|
export default async function loginSocialUser({ user, social_platform, invitation, database, additionalFields, debug, }) {
|
||||||
return __awaiter(this, arguments, void 0, function* ({ user, social_platform, invitation, database, additionalFields, debug, }) {
|
|
||||||
const finalDbName = database ? database : "datasquirel";
|
const finalDbName = database ? database : "datasquirel";
|
||||||
const dbAppend = database ? `\`${finalDbName}\`.` : "";
|
const dbAppend = database ? `\`${finalDbName}\`.` : "";
|
||||||
const foundUserQuery = `SELECT * FROM ${dbAppend}\`users\` WHERE email=?`;
|
const foundUserQuery = `SELECT * FROM ${dbAppend}\`users\` WHERE email=?`;
|
||||||
const foundUserValues = [user.email];
|
const foundUserValues = [user.email];
|
||||||
const foundUser = yield (0, varDatabaseDbHandler_1.default)({
|
const foundUser = await varDatabaseDbHandler({
|
||||||
database: finalDbName,
|
database: finalDbName,
|
||||||
queryString: foundUserQuery,
|
queryString: foundUserQuery,
|
||||||
queryValuesArray: foundUserValues,
|
queryValuesArray: foundUserValues,
|
||||||
@ -66,7 +50,7 @@ function loginSocialUser(_a) {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
if (invitation && (!database || (database === null || database === void 0 ? void 0 : database.match(/^datasquirel$/)))) {
|
if (invitation && (!database || (database === null || database === void 0 ? void 0 : database.match(/^datasquirel$/)))) {
|
||||||
(0, addAdminUserOnLogin_1.default)({
|
addAdminUserOnLogin({
|
||||||
query: invitation,
|
query: invitation,
|
||||||
user: userPayload,
|
user: userPayload,
|
||||||
});
|
});
|
||||||
@ -77,5 +61,4 @@ function loginSocialUser(_a) {
|
|||||||
csrf: csrfKey,
|
csrf: csrfKey,
|
||||||
};
|
};
|
||||||
return result;
|
return result;
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
@ -20,6 +20,6 @@ export default function apiCreateUser({ encryptionKey, payload, database, userId
|
|||||||
} | {
|
} | {
|
||||||
success: boolean;
|
success: boolean;
|
||||||
msg: string;
|
msg: string;
|
||||||
sqlResult: import("../../../types").PostInsertReturn | null;
|
sqlResult: import("../../../types").APIResponseObject<import("../../../types").PostInsertReturn>;
|
||||||
payload: null;
|
payload: null;
|
||||||
}>;
|
}>;
|
||||||
|
@ -1,30 +1,15 @@
|
|||||||
"use strict";
|
import { findDbNameInSchemaDir } from "../../../shell/createDbFromSchema/grab-required-database-schemas";
|
||||||
// @ts-check
|
import addUsersTableToDb from "../../backend/addUsersTableToDb";
|
||||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
import addDbEntry from "../../backend/db/addDbEntry";
|
||||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
import updateUsersTableSchema from "../../backend/updateUsersTableSchema";
|
||||||
return new (P || (P = Promise))(function (resolve, reject) {
|
import varDatabaseDbHandler from "../../backend/varDatabaseDbHandler";
|
||||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
import hashPassword from "../../dsql/hashPassword";
|
||||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
import validateEmail from "../../email/fns/validate-email";
|
||||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
||||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
||||||
});
|
|
||||||
};
|
|
||||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
||||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
||||||
};
|
|
||||||
Object.defineProperty(exports, "__esModule", { value: true });
|
|
||||||
exports.default = apiCreateUser;
|
|
||||||
const addUsersTableToDb_1 = __importDefault(require("../../backend/addUsersTableToDb"));
|
|
||||||
const addDbEntry_1 = __importDefault(require("../../backend/db/addDbEntry"));
|
|
||||||
const updateUsersTableSchema_1 = __importDefault(require("../../backend/updateUsersTableSchema"));
|
|
||||||
const varDatabaseDbHandler_1 = __importDefault(require("../../backend/varDatabaseDbHandler"));
|
|
||||||
const hashPassword_1 = __importDefault(require("../../dsql/hashPassword"));
|
|
||||||
const validate_email_1 = __importDefault(require("../../email/fns/validate-email"));
|
|
||||||
/**
|
/**
|
||||||
* # API Create User
|
* # API Create User
|
||||||
*/
|
*/
|
||||||
function apiCreateUser(_a) {
|
export default async function apiCreateUser({ encryptionKey, payload, database, userId, }) {
|
||||||
return __awaiter(this, arguments, void 0, function* ({ encryptionKey, payload, database, userId, }) {
|
var _a;
|
||||||
const dbFullName = database;
|
const dbFullName = database;
|
||||||
const API_USER_ID = userId || process.env.DSQL_API_USER_ID;
|
const API_USER_ID = userId || process.env.DSQL_API_USER_ID;
|
||||||
const finalEncryptionKey = encryptionKey || process.env.DSQL_ENCRYPTION_PASSWORD;
|
const finalEncryptionKey = encryptionKey || process.env.DSQL_ENCRYPTION_PASSWORD;
|
||||||
@ -42,23 +27,35 @@ function apiCreateUser(_a) {
|
|||||||
payload: null,
|
payload: null,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
const hashedPassword = (0, hashPassword_1.default)({
|
const targetDbSchema = findDbNameInSchemaDir({
|
||||||
|
dbName: dbFullName,
|
||||||
|
userId,
|
||||||
|
});
|
||||||
|
if (!(targetDbSchema === null || targetDbSchema === void 0 ? void 0 : targetDbSchema.id)) {
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
msg: "targetDbSchema not found",
|
||||||
|
payload: null,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
const hashedPassword = hashPassword({
|
||||||
encryptionKey: finalEncryptionKey,
|
encryptionKey: finalEncryptionKey,
|
||||||
password: String(payload.password),
|
password: String(payload.password),
|
||||||
});
|
});
|
||||||
payload.password = hashedPassword;
|
payload.password = hashedPassword;
|
||||||
const fieldsQuery = `SHOW COLUMNS FROM ${dbFullName}.users`;
|
const fieldsQuery = `SHOW COLUMNS FROM ${dbFullName}.users`;
|
||||||
let fields = yield (0, varDatabaseDbHandler_1.default)({
|
let fields = await varDatabaseDbHandler({
|
||||||
queryString: fieldsQuery,
|
queryString: fieldsQuery,
|
||||||
database: dbFullName,
|
database: dbFullName,
|
||||||
});
|
});
|
||||||
if (!(fields === null || fields === void 0 ? void 0 : fields[0])) {
|
if (!(fields === null || fields === void 0 ? void 0 : fields[0])) {
|
||||||
const newTable = yield (0, addUsersTableToDb_1.default)({
|
const newTable = await addUsersTableToDb({
|
||||||
userId: Number(API_USER_ID),
|
userId: Number(API_USER_ID),
|
||||||
database: dbFullName,
|
database: dbFullName,
|
||||||
payload: payload,
|
payload: payload,
|
||||||
|
dbId: targetDbSchema.id,
|
||||||
});
|
});
|
||||||
fields = yield (0, varDatabaseDbHandler_1.default)({
|
fields = await varDatabaseDbHandler({
|
||||||
queryString: fieldsQuery,
|
queryString: fieldsQuery,
|
||||||
database: dbFullName,
|
database: dbFullName,
|
||||||
});
|
});
|
||||||
@ -74,12 +71,13 @@ function apiCreateUser(_a) {
|
|||||||
for (let i = 0; i < Object.keys(payload).length; i++) {
|
for (let i = 0; i < Object.keys(payload).length; i++) {
|
||||||
const key = Object.keys(payload)[i];
|
const key = Object.keys(payload)[i];
|
||||||
if (!fieldsTitles.includes(key)) {
|
if (!fieldsTitles.includes(key)) {
|
||||||
yield (0, updateUsersTableSchema_1.default)({
|
await updateUsersTableSchema({
|
||||||
userId: Number(API_USER_ID),
|
userId: Number(API_USER_ID),
|
||||||
database: dbFullName,
|
database: dbFullName,
|
||||||
newPayload: {
|
newPayload: {
|
||||||
[key]: payload[key],
|
[key]: payload[key],
|
||||||
},
|
},
|
||||||
|
dbId: targetDbSchema.id,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -93,7 +91,7 @@ function apiCreateUser(_a) {
|
|||||||
const existingUserValues = payload.username
|
const existingUserValues = payload.username
|
||||||
? [payload.email, payload.username]
|
? [payload.email, payload.username]
|
||||||
: [payload.email];
|
: [payload.email];
|
||||||
const existingUser = yield (0, varDatabaseDbHandler_1.default)({
|
const existingUser = await varDatabaseDbHandler({
|
||||||
queryString: existingUserQuery,
|
queryString: existingUserQuery,
|
||||||
queryValuesArray: existingUserValues,
|
queryValuesArray: existingUserValues,
|
||||||
database: dbFullName,
|
database: dbFullName,
|
||||||
@ -105,7 +103,7 @@ function apiCreateUser(_a) {
|
|||||||
payload: null,
|
payload: null,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
const isEmailValid = yield (0, validate_email_1.default)({ email: payload.email });
|
const isEmailValid = await validateEmail({ email: payload.email });
|
||||||
if (!isEmailValid.isValid) {
|
if (!isEmailValid.isValid) {
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
@ -113,16 +111,16 @@ function apiCreateUser(_a) {
|
|||||||
payload: null,
|
payload: null,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
const addUser = yield (0, addDbEntry_1.default)({
|
const addUser = await addDbEntry({
|
||||||
dbFullName: dbFullName,
|
dbFullName: dbFullName,
|
||||||
tableName: "users",
|
tableName: "users",
|
||||||
data: Object.assign(Object.assign({}, payload), { image: process.env.DSQL_DEFAULT_USER_IMAGE ||
|
data: Object.assign(Object.assign({}, payload), { image: process.env.DSQL_DEFAULT_USER_IMAGE ||
|
||||||
"/images/user-preset.png", image_thumbnail: process.env.DSQL_DEFAULT_USER_IMAGE ||
|
"/images/user-preset.png", image_thumbnail: process.env.DSQL_DEFAULT_USER_IMAGE ||
|
||||||
"/images/user-preset-thumbnail.png" }),
|
"/images/user-preset-thumbnail.png" }),
|
||||||
});
|
});
|
||||||
if (addUser === null || addUser === void 0 ? void 0 : addUser.insertId) {
|
if ((_a = addUser === null || addUser === void 0 ? void 0 : addUser.payload) === null || _a === void 0 ? void 0 : _a.insertId) {
|
||||||
const newlyAddedUserQuery = `SELECT id,uuid,first_name,last_name,email,username,image,image_thumbnail,verification_status FROM ${dbFullName}.users WHERE id='${addUser.insertId}'`;
|
const newlyAddedUserQuery = `SELECT id,uuid,first_name,last_name,email,username,image,image_thumbnail,verification_status FROM ${dbFullName}.users WHERE id='${addUser.payload.insertId}'`;
|
||||||
const newlyAddedUser = yield (0, varDatabaseDbHandler_1.default)({
|
const newlyAddedUser = await varDatabaseDbHandler({
|
||||||
queryString: newlyAddedUserQuery,
|
queryString: newlyAddedUserQuery,
|
||||||
database: dbFullName,
|
database: dbFullName,
|
||||||
});
|
});
|
||||||
@ -139,5 +137,4 @@ function apiCreateUser(_a) {
|
|||||||
payload: null,
|
payload: null,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
@ -1,28 +1,12 @@
|
|||||||
"use strict";
|
import deleteDbEntry from "../../backend/db/deleteDbEntry";
|
||||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
import varDatabaseDbHandler from "../../backend/varDatabaseDbHandler";
|
||||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
|
||||||
return new (P || (P = Promise))(function (resolve, reject) {
|
|
||||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
|
||||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
||||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
||||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
||||||
});
|
|
||||||
};
|
|
||||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
||||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
||||||
};
|
|
||||||
Object.defineProperty(exports, "__esModule", { value: true });
|
|
||||||
exports.default = apiDeleteUser;
|
|
||||||
const deleteDbEntry_1 = __importDefault(require("../../backend/db/deleteDbEntry"));
|
|
||||||
const varDatabaseDbHandler_1 = __importDefault(require("../../backend/varDatabaseDbHandler"));
|
|
||||||
/**
|
/**
|
||||||
* # Update API User Function
|
* # Update API User Function
|
||||||
*/
|
*/
|
||||||
function apiDeleteUser(_a) {
|
export default async function apiDeleteUser({ dbFullName, deletedUserId, }) {
|
||||||
return __awaiter(this, arguments, void 0, function* ({ dbFullName, deletedUserId, }) {
|
|
||||||
const existingUserQuery = `SELECT * FROM ${dbFullName}.users WHERE id = ?`;
|
const existingUserQuery = `SELECT * FROM ${dbFullName}.users WHERE id = ?`;
|
||||||
const existingUserValues = [deletedUserId];
|
const existingUserValues = [deletedUserId];
|
||||||
const existingUser = yield (0, varDatabaseDbHandler_1.default)({
|
const existingUser = await varDatabaseDbHandler({
|
||||||
queryString: existingUserQuery,
|
queryString: existingUserQuery,
|
||||||
queryValuesArray: existingUserValues,
|
queryValuesArray: existingUserValues,
|
||||||
database: dbFullName,
|
database: dbFullName,
|
||||||
@ -33,7 +17,7 @@ function apiDeleteUser(_a) {
|
|||||||
msg: "User not found",
|
msg: "User not found",
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
const deleteUser = yield (0, deleteDbEntry_1.default)({
|
const deleteUser = await deleteDbEntry({
|
||||||
dbContext: "Dsql User",
|
dbContext: "Dsql User",
|
||||||
dbFullName,
|
dbFullName,
|
||||||
tableName: "users",
|
tableName: "users",
|
||||||
@ -44,5 +28,4 @@ function apiDeleteUser(_a) {
|
|||||||
success: true,
|
success: true,
|
||||||
result: deleteUser,
|
result: deleteUser,
|
||||||
};
|
};
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
@ -1,28 +1,12 @@
|
|||||||
"use strict";
|
import varDatabaseDbHandler from "../../backend/varDatabaseDbHandler";
|
||||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
|
||||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
|
||||||
return new (P || (P = Promise))(function (resolve, reject) {
|
|
||||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
|
||||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
||||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
||||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
||||||
});
|
|
||||||
};
|
|
||||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
||||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
||||||
};
|
|
||||||
Object.defineProperty(exports, "__esModule", { value: true });
|
|
||||||
exports.default = apiGetUser;
|
|
||||||
const varDatabaseDbHandler_1 = __importDefault(require("../../backend/varDatabaseDbHandler"));
|
|
||||||
/**
|
/**
|
||||||
* # API Get User
|
* # API Get User
|
||||||
*/
|
*/
|
||||||
function apiGetUser(_a) {
|
export default async function apiGetUser({ fields, dbFullName, userId, }) {
|
||||||
return __awaiter(this, arguments, void 0, function* ({ fields, dbFullName, userId, }) {
|
|
||||||
const finalDbName = dbFullName.replace(/[^a-z0-9_]/g, "");
|
const finalDbName = dbFullName.replace(/[^a-z0-9_]/g, "");
|
||||||
const query = `SELECT ${fields.join(",")} FROM ${finalDbName}.users WHERE id=?`;
|
const query = `SELECT ${fields.join(",")} FROM ${finalDbName}.users WHERE id=?`;
|
||||||
const API_USER_ID = userId || process.env.DSQL_API_USER_ID;
|
const API_USER_ID = userId || process.env.DSQL_API_USER_ID;
|
||||||
let foundUser = yield (0, varDatabaseDbHandler_1.default)({
|
let foundUser = await varDatabaseDbHandler({
|
||||||
queryString: query,
|
queryString: query,
|
||||||
queryValuesArray: [API_USER_ID],
|
queryValuesArray: [API_USER_ID],
|
||||||
database: finalDbName,
|
database: finalDbName,
|
||||||
@ -37,5 +21,4 @@ function apiGetUser(_a) {
|
|||||||
success: true,
|
success: true,
|
||||||
payload: foundUser[0],
|
payload: foundUser[0],
|
||||||
};
|
};
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
@ -1,27 +1,18 @@
|
|||||||
"use strict";
|
import grabDbFullName from "../../../utils/grab-db-full-name";
|
||||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
import varDatabaseDbHandler from "../../backend/varDatabaseDbHandler";
|
||||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
import hashPassword from "../../dsql/hashPassword";
|
||||||
return new (P || (P = Promise))(function (resolve, reject) {
|
|
||||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
|
||||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
||||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
||||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
||||||
});
|
|
||||||
};
|
|
||||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
||||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
||||||
};
|
|
||||||
Object.defineProperty(exports, "__esModule", { value: true });
|
|
||||||
exports.default = apiLoginUser;
|
|
||||||
const grab_db_full_name_1 = __importDefault(require("../../../utils/grab-db-full-name"));
|
|
||||||
const varDatabaseDbHandler_1 = __importDefault(require("../../backend/varDatabaseDbHandler"));
|
|
||||||
const hashPassword_1 = __importDefault(require("../../dsql/hashPassword"));
|
|
||||||
/**
|
/**
|
||||||
* # API Login
|
* # API Login
|
||||||
*/
|
*/
|
||||||
function apiLoginUser(_a) {
|
export default async function apiLoginUser({ encryptionKey, email, username, password, database, additionalFields, email_login, email_login_code, email_login_field, skipPassword, social, dbUserId, debug, }) {
|
||||||
return __awaiter(this, arguments, void 0, function* ({ encryptionKey, email, username, password, database, additionalFields, email_login, email_login_code, email_login_field, skipPassword, social, dbUserId, debug, }) {
|
const dbFullName = grabDbFullName({ dbName: database, userId: dbUserId });
|
||||||
const dbFullName = (0, grab_db_full_name_1.default)({ dbName: database, userId: dbUserId });
|
if (!dbFullName) {
|
||||||
|
console.log(`Database Full Name couldn't be grabbed`);
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
msg: `Database Full Name couldn't be grabbed`,
|
||||||
|
};
|
||||||
|
}
|
||||||
const dbAppend = global.DSQL_USE_LOCAL ? "" : `${dbFullName}.`;
|
const dbAppend = global.DSQL_USE_LOCAL ? "" : `${dbFullName}.`;
|
||||||
/**
|
/**
|
||||||
* Check input validity
|
* Check input validity
|
||||||
@ -42,7 +33,7 @@ function apiLoginUser(_a) {
|
|||||||
* @description Password hash
|
* @description Password hash
|
||||||
*/
|
*/
|
||||||
let hashedPassword = password
|
let hashedPassword = password
|
||||||
? (0, hashPassword_1.default)({
|
? hashPassword({
|
||||||
encryptionKey: encryptionKey,
|
encryptionKey: encryptionKey,
|
||||||
password: password,
|
password: password,
|
||||||
})
|
})
|
||||||
@ -51,7 +42,7 @@ function apiLoginUser(_a) {
|
|||||||
console.log("apiLoginUser:database:", dbFullName);
|
console.log("apiLoginUser:database:", dbFullName);
|
||||||
console.log("apiLoginUser:Finding User ...");
|
console.log("apiLoginUser:Finding User ...");
|
||||||
}
|
}
|
||||||
let foundUser = yield (0, varDatabaseDbHandler_1.default)({
|
let foundUser = await varDatabaseDbHandler({
|
||||||
queryString: `SELECT * FROM ${dbAppend}users WHERE email = ? OR username = ?`,
|
queryString: `SELECT * FROM ${dbAppend}users WHERE email = ? OR username = ?`,
|
||||||
queryValuesArray: [email, username],
|
queryValuesArray: [email, username],
|
||||||
database: dbFullName,
|
database: dbFullName,
|
||||||
@ -112,7 +103,7 @@ function apiLoginUser(_a) {
|
|||||||
console.log("apiLoginUser:email_login:", email_login);
|
console.log("apiLoginUser:email_login:", email_login);
|
||||||
}
|
}
|
||||||
if (isPasswordCorrect && email_login) {
|
if (isPasswordCorrect && email_login) {
|
||||||
const resetTempCode = yield (0, varDatabaseDbHandler_1.default)({
|
const resetTempCode = await varDatabaseDbHandler({
|
||||||
queryString: `UPDATE ${dbAppend}users SET ${email_login_field} = '' WHERE email = ? OR username = ?`,
|
queryString: `UPDATE ${dbAppend}users SET ${email_login_field} = '' WHERE email = ? OR username = ?`,
|
||||||
queryValuesArray: [email, username],
|
queryValuesArray: [email, username],
|
||||||
database: dbFullName,
|
database: dbFullName,
|
||||||
@ -123,6 +114,8 @@ function apiLoginUser(_a) {
|
|||||||
Math.random().toString(36).substring(2);
|
Math.random().toString(36).substring(2);
|
||||||
let userPayload = {
|
let userPayload = {
|
||||||
id: foundUser[0].id,
|
id: foundUser[0].id,
|
||||||
|
uid: foundUser[0].uid,
|
||||||
|
uuid: foundUser[0].uuid,
|
||||||
first_name: foundUser[0].first_name,
|
first_name: foundUser[0].first_name,
|
||||||
last_name: foundUser[0].last_name,
|
last_name: foundUser[0].last_name,
|
||||||
username: foundUser[0].username,
|
username: foundUser[0].username,
|
||||||
@ -158,5 +151,4 @@ function apiLoginUser(_a) {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
return resposeObject;
|
return resposeObject;
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
@ -1,31 +1,15 @@
|
|||||||
"use strict";
|
import varDatabaseDbHandler from "../../backend/varDatabaseDbHandler";
|
||||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
|
||||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
|
||||||
return new (P || (P = Promise))(function (resolve, reject) {
|
|
||||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
|
||||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
||||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
||||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
||||||
});
|
|
||||||
};
|
|
||||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
||||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
||||||
};
|
|
||||||
Object.defineProperty(exports, "__esModule", { value: true });
|
|
||||||
exports.default = apiReauthUser;
|
|
||||||
const varDatabaseDbHandler_1 = __importDefault(require("../../backend/varDatabaseDbHandler"));
|
|
||||||
/**
|
/**
|
||||||
* # Re-authenticate API user
|
* # Re-authenticate API user
|
||||||
*/
|
*/
|
||||||
function apiReauthUser(_a) {
|
export default async function apiReauthUser({ existingUser, database, additionalFields, }) {
|
||||||
return __awaiter(this, arguments, void 0, function* ({ existingUser, database, additionalFields, }) {
|
|
||||||
const dbAppend = global.DSQL_USE_LOCAL
|
const dbAppend = global.DSQL_USE_LOCAL
|
||||||
? ""
|
? ""
|
||||||
: database
|
: database
|
||||||
? `${database}.`
|
? `${database}.`
|
||||||
: "";
|
: "";
|
||||||
let foundUser = (existingUser === null || existingUser === void 0 ? void 0 : existingUser.id) && existingUser.id.toString().match(/./)
|
let foundUser = (existingUser === null || existingUser === void 0 ? void 0 : existingUser.id) && existingUser.id.toString().match(/./)
|
||||||
? yield (0, varDatabaseDbHandler_1.default)({
|
? await varDatabaseDbHandler({
|
||||||
queryString: `SELECT * FROM ${dbAppend}users WHERE id=?`,
|
queryString: `SELECT * FROM ${dbAppend}users WHERE id=?`,
|
||||||
queryValuesArray: [existingUser.id.toString()],
|
queryValuesArray: [existingUser.id.toString()],
|
||||||
database,
|
database,
|
||||||
@ -71,5 +55,4 @@ function apiReauthUser(_a) {
|
|||||||
payload: userPayload,
|
payload: userPayload,
|
||||||
csrf: csrfKey,
|
csrf: csrfKey,
|
||||||
};
|
};
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
@ -1,28 +1,12 @@
|
|||||||
"use strict";
|
import varDatabaseDbHandler from "../../backend/varDatabaseDbHandler";
|
||||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
import nodemailer from "nodemailer";
|
||||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
import getAuthCookieNames from "../../backend/cookies/get-auth-cookie-names";
|
||||||
return new (P || (P = Promise))(function (resolve, reject) {
|
import encrypt from "../../dsql/encrypt";
|
||||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
import serializeCookies from "../../../utils/serialize-cookies";
|
||||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
||||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
||||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
||||||
});
|
|
||||||
};
|
|
||||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
||||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
||||||
};
|
|
||||||
Object.defineProperty(exports, "__esModule", { value: true });
|
|
||||||
exports.default = apiSendEmailCode;
|
|
||||||
const varDatabaseDbHandler_1 = __importDefault(require("../../backend/varDatabaseDbHandler"));
|
|
||||||
const nodemailer_1 = __importDefault(require("nodemailer"));
|
|
||||||
const get_auth_cookie_names_1 = __importDefault(require("../../backend/cookies/get-auth-cookie-names"));
|
|
||||||
const encrypt_1 = __importDefault(require("../../dsql/encrypt"));
|
|
||||||
const serialize_cookies_1 = __importDefault(require("../../../utils/serialize-cookies"));
|
|
||||||
/**
|
/**
|
||||||
* # Send Email Login Code
|
* # Send Email Login Code
|
||||||
*/
|
*/
|
||||||
function apiSendEmailCode(_a) {
|
export default async function apiSendEmailCode({ email, database, email_login_field, mail_domain, mail_port, sender, mail_username, mail_password, html, response, extraCookies, }) {
|
||||||
return __awaiter(this, arguments, void 0, function* ({ email, database, email_login_field, mail_domain, mail_port, sender, mail_username, mail_password, html, response, extraCookies, }) {
|
|
||||||
if (email === null || email === void 0 ? void 0 : email.match(/ /)) {
|
if (email === null || email === void 0 ? void 0 : email.match(/ /)) {
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
@ -32,7 +16,7 @@ function apiSendEmailCode(_a) {
|
|||||||
const createdAt = Date.now();
|
const createdAt = Date.now();
|
||||||
const foundUserQuery = `SELECT * FROM ${database}.users WHERE email = ?`;
|
const foundUserQuery = `SELECT * FROM ${database}.users WHERE email = ?`;
|
||||||
const foundUserValues = [email];
|
const foundUserValues = [email];
|
||||||
let foundUser = yield (0, varDatabaseDbHandler_1.default)({
|
let foundUser = await varDatabaseDbHandler({
|
||||||
queryString: foundUserQuery,
|
queryString: foundUserQuery,
|
||||||
queryValuesArray: foundUserValues,
|
queryValuesArray: foundUserValues,
|
||||||
database,
|
database,
|
||||||
@ -56,7 +40,7 @@ function apiSendEmailCode(_a) {
|
|||||||
}
|
}
|
||||||
if ((foundUser === null || foundUser === void 0 ? void 0 : foundUser[0]) && email_login_field) {
|
if ((foundUser === null || foundUser === void 0 ? void 0 : foundUser[0]) && email_login_field) {
|
||||||
const tempCode = generateCode();
|
const tempCode = generateCode();
|
||||||
let transporter = nodemailer_1.default.createTransport({
|
let transporter = nodemailer.createTransport({
|
||||||
host: mail_domain || process.env.DSQL_MAIL_HOST,
|
host: mail_domain || process.env.DSQL_MAIL_HOST,
|
||||||
port: mail_port
|
port: mail_port
|
||||||
? mail_port
|
? mail_port
|
||||||
@ -75,12 +59,12 @@ function apiSendEmailCode(_a) {
|
|||||||
mailObject["to"] = email;
|
mailObject["to"] = email;
|
||||||
mailObject["subject"] = "One Time Login Code";
|
mailObject["subject"] = "One Time Login Code";
|
||||||
mailObject["html"] = html.replace(/{{code}}/, tempCode);
|
mailObject["html"] = html.replace(/{{code}}/, tempCode);
|
||||||
const info = yield transporter.sendMail(mailObject);
|
const info = await transporter.sendMail(mailObject);
|
||||||
if (!(info === null || info === void 0 ? void 0 : info.accepted))
|
if (!(info === null || info === void 0 ? void 0 : info.accepted))
|
||||||
throw new Error("Mail not Sent!");
|
throw new Error("Mail not Sent!");
|
||||||
const setTempCodeQuery = `UPDATE ${database}.users SET ${email_login_field} = ? WHERE email = ?`;
|
const setTempCodeQuery = `UPDATE ${database}.users SET ${email_login_field} = ? WHERE email = ?`;
|
||||||
const setTempCodeValues = [tempCode + `-${createdAt}`, email];
|
const setTempCodeValues = [tempCode + `-${createdAt}`, email];
|
||||||
let setTempCode = yield (0, varDatabaseDbHandler_1.default)({
|
let setTempCode = await varDatabaseDbHandler({
|
||||||
queryString: setTempCodeQuery,
|
queryString: setTempCodeQuery,
|
||||||
queryValuesArray: setTempCodeValues,
|
queryValuesArray: setTempCodeValues,
|
||||||
database,
|
database,
|
||||||
@ -94,9 +78,9 @@ function apiSendEmailCode(_a) {
|
|||||||
msg: "Success",
|
msg: "Success",
|
||||||
};
|
};
|
||||||
if (response) {
|
if (response) {
|
||||||
const cookieKeyNames = (0, get_auth_cookie_names_1.default)();
|
const cookieKeyNames = getAuthCookieNames();
|
||||||
const oneTimeCodeCookieName = cookieKeyNames.oneTimeCodeName;
|
const oneTimeCodeCookieName = cookieKeyNames.oneTimeCodeName;
|
||||||
const encryptedPayload = (0, encrypt_1.default)({
|
const encryptedPayload = encrypt({
|
||||||
data: JSON.stringify(resObject),
|
data: JSON.stringify(resObject),
|
||||||
});
|
});
|
||||||
if (!encryptedPayload) {
|
if (!encryptedPayload) {
|
||||||
@ -115,7 +99,7 @@ function apiSendEmailCode(_a) {
|
|||||||
const cookiesObjectArray = extraCookies
|
const cookiesObjectArray = extraCookies
|
||||||
? [...extraCookies, oneTimeCookieObject]
|
? [...extraCookies, oneTimeCookieObject]
|
||||||
: [oneTimeCookieObject];
|
: [oneTimeCookieObject];
|
||||||
const serializedCookies = (0, serialize_cookies_1.default)({
|
const serializedCookies = serializeCookies({
|
||||||
cookies: cookiesObjectArray,
|
cookies: cookiesObjectArray,
|
||||||
});
|
});
|
||||||
response.setHeader("Set-Cookie", serializedCookies);
|
response.setHeader("Set-Cookie", serializedCookies);
|
||||||
@ -128,5 +112,4 @@ function apiSendEmailCode(_a) {
|
|||||||
msg: "Invalid Email/Password format",
|
msg: "Invalid Email/Password format",
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
@ -1,31 +1,15 @@
|
|||||||
"use strict";
|
|
||||||
// @ts-check
|
// @ts-check
|
||||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
import updateDbEntry from "../../backend/db/updateDbEntry";
|
||||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
import encrypt from "../../dsql/encrypt";
|
||||||
return new (P || (P = Promise))(function (resolve, reject) {
|
import hashPassword from "../../dsql/hashPassword";
|
||||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
import varDatabaseDbHandler from "../../backend/varDatabaseDbHandler";
|
||||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
||||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
||||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
||||||
});
|
|
||||||
};
|
|
||||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
||||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
||||||
};
|
|
||||||
Object.defineProperty(exports, "__esModule", { value: true });
|
|
||||||
exports.default = apiUpdateUser;
|
|
||||||
const updateDbEntry_1 = __importDefault(require("../../backend/db/updateDbEntry"));
|
|
||||||
const encrypt_1 = __importDefault(require("../../dsql/encrypt"));
|
|
||||||
const hashPassword_1 = __importDefault(require("../../dsql/hashPassword"));
|
|
||||||
const varDatabaseDbHandler_1 = __importDefault(require("../../backend/varDatabaseDbHandler"));
|
|
||||||
/**
|
/**
|
||||||
* # Update API User Function
|
* # Update API User Function
|
||||||
*/
|
*/
|
||||||
function apiUpdateUser(_a) {
|
export default async function apiUpdateUser({ payload, dbFullName, updatedUserId, dbSchema, }) {
|
||||||
return __awaiter(this, arguments, void 0, function* ({ payload, dbFullName, updatedUserId, dbSchema, }) {
|
|
||||||
const existingUserQuery = `SELECT * FROM ${dbFullName}.users WHERE id = ?`;
|
const existingUserQuery = `SELECT * FROM ${dbFullName}.users WHERE id = ?`;
|
||||||
const existingUserValues = [updatedUserId];
|
const existingUserValues = [updatedUserId];
|
||||||
const existingUser = yield (0, varDatabaseDbHandler_1.default)({
|
const existingUser = await varDatabaseDbHandler({
|
||||||
queryString: existingUserQuery,
|
queryString: existingUserQuery,
|
||||||
queryValuesArray: existingUserValues,
|
queryValuesArray: existingUserValues,
|
||||||
database: dbFullName,
|
database: dbFullName,
|
||||||
@ -57,16 +41,16 @@ function apiUpdateUser(_a) {
|
|||||||
return;
|
return;
|
||||||
let value = payload[key];
|
let value = payload[key];
|
||||||
if (targetFieldSchema === null || targetFieldSchema === void 0 ? void 0 : targetFieldSchema.encrypted) {
|
if (targetFieldSchema === null || targetFieldSchema === void 0 ? void 0 : targetFieldSchema.encrypted) {
|
||||||
value = (0, encrypt_1.default)({ data: value });
|
value = encrypt({ data: value });
|
||||||
}
|
}
|
||||||
finalData[key] = value;
|
finalData[key] = value;
|
||||||
});
|
});
|
||||||
if (finalData.password && typeof finalData.password == "string") {
|
if (finalData.password && typeof finalData.password == "string") {
|
||||||
finalData.password = (0, hashPassword_1.default)({ password: finalData.password });
|
finalData.password = hashPassword({ password: finalData.password });
|
||||||
}
|
}
|
||||||
return finalData;
|
return finalData;
|
||||||
})();
|
})();
|
||||||
const updateUser = yield (0, updateDbEntry_1.default)({
|
const updateUser = await updateDbEntry({
|
||||||
dbFullName,
|
dbFullName,
|
||||||
tableName: "users",
|
tableName: "users",
|
||||||
identifierColumnName: "id",
|
identifierColumnName: "id",
|
||||||
@ -77,5 +61,4 @@ function apiUpdateUser(_a) {
|
|||||||
success: true,
|
success: true,
|
||||||
payload: updateUser,
|
payload: updateUser,
|
||||||
};
|
};
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
@ -1,18 +1,12 @@
|
|||||||
"use strict";
|
import EJSON from "../../../../../utils/ejson";
|
||||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
import encrypt from "../../../../dsql/encrypt";
|
||||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
export default function encryptReserPasswordUrl({ email, encryptionKey, encryptionSalt, }) {
|
||||||
};
|
|
||||||
Object.defineProperty(exports, "__esModule", { value: true });
|
|
||||||
exports.default = encryptReserPasswordUrl;
|
|
||||||
const ejson_1 = __importDefault(require("../../../../../utils/ejson"));
|
|
||||||
const encrypt_1 = __importDefault(require("../../../../dsql/encrypt"));
|
|
||||||
function encryptReserPasswordUrl({ email, encryptionKey, encryptionSalt, }) {
|
|
||||||
const encryptObject = {
|
const encryptObject = {
|
||||||
email,
|
email,
|
||||||
createdAt: Date.now(),
|
createdAt: Date.now(),
|
||||||
};
|
};
|
||||||
const encryptStr = (0, encrypt_1.default)({
|
const encryptStr = encrypt({
|
||||||
data: ejson_1.default.stringify(encryptObject),
|
data: EJSON.stringify(encryptObject),
|
||||||
encryptionKey,
|
encryptionKey,
|
||||||
encryptionSalt,
|
encryptionSalt,
|
||||||
});
|
});
|
||||||
|
@ -1,38 +1,23 @@
|
|||||||
"use strict";
|
import grabDbFullName from "../../../../utils/grab-db-full-name";
|
||||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
import varDatabaseDbHandler from "../../../backend/varDatabaseDbHandler";
|
||||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
|
||||||
return new (P || (P = Promise))(function (resolve, reject) {
|
|
||||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
|
||||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
||||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
||||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
||||||
});
|
|
||||||
};
|
|
||||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
||||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
||||||
};
|
|
||||||
Object.defineProperty(exports, "__esModule", { value: true });
|
|
||||||
exports.default = apiSendResetPasswordLink;
|
|
||||||
const grab_db_full_name_1 = __importDefault(require("../../../../utils/grab-db-full-name"));
|
|
||||||
const varDatabaseDbHandler_1 = __importDefault(require("../../../backend/varDatabaseDbHandler"));
|
|
||||||
/**
|
/**
|
||||||
* # API Login
|
* # API Login
|
||||||
*/
|
*/
|
||||||
function apiSendResetPasswordLink(_a) {
|
export default async function apiSendResetPasswordLink({ database, email, dbUserId, debug, }) {
|
||||||
return __awaiter(this, arguments, void 0, function* ({ database, email, dbUserId, debug, }) {
|
const dbFullName = grabDbFullName({ dbName: database, userId: dbUserId });
|
||||||
const dbFullName = (0, grab_db_full_name_1.default)({ dbName: database, userId: dbUserId });
|
if (!dbFullName) {
|
||||||
/**
|
return {
|
||||||
* Check input validity
|
success: false,
|
||||||
*
|
msg: `Couldn't get database full name`,
|
||||||
* @description Check input validity
|
};
|
||||||
*/
|
}
|
||||||
if (email === null || email === void 0 ? void 0 : email.match(/ /)) {
|
if (email === null || email === void 0 ? void 0 : email.match(/ /)) {
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
msg: "Invalid Email/Password format",
|
msg: "Invalid Email/Password format",
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
let foundUser = yield (0, varDatabaseDbHandler_1.default)({
|
let foundUser = await varDatabaseDbHandler({
|
||||||
queryString: `SELECT * FROM ${dbFullName}.users WHERE email = ? OR username = ?`,
|
queryString: `SELECT * FROM ${dbFullName}.users WHERE email = ? OR username = ?`,
|
||||||
queryValuesArray: [email, email],
|
queryValuesArray: [email, email],
|
||||||
database: dbFullName,
|
database: dbFullName,
|
||||||
@ -48,5 +33,4 @@ function apiSendResetPasswordLink(_a) {
|
|||||||
msg: "No user found",
|
msg: "No user found",
|
||||||
};
|
};
|
||||||
return { success: true };
|
return { success: true };
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
@ -1,26 +1,10 @@
|
|||||||
"use strict";
|
import handleSocialDb from "../../social-login/handleSocialDb";
|
||||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
import githubLogin from "../../social-login/githubLogin";
|
||||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
import camelJoinedtoCamelSpace from "../../../../utils/camelJoinedtoCamelSpace";
|
||||||
return new (P || (P = Promise))(function (resolve, reject) {
|
|
||||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
|
||||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
||||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
||||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
||||||
});
|
|
||||||
};
|
|
||||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
||||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
||||||
};
|
|
||||||
Object.defineProperty(exports, "__esModule", { value: true });
|
|
||||||
exports.default = apiGithubLogin;
|
|
||||||
const handleSocialDb_1 = __importDefault(require("../../social-login/handleSocialDb"));
|
|
||||||
const githubLogin_1 = __importDefault(require("../../social-login/githubLogin"));
|
|
||||||
const camelJoinedtoCamelSpace_1 = __importDefault(require("../../../../utils/camelJoinedtoCamelSpace"));
|
|
||||||
/**
|
/**
|
||||||
* # API Login with Github
|
* # API Login with Github
|
||||||
*/
|
*/
|
||||||
function apiGithubLogin(_a) {
|
export default async function apiGithubLogin({ code, clientId, clientSecret, database, additionalFields, email, additionalData, }) {
|
||||||
return __awaiter(this, arguments, void 0, function* ({ code, clientId, clientSecret, database, additionalFields, email, additionalData, }) {
|
|
||||||
if (!code || !clientId || !clientSecret || !database) {
|
if (!code || !clientId || !clientSecret || !database) {
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
@ -41,7 +25,7 @@ function apiGithubLogin(_a) {
|
|||||||
*
|
*
|
||||||
* @description Create new user folder and file
|
* @description Create new user folder and file
|
||||||
*/
|
*/
|
||||||
const gitHubUser = yield (0, githubLogin_1.default)({
|
const gitHubUser = await githubLogin({
|
||||||
code: code,
|
code: code,
|
||||||
clientId: clientId,
|
clientId: clientId,
|
||||||
clientSecret: clientSecret,
|
clientSecret: clientSecret,
|
||||||
@ -61,8 +45,8 @@ function apiGithubLogin(_a) {
|
|||||||
: [targetName];
|
: [targetName];
|
||||||
let payload = {
|
let payload = {
|
||||||
email: gitHubUser.email,
|
email: gitHubUser.email,
|
||||||
first_name: (0, camelJoinedtoCamelSpace_1.default)(nameArray[0]),
|
first_name: camelJoinedtoCamelSpace(nameArray[0]),
|
||||||
last_name: (0, camelJoinedtoCamelSpace_1.default)(nameArray[1]),
|
last_name: camelJoinedtoCamelSpace(nameArray[1]),
|
||||||
social_id: socialId,
|
social_id: socialId,
|
||||||
social_platform: "github",
|
social_platform: "github",
|
||||||
image: gitHubUser.avatar_url,
|
image: gitHubUser.avatar_url,
|
||||||
@ -72,7 +56,7 @@ function apiGithubLogin(_a) {
|
|||||||
if (additionalData) {
|
if (additionalData) {
|
||||||
payload = Object.assign(Object.assign({}, payload), additionalData);
|
payload = Object.assign(Object.assign({}, payload), additionalData);
|
||||||
}
|
}
|
||||||
const loggedInGithubUser = yield (0, handleSocialDb_1.default)({
|
const loggedInGithubUser = await handleSocialDb({
|
||||||
database,
|
database,
|
||||||
email: gitHubUser.email,
|
email: gitHubUser.email,
|
||||||
payload,
|
payload,
|
||||||
@ -84,5 +68,4 @@ function apiGithubLogin(_a) {
|
|||||||
////////////////////////////////////////////////
|
////////////////////////////////////////////////
|
||||||
////////////////////////////////////////////////
|
////////////////////////////////////////////////
|
||||||
return Object.assign({}, loggedInGithubUser);
|
return Object.assign({}, loggedInGithubUser);
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
@ -1,29 +1,13 @@
|
|||||||
"use strict";
|
import https from "https";
|
||||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
import handleSocialDb from "../../social-login/handleSocialDb";
|
||||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
import EJSON from "../../../../utils/ejson";
|
||||||
return new (P || (P = Promise))(function (resolve, reject) {
|
|
||||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
|
||||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
||||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
||||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
||||||
});
|
|
||||||
};
|
|
||||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
||||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
||||||
};
|
|
||||||
Object.defineProperty(exports, "__esModule", { value: true });
|
|
||||||
exports.default = apiGoogleLogin;
|
|
||||||
const https_1 = __importDefault(require("https"));
|
|
||||||
const handleSocialDb_1 = __importDefault(require("../../social-login/handleSocialDb"));
|
|
||||||
const ejson_1 = __importDefault(require("../../../../utils/ejson"));
|
|
||||||
/**
|
/**
|
||||||
* # API google login
|
* # API google login
|
||||||
*/
|
*/
|
||||||
function apiGoogleLogin(_a) {
|
export default async function apiGoogleLogin({ token, database, additionalFields, additionalData, debug, loginOnly, }) {
|
||||||
return __awaiter(this, arguments, void 0, function* ({ token, database, additionalFields, additionalData, debug, loginOnly, }) {
|
|
||||||
try {
|
try {
|
||||||
const gUser = yield new Promise((resolve, reject) => {
|
const gUser = await new Promise((resolve, reject) => {
|
||||||
https_1.default
|
https
|
||||||
.request({
|
.request({
|
||||||
method: "GET",
|
method: "GET",
|
||||||
hostname: "www.googleapis.com",
|
hostname: "www.googleapis.com",
|
||||||
@ -37,7 +21,7 @@ function apiGoogleLogin(_a) {
|
|||||||
data += chunk;
|
data += chunk;
|
||||||
});
|
});
|
||||||
res.on("end", () => {
|
res.on("end", () => {
|
||||||
resolve(ejson_1.default.parse(data));
|
resolve(EJSON.parse(data));
|
||||||
});
|
});
|
||||||
})
|
})
|
||||||
.end();
|
.end();
|
||||||
@ -63,7 +47,7 @@ function apiGoogleLogin(_a) {
|
|||||||
if (additionalData) {
|
if (additionalData) {
|
||||||
payloadObject = Object.assign(Object.assign({}, payloadObject), additionalData);
|
payloadObject = Object.assign(Object.assign({}, payloadObject), additionalData);
|
||||||
}
|
}
|
||||||
const loggedInGoogleUser = yield (0, handleSocialDb_1.default)({
|
const loggedInGoogleUser = await handleSocialDb({
|
||||||
database,
|
database,
|
||||||
email: email || "",
|
email: email || "",
|
||||||
payload: payloadObject,
|
payload: payloadObject,
|
||||||
@ -85,5 +69,4 @@ function apiGoogleLogin(_a) {
|
|||||||
msg: error.message,
|
msg: error.message,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
@ -1,22 +1,7 @@
|
|||||||
"use strict";
|
import serverError from "./serverError";
|
||||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
import DB_HANDLER from "../../utils/backend/global-db/DB_HANDLER";
|
||||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
import addDbEntry from "./db/addDbEntry";
|
||||||
return new (P || (P = Promise))(function (resolve, reject) {
|
import LOCAL_DB_HANDLER from "../../utils/backend/global-db/LOCAL_DB_HANDLER";
|
||||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
|
||||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
||||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
||||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
||||||
});
|
|
||||||
};
|
|
||||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
||||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
||||||
};
|
|
||||||
Object.defineProperty(exports, "__esModule", { value: true });
|
|
||||||
exports.default = addAdminUserOnLogin;
|
|
||||||
const serverError_1 = __importDefault(require("./serverError"));
|
|
||||||
const DB_HANDLER_1 = __importDefault(require("../../utils/backend/global-db/DB_HANDLER"));
|
|
||||||
const addDbEntry_1 = __importDefault(require("./db/addDbEntry"));
|
|
||||||
const LOCAL_DB_HANDLER_1 = __importDefault(require("../../utils/backend/global-db/LOCAL_DB_HANDLER"));
|
|
||||||
/**
|
/**
|
||||||
* Add Admin User on Login
|
* Add Admin User on Login
|
||||||
* ==============================================================================
|
* ==============================================================================
|
||||||
@ -25,17 +10,16 @@ const LOCAL_DB_HANDLER_1 = __importDefault(require("../../utils/backend/global-d
|
|||||||
* admin user. This fires when the invited user has been logged in or a new account
|
* admin user. This fires when the invited user has been logged in or a new account
|
||||||
* has been created for the invited user
|
* has been created for the invited user
|
||||||
*/
|
*/
|
||||||
function addAdminUserOnLogin(_a) {
|
export default async function addAdminUserOnLogin({ query, user, }) {
|
||||||
return __awaiter(this, arguments, void 0, function* ({ query, user, }) {
|
var _a;
|
||||||
var _b;
|
|
||||||
try {
|
try {
|
||||||
const finalDbHandler = global.DSQL_USE_LOCAL
|
const finalDbHandler = global.DSQL_USE_LOCAL
|
||||||
? LOCAL_DB_HANDLER_1.default
|
? LOCAL_DB_HANDLER
|
||||||
: DB_HANDLER_1.default;
|
: DB_HANDLER;
|
||||||
const { invite, database_access, priviledge, email } = query;
|
const { invite, database_access, priviledge, email } = query;
|
||||||
const lastInviteTimeQuery = `SELECT date_created_code FROM invitations WHERE inviting_user_id=? AND invited_user_email=?`;
|
const lastInviteTimeQuery = `SELECT date_created_code FROM invitations WHERE inviting_user_id=? AND invited_user_email=?`;
|
||||||
const lastInviteTimeValues = [invite, email];
|
const lastInviteTimeValues = [invite, email];
|
||||||
const lastInviteTimeArray = yield finalDbHandler(lastInviteTimeQuery, lastInviteTimeValues);
|
const lastInviteTimeArray = await finalDbHandler(lastInviteTimeQuery, lastInviteTimeValues);
|
||||||
if (!lastInviteTimeArray || !lastInviteTimeArray[0]) {
|
if (!lastInviteTimeArray || !lastInviteTimeArray[0]) {
|
||||||
throw new Error("No Invitation Found");
|
throw new Error("No Invitation Found");
|
||||||
}
|
}
|
||||||
@ -44,14 +28,14 @@ function addAdminUserOnLogin(_a) {
|
|||||||
////////////////////////////////////////////////
|
////////////////////////////////////////////////
|
||||||
const invitingUserDbQuery = `SELECT first_name,last_name,email FROM users WHERE id=?`;
|
const invitingUserDbQuery = `SELECT first_name,last_name,email FROM users WHERE id=?`;
|
||||||
const invitingUserDbValues = [invite];
|
const invitingUserDbValues = [invite];
|
||||||
const invitingUserDb = yield finalDbHandler(invitingUserDbQuery, invitingUserDbValues);
|
const invitingUserDb = await finalDbHandler(invitingUserDbQuery, invitingUserDbValues);
|
||||||
if (invitingUserDb === null || invitingUserDb === void 0 ? void 0 : invitingUserDb[0]) {
|
if (invitingUserDb === null || invitingUserDb === void 0 ? void 0 : invitingUserDb[0]) {
|
||||||
const existingUserUser = yield finalDbHandler(`SELECT email FROM user_users WHERE user_id=? AND invited_user_id=? AND user_type='admin' AND email=?`, [invite, user.id, email]);
|
const existingUserUser = await finalDbHandler(`SELECT email FROM user_users WHERE user_id=? AND invited_user_id=? AND user_type='admin' AND email=?`, [invite, user.id, email]);
|
||||||
if (existingUserUser === null || existingUserUser === void 0 ? void 0 : existingUserUser[0]) {
|
if (existingUserUser === null || existingUserUser === void 0 ? void 0 : existingUserUser[0]) {
|
||||||
console.log("User already added");
|
console.log("User already added");
|
||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
(0, addDbEntry_1.default)({
|
addDbEntry({
|
||||||
dbFullName: "datasquirel",
|
dbFullName: "datasquirel",
|
||||||
tableName: "user_users",
|
tableName: "user_users",
|
||||||
data: {
|
data: {
|
||||||
@ -72,8 +56,8 @@ function addAdminUserOnLogin(_a) {
|
|||||||
////////////////////////////////////////////////
|
////////////////////////////////////////////////
|
||||||
////////////////////////////////////////////////
|
////////////////////////////////////////////////
|
||||||
////////////////////////////////////////////////
|
////////////////////////////////////////////////
|
||||||
const dbTableData = yield finalDbHandler(`SELECT db_tables_data FROM invitations WHERE inviting_user_id=? AND invited_user_email=?`, [invite, email]);
|
const dbTableData = await finalDbHandler(`SELECT db_tables_data FROM invitations WHERE inviting_user_id=? AND invited_user_email=?`, [invite, email]);
|
||||||
const clearEntries = yield finalDbHandler(`DELETE FROM delegated_user_tables WHERE root_user_id=? AND delegated_user_id=?`, [invite, user.id]);
|
const clearEntries = await finalDbHandler(`DELETE FROM delegated_user_tables WHERE root_user_id=? AND delegated_user_id=?`, [invite, user.id]);
|
||||||
////////////////////////////////////////////////
|
////////////////////////////////////////////////
|
||||||
////////////////////////////////////////////////
|
////////////////////////////////////////////////
|
||||||
////////////////////////////////////////////////
|
////////////////////////////////////////////////
|
||||||
@ -83,7 +67,7 @@ function addAdminUserOnLogin(_a) {
|
|||||||
const dbTableEntry = dbTableEntries[i];
|
const dbTableEntry = dbTableEntries[i];
|
||||||
const dbTableEntryArray = dbTableEntry.split("-");
|
const dbTableEntryArray = dbTableEntry.split("-");
|
||||||
const [db_slug, table_slug] = dbTableEntryArray;
|
const [db_slug, table_slug] = dbTableEntryArray;
|
||||||
const newEntry = yield (0, addDbEntry_1.default)({
|
const newEntry = await addDbEntry({
|
||||||
dbFullName: "datasquirel",
|
dbFullName: "datasquirel",
|
||||||
tableName: "delegated_user_tables",
|
tableName: "delegated_user_tables",
|
||||||
data: {
|
data: {
|
||||||
@ -97,16 +81,15 @@ function addAdminUserOnLogin(_a) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
const inviteAccepted = yield finalDbHandler(`UPDATE invitations SET invitation_status='Accepted' WHERE inviting_user_id=? AND invited_user_email=?`, [invite, email]);
|
const inviteAccepted = await finalDbHandler(`UPDATE invitations SET invitation_status='Accepted' WHERE inviting_user_id=? AND invited_user_email=?`, [invite, email]);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
catch (error) {
|
catch (error) {
|
||||||
(_b = global.ERROR_CALLBACK) === null || _b === void 0 ? void 0 : _b.call(global, `Add Admin User On Login Error`, error);
|
(_a = global.ERROR_CALLBACK) === null || _a === void 0 ? void 0 : _a.call(global, `Add Admin User On Login Error`, error);
|
||||||
(0, serverError_1.default)({
|
serverError({
|
||||||
component: "addAdminUserOnLogin",
|
component: "addAdminUserOnLogin",
|
||||||
message: error.message,
|
message: error.message,
|
||||||
user: user,
|
user: user,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
@ -1,53 +1,38 @@
|
|||||||
"use strict";
|
import generator from "generate-password";
|
||||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
import DB_HANDLER from "../../utils/backend/global-db/DB_HANDLER";
|
||||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
import NO_DB_HANDLER from "../../utils/backend/global-db/NO_DB_HANDLER";
|
||||||
return new (P || (P = Promise))(function (resolve, reject) {
|
import addDbEntry from "./db/addDbEntry";
|
||||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
import encrypt from "../dsql/encrypt";
|
||||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
import LOCAL_DB_HANDLER from "../../utils/backend/global-db/LOCAL_DB_HANDLER";
|
||||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
import grabSQLKeyName from "../../utils/grab-sql-key-name";
|
||||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
||||||
});
|
|
||||||
};
|
|
||||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
||||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
||||||
};
|
|
||||||
Object.defineProperty(exports, "__esModule", { value: true });
|
|
||||||
exports.default = addMariadbUser;
|
|
||||||
const generate_password_1 = __importDefault(require("generate-password"));
|
|
||||||
const DB_HANDLER_1 = __importDefault(require("../../utils/backend/global-db/DB_HANDLER"));
|
|
||||||
const NO_DB_HANDLER_1 = __importDefault(require("../../utils/backend/global-db/NO_DB_HANDLER"));
|
|
||||||
const addDbEntry_1 = __importDefault(require("./db/addDbEntry"));
|
|
||||||
const encrypt_1 = __importDefault(require("../dsql/encrypt"));
|
|
||||||
const LOCAL_DB_HANDLER_1 = __importDefault(require("../../utils/backend/global-db/LOCAL_DB_HANDLER"));
|
|
||||||
/**
|
/**
|
||||||
* # Add Mariadb User
|
* # Add Mariadb User
|
||||||
*/
|
*/
|
||||||
function addMariadbUser(_a) {
|
export default async function addMariadbUser({ userId }) {
|
||||||
return __awaiter(this, arguments, void 0, function* ({ userId }) {
|
|
||||||
try {
|
try {
|
||||||
const defaultMariadbUserHost = process.env.DSQL_DB_HOST || "127.0.0.1";
|
const defaultMariadbUserHost = process.env.DSQL_DB_HOST || "127.0.0.1";
|
||||||
const username = `dsql_user_${userId}`;
|
const username = grabSQLKeyName({ type: "user", userId });
|
||||||
const password = generate_password_1.default.generate({
|
const password = generator.generate({
|
||||||
length: 16,
|
length: 16,
|
||||||
numbers: true,
|
numbers: true,
|
||||||
symbols: true,
|
symbols: true,
|
||||||
uppercase: true,
|
uppercase: true,
|
||||||
exclude: "*#.'`\"",
|
exclude: "*#.'`\"",
|
||||||
});
|
});
|
||||||
const encryptedPassword = (0, encrypt_1.default)({ data: password });
|
const encryptedPassword = encrypt({ data: password });
|
||||||
const createMariadbUsersQuery = `CREATE USER IF NOT EXISTS '${username}'@'127.0.0.1' IDENTIFIED BY '${password}'`;
|
const createMariadbUsersQuery = `CREATE USER IF NOT EXISTS '${username}'@'127.0.0.1' IDENTIFIED BY '${password}'`;
|
||||||
if (global.DSQL_USE_LOCAL) {
|
if (global.DSQL_USE_LOCAL) {
|
||||||
yield (0, LOCAL_DB_HANDLER_1.default)(createMariadbUsersQuery);
|
await LOCAL_DB_HANDLER(createMariadbUsersQuery);
|
||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
yield (0, NO_DB_HANDLER_1.default)(createMariadbUsersQuery);
|
await NO_DB_HANDLER(createMariadbUsersQuery);
|
||||||
}
|
}
|
||||||
const updateUserQuery = `UPDATE users SET mariadb_user = ?, mariadb_host = '127.0.0.1', mariadb_pass = ? WHERE id = ?`;
|
const updateUserQuery = `UPDATE users SET mariadb_user = ?, mariadb_host = '127.0.0.1', mariadb_pass = ? WHERE id = ?`;
|
||||||
const updateUserValues = [username, encryptedPassword, userId];
|
const updateUserValues = [username, encryptedPassword, userId];
|
||||||
const updateUser = global.DSQL_USE_LOCAL
|
const updateUser = global.DSQL_USE_LOCAL
|
||||||
? yield (0, LOCAL_DB_HANDLER_1.default)(updateUserQuery, updateUserValues)
|
? await LOCAL_DB_HANDLER(updateUserQuery, updateUserValues)
|
||||||
: yield (0, DB_HANDLER_1.default)(updateUserQuery, updateUserValues);
|
: await DB_HANDLER(updateUserQuery, updateUserValues);
|
||||||
const addMariadbUser = yield (0, addDbEntry_1.default)({
|
const addMariadbUser = await addDbEntry({
|
||||||
tableName: "mariadb_users",
|
tableName: "mariadb_users",
|
||||||
data: {
|
data: {
|
||||||
user_id: userId,
|
user_id: userId,
|
||||||
@ -64,7 +49,6 @@ function addMariadbUser(_a) {
|
|||||||
catch ( /** @type {any} */error) {
|
catch ( /** @type {any} */error) {
|
||||||
console.log(`Error in adding SQL user in 'addMariadbUser' function =>`, error.message);
|
console.log(`Error in adding SQL user in 'addMariadbUser' function =>`, error.message);
|
||||||
}
|
}
|
||||||
});
|
|
||||||
}
|
}
|
||||||
////////////////////////////////////////////////
|
////////////////////////////////////////////////
|
||||||
////////////////////////////////////////////////
|
////////////////////////////////////////////////
|
||||||
|
@ -4,9 +4,10 @@ type Param = {
|
|||||||
payload?: {
|
payload?: {
|
||||||
[s: string]: any;
|
[s: string]: any;
|
||||||
};
|
};
|
||||||
|
dbId: string | number;
|
||||||
};
|
};
|
||||||
/**
|
/**
|
||||||
* # Add User Table to Database
|
* # Add User Table to Database
|
||||||
*/
|
*/
|
||||||
export default function addUsersTableToDb({ userId, database, payload, }: Param): Promise<any>;
|
export default function addUsersTableToDb({ userId, database, payload, dbId, }: Param): Promise<any>;
|
||||||
export {};
|
export {};
|
||||||
|
@ -1,40 +1,23 @@
|
|||||||
"use strict";
|
import serverError from "./serverError";
|
||||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
import DB_HANDLER from "../../utils/backend/global-db/DB_HANDLER";
|
||||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
import addDbEntry from "./db/addDbEntry";
|
||||||
return new (P || (P = Promise))(function (resolve, reject) {
|
import createDbFromSchema from "../../shell/createDbFromSchema";
|
||||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
import LOCAL_DB_HANDLER from "../../utils/backend/global-db/LOCAL_DB_HANDLER";
|
||||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
import grabNewUsersTableSchema from "./grabNewUsersTableSchema";
|
||||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
import { grabPrimaryRequiredDbSchema, writeUpdatedDbSchema, } from "../../shell/createDbFromSchema/grab-required-database-schemas";
|
||||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
||||||
});
|
|
||||||
};
|
|
||||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
||||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
||||||
};
|
|
||||||
Object.defineProperty(exports, "__esModule", { value: true });
|
|
||||||
exports.default = addUsersTableToDb;
|
|
||||||
const serverError_1 = __importDefault(require("./serverError"));
|
|
||||||
const DB_HANDLER_1 = __importDefault(require("../../utils/backend/global-db/DB_HANDLER"));
|
|
||||||
const grabUserSchemaData_1 = __importDefault(require("./grabUserSchemaData"));
|
|
||||||
const setUserSchemaData_1 = __importDefault(require("./setUserSchemaData"));
|
|
||||||
const addDbEntry_1 = __importDefault(require("./db/addDbEntry"));
|
|
||||||
const createDbFromSchema_1 = __importDefault(require("../../shell/createDbFromSchema"));
|
|
||||||
const LOCAL_DB_HANDLER_1 = __importDefault(require("../../utils/backend/global-db/LOCAL_DB_HANDLER"));
|
|
||||||
const grabNewUsersTableSchema_1 = __importDefault(require("./grabNewUsersTableSchema"));
|
|
||||||
/**
|
/**
|
||||||
* # Add User Table to Database
|
* # Add User Table to Database
|
||||||
*/
|
*/
|
||||||
function addUsersTableToDb(_a) {
|
export default async function addUsersTableToDb({ userId, database, payload, dbId, }) {
|
||||||
return __awaiter(this, arguments, void 0, function* ({ userId, database, payload, }) {
|
|
||||||
try {
|
try {
|
||||||
const dbFullName = database;
|
const dbFullName = database;
|
||||||
const userPreset = (0, grabNewUsersTableSchema_1.default)({ payload });
|
const userPreset = grabNewUsersTableSchema({ payload });
|
||||||
if (!userPreset)
|
if (!userPreset)
|
||||||
throw new Error("Couldn't Get User Preset!");
|
throw new Error("Couldn't Get User Preset!");
|
||||||
const userSchemaData = (0, grabUserSchemaData_1.default)({ userId });
|
let targetDatabase = grabPrimaryRequiredDbSchema({
|
||||||
if (!userSchemaData)
|
dbId,
|
||||||
throw new Error("User schema data not found!");
|
userId,
|
||||||
let targetDatabase = userSchemaData.find((db) => db.dbFullName === database);
|
});
|
||||||
if (!targetDatabase) {
|
if (!targetDatabase) {
|
||||||
throw new Error("Couldn't Find Target Database!");
|
throw new Error("Couldn't Find Target Database!");
|
||||||
}
|
}
|
||||||
@ -45,12 +28,12 @@ function addUsersTableToDb(_a) {
|
|||||||
else {
|
else {
|
||||||
targetDatabase.tables.push(userPreset);
|
targetDatabase.tables.push(userPreset);
|
||||||
}
|
}
|
||||||
(0, setUserSchemaData_1.default)({ schemaData: userSchemaData, userId });
|
writeUpdatedDbSchema({ dbSchema: targetDatabase, userId });
|
||||||
const targetDb = global.DSQL_USE_LOCAL
|
const targetDb = global.DSQL_USE_LOCAL
|
||||||
? yield (0, LOCAL_DB_HANDLER_1.default)(`SELECT id FROM user_databases WHERE user_id=? AND db_slug=?`, [userId, database])
|
? await LOCAL_DB_HANDLER(`SELECT id FROM user_databases WHERE user_id=? AND db_slug=?`, [userId, database])
|
||||||
: yield (0, DB_HANDLER_1.default)(`SELECT id FROM user_databases WHERE user_id=? AND db_slug=?`, [userId, database]);
|
: await DB_HANDLER(`SELECT id FROM user_databases WHERE user_id=? AND db_slug=?`, [userId, database]);
|
||||||
if (targetDb === null || targetDb === void 0 ? void 0 : targetDb[0]) {
|
if (targetDb === null || targetDb === void 0 ? void 0 : targetDb[0]) {
|
||||||
const newTableEntry = yield (0, addDbEntry_1.default)({
|
const newTableEntry = await addDbEntry({
|
||||||
dbFullName: "datasquirel",
|
dbFullName: "datasquirel",
|
||||||
tableName: "user_database_tables",
|
tableName: "user_database_tables",
|
||||||
data: {
|
data: {
|
||||||
@ -62,7 +45,7 @@ function addUsersTableToDb(_a) {
|
|||||||
},
|
},
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
const dbShellUpdate = yield (0, createDbFromSchema_1.default)({
|
const dbShellUpdate = await createDbFromSchema({
|
||||||
userId,
|
userId,
|
||||||
targetDatabase: dbFullName,
|
targetDatabase: dbFullName,
|
||||||
});
|
});
|
||||||
@ -70,12 +53,11 @@ function addUsersTableToDb(_a) {
|
|||||||
}
|
}
|
||||||
catch ( /** @type {any} */error) {
|
catch ( /** @type {any} */error) {
|
||||||
console.log(`addUsersTableToDb.ts ERROR: ${error.message}`);
|
console.log(`addUsersTableToDb.ts ERROR: ${error.message}`);
|
||||||
(0, serverError_1.default)({
|
serverError({
|
||||||
component: "addUsersTableToDb",
|
component: "addUsersTableToDb",
|
||||||
message: error.message,
|
message: error.message,
|
||||||
user: { id: userId },
|
user: { id: userId },
|
||||||
});
|
});
|
||||||
return error.message;
|
return error.message;
|
||||||
}
|
}
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
@ -1,6 +1,4 @@
|
|||||||
import { CheckApiCredentialsFn } from "../../types";
|
export {};
|
||||||
/**
|
/**
|
||||||
* # Grap API Credentials
|
* # Grap API Credentials
|
||||||
*/
|
*/
|
||||||
declare const grabApiCred: CheckApiCredentialsFn;
|
|
||||||
export default grabApiCred;
|
|
||||||
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user