Updates
This commit is contained in:
parent
6e334c2525
commit
7e8bb37c09
@ -1,7 +1,6 @@
|
||||
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:
|
||||
| "POST"
|
||||
| "GET"
|
||||
@ -13,7 +12,7 @@ type FetchApiOptions = {
|
||||
| "delete"
|
||||
| "put"
|
||||
| "patch";
|
||||
body?: object | string;
|
||||
body?: T | string;
|
||||
headers?: FetchHeader;
|
||||
};
|
||||
|
||||
@ -31,25 +30,34 @@ export type FetchApiReturn = {
|
||||
/**
|
||||
* # 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,
|
||||
options?: FetchApiOptions,
|
||||
options?: FetchApiOptions<T>,
|
||||
csrf?: boolean,
|
||||
/** Key to use to grab local Storage csrf value. */
|
||||
localStorageCSRFKey?: string
|
||||
): Promise<any> {
|
||||
/**
|
||||
* 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> {
|
||||
let data;
|
||||
|
||||
const csrfValue = localStorage.getItem(
|
||||
localStorageCSRFKey || getCsrfHeaderName()
|
||||
);
|
||||
const csrfKey = "x-dsql-csrf-key";
|
||||
const csrfValue = localStorage.getItem(localStorageCSRFKey || csrfKey);
|
||||
|
||||
let finalHeaders = {
|
||||
"Content-Type": "application/json",
|
||||
} as FetchHeader;
|
||||
|
||||
if (csrf && csrfValue) {
|
||||
finalHeaders[getCsrfHeaderName()] = csrfValue;
|
||||
finalHeaders[localStorageCSRFKey || csrfKey] = csrfValue;
|
||||
}
|
||||
|
||||
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
|
||||
* ===============================================================================
|
||||
* @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)
|
||||
setLoading(true);
|
||||
const scopeString = scopes ? scopes.join("%20") : "read:user";
|
||||
|
47
dist/client/auth/google/getAccessToken.js
vendored
47
dist/client/auth/google/getAccessToken.js
vendored
@ -1,44 +1,29 @@
|
||||
"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;
|
||||
/**
|
||||
* Login with Google Function
|
||||
* ===============================================================================
|
||||
* @description This function uses google identity api to login a user with datasquirel
|
||||
*/
|
||||
function getAccessToken(params) {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
var _a, _b;
|
||||
(_a = params.setLoading) === null || _a === void 0 ? void 0 : _a.call(params, true);
|
||||
const response = (yield new Promise((resolve, reject) => {
|
||||
interval = setInterval(() => {
|
||||
// @ts-ignore
|
||||
let google = window.google;
|
||||
if (google) {
|
||||
window.clearInterval(interval);
|
||||
resolve(googleLogin(Object.assign(Object.assign({}, params), { google })));
|
||||
}
|
||||
}, 500);
|
||||
}));
|
||||
(_b = params.setLoading) === null || _b === void 0 ? void 0 : _b.call(params, false);
|
||||
return response;
|
||||
});
|
||||
export default async function getAccessToken(params) {
|
||||
var _a, _b;
|
||||
(_a = params.setLoading) === null || _a === void 0 ? void 0 : _a.call(params, true);
|
||||
const response = (await new Promise((resolve, reject) => {
|
||||
interval = setInterval(() => {
|
||||
// @ts-ignore
|
||||
let google = window.google;
|
||||
if (google) {
|
||||
window.clearInterval(interval);
|
||||
resolve(googleLogin(Object.assign(Object.assign({}, params), { google })));
|
||||
}
|
||||
}, 500);
|
||||
}));
|
||||
(_b = params.setLoading) === null || _b === void 0 ? void 0 : _b.call(params, false);
|
||||
return response;
|
||||
}
|
||||
/**
|
||||
* # Google Login Function
|
||||
*/
|
||||
function googleLogin({ google, clientId, setLoading, triggerPrompt, }) {
|
||||
export function googleLogin({ google, clientId, setLoading, triggerPrompt, }) {
|
||||
setTimeout(() => {
|
||||
setLoading === null || setLoading === void 0 ? void 0 : setLoading(false);
|
||||
}, 3000);
|
||||
|
161
dist/client/auth/logout.js
vendored
161
dist/client/auth/logout.js
vendored
@ -1,103 +1,86 @@
|
||||
"use strict";
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = logout;
|
||||
const get_csrf_header_name_1 = __importDefault(require("../../package-shared/actions/get-csrf-header-name"));
|
||||
const parseClientCookies_1 = __importDefault(require("../utils/parseClientCookies"));
|
||||
import getCsrfHeaderName from "../../package-shared/actions/get-csrf-header-name";
|
||||
import parseClientCookies from "../utils/parseClientCookies";
|
||||
/**
|
||||
* Login with Google Function
|
||||
* ===============================================================================
|
||||
* @description This function uses google identity api to login a user with datasquirel
|
||||
*/
|
||||
function logout(params) {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
export default async function logout(params) {
|
||||
try {
|
||||
const localUser = localStorage.getItem("user");
|
||||
let targetUser;
|
||||
try {
|
||||
const localUser = localStorage.getItem("user");
|
||||
let targetUser;
|
||||
try {
|
||||
targetUser = JSON.parse(localUser || "");
|
||||
}
|
||||
catch (error) {
|
||||
console.log(error);
|
||||
}
|
||||
if (!targetUser) {
|
||||
return false;
|
||||
}
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
const cookies = (0, parseClientCookies_1.default)();
|
||||
const socialId = (cookies === null || cookies === void 0 ? void 0 : cookies.datasquirel_social_id) &&
|
||||
typeof cookies.datasquirel_social_id == "string" &&
|
||||
!cookies.datasquirel_social_id.match(/^null$/i)
|
||||
? cookies.datasquirel_social_id
|
||||
: null;
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
localStorage.setItem("user", "{}");
|
||||
localStorage.removeItem((0, get_csrf_header_name_1.default)());
|
||||
document.cookie = `datasquirel_social_id=null;samesite=strict;path=/`;
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
const response = yield new Promise((resolve, reject) => {
|
||||
if (socialId && !(socialId === null || socialId === void 0 ? void 0 : socialId.match(/^null$/i))) {
|
||||
const googleClientId = params === null || params === void 0 ? void 0 : params.googleClientId;
|
||||
if (googleClientId) {
|
||||
const googleScript = document.createElement("script");
|
||||
googleScript.src = "https://accounts.google.com/gsi/client";
|
||||
googleScript.className = "social-script-tag";
|
||||
document.body.appendChild(googleScript);
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
googleScript.onload = function (e) {
|
||||
// @ts-ignore
|
||||
const google = window.google;
|
||||
if (google) {
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
google.accounts.id.initialize({
|
||||
client_id: googleClientId,
|
||||
});
|
||||
google.accounts.id.revoke(socialId, (done) => {
|
||||
console.log(done.error);
|
||||
resolve(true);
|
||||
});
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
}
|
||||
};
|
||||
}
|
||||
else {
|
||||
resolve(true);
|
||||
}
|
||||
targetUser = JSON.parse(localUser || "");
|
||||
}
|
||||
catch (error) {
|
||||
console.log(error);
|
||||
}
|
||||
if (!targetUser) {
|
||||
return false;
|
||||
}
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
const cookies = parseClientCookies();
|
||||
const socialId = (cookies === null || cookies === void 0 ? void 0 : cookies.datasquirel_social_id) &&
|
||||
typeof cookies.datasquirel_social_id == "string" &&
|
||||
!cookies.datasquirel_social_id.match(/^null$/i)
|
||||
? cookies.datasquirel_social_id
|
||||
: null;
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
localStorage.setItem("user", "{}");
|
||||
localStorage.removeItem(getCsrfHeaderName());
|
||||
document.cookie = `datasquirel_social_id=null;samesite=strict;path=/`;
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
const response = await new Promise((resolve, reject) => {
|
||||
if (socialId && !(socialId === null || socialId === void 0 ? void 0 : socialId.match(/^null$/i))) {
|
||||
const googleClientId = params === null || params === void 0 ? void 0 : params.googleClientId;
|
||||
if (googleClientId) {
|
||||
const googleScript = document.createElement("script");
|
||||
googleScript.src = "https://accounts.google.com/gsi/client";
|
||||
googleScript.className = "social-script-tag";
|
||||
document.body.appendChild(googleScript);
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
googleScript.onload = function (e) {
|
||||
// @ts-ignore
|
||||
const google = window.google;
|
||||
if (google) {
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
google.accounts.id.initialize({
|
||||
client_id: googleClientId,
|
||||
});
|
||||
google.accounts.id.revoke(socialId, (done) => {
|
||||
console.log(done.error);
|
||||
resolve(true);
|
||||
});
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
}
|
||||
};
|
||||
}
|
||||
else {
|
||||
resolve(true);
|
||||
}
|
||||
});
|
||||
return response;
|
||||
}
|
||||
catch (error) {
|
||||
return false;
|
||||
}
|
||||
});
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
}
|
||||
else {
|
||||
resolve(true);
|
||||
}
|
||||
});
|
||||
return response;
|
||||
}
|
||||
catch (error) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
12
dist/client/auth/post-login.js
vendored
12
dist/client/auth/post-login.js
vendored
@ -1,10 +1,4 @@
|
||||
"use strict";
|
||||
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"));
|
||||
import getCsrfHeaderName from "../../package-shared/actions/get-csrf-header-name";
|
||||
/**
|
||||
* 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`
|
||||
* function
|
||||
*/
|
||||
function postLogin(res) {
|
||||
export default function postLogin(res) {
|
||||
try {
|
||||
if (!res.payload)
|
||||
return false;
|
||||
if (!res.payload.csrf_k)
|
||||
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));
|
||||
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";
|
||||
body?: object | string;
|
||||
body?: T | string;
|
||||
headers?: FetchHeader;
|
||||
};
|
||||
type FetchHeader = HeadersInit & {
|
||||
@ -15,7 +19,18 @@ export type FetchApiReturn = {
|
||||
/**
|
||||
* # Fetch API
|
||||
*/
|
||||
export default function fetchApi(url: string, options?: FetchApiOptions, csrf?: boolean,
|
||||
/** Key to use to grab local Storage csrf value. */
|
||||
localStorageCSRFKey?: string): Promise<any>;
|
||||
export default function fetchApi<T extends {
|
||||
[k: string]: 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 {};
|
||||
|
150
dist/client/fetch/index.js
vendored
150
dist/client/fetch/index.js
vendored
@ -1,90 +1,80 @@
|
||||
"use strict";
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = fetchApi;
|
||||
const lodash_1 = __importDefault(require("lodash"));
|
||||
const get_csrf_header_name_1 = __importDefault(require("../../package-shared/actions/get-csrf-header-name"));
|
||||
import _ from "lodash";
|
||||
/**
|
||||
* # Fetch API
|
||||
*/
|
||||
function fetchApi(url, options, csrf,
|
||||
/** Key to use to grab local Storage csrf value. */
|
||||
localStorageCSRFKey) {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
let data;
|
||||
const csrfValue = localStorage.getItem(localStorageCSRFKey || (0, get_csrf_header_name_1.default)());
|
||||
let finalHeaders = {
|
||||
"Content-Type": "application/json",
|
||||
};
|
||||
if (csrf && csrfValue) {
|
||||
finalHeaders[(0, get_csrf_header_name_1.default)()] = csrfValue;
|
||||
}
|
||||
if (typeof options === "string") {
|
||||
try {
|
||||
let fetchData;
|
||||
switch (options) {
|
||||
case "post":
|
||||
fetchData = yield fetch(url, {
|
||||
method: options,
|
||||
headers: finalHeaders,
|
||||
});
|
||||
data = fetchData.json();
|
||||
break;
|
||||
default:
|
||||
fetchData = yield fetch(url);
|
||||
data = fetchData.json();
|
||||
break;
|
||||
}
|
||||
}
|
||||
catch (error) {
|
||||
console.log("FetchAPI error #1:", error.message);
|
||||
data = null;
|
||||
export default async function fetchApi(url, options, csrf,
|
||||
/**
|
||||
* Key to use to grab local Storage csrf value.
|
||||
*/
|
||||
localStorageCSRFKey,
|
||||
/**
|
||||
* Key with which to set the request header csrf
|
||||
* value
|
||||
*/
|
||||
csrfHeaderKey) {
|
||||
let data;
|
||||
const csrfKey = "x-dsql-csrf-key";
|
||||
const csrfValue = localStorage.getItem(localStorageCSRFKey || csrfKey);
|
||||
let finalHeaders = {
|
||||
"Content-Type": "application/json",
|
||||
};
|
||||
if (csrf && csrfValue) {
|
||||
finalHeaders[localStorageCSRFKey || csrfKey] = csrfValue;
|
||||
}
|
||||
if (typeof options === "string") {
|
||||
try {
|
||||
let fetchData;
|
||||
switch (options) {
|
||||
case "post":
|
||||
fetchData = await fetch(url, {
|
||||
method: options,
|
||||
headers: finalHeaders,
|
||||
});
|
||||
data = fetchData.json();
|
||||
break;
|
||||
default:
|
||||
fetchData = await fetch(url);
|
||||
data = fetchData.json();
|
||||
break;
|
||||
}
|
||||
}
|
||||
else if (typeof options === "object") {
|
||||
try {
|
||||
let fetchData;
|
||||
if (options.body && typeof options.body === "object") {
|
||||
let oldOptionsBody = lodash_1.default.cloneDeep(options.body);
|
||||
options.body = JSON.stringify(oldOptionsBody);
|
||||
}
|
||||
if (options.headers) {
|
||||
options.headers = lodash_1.default.merge(options.headers, finalHeaders);
|
||||
const finalOptions = Object.assign({}, options);
|
||||
fetchData = yield fetch(url, finalOptions);
|
||||
}
|
||||
else {
|
||||
const finalOptions = Object.assign(Object.assign({}, options), { headers: finalHeaders });
|
||||
fetchData = yield fetch(url, finalOptions);
|
||||
}
|
||||
data = fetchData.json();
|
||||
}
|
||||
catch (error) {
|
||||
console.log("FetchAPI error #2:", error.message);
|
||||
data = null;
|
||||
}
|
||||
catch (error) {
|
||||
console.log("FetchAPI error #1:", error.message);
|
||||
data = null;
|
||||
}
|
||||
else {
|
||||
try {
|
||||
let fetchData = yield fetch(url);
|
||||
data = yield fetchData.json();
|
||||
}
|
||||
else if (typeof options === "object") {
|
||||
try {
|
||||
let fetchData;
|
||||
if (options.body && typeof options.body === "object") {
|
||||
let oldOptionsBody = _.cloneDeep(options.body);
|
||||
options.body = JSON.stringify(oldOptionsBody);
|
||||
}
|
||||
catch (error) {
|
||||
console.log("FetchAPI error #3:", error.message);
|
||||
data = null;
|
||||
if (options.headers) {
|
||||
options.headers = _.merge(options.headers, finalHeaders);
|
||||
const finalOptions = Object.assign({}, options);
|
||||
fetchData = await fetch(url, finalOptions);
|
||||
}
|
||||
else {
|
||||
const finalOptions = Object.assign(Object.assign({}, options), { headers: finalHeaders });
|
||||
fetchData = await fetch(url, finalOptions);
|
||||
}
|
||||
data = fetchData.json();
|
||||
}
|
||||
return data;
|
||||
});
|
||||
catch (error) {
|
||||
console.log("FetchAPI error #2:", error.message);
|
||||
data = null;
|
||||
}
|
||||
}
|
||||
else {
|
||||
try {
|
||||
let fetchData = await fetch(url);
|
||||
data = await fetchData.json();
|
||||
}
|
||||
catch (error) {
|
||||
console.log("FetchAPI error #3:", error.message);
|
||||
data = null;
|
||||
}
|
||||
}
|
||||
return data;
|
||||
}
|
||||
|
71
dist/client/index.js
vendored
71
dist/client/index.js
vendored
@ -1,60 +1,55 @@
|
||||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const imageInputFileToBase64_1 = __importDefault(require("./media/imageInputFileToBase64"));
|
||||
const imageInputToBase64_1 = __importDefault(require("./media/imageInputToBase64"));
|
||||
const inputFileToBase64_1 = __importDefault(require("./media/inputFileToBase64"));
|
||||
const getAccessToken_1 = __importDefault(require("./auth/google/getAccessToken"));
|
||||
const getAccessToken_2 = __importDefault(require("./auth/github/getAccessToken"));
|
||||
const logout_1 = __importDefault(require("./auth/logout"));
|
||||
const fetch_1 = __importDefault(require("./fetch"));
|
||||
const fetch_2 = __importDefault(require("./fetch"));
|
||||
const serialize_query_1 = __importDefault(require("../package-shared/utils/serialize-query"));
|
||||
const serialize_cookies_1 = __importDefault(require("../package-shared/utils/serialize-cookies"));
|
||||
const ejson_1 = __importDefault(require("../package-shared/utils/ejson"));
|
||||
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"));
|
||||
import imageInputFileToBase64 from "./media/imageInputFileToBase64";
|
||||
import imageInputToBase64 from "./media/imageInputToBase64";
|
||||
import inputFileToBase64 from "./media/inputFileToBase64";
|
||||
import getAccessToken from "./auth/google/getAccessToken";
|
||||
import getGithubAccessToken from "./auth/github/getAccessToken";
|
||||
import logout from "./auth/logout";
|
||||
import fetchApi from "./fetch";
|
||||
import clientFetch from "./fetch";
|
||||
import serializeQuery from "../package-shared/utils/serialize-query";
|
||||
import serializeCookies from "../package-shared/utils/serialize-cookies";
|
||||
import EJSON from "../package-shared/utils/ejson";
|
||||
import numberfy from "../package-shared/utils/numberfy";
|
||||
import slugify from "../package-shared/utils/slugify";
|
||||
import postLogin from "./auth/post-login";
|
||||
import deserializeQuery from "../package-shared/utils/deserialize-query";
|
||||
import debugLog from "../package-shared/utils/logging/debug-log";
|
||||
const media = {
|
||||
imageInputToBase64: imageInputToBase64_1.default,
|
||||
imageInputFileToBase64: imageInputFileToBase64_1.default,
|
||||
inputFileToBase64: inputFileToBase64_1.default,
|
||||
imageInputToBase64: imageInputToBase64,
|
||||
imageInputFileToBase64: imageInputFileToBase64,
|
||||
inputFileToBase64: inputFileToBase64,
|
||||
};
|
||||
/**
|
||||
* User Auth Object
|
||||
*/
|
||||
const auth = {
|
||||
google: {
|
||||
getAccessToken: getAccessToken_1.default,
|
||||
getAccessToken: getAccessToken,
|
||||
},
|
||||
github: {
|
||||
getAccessToken: getAccessToken_2.default,
|
||||
getAccessToken: getGithubAccessToken,
|
||||
},
|
||||
logout: logout_1.default,
|
||||
postLogin: post_login_1.default,
|
||||
logout,
|
||||
postLogin,
|
||||
};
|
||||
const utils = {
|
||||
deserializeQuery: deserialize_query_1.default,
|
||||
serializeQuery: serialize_query_1.default,
|
||||
serializeCookies: serialize_cookies_1.default,
|
||||
EJSON: ejson_1.default,
|
||||
numberfy: numberfy_1.default,
|
||||
slugify: slugify_1.default,
|
||||
debugLog: debug_log_1.default,
|
||||
deserializeQuery,
|
||||
serializeQuery,
|
||||
serializeCookies,
|
||||
EJSON,
|
||||
numberfy,
|
||||
slugify,
|
||||
debugLog,
|
||||
};
|
||||
/**
|
||||
* Fetch
|
||||
*/
|
||||
const fetch = {
|
||||
fetchApi: fetch_1.default,
|
||||
clientFetch: fetch_2.default,
|
||||
fetchApi,
|
||||
clientFetch,
|
||||
};
|
||||
/**
|
||||
* Main Export
|
||||
*/
|
||||
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";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
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"));
|
||||
import imageInputFileToBase64 from "./imageInputFileToBase64";
|
||||
import imageInputToBase64 from "./imageInputToBase64";
|
||||
/**
|
||||
* ==========================
|
||||
* Media Functions Object
|
||||
* ==========================
|
||||
*/
|
||||
const media = {
|
||||
imageInputToBase64: imageInputToBase64_1.default,
|
||||
imageInputFileToBase64: imageInputFileToBase64_1.default,
|
||||
imageInputToBase64: imageInputToBase64,
|
||||
imageInputFileToBase64: imageInputFileToBase64,
|
||||
};
|
||||
/**
|
||||
* ==========================
|
||||
@ -20,8 +15,8 @@ const media = {
|
||||
* ==========================
|
||||
*/
|
||||
const auth = {
|
||||
imageInputToBase64: imageInputToBase64_1.default,
|
||||
imageInputFileToBase64: imageInputFileToBase64_1.default,
|
||||
imageInputToBase64: imageInputToBase64,
|
||||
imageInputFileToBase64: imageInputFileToBase64,
|
||||
};
|
||||
/**
|
||||
* ==========================
|
||||
@ -31,4 +26,4 @@ const auth = {
|
||||
const datasquirelClient = {
|
||||
media: media,
|
||||
};
|
||||
exports.default = datasquirelClient;
|
||||
export default datasquirelClient;
|
||||
|
158
dist/client/media/imageInputFileToBase64.js
vendored
158
dist/client/media/imageInputFileToBase64.js
vendored
@ -1,92 +1,78 @@
|
||||
"use strict";
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = imageInputFileToBase64;
|
||||
/**
|
||||
* # Image input File top Base64
|
||||
*/
|
||||
function imageInputFileToBase64(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ imageInputFile, maxWidth, imagePreviewNode, }) {
|
||||
/**
|
||||
* Make https request
|
||||
*
|
||||
* @description make a request to datasquirel.com
|
||||
*/
|
||||
try {
|
||||
let imageName = imageInputFile.name.replace(/\..*/, "");
|
||||
let imageDataBase64;
|
||||
let imageSize;
|
||||
let canvas = document.createElement("canvas");
|
||||
const MIME_TYPE = imageInputFile.type;
|
||||
const QUALITY = 0.95;
|
||||
const MAX_WIDTH = maxWidth ? maxWidth : null;
|
||||
const file = imageInputFile;
|
||||
const blobURL = URL.createObjectURL(file);
|
||||
const img = new Image();
|
||||
/** ********************* Add source to new image */
|
||||
img.src = blobURL;
|
||||
imageDataBase64 = yield new Promise((res, rej) => {
|
||||
/** ********************* Handle Errors in loading image */
|
||||
img.onerror = function () {
|
||||
URL.revokeObjectURL(this.src);
|
||||
console.log("Cannot load image");
|
||||
};
|
||||
/** ********************* Handle new image when loaded */
|
||||
img.onload = function (e) {
|
||||
const imgEl = e.target;
|
||||
URL.revokeObjectURL(imgEl.src);
|
||||
if (MAX_WIDTH) {
|
||||
const scaleSize = MAX_WIDTH / img.naturalWidth;
|
||||
canvas.width =
|
||||
img.naturalWidth < MAX_WIDTH
|
||||
? img.naturalWidth
|
||||
: MAX_WIDTH;
|
||||
canvas.height =
|
||||
img.naturalWidth < MAX_WIDTH
|
||||
? img.naturalHeight
|
||||
: img.naturalHeight * scaleSize;
|
||||
}
|
||||
else {
|
||||
canvas.width = img.naturalWidth;
|
||||
canvas.height = img.naturalHeight;
|
||||
}
|
||||
const ctx = canvas.getContext("2d");
|
||||
ctx === null || ctx === void 0 ? void 0 : ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
|
||||
const srcEncoded = canvas.toDataURL(MIME_TYPE, QUALITY);
|
||||
if (imagePreviewNode) {
|
||||
imagePreviewNode.src = srcEncoded;
|
||||
}
|
||||
res(srcEncoded);
|
||||
};
|
||||
});
|
||||
imageSize = yield new Promise((res, rej) => {
|
||||
canvas.toBlob((blob) => {
|
||||
res(blob === null || blob === void 0 ? void 0 : blob.size);
|
||||
}, MIME_TYPE, QUALITY);
|
||||
});
|
||||
return {
|
||||
imageBase64: imageDataBase64 === null || imageDataBase64 === void 0 ? void 0 : imageDataBase64.replace(/.*?base64,/, ""),
|
||||
imageBase64Full: imageDataBase64,
|
||||
imageName: imageName,
|
||||
imageSize: imageSize,
|
||||
export default async function imageInputFileToBase64({ imageInputFile, maxWidth, imagePreviewNode, }) {
|
||||
/**
|
||||
* Make https request
|
||||
*
|
||||
* @description make a request to datasquirel.com
|
||||
*/
|
||||
try {
|
||||
let imageName = imageInputFile.name.replace(/\..*/, "");
|
||||
let imageDataBase64;
|
||||
let imageSize;
|
||||
let canvas = document.createElement("canvas");
|
||||
const MIME_TYPE = imageInputFile.type;
|
||||
const QUALITY = 0.95;
|
||||
const MAX_WIDTH = maxWidth ? maxWidth : null;
|
||||
const file = imageInputFile;
|
||||
const blobURL = URL.createObjectURL(file);
|
||||
const img = new Image();
|
||||
/** ********************* Add source to new image */
|
||||
img.src = blobURL;
|
||||
imageDataBase64 = await new Promise((res, rej) => {
|
||||
/** ********************* Handle Errors in loading image */
|
||||
img.onerror = function () {
|
||||
URL.revokeObjectURL(this.src);
|
||||
console.log("Cannot load image");
|
||||
};
|
||||
}
|
||||
catch (error) {
|
||||
console.log("Image Processing Error! =>", error.message);
|
||||
return {
|
||||
imageBase64: undefined,
|
||||
imageBase64Full: undefined,
|
||||
imageName: undefined,
|
||||
imageSize: undefined,
|
||||
/** ********************* Handle new image when loaded */
|
||||
img.onload = function (e) {
|
||||
const imgEl = e.target;
|
||||
URL.revokeObjectURL(imgEl.src);
|
||||
if (MAX_WIDTH) {
|
||||
const scaleSize = MAX_WIDTH / img.naturalWidth;
|
||||
canvas.width =
|
||||
img.naturalWidth < MAX_WIDTH
|
||||
? img.naturalWidth
|
||||
: MAX_WIDTH;
|
||||
canvas.height =
|
||||
img.naturalWidth < MAX_WIDTH
|
||||
? img.naturalHeight
|
||||
: img.naturalHeight * scaleSize;
|
||||
}
|
||||
else {
|
||||
canvas.width = img.naturalWidth;
|
||||
canvas.height = img.naturalHeight;
|
||||
}
|
||||
const ctx = canvas.getContext("2d");
|
||||
ctx === null || ctx === void 0 ? void 0 : ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
|
||||
const srcEncoded = canvas.toDataURL(MIME_TYPE, QUALITY);
|
||||
if (imagePreviewNode) {
|
||||
imagePreviewNode.src = srcEncoded;
|
||||
}
|
||||
res(srcEncoded);
|
||||
};
|
||||
}
|
||||
});
|
||||
});
|
||||
imageSize = await new Promise((res, rej) => {
|
||||
canvas.toBlob((blob) => {
|
||||
res(blob === null || blob === void 0 ? void 0 : blob.size);
|
||||
}, MIME_TYPE, QUALITY);
|
||||
});
|
||||
return {
|
||||
imageBase64: imageDataBase64 === null || imageDataBase64 === void 0 ? void 0 : imageDataBase64.replace(/.*?base64,/, ""),
|
||||
imageBase64Full: imageDataBase64,
|
||||
imageName: imageName,
|
||||
imageSize: imageSize,
|
||||
};
|
||||
}
|
||||
catch (error) {
|
||||
console.log("Image Processing Error! =>", error.message);
|
||||
return {
|
||||
imageBase64: undefined,
|
||||
imageBase64Full: undefined,
|
||||
imageName: undefined,
|
||||
imageSize: undefined,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
150
dist/client/media/imageInputToBase64.js
vendored
150
dist/client/media/imageInputToBase64.js
vendored
@ -1,90 +1,76 @@
|
||||
"use strict";
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = imageInputToBase64;
|
||||
/**
|
||||
* # Image Input Element to Base 64
|
||||
*/
|
||||
function imageInputToBase64(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ imageInput, maxWidth, mimeType, }) {
|
||||
var _b, _c;
|
||||
/**
|
||||
* Make https request
|
||||
*
|
||||
* @description make a request to datasquirel.com
|
||||
*/
|
||||
try {
|
||||
let imagePreviewNode = document.querySelector(`[data-imagepreview='image']`);
|
||||
let imageName = (_b = imageInput.files) === null || _b === void 0 ? void 0 : _b[0].name.replace(/\..*/, "");
|
||||
let imageDataBase64;
|
||||
const MIME_TYPE = mimeType ? mimeType : "image/jpeg";
|
||||
const QUALITY = 0.95;
|
||||
const MAX_WIDTH = maxWidth ? maxWidth : null;
|
||||
const file = (_c = imageInput.files) === null || _c === void 0 ? void 0 : _c[0];
|
||||
const blobURL = file ? URL.createObjectURL(file) : undefined;
|
||||
const img = new Image();
|
||||
if (blobURL) {
|
||||
img.src = blobURL;
|
||||
imageDataBase64 = yield new Promise((res, rej) => {
|
||||
/** ********************* Handle Errors in loading image */
|
||||
img.onerror = function () {
|
||||
URL.revokeObjectURL(this.src);
|
||||
window.alert("Cannot load image!");
|
||||
};
|
||||
img.onload = function (e) {
|
||||
const imgEl = e.target;
|
||||
URL.revokeObjectURL(imgEl.src);
|
||||
const canvas = document.createElement("canvas");
|
||||
if (MAX_WIDTH) {
|
||||
const scaleSize = MAX_WIDTH / img.naturalWidth;
|
||||
canvas.width =
|
||||
img.naturalWidth < MAX_WIDTH
|
||||
? img.naturalWidth
|
||||
: MAX_WIDTH;
|
||||
canvas.height =
|
||||
img.naturalWidth < MAX_WIDTH
|
||||
? img.naturalHeight
|
||||
: img.naturalHeight * scaleSize;
|
||||
}
|
||||
else {
|
||||
canvas.width = img.naturalWidth;
|
||||
canvas.height = img.naturalHeight;
|
||||
}
|
||||
const ctx = canvas.getContext("2d");
|
||||
ctx === null || ctx === void 0 ? void 0 : ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
|
||||
const srcEncoded = canvas.toDataURL(MIME_TYPE, QUALITY);
|
||||
if (imagePreviewNode) {
|
||||
document
|
||||
.querySelectorAll(`[data-imagepreview='image']`)
|
||||
.forEach((_img) => {
|
||||
const _imgEl = _img;
|
||||
_imgEl.src = srcEncoded;
|
||||
});
|
||||
}
|
||||
res(srcEncoded);
|
||||
};
|
||||
});
|
||||
return {
|
||||
imageBase64: imageDataBase64 === null || imageDataBase64 === void 0 ? void 0 : imageDataBase64.replace(/.*?base64,/, ""),
|
||||
imageBase64Full: imageDataBase64,
|
||||
imageName: imageName,
|
||||
export default async function imageInputToBase64({ imageInput, maxWidth, mimeType, }) {
|
||||
var _a, _b;
|
||||
/**
|
||||
* Make https request
|
||||
*
|
||||
* @description make a request to datasquirel.com
|
||||
*/
|
||||
try {
|
||||
let imagePreviewNode = document.querySelector(`[data-imagepreview='image']`);
|
||||
let imageName = (_a = imageInput.files) === null || _a === void 0 ? void 0 : _a[0].name.replace(/\..*/, "");
|
||||
let imageDataBase64;
|
||||
const MIME_TYPE = mimeType ? mimeType : "image/jpeg";
|
||||
const QUALITY = 0.95;
|
||||
const MAX_WIDTH = maxWidth ? maxWidth : null;
|
||||
const file = (_b = imageInput.files) === null || _b === void 0 ? void 0 : _b[0];
|
||||
const blobURL = file ? URL.createObjectURL(file) : undefined;
|
||||
const img = new Image();
|
||||
if (blobURL) {
|
||||
img.src = blobURL;
|
||||
imageDataBase64 = await new Promise((res, rej) => {
|
||||
/** ********************* Handle Errors in loading image */
|
||||
img.onerror = function () {
|
||||
URL.revokeObjectURL(this.src);
|
||||
window.alert("Cannot load image!");
|
||||
};
|
||||
}
|
||||
else {
|
||||
return {};
|
||||
}
|
||||
img.onload = function (e) {
|
||||
const imgEl = e.target;
|
||||
URL.revokeObjectURL(imgEl.src);
|
||||
const canvas = document.createElement("canvas");
|
||||
if (MAX_WIDTH) {
|
||||
const scaleSize = MAX_WIDTH / img.naturalWidth;
|
||||
canvas.width =
|
||||
img.naturalWidth < MAX_WIDTH
|
||||
? img.naturalWidth
|
||||
: MAX_WIDTH;
|
||||
canvas.height =
|
||||
img.naturalWidth < MAX_WIDTH
|
||||
? img.naturalHeight
|
||||
: img.naturalHeight * scaleSize;
|
||||
}
|
||||
else {
|
||||
canvas.width = img.naturalWidth;
|
||||
canvas.height = img.naturalHeight;
|
||||
}
|
||||
const ctx = canvas.getContext("2d");
|
||||
ctx === null || ctx === void 0 ? void 0 : ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
|
||||
const srcEncoded = canvas.toDataURL(MIME_TYPE, QUALITY);
|
||||
if (imagePreviewNode) {
|
||||
document
|
||||
.querySelectorAll(`[data-imagepreview='image']`)
|
||||
.forEach((_img) => {
|
||||
const _imgEl = _img;
|
||||
_imgEl.src = srcEncoded;
|
||||
});
|
||||
}
|
||||
res(srcEncoded);
|
||||
};
|
||||
});
|
||||
return {
|
||||
imageBase64: imageDataBase64 === null || imageDataBase64 === void 0 ? void 0 : imageDataBase64.replace(/.*?base64,/, ""),
|
||||
imageBase64Full: imageDataBase64,
|
||||
imageName: imageName,
|
||||
};
|
||||
}
|
||||
catch ( /** @type {*} */error) {
|
||||
console.log("Image Processing Error! =>", error.message);
|
||||
else {
|
||||
return {};
|
||||
}
|
||||
});
|
||||
}
|
||||
catch ( /** @type {*} */error) {
|
||||
console.log("Image Processing Error! =>", error.message);
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
82
dist/client/media/inputFileToBase64.js
vendored
82
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
|
||||
* ==============================================================================
|
||||
@ -18,42 +6,40 @@ exports.default = inputFileToBase64;
|
||||
* HTML file input elements usually return an array of input objects, so be sure to select the target
|
||||
* file from the array.
|
||||
*/
|
||||
function inputFileToBase64(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ inputFile, allowedRegex, }) {
|
||||
var _b;
|
||||
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))) {
|
||||
window.alert(`We currently don't support ${inputFile.type} file types. Support is coming soon. For now we support only images and PDFs.`);
|
||||
return {
|
||||
fileName: inputFile.name,
|
||||
export default async function inputFileToBase64({ inputFile, allowedRegex, }) {
|
||||
var _a;
|
||||
const allowedTypesRegex = allowedRegex ? allowedRegex : /image\/*|\/pdf/;
|
||||
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.`);
|
||||
return {
|
||||
fileName: inputFile.name,
|
||||
};
|
||||
}
|
||||
try {
|
||||
let fileName = inputFile.name.replace(/\..*/, "");
|
||||
const fileData = await new Promise((resolve, reject) => {
|
||||
var reader = new FileReader();
|
||||
reader.readAsDataURL(inputFile);
|
||||
reader.onload = function () {
|
||||
var _a;
|
||||
resolve((_a = reader.result) === null || _a === void 0 ? void 0 : _a.toString());
|
||||
};
|
||||
}
|
||||
try {
|
||||
let fileName = inputFile.name.replace(/\..*/, "");
|
||||
const fileData = yield new Promise((resolve, reject) => {
|
||||
var reader = new FileReader();
|
||||
reader.readAsDataURL(inputFile);
|
||||
reader.onload = function () {
|
||||
var _a;
|
||||
resolve((_a = reader.result) === null || _a === void 0 ? void 0 : _a.toString());
|
||||
};
|
||||
reader.onerror = function (/** @type {*} */ error) {
|
||||
console.log("Error: ", error.message);
|
||||
};
|
||||
});
|
||||
return {
|
||||
fileBase64: fileData === null || fileData === void 0 ? void 0 : fileData.replace(/.*?base64,/, ""),
|
||||
fileBase64Full: fileData,
|
||||
fileName: fileName,
|
||||
fileSize: inputFile.size,
|
||||
fileType: inputFile.type,
|
||||
reader.onerror = function (/** @type {*} */ error) {
|
||||
console.log("Error: ", error.message);
|
||||
};
|
||||
}
|
||||
catch (error) {
|
||||
console.log("File Processing Error! =>", error.message);
|
||||
return {
|
||||
fileName: inputFile.name,
|
||||
};
|
||||
}
|
||||
});
|
||||
});
|
||||
return {
|
||||
fileBase64: fileData === null || fileData === void 0 ? void 0 : fileData.replace(/.*?base64,/, ""),
|
||||
fileBase64Full: fileData,
|
||||
fileName: fileName,
|
||||
fileSize: inputFile.size,
|
||||
fileType: inputFile.type,
|
||||
};
|
||||
}
|
||||
catch (error) {
|
||||
console.log("File Processing Error! =>", error.message);
|
||||
return {
|
||||
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
|
||||
* ============================================================================== *
|
||||
* @description This function takes in a request object and returns the cookies as a JS object
|
||||
*/
|
||||
function default_1() {
|
||||
export default function () {
|
||||
/**
|
||||
* 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 = {
|
||||
Reset: "\x1b[0m",
|
||||
Bright: "\x1b[1m",
|
||||
@ -27,4 +25,4 @@ const colors = {
|
||||
BgWhite: "\x1b[47m",
|
||||
BgGray: "\x1b[100m",
|
||||
};
|
||||
exports.default = colors;
|
||||
export default colors;
|
||||
|
149
dist/engine/dsql.js
vendored
149
dist/engine/dsql.js
vendored
@ -1,28 +1,13 @@
|
||||
#! /usr/bin/env node
|
||||
"use strict";
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = run;
|
||||
const fs_1 = __importDefault(require("fs"));
|
||||
const path_1 = __importDefault(require("path"));
|
||||
import fs from "fs";
|
||||
import path from "path";
|
||||
require("dotenv").config({
|
||||
path: path_1.default.resolve(process.cwd(), ".env"),
|
||||
path: path.resolve(process.cwd(), ".env"),
|
||||
});
|
||||
const index_1 = __importDefault(require("../index"));
|
||||
const console_colors_1 = __importDefault(require("../console-colors"));
|
||||
const createDbFromSchema_1 = __importDefault(require("../package-shared/shell/createDbFromSchema"));
|
||||
if (!fs_1.default.existsSync(path_1.default.resolve(process.cwd(), ".env"))) {
|
||||
import datasquirel from "../index";
|
||||
import colors from "../console-colors";
|
||||
import createDbFromSchema from "../package-shared/shell/createDbFromSchema";
|
||||
if (!fs.existsSync(path.resolve(process.cwd(), ".env"))) {
|
||||
console.log(".env file not found");
|
||||
process.exit();
|
||||
}
|
||||
@ -39,76 +24,74 @@ if (!(DSQL_PASS === null || DSQL_PASS === void 0 ? void 0 : DSQL_PASS.match(/./)
|
||||
console.log("DSQL_PASS is required in your `.env` file");
|
||||
process.exit();
|
||||
}
|
||||
const dbSchemaLocalFilePath = path_1.default.resolve(process.cwd(), "dsql.schema.json");
|
||||
function run() {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
let schemaData;
|
||||
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({
|
||||
key: DSQL_KEY,
|
||||
database: DSQL_REF_DB_NAME || undefined,
|
||||
});
|
||||
if (!dbSchemaDataResponse.payload ||
|
||||
Array.isArray(dbSchemaDataResponse.payload)) {
|
||||
console.log("DSQL_KEY+DSQL_REF_DB_NAME => Error in fetching DB schema");
|
||||
console.log(dbSchemaDataResponse);
|
||||
process.exit();
|
||||
}
|
||||
let fetchedDbSchemaObject = dbSchemaDataResponse.payload;
|
||||
if (DSQL_DB_NAME)
|
||||
fetchedDbSchemaObject.dbFullName = DSQL_DB_NAME;
|
||||
schemaData = [fetchedDbSchemaObject];
|
||||
}
|
||||
else if (DSQL_KEY) {
|
||||
const dbSchemaDataResponse = yield index_1.default.getSchema({
|
||||
key: DSQL_KEY,
|
||||
database: DSQL_REF_DB_NAME || undefined,
|
||||
});
|
||||
if (!dbSchemaDataResponse.payload ||
|
||||
!Array.isArray(dbSchemaDataResponse.payload)) {
|
||||
console.log("DSQL_KEY => Error in fetching DB schema");
|
||||
console.log(dbSchemaDataResponse);
|
||||
process.exit();
|
||||
}
|
||||
let fetchedDbSchemaObject = dbSchemaDataResponse.payload;
|
||||
// fetchedDbSchemaObject.forEach((db, index) => {
|
||||
// db.dbFullName = db.dbFullName?.replace(/^datasquirel_user_\d+_/, "");
|
||||
// });
|
||||
schemaData = fetchedDbSchemaObject;
|
||||
}
|
||||
else if (fs_1.default.existsSync(dbSchemaLocalFilePath)) {
|
||||
schemaData = [
|
||||
JSON.parse(fs_1.default.readFileSync(dbSchemaLocalFilePath, "utf8")),
|
||||
];
|
||||
}
|
||||
else {
|
||||
console.log("No source for DB Schema. Please provide a local `dsql.schema.json` file, or provide `DSQL_KEY` and `DSQL_REF_DB_NAME` environment variables.");
|
||||
process.exit();
|
||||
}
|
||||
if (!schemaData) {
|
||||
console.log("No schema found");
|
||||
process.exit();
|
||||
}
|
||||
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");
|
||||
}
|
||||
console.log(` - ${console_colors_1.default.FgBlue}Info:${console_colors_1.default.Reset} Now generating and mapping databases ...`);
|
||||
yield (0, createDbFromSchema_1.default)({
|
||||
dbSchemaData: schemaData,
|
||||
const dbSchemaLocalFilePath = path.resolve(process.cwd(), "dsql.schema.json");
|
||||
export default async function run() {
|
||||
let schemaData;
|
||||
if (DSQL_KEY && (DSQL_REF_DB_NAME === null || DSQL_REF_DB_NAME === void 0 ? void 0 : DSQL_REF_DB_NAME.match(/./))) {
|
||||
const dbSchemaDataResponse = await datasquirel.getSchema({
|
||||
key: DSQL_KEY,
|
||||
database: DSQL_REF_DB_NAME || undefined,
|
||||
});
|
||||
console.log(` - ${console_colors_1.default.FgGreen}Success:${console_colors_1.default.Reset} Databases created Successfully!`);
|
||||
if (!dbSchemaDataResponse.payload ||
|
||||
Array.isArray(dbSchemaDataResponse.payload)) {
|
||||
console.log("DSQL_KEY+DSQL_REF_DB_NAME => Error in fetching DB schema");
|
||||
console.log(dbSchemaDataResponse);
|
||||
process.exit();
|
||||
}
|
||||
let fetchedDbSchemaObject = dbSchemaDataResponse.payload;
|
||||
if (DSQL_DB_NAME)
|
||||
fetchedDbSchemaObject.dbFullName = DSQL_DB_NAME;
|
||||
schemaData = [fetchedDbSchemaObject];
|
||||
}
|
||||
else if (DSQL_KEY) {
|
||||
const dbSchemaDataResponse = await datasquirel.getSchema({
|
||||
key: DSQL_KEY,
|
||||
database: DSQL_REF_DB_NAME || undefined,
|
||||
});
|
||||
if (!dbSchemaDataResponse.payload ||
|
||||
!Array.isArray(dbSchemaDataResponse.payload)) {
|
||||
console.log("DSQL_KEY => Error in fetching DB schema");
|
||||
console.log(dbSchemaDataResponse);
|
||||
process.exit();
|
||||
}
|
||||
let fetchedDbSchemaObject = dbSchemaDataResponse.payload;
|
||||
// fetchedDbSchemaObject.forEach((db, index) => {
|
||||
// db.dbFullName = db.dbFullName?.replace(/^datasquirel_user_\d+_/, "");
|
||||
// });
|
||||
schemaData = fetchedDbSchemaObject;
|
||||
}
|
||||
else if (fs.existsSync(dbSchemaLocalFilePath)) {
|
||||
schemaData = [
|
||||
JSON.parse(fs.readFileSync(dbSchemaLocalFilePath, "utf8")),
|
||||
];
|
||||
}
|
||||
else {
|
||||
console.log("No source for DB Schema. Please provide a local `dsql.schema.json` file, or provide `DSQL_KEY` and `DSQL_REF_DB_NAME` environment variables.");
|
||||
process.exit();
|
||||
}
|
||||
if (!schemaData) {
|
||||
console.log("No schema found");
|
||||
process.exit();
|
||||
}
|
||||
if (DSQL_FULL_SYNC === null || DSQL_FULL_SYNC === void 0 ? void 0 : DSQL_FULL_SYNC.match(/true/i)) {
|
||||
fs.writeFileSync(dbSchemaLocalFilePath, JSON.stringify(schemaData[0], null, 4), "utf8");
|
||||
}
|
||||
console.log(` - ${colors.FgBlue}Info:${colors.Reset} Now generating and mapping databases ...`);
|
||||
await createDbFromSchema({
|
||||
dbSchemaData: schemaData,
|
||||
});
|
||||
console.log(` - ${colors.FgGreen}Success:${colors.Reset} Databases created Successfully!`);
|
||||
}
|
||||
let interval;
|
||||
if (fs_1.default.existsSync(dbSchemaLocalFilePath) && !(DSQL_KEY === null || DSQL_KEY === void 0 ? void 0 : DSQL_KEY.match(/....../))) {
|
||||
fs_1.default.watchFile(dbSchemaLocalFilePath, { interval: 1000 }, (curr, prev) => {
|
||||
console.log(` - ${console_colors_1.default.FgBlue}Info:${console_colors_1.default.Reset} Syncing Databases Locally ...`);
|
||||
if (fs.existsSync(dbSchemaLocalFilePath) && !(DSQL_KEY === null || DSQL_KEY === void 0 ? void 0 : DSQL_KEY.match(/....../))) {
|
||||
fs.watchFile(dbSchemaLocalFilePath, { interval: 1000 }, (curr, prev) => {
|
||||
console.log(` - ${colors.FgBlue}Info:${colors.Reset} Syncing Databases Locally ...`);
|
||||
run();
|
||||
});
|
||||
}
|
||||
else if (DSQL_KEY === null || DSQL_KEY === void 0 ? void 0 : DSQL_KEY.match(/....../)) {
|
||||
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();
|
||||
}, 20000);
|
||||
}
|
||||
|
13
dist/engine/dump.js
vendored
13
dist/engine/dump.js
vendored
@ -1,14 +1,9 @@
|
||||
#! /usr/bin/env node
|
||||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
var _a, _b, _c;
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const path_1 = __importDefault(require("path"));
|
||||
const child_process_1 = require("child_process");
|
||||
import path from "path";
|
||||
import { execSync } from "child_process";
|
||||
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))
|
||||
? "'" + "C:\\Program Files\\MySQL\\MySQL Server 8.0\\bin\\mysql.exe" + "'"
|
||||
@ -39,7 +34,7 @@ try {
|
||||
cwd: process.cwd(),
|
||||
};
|
||||
// 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());
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
68
dist/engine/schema-to-typedef.js
vendored
68
dist/engine/schema-to-typedef.js
vendored
@ -1,26 +1,12 @@
|
||||
#! /usr/bin/env node
|
||||
"use strict";
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
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)({
|
||||
import fs from "fs";
|
||||
import datasquirel from "..";
|
||||
import { parseArgs } from "util";
|
||||
import dbSchemaToType from "../package-shared/functions/dsql/db-schema-to-type";
|
||||
import path from "path";
|
||||
import debugLog from "../package-shared/utils/logging/debug-log";
|
||||
import parseEnv from "../package-shared/utils/parse-env";
|
||||
const args = parseArgs({
|
||||
args: process.argv,
|
||||
options: {
|
||||
apiKey: {
|
||||
@ -55,12 +41,12 @@ const args = (0, util_1.parseArgs)({
|
||||
});
|
||||
let appendedEnv = {};
|
||||
if (args.values.envfile && typeof args.values.envfile == "string") {
|
||||
const finalEnvPath = path_1.default.resolve(process.cwd(), args.values.envfile);
|
||||
if (fs_1.default.existsSync(finalEnvPath)) {
|
||||
const parsedEnv = (0, parse_env_1.default)(finalEnvPath);
|
||||
appendedEnv = parsedEnv || {};
|
||||
const finalEnvPath = path.resolve(process.cwd(), args.values.envfile);
|
||||
if (fs.existsSync(finalEnvPath)) {
|
||||
const parsedEnv = parseEnv(finalEnvPath);
|
||||
appendedEnv = (parsedEnv || {});
|
||||
if (args.values.debug) {
|
||||
(0, debug_log_1.default)({
|
||||
debugLog({
|
||||
log: appendedEnv,
|
||||
label: "Appended env",
|
||||
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);
|
||||
process.env = Object.assign(Object.assign({}, process.env), appendedEnv);
|
||||
(() => __awaiter(void 0, void 0, void 0, function* () {
|
||||
(async () => {
|
||||
try {
|
||||
const key = args.values.apiKey || finalEnv["DSQL_FULL_ACCESS_API_KEY"];
|
||||
const database = args.values.database || finalEnv["DSQL_DB_NAME"];
|
||||
const user_id = args.values.userid || finalEnv["DSQL_API_USER_ID"] || "1";
|
||||
if (args.values.debug) {
|
||||
(0, debug_log_1.default)({
|
||||
debugLog({
|
||||
log: args.values,
|
||||
label: "Arguments",
|
||||
title: "Schema to Typedef",
|
||||
addTime: true,
|
||||
});
|
||||
(0, debug_log_1.default)({
|
||||
debugLog({
|
||||
log: process.env.DSQL_FULL_ACCESS_API_KEY,
|
||||
label: "process.env.DSQL_FULL_ACCESS_API_KEY",
|
||||
title: "Schema to Typedef",
|
||||
addTime: true,
|
||||
});
|
||||
(0, debug_log_1.default)({
|
||||
debugLog({
|
||||
log: process.env.DSQL_DB_NAME,
|
||||
label: "process.env.DSQL_DB_NAME",
|
||||
title: "Schema to Typedef",
|
||||
@ -104,7 +90,7 @@ process.env = Object.assign(Object.assign({}, process.env), appendedEnv);
|
||||
throw new Error("Outfile are required");
|
||||
if (!user_id || typeof user_id !== "string")
|
||||
throw new Error("Outfile are required");
|
||||
const schema = yield __1.default.getSchema({
|
||||
const schema = await datasquirel.getSchema({
|
||||
key,
|
||||
database,
|
||||
user_id,
|
||||
@ -112,7 +98,7 @@ process.env = Object.assign(Object.assign({}, process.env), appendedEnv);
|
||||
});
|
||||
const dbSchema = schema.payload;
|
||||
if (args.values.debug) {
|
||||
(0, debug_log_1.default)({
|
||||
debugLog({
|
||||
log: schema,
|
||||
label: "schema",
|
||||
title: "Schema to Typedef",
|
||||
@ -121,16 +107,16 @@ process.env = Object.assign(Object.assign({}, process.env), appendedEnv);
|
||||
}
|
||||
if (!dbSchema)
|
||||
throw new Error("No schema found");
|
||||
const definitions = (0, db_schema_to_type_1.default)({ dbSchema });
|
||||
const finalOutfile = path_1.default.resolve(process.cwd(), args.values.outfile);
|
||||
const ourfileDir = path_1.default.dirname(finalOutfile);
|
||||
if (!fs_1.default.existsSync(ourfileDir)) {
|
||||
fs_1.default.mkdirSync(ourfileDir, { recursive: true });
|
||||
const definitions = dbSchemaToType({ dbSchema });
|
||||
const finalOutfile = path.resolve(process.cwd(), args.values.outfile);
|
||||
const ourfileDir = path.dirname(finalOutfile);
|
||||
if (!fs.existsSync(ourfileDir)) {
|
||||
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) {
|
||||
(0, debug_log_1.default)({
|
||||
debugLog({
|
||||
log: error.message,
|
||||
label: "Error",
|
||||
title: "Schema to Typedef",
|
||||
@ -139,4 +125,4 @@ process.env = Object.assign(Object.assign({}, process.env), appendedEnv);
|
||||
});
|
||||
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 post from "./package-shared/actions/post";
|
||||
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 updateUser from "./package-shared/actions/users/update-user";
|
||||
import loginUser from "./package-shared/actions/users/login-user";
|
||||
@ -44,6 +41,23 @@ import parseEnv from "./package-shared/utils/parse-env";
|
||||
* Main Export
|
||||
*/
|
||||
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
|
||||
*/
|
||||
@ -52,11 +66,6 @@ declare const datasquirel: {
|
||||
* Post Action
|
||||
*/
|
||||
post: typeof post;
|
||||
media: {
|
||||
uploadImage: typeof uploadImage;
|
||||
uploadFile: typeof uploadFile;
|
||||
deleteFile: typeof deleteFile;
|
||||
};
|
||||
user: {
|
||||
createUser: typeof createUser;
|
||||
deleteUser: typeof deleteUser;
|
||||
|
150
dist/index.js
vendored
150
dist/index.js
vendored
@ -1,117 +1,113 @@
|
||||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const get_1 = __importDefault(require("./package-shared/actions/get"));
|
||||
const post_1 = __importDefault(require("./package-shared/actions/post"));
|
||||
const get_schema_1 = __importDefault(require("./package-shared/actions/get-schema"));
|
||||
const upload_image_1 = __importDefault(require("./package-shared/actions/upload-image"));
|
||||
const upload_file_1 = __importDefault(require("./package-shared/actions/upload-file"));
|
||||
const delete_file_1 = __importDefault(require("./package-shared/actions/delete-file"));
|
||||
const add_user_1 = __importDefault(require("./package-shared/actions/users/add-user"));
|
||||
const update_user_1 = __importDefault(require("./package-shared/actions/users/update-user"));
|
||||
const login_user_1 = __importDefault(require("./package-shared/actions/users/login-user"));
|
||||
const send_email_code_1 = __importDefault(require("./package-shared/actions/users/send-email-code"));
|
||||
const logout_user_1 = __importDefault(require("./package-shared/actions/users/logout-user"));
|
||||
const user_auth_1 = __importDefault(require("./package-shared/actions/users/user-auth"));
|
||||
const reauth_user_1 = __importDefault(require("./package-shared/actions/users/reauth-user"));
|
||||
const get_user_1 = __importDefault(require("./package-shared/actions/users/get-user"));
|
||||
const google_auth_1 = __importDefault(require("./package-shared/actions/users/social/google-auth"));
|
||||
const github_auth_1 = __importDefault(require("./package-shared/actions/users/social/github-auth"));
|
||||
const get_token_1 = __importDefault(require("./package-shared/actions/users/get-token"));
|
||||
const validate_token_1 = __importDefault(require("./package-shared/actions/users/validate-token"));
|
||||
const client_1 = __importDefault(require("./client"));
|
||||
const sql_generator_1 = __importDefault(require("./package-shared/functions/dsql/sql/sql-generator"));
|
||||
const sql_insert_generator_1 = __importDefault(require("./package-shared/functions/dsql/sql/sql-insert-generator"));
|
||||
const sql_delete_generator_1 = __importDefault(require("./package-shared/functions/dsql/sql/sql-delete-generator"));
|
||||
const trim_sql_1 = __importDefault(require("./package-shared/utils/trim-sql"));
|
||||
const parseCookies_1 = __importDefault(require("./package-shared/utils/backend/parseCookies"));
|
||||
const conn_db_handler_1 = __importDefault(require("./package-shared/utils/db/conn-db-handler"));
|
||||
const encrypt_1 = __importDefault(require("./package-shared/functions/dsql/encrypt"));
|
||||
const decrypt_1 = __importDefault(require("./package-shared/functions/dsql/decrypt"));
|
||||
const hashPassword_1 = __importDefault(require("./package-shared/functions/dsql/hashPassword"));
|
||||
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"));
|
||||
import get from "./package-shared/actions/get";
|
||||
import post from "./package-shared/actions/post";
|
||||
import getSchema from "./package-shared/actions/get-schema";
|
||||
import createUser from "./package-shared/actions/users/add-user";
|
||||
import updateUser from "./package-shared/actions/users/update-user";
|
||||
import loginUser from "./package-shared/actions/users/login-user";
|
||||
import sendEmailCode from "./package-shared/actions/users/send-email-code";
|
||||
import logoutUser from "./package-shared/actions/users/logout-user";
|
||||
import userAuth from "./package-shared/actions/users/user-auth";
|
||||
import reAuthUser from "./package-shared/actions/users/reauth-user";
|
||||
import getUser from "./package-shared/actions/users/get-user";
|
||||
import loginWithGoogle from "./package-shared/actions/users/social/google-auth";
|
||||
import loginWithGithub from "./package-shared/actions/users/social/github-auth";
|
||||
import getToken from "./package-shared/actions/users/get-token";
|
||||
import validateToken from "./package-shared/actions/users/validate-token";
|
||||
import datasquirelClient from "./client";
|
||||
import sqlGenerator from "./package-shared/functions/dsql/sql/sql-generator";
|
||||
import sqlInsertGenerator from "./package-shared/functions/dsql/sql/sql-insert-generator";
|
||||
import sqlDeleteGenerator from "./package-shared/functions/dsql/sql/sql-delete-generator";
|
||||
import trimSql from "./package-shared/utils/trim-sql";
|
||||
import parseCookies from "./package-shared/utils/backend/parseCookies";
|
||||
import connDbHandler from "./package-shared/utils/db/conn-db-handler";
|
||||
import encrypt from "./package-shared/functions/dsql/encrypt";
|
||||
import decrypt from "./package-shared/functions/dsql/decrypt";
|
||||
import hashPassword from "./package-shared/functions/dsql/hashPassword";
|
||||
import validateTempEmailCode from "./package-shared/actions/users/validate-temp-email-code";
|
||||
import deleteUser from "./package-shared/actions/users/delete-user";
|
||||
import dsqlCrud from "./package-shared/utils/data-fetching/crud";
|
||||
import dsqlMethodCrud from "./package-shared/utils/data-fetching/method-crud";
|
||||
import debugLog from "./package-shared/utils/logging/debug-log";
|
||||
import parseEnv from "./package-shared/utils/parse-env";
|
||||
import crud from "./package-shared/api/crud";
|
||||
import media from "./package-shared/api/media";
|
||||
/**
|
||||
* User Functions Object
|
||||
*/
|
||||
const user = {
|
||||
createUser: add_user_1.default,
|
||||
deleteUser: delete_user_1.default,
|
||||
loginUser: login_user_1.default,
|
||||
sendEmailCode: send_email_code_1.default,
|
||||
logoutUser: logout_user_1.default,
|
||||
userAuth: user_auth_1.default,
|
||||
reAuthUser: reauth_user_1.default,
|
||||
updateUser: update_user_1.default,
|
||||
getUser: get_user_1.default,
|
||||
getToken: get_token_1.default,
|
||||
validateToken: validate_token_1.default,
|
||||
validateTempEmailCode: validate_temp_email_code_1.default,
|
||||
createUser: createUser,
|
||||
deleteUser,
|
||||
loginUser: loginUser,
|
||||
sendEmailCode: sendEmailCode,
|
||||
logoutUser: logoutUser,
|
||||
userAuth: userAuth,
|
||||
reAuthUser: reAuthUser,
|
||||
updateUser: updateUser,
|
||||
getUser: getUser,
|
||||
getToken: getToken,
|
||||
validateToken: validateToken,
|
||||
validateTempEmailCode,
|
||||
social: {
|
||||
loginWithGoogle: google_auth_1.default,
|
||||
loginWithGithub: github_auth_1.default,
|
||||
loginWithGoogle: loginWithGoogle,
|
||||
loginWithGithub: loginWithGithub,
|
||||
},
|
||||
};
|
||||
/**
|
||||
* Media Functions Object
|
||||
* API Functions Object
|
||||
*/
|
||||
const media = {
|
||||
uploadImage: upload_image_1.default,
|
||||
uploadFile: upload_file_1.default,
|
||||
deleteFile: delete_file_1.default,
|
||||
const api = {
|
||||
crud,
|
||||
media,
|
||||
};
|
||||
/**
|
||||
* SQL Utils
|
||||
*/
|
||||
const sql = {
|
||||
sqlGenerator: sql_generator_1.default,
|
||||
sqlInsertGenerator: sql_insert_generator_1.default,
|
||||
sqlDeleteGenerator: sql_delete_generator_1.default,
|
||||
trim: trim_sql_1.default,
|
||||
sqlGenerator,
|
||||
sqlInsertGenerator,
|
||||
sqlDeleteGenerator,
|
||||
trim: trimSql,
|
||||
};
|
||||
/**
|
||||
* Main Export
|
||||
*/
|
||||
const datasquirel = {
|
||||
/**
|
||||
* API Actions
|
||||
*/
|
||||
api,
|
||||
/**
|
||||
* Get Action
|
||||
*/
|
||||
get: get_1.default,
|
||||
get,
|
||||
/**
|
||||
* Post Action
|
||||
*/
|
||||
post: post_1.default,
|
||||
media,
|
||||
post,
|
||||
user,
|
||||
getSchema: get_schema_1.default,
|
||||
client: client_1.default,
|
||||
getSchema,
|
||||
client: datasquirelClient,
|
||||
sql,
|
||||
utils: {
|
||||
crypto: {
|
||||
encrypt: encrypt_1.default,
|
||||
decrypt: decrypt_1.default,
|
||||
hashPassword: hashPassword_1.default,
|
||||
encrypt,
|
||||
decrypt,
|
||||
hashPassword,
|
||||
},
|
||||
parseCookies: parseCookies_1.default,
|
||||
connDbHandler: conn_db_handler_1.default,
|
||||
debugLog: debug_log_1.default,
|
||||
parseEnv: parse_env_1.default,
|
||||
parseCookies,
|
||||
connDbHandler,
|
||||
debugLog,
|
||||
parseEnv,
|
||||
},
|
||||
/**
|
||||
* Run Crud actions `get`, `insert`, `update`, `delete`
|
||||
* @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`
|
||||
* @note *Requires global variables `DSQL_USE_LOCAL` and `DSQL_DB_CONN`
|
||||
*/
|
||||
methodCrud: method_crud_1.default,
|
||||
methodCrud: dsqlMethodCrud,
|
||||
};
|
||||
exports.default = datasquirel;
|
||||
export default datasquirel;
|
||||
|
117
dist/package-shared/actions/delete-file.js
vendored
117
dist/package-shared/actions/delete-file.js
vendored
@ -1,76 +1,59 @@
|
||||
"use strict";
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = deleteFile;
|
||||
const grab_host_names_1 = __importDefault(require("../utils/grab-host-names"));
|
||||
import grabHostNames from "../utils/grab-host-names";
|
||||
/**
|
||||
* # Delete File via API
|
||||
*/
|
||||
function deleteFile(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ key, url, user_id, }) {
|
||||
const grabedHostNames = (0, grab_host_names_1.default)();
|
||||
const { host, port, scheme } = grabedHostNames;
|
||||
try {
|
||||
export default async function deleteFile({ key, url, user_id, }) {
|
||||
const grabedHostNames = grabHostNames();
|
||||
const { host, port, scheme } = grabedHostNames;
|
||||
try {
|
||||
/**
|
||||
* Make https request
|
||||
*
|
||||
* @description make a request to datasquirel.com
|
||||
*/
|
||||
const httpResponse = await new Promise((resolve, reject) => {
|
||||
const reqPayload = JSON.stringify({ url: url });
|
||||
const httpsRequest = scheme.request({
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Content-Length": Buffer.from(reqPayload).length,
|
||||
Authorization: key ||
|
||||
process.env.DSQL_FULL_ACCESS_API_KEY ||
|
||||
process.env.DSQL_API_KEY,
|
||||
},
|
||||
port,
|
||||
hostname: host,
|
||||
path: `/api/query/${user_id || grabedHostNames.user_id}/delete-file`,
|
||||
},
|
||||
/**
|
||||
* Make https request
|
||||
* Callback Function
|
||||
*
|
||||
* @description make a request to datasquirel.com
|
||||
* @description https request callback
|
||||
*/
|
||||
const httpResponse = yield new Promise((resolve, reject) => {
|
||||
const reqPayload = JSON.stringify({ url: url });
|
||||
const httpsRequest = scheme.request({
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Content-Length": Buffer.from(reqPayload).length,
|
||||
Authorization: key ||
|
||||
process.env.DSQL_FULL_ACCESS_API_KEY ||
|
||||
process.env.DSQL_API_KEY,
|
||||
},
|
||||
port,
|
||||
hostname: host,
|
||||
path: `/api/query/${user_id || grabedHostNames.user_id}/delete-file`,
|
||||
},
|
||||
/**
|
||||
* Callback Function
|
||||
*
|
||||
* @description https request callback
|
||||
*/
|
||||
(response) => {
|
||||
var str = "";
|
||||
response.on("data", function (chunk) {
|
||||
str += chunk;
|
||||
});
|
||||
response.on("end", function () {
|
||||
resolve(JSON.parse(str));
|
||||
});
|
||||
response.on("error", (err) => {
|
||||
reject(err);
|
||||
});
|
||||
(response) => {
|
||||
var str = "";
|
||||
response.on("data", function (chunk) {
|
||||
str += chunk;
|
||||
});
|
||||
response.on("end", function () {
|
||||
resolve(JSON.parse(str));
|
||||
});
|
||||
response.on("error", (err) => {
|
||||
reject(err);
|
||||
});
|
||||
httpsRequest.write(reqPayload);
|
||||
httpsRequest.end();
|
||||
});
|
||||
return httpResponse;
|
||||
}
|
||||
catch ( /** @type {*} */error) {
|
||||
console.log("Error deleting file: ", error.message);
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: error.message,
|
||||
};
|
||||
}
|
||||
});
|
||||
httpsRequest.write(reqPayload);
|
||||
httpsRequest.end();
|
||||
});
|
||||
return httpResponse;
|
||||
}
|
||||
catch ( /** @type {*} */error) {
|
||||
console.log("Error deleting file: ", error.message);
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: error.message,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
@ -1,6 +1,3 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = getCsrfHeaderName;
|
||||
function getCsrfHeaderName() {
|
||||
export default function getCsrfHeaderName() {
|
||||
return "x-dsql-csrf-key";
|
||||
}
|
||||
|
105
dist/package-shared/actions/get-schema.js
vendored
105
dist/package-shared/actions/get-schema.js
vendored
@ -1,69 +1,52 @@
|
||||
"use strict";
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = getSchema;
|
||||
const grab_host_names_1 = __importDefault(require("../utils/grab-host-names"));
|
||||
import grabHostNames from "../utils/grab-host-names";
|
||||
/**
|
||||
* # Get Schema for Database, table, or field *
|
||||
*/
|
||||
function getSchema(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ key, database, field, table, user_id, env, }) {
|
||||
const grabedHostNames = (0, grab_host_names_1.default)({ env });
|
||||
const { host, port, scheme } = grabedHostNames;
|
||||
export default async function getSchema({ key, database, field, table, user_id, env, }) {
|
||||
const grabedHostNames = grabHostNames({ env });
|
||||
const { host, port, scheme } = grabedHostNames;
|
||||
/**
|
||||
* Make https request
|
||||
*
|
||||
* @description make a request to datasquirel.com
|
||||
*/
|
||||
const httpResponse = await new Promise((resolve, reject) => {
|
||||
const queryObject = { database, field, table };
|
||||
let query = Object.keys(queryObject)
|
||||
.filter((k) => queryObject[k])
|
||||
.map((k) => `${k}=${queryObject[k]}`)
|
||||
.join("&");
|
||||
scheme
|
||||
.request({
|
||||
method: "GET",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: key ||
|
||||
process.env.DSQL_FULL_ACCESS_API_KEY ||
|
||||
process.env.DSQL_API_KEY,
|
||||
},
|
||||
port,
|
||||
hostname: host,
|
||||
path: `/api/query/${user_id || grabedHostNames.user_id}/get-schema` + ((query === null || query === void 0 ? void 0 : query.match(/./)) ? `?${query}` : ""),
|
||||
},
|
||||
/**
|
||||
* Make https request
|
||||
* Callback Function
|
||||
*
|
||||
* @description make a request to datasquirel.com
|
||||
* @description https request callback
|
||||
*/
|
||||
const httpResponse = yield new Promise((resolve, reject) => {
|
||||
const queryObject = { database, field, table };
|
||||
let query = Object.keys(queryObject)
|
||||
.filter((k) => queryObject[k])
|
||||
.map((k) => `${k}=${queryObject[k]}`)
|
||||
.join("&");
|
||||
scheme
|
||||
.request({
|
||||
method: "GET",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: key ||
|
||||
process.env.DSQL_FULL_ACCESS_API_KEY ||
|
||||
process.env.DSQL_API_KEY,
|
||||
},
|
||||
port,
|
||||
hostname: host,
|
||||
path: `/api/query/${user_id || grabedHostNames.user_id}/get-schema` + ((query === null || query === void 0 ? void 0 : query.match(/./)) ? `?${query}` : ""),
|
||||
},
|
||||
/**
|
||||
* Callback Function
|
||||
*
|
||||
* @description https request callback
|
||||
*/
|
||||
(response) => {
|
||||
var str = "";
|
||||
response.on("data", function (chunk) {
|
||||
str += chunk;
|
||||
});
|
||||
response.on("end", function () {
|
||||
resolve(JSON.parse(str));
|
||||
});
|
||||
response.on("error", (err) => {
|
||||
resolve(null);
|
||||
});
|
||||
})
|
||||
.end();
|
||||
});
|
||||
return httpResponse;
|
||||
(response) => {
|
||||
var str = "";
|
||||
response.on("data", function (chunk) {
|
||||
str += chunk;
|
||||
});
|
||||
response.on("end", function () {
|
||||
resolve(JSON.parse(str));
|
||||
});
|
||||
response.on("error", (err) => {
|
||||
resolve(null);
|
||||
});
|
||||
})
|
||||
.end();
|
||||
});
|
||||
return httpResponse;
|
||||
}
|
||||
|
231
dist/package-shared/actions/get.js
vendored
231
dist/package-shared/actions/get.js
vendored
@ -1,132 +1,115 @@
|
||||
"use strict";
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = get;
|
||||
const path_1 = __importDefault(require("path"));
|
||||
const fs_1 = __importDefault(require("fs"));
|
||||
const grab_host_names_1 = __importDefault(require("../utils/grab-host-names"));
|
||||
const get_1 = __importDefault(require("../functions/api/query/get"));
|
||||
const serialize_query_1 = __importDefault(require("../utils/serialize-query"));
|
||||
const grab_query_and_values_1 = __importDefault(require("../utils/grab-query-and-values"));
|
||||
const debug_log_1 = __importDefault(require("../utils/logging/debug-log"));
|
||||
import path from "path";
|
||||
import fs from "fs";
|
||||
import grabHostNames from "../utils/grab-host-names";
|
||||
import apiGet from "../functions/api/query/get";
|
||||
import serializeQuery from "../utils/serialize-query";
|
||||
import apiGetGrabQueryAndValues from "../utils/grab-query-and-values";
|
||||
import debugLog from "../utils/logging/debug-log";
|
||||
/**
|
||||
* # Make a get request to Datasquirel API
|
||||
*/
|
||||
function get(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ key, db, query, queryValues, tableName, user_id, debug, forceLocal, }) {
|
||||
const grabedHostNames = (0, grab_host_names_1.default)();
|
||||
const { host, port, scheme } = grabedHostNames;
|
||||
function debugFn(log, label) {
|
||||
(0, debug_log_1.default)({ log, addTime: true, title: "apiGet", label });
|
||||
export default async function get({ key, db, query, queryValues, tableName, user_id, debug, forceLocal, }) {
|
||||
const grabedHostNames = grabHostNames();
|
||||
const { host, port, scheme } = grabedHostNames;
|
||||
function debugFn(log, label) {
|
||||
debugLog({ log, addTime: true, title: "apiGet", label });
|
||||
}
|
||||
/**
|
||||
* Check for local DB settings
|
||||
*
|
||||
* @description Look for local db settings in `.env` file and by pass the http request if available
|
||||
*/
|
||||
const { DSQL_DB_NAME } = process.env;
|
||||
if ((DSQL_DB_NAME === null || DSQL_DB_NAME === void 0 ? void 0 : DSQL_DB_NAME.match(/./)) && global.DSQL_USE_LOCAL) {
|
||||
let dbSchema;
|
||||
try {
|
||||
const localDbSchemaPath = path.resolve(process.cwd(), "dsql.schema.json");
|
||||
dbSchema = JSON.parse(fs.readFileSync(localDbSchemaPath, "utf8"));
|
||||
}
|
||||
/**
|
||||
* Check for local DB settings
|
||||
*
|
||||
* @description Look for local db settings in `.env` file and by pass the http request if available
|
||||
*/
|
||||
const { DSQL_DB_NAME } = process.env;
|
||||
if ((DSQL_DB_NAME === null || DSQL_DB_NAME === void 0 ? void 0 : DSQL_DB_NAME.match(/./)) && global.DSQL_USE_LOCAL) {
|
||||
let dbSchema;
|
||||
try {
|
||||
const localDbSchemaPath = path_1.default.resolve(process.cwd(), "dsql.schema.json");
|
||||
dbSchema = JSON.parse(fs_1.default.readFileSync(localDbSchemaPath, "utf8"));
|
||||
}
|
||||
catch (error) { }
|
||||
if (debug) {
|
||||
debugFn("Running Locally ...");
|
||||
}
|
||||
return yield (0, get_1.default)({
|
||||
dbFullName: DSQL_DB_NAME,
|
||||
query,
|
||||
queryValues,
|
||||
tableName,
|
||||
dbSchema,
|
||||
debug,
|
||||
forceLocal,
|
||||
});
|
||||
catch (error) { }
|
||||
if (debug) {
|
||||
debugFn("Running Locally ...");
|
||||
}
|
||||
/**
|
||||
* Make https request
|
||||
*
|
||||
* @description make a request to datasquirel.com
|
||||
*/
|
||||
const httpResponse = yield new Promise((resolve, reject) => {
|
||||
const queryAndValues = (0, grab_query_and_values_1.default)({
|
||||
query,
|
||||
values: queryValues,
|
||||
});
|
||||
const queryObject = {
|
||||
db: process.env.DSQL_API_DB_NAME || String(db),
|
||||
query: queryAndValues.query,
|
||||
queryValues: queryAndValues.valuesString,
|
||||
tableName,
|
||||
debug,
|
||||
};
|
||||
if (debug) {
|
||||
debugFn(queryObject, "queryObject");
|
||||
}
|
||||
const queryString = (0, serialize_query_1.default)(Object.assign({}, queryObject));
|
||||
if (debug) {
|
||||
debugFn(queryString, "queryString");
|
||||
}
|
||||
let path = `/api/query/${user_id || grabedHostNames.user_id}/get${queryString}`;
|
||||
if (debug) {
|
||||
debugFn(path, "path");
|
||||
}
|
||||
const requestObject = {
|
||||
method: "GET",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: key ||
|
||||
process.env.DSQL_READ_ONLY_API_KEY ||
|
||||
process.env.DSQL_FULL_ACCESS_API_KEY ||
|
||||
process.env.DSQL_API_KEY,
|
||||
},
|
||||
port,
|
||||
hostname: host,
|
||||
path,
|
||||
};
|
||||
scheme
|
||||
.request(requestObject,
|
||||
/**
|
||||
* Callback Function
|
||||
*
|
||||
* @description https request callback
|
||||
*/
|
||||
(response) => {
|
||||
var str = "";
|
||||
response.on("data", function (chunk) {
|
||||
str += chunk;
|
||||
});
|
||||
response.on("end", function () {
|
||||
try {
|
||||
resolve(JSON.parse(str));
|
||||
}
|
||||
catch ( /** @type {any} */error) {
|
||||
reject({
|
||||
error: error.message,
|
||||
result: str,
|
||||
});
|
||||
}
|
||||
});
|
||||
response.on("error", (err) => {
|
||||
console.log("DSQL get Error,", err.message);
|
||||
resolve(null);
|
||||
});
|
||||
})
|
||||
.end();
|
||||
return await apiGet({
|
||||
dbFullName: DSQL_DB_NAME,
|
||||
query,
|
||||
queryValues,
|
||||
tableName,
|
||||
dbSchema,
|
||||
debug,
|
||||
forceLocal,
|
||||
});
|
||||
return httpResponse;
|
||||
}
|
||||
/**
|
||||
* Make https request
|
||||
*
|
||||
* @description make a request to datasquirel.com
|
||||
*/
|
||||
const httpResponse = await new Promise((resolve, reject) => {
|
||||
const queryAndValues = apiGetGrabQueryAndValues({
|
||||
query,
|
||||
values: queryValues,
|
||||
});
|
||||
const queryObject = {
|
||||
db: process.env.DSQL_API_DB_NAME || String(db),
|
||||
query: queryAndValues.query,
|
||||
queryValues: queryAndValues.valuesString,
|
||||
tableName,
|
||||
debug,
|
||||
};
|
||||
if (debug) {
|
||||
debugFn(queryObject, "queryObject");
|
||||
}
|
||||
const queryString = serializeQuery(Object.assign({}, queryObject));
|
||||
if (debug) {
|
||||
debugFn(queryString, "queryString");
|
||||
}
|
||||
let path = `/api/query/${user_id || grabedHostNames.user_id}/get${queryString}`;
|
||||
if (debug) {
|
||||
debugFn(path, "path");
|
||||
}
|
||||
const requestObject = {
|
||||
method: "GET",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: key ||
|
||||
process.env.DSQL_READ_ONLY_API_KEY ||
|
||||
process.env.DSQL_FULL_ACCESS_API_KEY ||
|
||||
process.env.DSQL_API_KEY,
|
||||
},
|
||||
port,
|
||||
hostname: host,
|
||||
path,
|
||||
};
|
||||
scheme
|
||||
.request(requestObject,
|
||||
/**
|
||||
* Callback Function
|
||||
*
|
||||
* @description https request callback
|
||||
*/
|
||||
(response) => {
|
||||
var str = "";
|
||||
response.on("data", function (chunk) {
|
||||
str += chunk;
|
||||
});
|
||||
response.on("end", function () {
|
||||
try {
|
||||
resolve(JSON.parse(str));
|
||||
}
|
||||
catch ( /** @type {any} */error) {
|
||||
reject({
|
||||
error: error.message,
|
||||
result: str,
|
||||
});
|
||||
}
|
||||
});
|
||||
response.on("error", (err) => {
|
||||
console.log("DSQL get Error,", err.message);
|
||||
resolve(null);
|
||||
});
|
||||
})
|
||||
.end();
|
||||
});
|
||||
return httpResponse;
|
||||
}
|
||||
|
239
dist/package-shared/actions/post.js
vendored
239
dist/package-shared/actions/post.js
vendored
@ -1,149 +1,132 @@
|
||||
"use strict";
|
||||
// @ts-check
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = post;
|
||||
const path_1 = __importDefault(require("path"));
|
||||
const fs_1 = __importDefault(require("fs"));
|
||||
const grab_host_names_1 = __importDefault(require("../utils/grab-host-names"));
|
||||
const post_1 = __importDefault(require("../functions/api/query/post"));
|
||||
const debug_log_1 = __importDefault(require("../utils/logging/debug-log"));
|
||||
import path from "path";
|
||||
import fs from "fs";
|
||||
import grabHostNames from "../utils/grab-host-names";
|
||||
import apiPost from "../functions/api/query/post";
|
||||
import debugLog from "../utils/logging/debug-log";
|
||||
/**
|
||||
* # Make a post request to Datasquirel API
|
||||
*/
|
||||
function post(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ key, query, queryValues, database, tableName, user_id, forceLocal, debug, }) {
|
||||
const grabedHostNames = (0, grab_host_names_1.default)();
|
||||
const { host, port, scheme } = grabedHostNames;
|
||||
export default async function post({ key, query, queryValues, database, tableName, user_id, forceLocal, debug, }) {
|
||||
const grabedHostNames = grabHostNames();
|
||||
const { host, port, scheme } = grabedHostNames;
|
||||
if (debug) {
|
||||
debugLog({
|
||||
log: grabedHostNames,
|
||||
addTime: true,
|
||||
label: "grabedHostNames",
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Check for local DB settings
|
||||
*
|
||||
* @description Look for local db settings in `.env` file and by pass the http request if available
|
||||
*/
|
||||
const { DSQL_DB_HOST, DSQL_DB_USERNAME, DSQL_DB_PASSWORD, DSQL_DB_NAME } = process.env;
|
||||
if ((DSQL_DB_HOST === null || DSQL_DB_HOST === void 0 ? void 0 : DSQL_DB_HOST.match(/./)) &&
|
||||
(DSQL_DB_USERNAME === null || DSQL_DB_USERNAME === void 0 ? void 0 : DSQL_DB_USERNAME.match(/./)) &&
|
||||
(DSQL_DB_PASSWORD === null || DSQL_DB_PASSWORD === void 0 ? void 0 : DSQL_DB_PASSWORD.match(/./)) &&
|
||||
(DSQL_DB_NAME === null || DSQL_DB_NAME === void 0 ? void 0 : DSQL_DB_NAME.match(/./)) &&
|
||||
global.DSQL_USE_LOCAL) {
|
||||
/** @type {import("../types").DSQL_DatabaseSchemaType | undefined} */
|
||||
let dbSchema;
|
||||
try {
|
||||
const localDbSchemaPath = path.resolve(process.cwd(), "dsql.schema.json");
|
||||
dbSchema = JSON.parse(fs.readFileSync(localDbSchemaPath, "utf8"));
|
||||
}
|
||||
catch (error) { }
|
||||
if (debug) {
|
||||
(0, debug_log_1.default)({
|
||||
log: grabedHostNames,
|
||||
debugLog({
|
||||
log: "Using Local DB ...",
|
||||
addTime: true,
|
||||
label: "grabedHostNames",
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Check for local DB settings
|
||||
*
|
||||
* @description Look for local db settings in `.env` file and by pass the http request if available
|
||||
*/
|
||||
const { DSQL_DB_HOST, DSQL_DB_USERNAME, DSQL_DB_PASSWORD, DSQL_DB_NAME } = process.env;
|
||||
if ((DSQL_DB_HOST === null || DSQL_DB_HOST === void 0 ? void 0 : DSQL_DB_HOST.match(/./)) &&
|
||||
(DSQL_DB_USERNAME === null || DSQL_DB_USERNAME === void 0 ? void 0 : DSQL_DB_USERNAME.match(/./)) &&
|
||||
(DSQL_DB_PASSWORD === null || DSQL_DB_PASSWORD === void 0 ? void 0 : DSQL_DB_PASSWORD.match(/./)) &&
|
||||
(DSQL_DB_NAME === null || DSQL_DB_NAME === void 0 ? void 0 : DSQL_DB_NAME.match(/./)) &&
|
||||
global.DSQL_USE_LOCAL) {
|
||||
/** @type {import("../types").DSQL_DatabaseSchemaType | undefined} */
|
||||
let dbSchema;
|
||||
try {
|
||||
const localDbSchemaPath = path_1.default.resolve(process.cwd(), "dsql.schema.json");
|
||||
dbSchema = JSON.parse(fs_1.default.readFileSync(localDbSchemaPath, "utf8"));
|
||||
}
|
||||
catch (error) { }
|
||||
if (debug) {
|
||||
(0, debug_log_1.default)({
|
||||
log: "Using Local DB ...",
|
||||
addTime: true,
|
||||
});
|
||||
}
|
||||
return yield (0, post_1.default)({
|
||||
dbFullName: DSQL_DB_NAME,
|
||||
query,
|
||||
dbSchema,
|
||||
queryValues,
|
||||
tableName,
|
||||
forceLocal,
|
||||
debug,
|
||||
});
|
||||
return await apiPost({
|
||||
dbFullName: database || DSQL_DB_NAME,
|
||||
query,
|
||||
dbSchema,
|
||||
queryValues,
|
||||
tableName,
|
||||
forceLocal,
|
||||
debug,
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Make https request
|
||||
*
|
||||
* @description make a request to datasquirel.com
|
||||
*/
|
||||
const httpResponse = await new Promise((resolve, reject) => {
|
||||
var _a;
|
||||
const reqPayloadString = JSON.stringify({
|
||||
query,
|
||||
queryValues,
|
||||
database: process.env.DSQL_API_DB_NAME || database,
|
||||
tableName: tableName ? tableName : null,
|
||||
}).replace(/\n|\r|\n\r/gm, "");
|
||||
try {
|
||||
JSON.parse(reqPayloadString);
|
||||
}
|
||||
catch (error) {
|
||||
(_a = global.ERROR_CALLBACK) === null || _a === void 0 ? void 0 : _a.call(global, `Error Parsing HTTP response for post action`, error);
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
error: "Query object is invalid. Please Check query data values",
|
||||
};
|
||||
}
|
||||
const reqPayload = reqPayloadString;
|
||||
const requPath = `/api/query/${user_id || grabedHostNames.user_id}/post`;
|
||||
const httpsRequest = scheme.request({
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Content-Length": Buffer.from(reqPayload).length,
|
||||
Authorization: key ||
|
||||
process.env.DSQL_FULL_ACCESS_API_KEY ||
|
||||
process.env.DSQL_API_KEY,
|
||||
},
|
||||
port,
|
||||
hostname: host,
|
||||
path: requPath,
|
||||
},
|
||||
/**
|
||||
* Make https request
|
||||
* Callback Function
|
||||
*
|
||||
* @description make a request to datasquirel.com
|
||||
* @description https request callback
|
||||
*/
|
||||
const httpResponse = yield new Promise((resolve, reject) => {
|
||||
var _a;
|
||||
const reqPayloadString = JSON.stringify({
|
||||
query,
|
||||
queryValues,
|
||||
database: process.env.DSQL_API_DB_NAME || database,
|
||||
tableName: tableName ? tableName : null,
|
||||
}).replace(/\n|\r|\n\r/gm, "");
|
||||
try {
|
||||
JSON.parse(reqPayloadString);
|
||||
}
|
||||
catch (error) {
|
||||
(_a = global.ERROR_CALLBACK) === null || _a === void 0 ? void 0 : _a.call(global, `Error Parsing HTTP response for post action`, error);
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
error: "Query object is invalid. Please Check query data values",
|
||||
};
|
||||
}
|
||||
const reqPayload = reqPayloadString;
|
||||
const requPath = `/api/query/${user_id || grabedHostNames.user_id}/post`;
|
||||
const httpsRequest = scheme.request({
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Content-Length": Buffer.from(reqPayload).length,
|
||||
Authorization: key ||
|
||||
process.env.DSQL_FULL_ACCESS_API_KEY ||
|
||||
process.env.DSQL_API_KEY,
|
||||
},
|
||||
port,
|
||||
hostname: host,
|
||||
path: requPath,
|
||||
},
|
||||
/**
|
||||
* Callback Function
|
||||
*
|
||||
* @description https request callback
|
||||
*/
|
||||
(response) => {
|
||||
var str = "";
|
||||
response.on("data", function (chunk) {
|
||||
str += chunk;
|
||||
});
|
||||
response.on("end", function () {
|
||||
try {
|
||||
resolve(JSON.parse(str));
|
||||
}
|
||||
catch (error) {
|
||||
console.log("Route ERROR:", error.message);
|
||||
resolve({
|
||||
success: false,
|
||||
payload: null,
|
||||
error: error.message,
|
||||
errPayload: str,
|
||||
});
|
||||
}
|
||||
});
|
||||
response.on("error", (err) => {
|
||||
(response) => {
|
||||
var str = "";
|
||||
response.on("data", function (chunk) {
|
||||
str += chunk;
|
||||
});
|
||||
response.on("end", function () {
|
||||
try {
|
||||
resolve(JSON.parse(str));
|
||||
}
|
||||
catch (error) {
|
||||
console.log("Route ERROR:", error.message);
|
||||
resolve({
|
||||
success: false,
|
||||
payload: null,
|
||||
error: err.message,
|
||||
error: error.message,
|
||||
errPayload: str,
|
||||
});
|
||||
}
|
||||
});
|
||||
response.on("error", (err) => {
|
||||
resolve({
|
||||
success: false,
|
||||
payload: null,
|
||||
error: err.message,
|
||||
});
|
||||
});
|
||||
httpsRequest.write(reqPayload);
|
||||
httpsRequest.on("error", (error) => {
|
||||
console.log("HTTPS request ERROR =>", error);
|
||||
});
|
||||
httpsRequest.end();
|
||||
});
|
||||
return httpResponse;
|
||||
httpsRequest.write(reqPayload);
|
||||
httpsRequest.on("error", (error) => {
|
||||
console.log("HTTPS request ERROR =>", error);
|
||||
});
|
||||
httpsRequest.end();
|
||||
});
|
||||
return httpResponse;
|
||||
}
|
||||
|
121
dist/package-shared/actions/upload-file.js
vendored
121
dist/package-shared/actions/upload-file.js
vendored
@ -1,78 +1,61 @@
|
||||
"use strict";
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = uploadImage;
|
||||
const grab_host_names_1 = __importDefault(require("../utils/grab-host-names"));
|
||||
import grabHostNames from "../utils/grab-host-names";
|
||||
/**
|
||||
* # Upload File via API
|
||||
*/
|
||||
function uploadImage(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ key, payload, user_id, useDefault, }) {
|
||||
var _b;
|
||||
const grabedHostNames = (0, grab_host_names_1.default)({ useDefault });
|
||||
const { host, port, scheme } = grabedHostNames;
|
||||
try {
|
||||
export default async function uploadImage({ key, payload, user_id, useDefault, }) {
|
||||
var _a;
|
||||
const grabedHostNames = grabHostNames({ useDefault });
|
||||
const { host, port, scheme } = grabedHostNames;
|
||||
try {
|
||||
/**
|
||||
* Make https request
|
||||
*
|
||||
* @description make a request to datasquirel.com
|
||||
*/
|
||||
const httpResponse = await new Promise((resolve, reject) => {
|
||||
const reqPayload = JSON.stringify(payload);
|
||||
const httpsRequest = scheme.request({
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Content-Length": Buffer.from(reqPayload).length,
|
||||
Authorization: key ||
|
||||
process.env.DSQL_FULL_ACCESS_API_KEY ||
|
||||
process.env.DSQL_API_KEY,
|
||||
},
|
||||
port,
|
||||
hostname: host,
|
||||
path: `/api/query/${user_id || grabedHostNames.user_id}/add-file`,
|
||||
},
|
||||
/**
|
||||
* Make https request
|
||||
* Callback Function
|
||||
*
|
||||
* @description make a request to datasquirel.com
|
||||
* @description https request callback
|
||||
*/
|
||||
const httpResponse = yield new Promise((resolve, reject) => {
|
||||
const reqPayload = JSON.stringify(payload);
|
||||
const httpsRequest = scheme.request({
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Content-Length": Buffer.from(reqPayload).length,
|
||||
Authorization: key ||
|
||||
process.env.DSQL_FULL_ACCESS_API_KEY ||
|
||||
process.env.DSQL_API_KEY,
|
||||
},
|
||||
port,
|
||||
hostname: host,
|
||||
path: `/api/query/${user_id || grabedHostNames.user_id}/add-file`,
|
||||
},
|
||||
/**
|
||||
* Callback Function
|
||||
*
|
||||
* @description https request callback
|
||||
*/
|
||||
(response) => {
|
||||
var str = "";
|
||||
response.on("data", function (chunk) {
|
||||
str += chunk;
|
||||
});
|
||||
response.on("end", function () {
|
||||
resolve(JSON.parse(str));
|
||||
});
|
||||
response.on("error", (err) => {
|
||||
reject(err);
|
||||
});
|
||||
(response) => {
|
||||
var str = "";
|
||||
response.on("data", function (chunk) {
|
||||
str += chunk;
|
||||
});
|
||||
response.on("end", function () {
|
||||
resolve(JSON.parse(str));
|
||||
});
|
||||
response.on("error", (err) => {
|
||||
reject(err);
|
||||
});
|
||||
httpsRequest.write(reqPayload);
|
||||
httpsRequest.end();
|
||||
});
|
||||
return httpResponse;
|
||||
}
|
||||
catch (error) {
|
||||
console.log("Error in uploading file: ", error.message);
|
||||
(_b = global.ERROR_CALLBACK) === null || _b === void 0 ? void 0 : _b.call(global, `Error Uploading File`, error);
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: error.message,
|
||||
};
|
||||
}
|
||||
});
|
||||
httpsRequest.write(reqPayload);
|
||||
httpsRequest.end();
|
||||
});
|
||||
return httpResponse;
|
||||
}
|
||||
catch (error) {
|
||||
console.log("Error in uploading file: ", error.message);
|
||||
(_a = global.ERROR_CALLBACK) === null || _a === void 0 ? void 0 : _a.call(global, `Error Uploading File`, error);
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: error.message,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
121
dist/package-shared/actions/upload-image.js
vendored
121
dist/package-shared/actions/upload-image.js
vendored
@ -1,78 +1,61 @@
|
||||
"use strict";
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = uploadImage;
|
||||
const grab_host_names_1 = __importDefault(require("../utils/grab-host-names"));
|
||||
import grabHostNames from "../utils/grab-host-names";
|
||||
/**
|
||||
* # Upload Image via API
|
||||
*/
|
||||
function uploadImage(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ key, payload, user_id, useDefault, }) {
|
||||
var _b;
|
||||
const grabedHostNames = (0, grab_host_names_1.default)({ useDefault });
|
||||
const { host, port, scheme } = grabedHostNames;
|
||||
try {
|
||||
export default async function uploadImage({ key, payload, user_id, useDefault, }) {
|
||||
var _a;
|
||||
const grabedHostNames = grabHostNames({ useDefault });
|
||||
const { host, port, scheme } = grabedHostNames;
|
||||
try {
|
||||
/**
|
||||
* Make https request
|
||||
*
|
||||
* @description make a request to datasquirel.com
|
||||
*/
|
||||
const httpResponse = await new Promise((resolve, reject) => {
|
||||
const reqPayload = JSON.stringify(payload);
|
||||
const httpsRequest = scheme.request({
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Content-Length": Buffer.from(reqPayload).length,
|
||||
Authorization: key ||
|
||||
process.env.DSQL_FULL_ACCESS_API_KEY ||
|
||||
process.env.DSQL_API_KEY,
|
||||
},
|
||||
port,
|
||||
hostname: host,
|
||||
path: `/api/query/${user_id || grabedHostNames.user_id}/add-image`,
|
||||
},
|
||||
/**
|
||||
* Make https request
|
||||
* Callback Function
|
||||
*
|
||||
* @description make a request to datasquirel.com
|
||||
* @description https request callback
|
||||
*/
|
||||
const httpResponse = yield new Promise((resolve, reject) => {
|
||||
const reqPayload = JSON.stringify(payload);
|
||||
const httpsRequest = scheme.request({
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Content-Length": Buffer.from(reqPayload).length,
|
||||
Authorization: key ||
|
||||
process.env.DSQL_FULL_ACCESS_API_KEY ||
|
||||
process.env.DSQL_API_KEY,
|
||||
},
|
||||
port,
|
||||
hostname: host,
|
||||
path: `/api/query/${user_id || grabedHostNames.user_id}/add-image`,
|
||||
},
|
||||
/**
|
||||
* Callback Function
|
||||
*
|
||||
* @description https request callback
|
||||
*/
|
||||
(response) => {
|
||||
var str = "";
|
||||
response.on("data", function (chunk) {
|
||||
str += chunk;
|
||||
});
|
||||
response.on("end", function () {
|
||||
resolve(JSON.parse(str));
|
||||
});
|
||||
response.on("error", (err) => {
|
||||
reject(err);
|
||||
});
|
||||
(response) => {
|
||||
var str = "";
|
||||
response.on("data", function (chunk) {
|
||||
str += chunk;
|
||||
});
|
||||
response.on("end", function () {
|
||||
resolve(JSON.parse(str));
|
||||
});
|
||||
response.on("error", (err) => {
|
||||
reject(err);
|
||||
});
|
||||
httpsRequest.write(reqPayload);
|
||||
httpsRequest.end();
|
||||
});
|
||||
return httpResponse;
|
||||
}
|
||||
catch (error) {
|
||||
console.log("Error in uploading image: ", error.message);
|
||||
(_b = global.ERROR_CALLBACK) === null || _b === void 0 ? void 0 : _b.call(global, `Error Uploading Image`, error);
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: error.message,
|
||||
};
|
||||
}
|
||||
});
|
||||
httpsRequest.write(reqPayload);
|
||||
httpsRequest.end();
|
||||
});
|
||||
return httpResponse;
|
||||
}
|
||||
catch (error) {
|
||||
console.log("Error in uploading image: ", error.message);
|
||||
(_a = global.ERROR_CALLBACK) === null || _a === void 0 ? void 0 : _a.call(global, `Error Uploading Image`, error);
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: error.message,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
165
dist/package-shared/actions/users/add-user.js
vendored
165
dist/package-shared/actions/users/add-user.js
vendored
@ -1,98 +1,81 @@
|
||||
"use strict";
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = addUser;
|
||||
const path_1 = __importDefault(require("path"));
|
||||
const fs_1 = __importDefault(require("fs"));
|
||||
const grab_host_names_1 = __importDefault(require("../../utils/grab-host-names"));
|
||||
const api_create_user_1 = __importDefault(require("../../functions/api/users/api-create-user"));
|
||||
import path from "path";
|
||||
import fs from "fs";
|
||||
import grabHostNames from "../../utils/grab-host-names";
|
||||
import apiCreateUser from "../../functions/api/users/api-create-user";
|
||||
/**
|
||||
* # Add User to Database
|
||||
*/
|
||||
function addUser(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ key, payload, database, encryptionKey, user_id, apiUserId, }) {
|
||||
/**
|
||||
* Check for local DB settings
|
||||
*
|
||||
* @description Look for local db settings in `.env` file and by pass the http request if available
|
||||
*/
|
||||
const { DSQL_DB_HOST, DSQL_DB_USERNAME, DSQL_DB_PASSWORD, DSQL_DB_NAME, DSQL_API_USER_ID, } = process.env;
|
||||
const grabedHostNames = (0, grab_host_names_1.default)();
|
||||
const { host, port, scheme } = grabedHostNames;
|
||||
if ((DSQL_DB_HOST === null || DSQL_DB_HOST === void 0 ? void 0 : DSQL_DB_HOST.match(/./)) &&
|
||||
(DSQL_DB_USERNAME === null || DSQL_DB_USERNAME === void 0 ? void 0 : DSQL_DB_USERNAME.match(/./)) &&
|
||||
(DSQL_DB_PASSWORD === null || DSQL_DB_PASSWORD === void 0 ? void 0 : DSQL_DB_PASSWORD.match(/./)) &&
|
||||
(DSQL_DB_NAME === null || DSQL_DB_NAME === void 0 ? void 0 : DSQL_DB_NAME.match(/./)) &&
|
||||
global.DSQL_USE_LOCAL) {
|
||||
/** @type {import("../../types").DSQL_DatabaseSchemaType | undefined} */
|
||||
let dbSchema;
|
||||
try {
|
||||
const localDbSchemaPath = path_1.default.resolve(process.cwd(), "dsql.schema.json");
|
||||
dbSchema = JSON.parse(fs_1.default.readFileSync(localDbSchemaPath, "utf8"));
|
||||
}
|
||||
catch (error) { }
|
||||
return yield (0, api_create_user_1.default)({
|
||||
database: DSQL_DB_NAME,
|
||||
encryptionKey,
|
||||
payload,
|
||||
userId: apiUserId,
|
||||
});
|
||||
export default async function addUser({ key, payload, database, encryptionKey, user_id, apiUserId, }) {
|
||||
/**
|
||||
* Check for local DB settings
|
||||
*
|
||||
* @description Look for local db settings in `.env` file and by pass the http request if available
|
||||
*/
|
||||
const { DSQL_DB_HOST, DSQL_DB_USERNAME, DSQL_DB_PASSWORD, DSQL_DB_NAME, DSQL_API_USER_ID, } = process.env;
|
||||
const grabedHostNames = grabHostNames();
|
||||
const { host, port, scheme } = grabedHostNames;
|
||||
if ((DSQL_DB_HOST === null || DSQL_DB_HOST === void 0 ? void 0 : DSQL_DB_HOST.match(/./)) &&
|
||||
(DSQL_DB_USERNAME === null || DSQL_DB_USERNAME === void 0 ? void 0 : DSQL_DB_USERNAME.match(/./)) &&
|
||||
(DSQL_DB_PASSWORD === null || DSQL_DB_PASSWORD === void 0 ? void 0 : DSQL_DB_PASSWORD.match(/./)) &&
|
||||
(DSQL_DB_NAME === null || DSQL_DB_NAME === void 0 ? void 0 : DSQL_DB_NAME.match(/./)) &&
|
||||
global.DSQL_USE_LOCAL) {
|
||||
/** @type {import("../../types").DSQL_DatabaseSchemaType | undefined} */
|
||||
let dbSchema;
|
||||
try {
|
||||
const localDbSchemaPath = path.resolve(process.cwd(), "dsql.schema.json");
|
||||
dbSchema = JSON.parse(fs.readFileSync(localDbSchemaPath, "utf8"));
|
||||
}
|
||||
/**
|
||||
* Make https request
|
||||
*
|
||||
* @description make a request to datasquirel.com
|
||||
*/
|
||||
const httpResponse = yield new Promise((resolve, reject) => {
|
||||
const reqPayload = JSON.stringify({
|
||||
payload,
|
||||
database,
|
||||
encryptionKey,
|
||||
});
|
||||
const httpsRequest = scheme.request({
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Content-Length": Buffer.from(reqPayload).length,
|
||||
Authorization: key ||
|
||||
process.env.DSQL_FULL_ACCESS_API_KEY ||
|
||||
process.env.DSQL_API_KEY,
|
||||
},
|
||||
port,
|
||||
hostname: host,
|
||||
path: `/api/user/${user_id || grabedHostNames.user_id}/add-user`,
|
||||
},
|
||||
/**
|
||||
* Callback Function
|
||||
*
|
||||
* @description https request callback
|
||||
*/
|
||||
(response) => {
|
||||
var str = "";
|
||||
response.on("data", function (chunk) {
|
||||
str += chunk;
|
||||
});
|
||||
response.on("end", function () {
|
||||
resolve(JSON.parse(str));
|
||||
});
|
||||
response.on("error", (err) => {
|
||||
reject(err);
|
||||
});
|
||||
});
|
||||
httpsRequest.write(reqPayload);
|
||||
httpsRequest.end();
|
||||
catch (error) { }
|
||||
return await apiCreateUser({
|
||||
database: DSQL_DB_NAME,
|
||||
encryptionKey,
|
||||
payload,
|
||||
userId: apiUserId,
|
||||
});
|
||||
return httpResponse;
|
||||
}
|
||||
/**
|
||||
* Make https request
|
||||
*
|
||||
* @description make a request to datasquirel.com
|
||||
*/
|
||||
const httpResponse = await new Promise((resolve, reject) => {
|
||||
const reqPayload = JSON.stringify({
|
||||
payload,
|
||||
database,
|
||||
encryptionKey,
|
||||
});
|
||||
const httpsRequest = scheme.request({
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Content-Length": Buffer.from(reqPayload).length,
|
||||
Authorization: key ||
|
||||
process.env.DSQL_FULL_ACCESS_API_KEY ||
|
||||
process.env.DSQL_API_KEY,
|
||||
},
|
||||
port,
|
||||
hostname: host,
|
||||
path: `/api/user/${user_id || grabedHostNames.user_id}/add-user`,
|
||||
},
|
||||
/**
|
||||
* Callback Function
|
||||
*
|
||||
* @description https request callback
|
||||
*/
|
||||
(response) => {
|
||||
var str = "";
|
||||
response.on("data", function (chunk) {
|
||||
str += chunk;
|
||||
});
|
||||
response.on("end", function () {
|
||||
resolve(JSON.parse(str));
|
||||
});
|
||||
response.on("error", (err) => {
|
||||
reject(err);
|
||||
});
|
||||
});
|
||||
httpsRequest.write(reqPayload);
|
||||
httpsRequest.end();
|
||||
});
|
||||
return httpResponse;
|
||||
}
|
||||
|
153
dist/package-shared/actions/users/delete-user.js
vendored
153
dist/package-shared/actions/users/delete-user.js
vendored
@ -1,95 +1,78 @@
|
||||
"use strict";
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = deleteUser;
|
||||
const path_1 = __importDefault(require("path"));
|
||||
const fs_1 = __importDefault(require("fs"));
|
||||
const grab_host_names_1 = __importDefault(require("../../utils/grab-host-names"));
|
||||
const api_delete_user_1 = __importDefault(require("../../functions/api/users/api-delete-user"));
|
||||
import path from "path";
|
||||
import fs from "fs";
|
||||
import grabHostNames from "../../utils/grab-host-names";
|
||||
import apiDeleteUser from "../../functions/api/users/api-delete-user";
|
||||
/**
|
||||
* # Update User
|
||||
*/
|
||||
function deleteUser(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ key, database, user_id, deletedUserId, }) {
|
||||
/**
|
||||
* Check for local DB settings
|
||||
*
|
||||
* @description Look for local db settings in `.env` file and by pass the http request if available
|
||||
*/
|
||||
const { DSQL_DB_HOST, DSQL_DB_USERNAME, DSQL_DB_PASSWORD, DSQL_DB_NAME } = process.env;
|
||||
const grabedHostNames = (0, grab_host_names_1.default)();
|
||||
const { host, port, scheme } = grabedHostNames;
|
||||
if ((DSQL_DB_HOST === null || DSQL_DB_HOST === void 0 ? void 0 : DSQL_DB_HOST.match(/./)) &&
|
||||
(DSQL_DB_USERNAME === null || DSQL_DB_USERNAME === void 0 ? void 0 : DSQL_DB_USERNAME.match(/./)) &&
|
||||
(DSQL_DB_PASSWORD === null || DSQL_DB_PASSWORD === void 0 ? void 0 : DSQL_DB_PASSWORD.match(/./)) &&
|
||||
(DSQL_DB_NAME === null || DSQL_DB_NAME === void 0 ? void 0 : DSQL_DB_NAME.match(/./)) &&
|
||||
global.DSQL_USE_LOCAL) {
|
||||
/** @type {import("../../types").DSQL_DatabaseSchemaType | undefined} */
|
||||
let dbSchema;
|
||||
try {
|
||||
const localDbSchemaPath = path_1.default.resolve(process.cwd(), "dsql.schema.json");
|
||||
dbSchema = JSON.parse(fs_1.default.readFileSync(localDbSchemaPath, "utf8"));
|
||||
}
|
||||
catch (error) { }
|
||||
return yield (0, api_delete_user_1.default)({
|
||||
dbFullName: DSQL_DB_NAME,
|
||||
deletedUserId,
|
||||
});
|
||||
export default async function deleteUser({ key, database, user_id, deletedUserId, }) {
|
||||
/**
|
||||
* Check for local DB settings
|
||||
*
|
||||
* @description Look for local db settings in `.env` file and by pass the http request if available
|
||||
*/
|
||||
const { DSQL_DB_HOST, DSQL_DB_USERNAME, DSQL_DB_PASSWORD, DSQL_DB_NAME } = process.env;
|
||||
const grabedHostNames = grabHostNames();
|
||||
const { host, port, scheme } = grabedHostNames;
|
||||
if ((DSQL_DB_HOST === null || DSQL_DB_HOST === void 0 ? void 0 : DSQL_DB_HOST.match(/./)) &&
|
||||
(DSQL_DB_USERNAME === null || DSQL_DB_USERNAME === void 0 ? void 0 : DSQL_DB_USERNAME.match(/./)) &&
|
||||
(DSQL_DB_PASSWORD === null || DSQL_DB_PASSWORD === void 0 ? void 0 : DSQL_DB_PASSWORD.match(/./)) &&
|
||||
(DSQL_DB_NAME === null || DSQL_DB_NAME === void 0 ? void 0 : DSQL_DB_NAME.match(/./)) &&
|
||||
global.DSQL_USE_LOCAL) {
|
||||
/** @type {import("../../types").DSQL_DatabaseSchemaType | undefined} */
|
||||
let dbSchema;
|
||||
try {
|
||||
const localDbSchemaPath = path.resolve(process.cwd(), "dsql.schema.json");
|
||||
dbSchema = JSON.parse(fs.readFileSync(localDbSchemaPath, "utf8"));
|
||||
}
|
||||
catch (error) { }
|
||||
return await apiDeleteUser({
|
||||
dbFullName: DSQL_DB_NAME,
|
||||
deletedUserId,
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Make https request
|
||||
*
|
||||
* @description make a request to datasquirel.com
|
||||
*/
|
||||
const httpResponse = (await new Promise((resolve, reject) => {
|
||||
const reqPayload = JSON.stringify({
|
||||
database,
|
||||
deletedUserId,
|
||||
});
|
||||
const httpsRequest = scheme.request({
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Content-Length": Buffer.from(reqPayload).length,
|
||||
Authorization: process.env.DSQL_FULL_ACCESS_API_KEY ||
|
||||
process.env.DSQL_API_KEY ||
|
||||
key,
|
||||
},
|
||||
port,
|
||||
hostname: host,
|
||||
path: `/api/user/${user_id || grabedHostNames.user_id}/delete-user`,
|
||||
},
|
||||
/**
|
||||
* Make https request
|
||||
* Callback Function
|
||||
*
|
||||
* @description make a request to datasquirel.com
|
||||
* @description https request callback
|
||||
*/
|
||||
const httpResponse = (yield new Promise((resolve, reject) => {
|
||||
const reqPayload = JSON.stringify({
|
||||
database,
|
||||
deletedUserId,
|
||||
(response) => {
|
||||
var str = "";
|
||||
response.on("data", function (chunk) {
|
||||
str += chunk;
|
||||
});
|
||||
const httpsRequest = scheme.request({
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Content-Length": Buffer.from(reqPayload).length,
|
||||
Authorization: process.env.DSQL_FULL_ACCESS_API_KEY ||
|
||||
process.env.DSQL_API_KEY ||
|
||||
key,
|
||||
},
|
||||
port,
|
||||
hostname: host,
|
||||
path: `/api/user/${user_id || grabedHostNames.user_id}/delete-user`,
|
||||
},
|
||||
/**
|
||||
* Callback Function
|
||||
*
|
||||
* @description https request callback
|
||||
*/
|
||||
(response) => {
|
||||
var str = "";
|
||||
response.on("data", function (chunk) {
|
||||
str += chunk;
|
||||
});
|
||||
response.on("end", function () {
|
||||
resolve(JSON.parse(str));
|
||||
});
|
||||
response.on("error", (err) => {
|
||||
reject(err);
|
||||
});
|
||||
response.on("end", function () {
|
||||
resolve(JSON.parse(str));
|
||||
});
|
||||
httpsRequest.write(reqPayload);
|
||||
httpsRequest.end();
|
||||
}));
|
||||
return httpResponse;
|
||||
});
|
||||
response.on("error", (err) => {
|
||||
reject(err);
|
||||
});
|
||||
});
|
||||
httpsRequest.write(reqPayload);
|
||||
httpsRequest.end();
|
||||
}));
|
||||
return httpResponse;
|
||||
}
|
||||
|
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";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = getToken;
|
||||
const decrypt_1 = __importDefault(require("../../functions/dsql/decrypt"));
|
||||
const get_auth_cookie_names_1 = __importDefault(require("../../functions/backend/cookies/get-auth-cookie-names"));
|
||||
const parseCookies_1 = __importDefault(require("../../utils/backend/parseCookies"));
|
||||
import decrypt from "../../functions/dsql/decrypt";
|
||||
import getAuthCookieNames from "../../functions/backend/cookies/get-auth-cookie-names";
|
||||
import parseCookies from "../../utils/backend/parseCookies";
|
||||
/**
|
||||
* Get just the access token for user
|
||||
* ==============================================================================
|
||||
* @description This Function takes in a request object and returns a user token
|
||||
* string and csrf token string
|
||||
*/
|
||||
function getToken({ request, encryptionKey, encryptionSalt, cookieString, }) {
|
||||
export default function getToken({ request, encryptionKey, encryptionSalt, cookieString, }) {
|
||||
var _a;
|
||||
try {
|
||||
/**
|
||||
@ -21,8 +15,8 @@ function getToken({ request, encryptionKey, encryptionSalt, cookieString, }) {
|
||||
*
|
||||
* @description Grab the payload
|
||||
*/
|
||||
const cookies = (0, parseCookies_1.default)({ request, cookieString });
|
||||
const keynames = (0, get_auth_cookie_names_1.default)();
|
||||
const cookies = parseCookies({ request, cookieString });
|
||||
const keynames = getAuthCookieNames();
|
||||
const authKeyName = keynames.keyCookieName;
|
||||
const csrfName = keynames.csrfCookieName;
|
||||
const key = cookies[authKeyName];
|
||||
@ -32,7 +26,7 @@ function getToken({ request, encryptionKey, encryptionSalt, cookieString, }) {
|
||||
*
|
||||
* @description Grab the payload
|
||||
*/
|
||||
let userPayload = (0, decrypt_1.default)({
|
||||
let userPayload = decrypt({
|
||||
encryptedString: key,
|
||||
encryptionKey,
|
||||
encryptionSalt,
|
||||
|
213
dist/package-shared/actions/users/get-user.js
vendored
213
dist/package-shared/actions/users/get-user.js
vendored
@ -1,120 +1,103 @@
|
||||
"use strict";
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = getUser;
|
||||
const path_1 = __importDefault(require("path"));
|
||||
const fs_1 = __importDefault(require("fs"));
|
||||
const grab_host_names_1 = __importDefault(require("../../utils/grab-host-names"));
|
||||
const api_get_user_1 = __importDefault(require("../../functions/api/users/api-get-user"));
|
||||
import path from "path";
|
||||
import fs from "fs";
|
||||
import grabHostNames from "../../utils/grab-host-names";
|
||||
import apiGetUser from "../../functions/api/users/api-get-user";
|
||||
/**
|
||||
* # Get User
|
||||
*/
|
||||
function getUser(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ key, userId, database, fields, apiUserId, }) {
|
||||
/**
|
||||
* Initialize
|
||||
*/
|
||||
const defaultFields = [
|
||||
"id",
|
||||
"first_name",
|
||||
"last_name",
|
||||
"email",
|
||||
"username",
|
||||
"image",
|
||||
"image_thumbnail",
|
||||
"verification_status",
|
||||
"date_created",
|
||||
"date_created_code",
|
||||
"date_created_timestamp",
|
||||
"date_updated",
|
||||
"date_updated_code",
|
||||
"date_updated_timestamp",
|
||||
];
|
||||
const updatedFields = fields && fields[0] ? [...defaultFields, ...fields] : defaultFields;
|
||||
const reqPayload = JSON.stringify({
|
||||
userId,
|
||||
database,
|
||||
fields: [...new Set(updatedFields)],
|
||||
});
|
||||
const grabedHostNames = (0, grab_host_names_1.default)();
|
||||
const { host, port, scheme } = grabedHostNames;
|
||||
/**
|
||||
* Check for local DB settings
|
||||
*
|
||||
* @description Look for local db settings in `.env` file and by pass the http request if available
|
||||
*/
|
||||
const { DSQL_DB_HOST, DSQL_DB_USERNAME, DSQL_DB_PASSWORD, DSQL_DB_NAME } = process.env;
|
||||
if ((DSQL_DB_HOST === null || DSQL_DB_HOST === void 0 ? void 0 : DSQL_DB_HOST.match(/./)) &&
|
||||
(DSQL_DB_USERNAME === null || DSQL_DB_USERNAME === void 0 ? void 0 : DSQL_DB_USERNAME.match(/./)) &&
|
||||
(DSQL_DB_PASSWORD === null || DSQL_DB_PASSWORD === void 0 ? void 0 : DSQL_DB_PASSWORD.match(/./)) &&
|
||||
(DSQL_DB_NAME === null || DSQL_DB_NAME === void 0 ? void 0 : DSQL_DB_NAME.match(/./)) &&
|
||||
global.DSQL_USE_LOCAL) {
|
||||
/** @type {import("../../types").DSQL_DatabaseSchemaType | undefined} */
|
||||
let dbSchema;
|
||||
try {
|
||||
const localDbSchemaPath = path_1.default.resolve(process.cwd(), "dsql.schema.json");
|
||||
dbSchema = JSON.parse(fs_1.default.readFileSync(localDbSchemaPath, "utf8"));
|
||||
}
|
||||
catch (error) { }
|
||||
return yield (0, api_get_user_1.default)({
|
||||
userId,
|
||||
fields: [...new Set(updatedFields)],
|
||||
dbFullName: DSQL_DB_NAME,
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Make https request
|
||||
*
|
||||
* @description make a request to datasquirel.com
|
||||
*/
|
||||
const httpResponse = yield new Promise((resolve, reject) => {
|
||||
const httpsRequest = scheme.request({
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Content-Length": Buffer.from(reqPayload).length,
|
||||
Authorization: key ||
|
||||
process.env.DSQL_FULL_ACCESS_API_KEY ||
|
||||
process.env.DSQL_API_KEY,
|
||||
},
|
||||
port,
|
||||
hostname: host,
|
||||
path: `/api/user/${apiUserId || grabedHostNames.user_id}/get-user`,
|
||||
},
|
||||
/**
|
||||
* Callback Function
|
||||
*
|
||||
* @description https request callback
|
||||
*/
|
||||
(response) => {
|
||||
var str = "";
|
||||
response.on("data", function (chunk) {
|
||||
str += chunk;
|
||||
});
|
||||
response.on("end", function () {
|
||||
resolve(JSON.parse(str));
|
||||
});
|
||||
response.on("error", (err) => {
|
||||
reject(err);
|
||||
});
|
||||
});
|
||||
httpsRequest.write(reqPayload);
|
||||
httpsRequest.end();
|
||||
});
|
||||
/** ********************************************** */
|
||||
/** ********************************************** */
|
||||
/** ********************************************** */
|
||||
return httpResponse;
|
||||
export default async function getUser({ key, userId, database, fields, apiUserId, }) {
|
||||
/**
|
||||
* Initialize
|
||||
*/
|
||||
const defaultFields = [
|
||||
"id",
|
||||
"first_name",
|
||||
"last_name",
|
||||
"email",
|
||||
"username",
|
||||
"image",
|
||||
"image_thumbnail",
|
||||
"verification_status",
|
||||
"date_created",
|
||||
"date_created_code",
|
||||
"date_created_timestamp",
|
||||
"date_updated",
|
||||
"date_updated_code",
|
||||
"date_updated_timestamp",
|
||||
];
|
||||
const updatedFields = fields && fields[0] ? [...defaultFields, ...fields] : defaultFields;
|
||||
const reqPayload = JSON.stringify({
|
||||
userId,
|
||||
database,
|
||||
fields: [...new Set(updatedFields)],
|
||||
});
|
||||
const grabedHostNames = grabHostNames();
|
||||
const { host, port, scheme } = grabedHostNames;
|
||||
/**
|
||||
* Check for local DB settings
|
||||
*
|
||||
* @description Look for local db settings in `.env` file and by pass the http request if available
|
||||
*/
|
||||
const { DSQL_DB_HOST, DSQL_DB_USERNAME, DSQL_DB_PASSWORD, DSQL_DB_NAME } = process.env;
|
||||
if ((DSQL_DB_HOST === null || DSQL_DB_HOST === void 0 ? void 0 : DSQL_DB_HOST.match(/./)) &&
|
||||
(DSQL_DB_USERNAME === null || DSQL_DB_USERNAME === void 0 ? void 0 : DSQL_DB_USERNAME.match(/./)) &&
|
||||
(DSQL_DB_PASSWORD === null || DSQL_DB_PASSWORD === void 0 ? void 0 : DSQL_DB_PASSWORD.match(/./)) &&
|
||||
(DSQL_DB_NAME === null || DSQL_DB_NAME === void 0 ? void 0 : DSQL_DB_NAME.match(/./)) &&
|
||||
global.DSQL_USE_LOCAL) {
|
||||
/** @type {import("../../types").DSQL_DatabaseSchemaType | undefined} */
|
||||
let dbSchema;
|
||||
try {
|
||||
const localDbSchemaPath = path.resolve(process.cwd(), "dsql.schema.json");
|
||||
dbSchema = JSON.parse(fs.readFileSync(localDbSchemaPath, "utf8"));
|
||||
}
|
||||
catch (error) { }
|
||||
return await apiGetUser({
|
||||
userId,
|
||||
fields: [...new Set(updatedFields)],
|
||||
dbFullName: DSQL_DB_NAME,
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Make https request
|
||||
*
|
||||
* @description make a request to datasquirel.com
|
||||
*/
|
||||
const httpResponse = await new Promise((resolve, reject) => {
|
||||
const httpsRequest = scheme.request({
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Content-Length": Buffer.from(reqPayload).length,
|
||||
Authorization: key ||
|
||||
process.env.DSQL_FULL_ACCESS_API_KEY ||
|
||||
process.env.DSQL_API_KEY,
|
||||
},
|
||||
port,
|
||||
hostname: host,
|
||||
path: `/api/user/${apiUserId || grabedHostNames.user_id}/get-user`,
|
||||
},
|
||||
/**
|
||||
* Callback Function
|
||||
*
|
||||
* @description https request callback
|
||||
*/
|
||||
(response) => {
|
||||
var str = "";
|
||||
response.on("data", function (chunk) {
|
||||
str += chunk;
|
||||
});
|
||||
response.on("end", function () {
|
||||
resolve(JSON.parse(str));
|
||||
});
|
||||
response.on("error", (err) => {
|
||||
reject(err);
|
||||
});
|
||||
});
|
||||
httpsRequest.write(reqPayload);
|
||||
httpsRequest.end();
|
||||
});
|
||||
/** ********************************************** */
|
||||
/** ********************************************** */
|
||||
/** ********************************************** */
|
||||
return httpResponse;
|
||||
}
|
||||
|
@ -1,37 +1,5 @@
|
||||
import http from "http";
|
||||
import { APILoginFunctionReturn } from "../../types";
|
||||
type Param = {
|
||||
key?: string;
|
||||
database: string;
|
||||
payload: {
|
||||
email?: string;
|
||||
username?: string;
|
||||
password?: string;
|
||||
};
|
||||
additionalFields?: string[];
|
||||
request?: http.IncomingMessage & {
|
||||
[s: string]: any;
|
||||
};
|
||||
response?: http.ServerResponse & {
|
||||
[s: string]: any;
|
||||
};
|
||||
encryptionKey?: string;
|
||||
encryptionSalt?: string;
|
||||
email_login?: boolean;
|
||||
email_login_code?: string;
|
||||
temp_code_field?: string;
|
||||
token?: boolean;
|
||||
user_id?: string | number;
|
||||
skipPassword?: boolean;
|
||||
debug?: boolean;
|
||||
skipWriteAuthFile?: boolean;
|
||||
apiUserID?: string | number;
|
||||
dbUserId?: string | number;
|
||||
cleanupTokens?: boolean;
|
||||
secureCookie?: boolean;
|
||||
};
|
||||
import { APILoginFunctionReturn, LoginUserParam } from "../../types";
|
||||
/**
|
||||
* # Login A user
|
||||
*/
|
||||
export default function loginUser({ key, payload, database, additionalFields, response, encryptionKey, encryptionSalt, email_login, email_login_code, temp_code_field, token, user_id, skipPassword, apiUserID, skipWriteAuthFile, dbUserId, debug, cleanupTokens, secureCookie, request, }: Param): Promise<APILoginFunctionReturn>;
|
||||
export {};
|
||||
export default function loginUser({ key, payload, database, additionalFields, response, encryptionKey, encryptionSalt, email_login, email_login_code, temp_code_field, token, user_id, skipPassword, apiUserID, skipWriteAuthFile, dbUserId, debug, cleanupTokens, secureCookie, request, }: LoginUserParam): Promise<APILoginFunctionReturn>;
|
||||
|
345
dist/package-shared/actions/users/login-user.js
vendored
345
dist/package-shared/actions/users/login-user.js
vendored
@ -1,200 +1,183 @@
|
||||
"use strict";
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = loginUser;
|
||||
const fs_1 = __importDefault(require("fs"));
|
||||
const path_1 = __importDefault(require("path"));
|
||||
const encrypt_1 = __importDefault(require("../../functions/dsql/encrypt"));
|
||||
const grab_host_names_1 = __importDefault(require("../../utils/grab-host-names"));
|
||||
const api_login_1 = __importDefault(require("../../functions/api/users/api-login"));
|
||||
const get_auth_cookie_names_1 = __importDefault(require("../../functions/backend/cookies/get-auth-cookie-names"));
|
||||
const write_auth_files_1 = require("../../functions/backend/auth/write-auth-files");
|
||||
const debug_log_1 = __importDefault(require("../../utils/logging/debug-log"));
|
||||
const grab_cookie_expirt_date_1 = __importDefault(require("../../utils/grab-cookie-expirt-date"));
|
||||
import fs from "fs";
|
||||
import path from "path";
|
||||
import encrypt from "../../functions/dsql/encrypt";
|
||||
import grabHostNames from "../../utils/grab-host-names";
|
||||
import apiLoginUser from "../../functions/api/users/api-login";
|
||||
import getAuthCookieNames from "../../functions/backend/cookies/get-auth-cookie-names";
|
||||
import { writeAuthFile } from "../../functions/backend/auth/write-auth-files";
|
||||
import debugLog from "../../utils/logging/debug-log";
|
||||
import grabCookieExpiryDate from "../../utils/grab-cookie-expirt-date";
|
||||
/**
|
||||
* # Login A user
|
||||
*/
|
||||
function loginUser(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ key, payload, database, additionalFields, response, encryptionKey, encryptionSalt, email_login, email_login_code, temp_code_field, token, user_id, skipPassword, apiUserID, skipWriteAuthFile, dbUserId, debug, cleanupTokens, secureCookie, request, }) {
|
||||
var _b, _c, _d;
|
||||
const grabedHostNames = (0, grab_host_names_1.default)({ userId: user_id || apiUserID });
|
||||
const { host, port, scheme } = grabedHostNames;
|
||||
const COOKIE_EXPIRY_DATE = (0, grab_cookie_expirt_date_1.default)();
|
||||
const defaultTempLoginFieldName = "temp_login_code";
|
||||
const emailLoginTempCodeFieldName = email_login
|
||||
export default async function loginUser({ key, payload, database, additionalFields, response, encryptionKey, encryptionSalt, email_login, email_login_code, temp_code_field, token, user_id, skipPassword, apiUserID, skipWriteAuthFile, dbUserId, debug, cleanupTokens, secureCookie, request, }) {
|
||||
var _a, _b, _c;
|
||||
const grabedHostNames = grabHostNames({ userId: user_id || apiUserID });
|
||||
const { host, port, scheme } = grabedHostNames;
|
||||
const COOKIE_EXPIRY_DATE = grabCookieExpiryDate();
|
||||
const defaultTempLoginFieldName = "temp_login_code";
|
||||
const emailLoginTempCodeFieldName = email_login
|
||||
? temp_code_field
|
||||
? temp_code_field
|
||||
? temp_code_field
|
||||
: defaultTempLoginFieldName
|
||||
: undefined;
|
||||
const finalEncryptionKey = encryptionKey || process.env.DSQL_ENCRYPTION_PASSWORD;
|
||||
const finalEncryptionSalt = encryptionSalt || process.env.DSQL_ENCRYPTION_SALT;
|
||||
function debugFn(log, label) {
|
||||
(0, debug_log_1.default)({ log, addTime: true, title: "loginUser", label });
|
||||
}
|
||||
if (!(finalEncryptionKey === null || finalEncryptionKey === void 0 ? void 0 : finalEncryptionKey.match(/.{8,}/))) {
|
||||
console.log("Encryption key is invalid");
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: "Encryption key is invalid",
|
||||
};
|
||||
}
|
||||
if (!(finalEncryptionSalt === null || finalEncryptionSalt === void 0 ? void 0 : finalEncryptionSalt.match(/.{8,}/))) {
|
||||
console.log("Encryption salt is invalid");
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: "Encryption salt is invalid",
|
||||
};
|
||||
}
|
||||
/**
|
||||
* Check required fields
|
||||
*
|
||||
* @description Check required fields
|
||||
*/
|
||||
// const isEmailValid = await validateEmail({ email: payload.email });
|
||||
// if (!payload.email) {
|
||||
// return {
|
||||
// success: false,
|
||||
// payload: null,
|
||||
// msg: isEmailValid.message,
|
||||
// };
|
||||
// }
|
||||
/**
|
||||
* Initialize HTTP response variable
|
||||
*/
|
||||
let httpResponse = {
|
||||
: defaultTempLoginFieldName
|
||||
: undefined;
|
||||
const finalEncryptionKey = encryptionKey || process.env.DSQL_ENCRYPTION_PASSWORD;
|
||||
const finalEncryptionSalt = encryptionSalt || process.env.DSQL_ENCRYPTION_SALT;
|
||||
function debugFn(log, label) {
|
||||
debugLog({ log, addTime: true, title: "loginUser", label });
|
||||
}
|
||||
if (!(finalEncryptionKey === null || finalEncryptionKey === void 0 ? void 0 : finalEncryptionKey.match(/.{8,}/))) {
|
||||
console.log("Encryption key is invalid");
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: "Encryption key is invalid",
|
||||
};
|
||||
/**
|
||||
* Check for local DB settings
|
||||
*
|
||||
* @description Look for local db settings in `.env` file and by pass the http request if available
|
||||
*/
|
||||
const { DSQL_DB_HOST, DSQL_DB_USERNAME, DSQL_DB_PASSWORD, DSQL_DB_NAME } = process.env;
|
||||
if ((DSQL_DB_HOST === null || DSQL_DB_HOST === void 0 ? void 0 : DSQL_DB_HOST.match(/./)) &&
|
||||
(DSQL_DB_USERNAME === null || DSQL_DB_USERNAME === void 0 ? void 0 : DSQL_DB_USERNAME.match(/./)) &&
|
||||
(DSQL_DB_PASSWORD === null || DSQL_DB_PASSWORD === void 0 ? void 0 : DSQL_DB_PASSWORD.match(/./)) &&
|
||||
(DSQL_DB_NAME === null || DSQL_DB_NAME === void 0 ? void 0 : DSQL_DB_NAME.match(/./)) &&
|
||||
global.DSQL_USE_LOCAL) {
|
||||
let dbSchema;
|
||||
try {
|
||||
const localDbSchemaPath = path_1.default.resolve(process.cwd(), "dsql.schema.json");
|
||||
dbSchema = JSON.parse(fs_1.default.readFileSync(localDbSchemaPath, "utf8"));
|
||||
}
|
||||
catch (error) { }
|
||||
httpResponse = yield (0, api_login_1.default)({
|
||||
database: process.env.DSQL_DB_NAME || "",
|
||||
email: payload.email,
|
||||
username: payload.username,
|
||||
password: payload.password,
|
||||
skipPassword,
|
||||
}
|
||||
if (!(finalEncryptionSalt === null || finalEncryptionSalt === void 0 ? void 0 : finalEncryptionSalt.match(/.{8,}/))) {
|
||||
console.log("Encryption salt is invalid");
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: "Encryption salt is invalid",
|
||||
};
|
||||
}
|
||||
/**
|
||||
* Check required fields
|
||||
*
|
||||
* @description Check required fields
|
||||
*/
|
||||
// const isEmailValid = await validateEmail({ email: payload.email });
|
||||
// if (!payload.email) {
|
||||
// return {
|
||||
// success: false,
|
||||
// payload: null,
|
||||
// msg: isEmailValid.message,
|
||||
// };
|
||||
// }
|
||||
/**
|
||||
* Initialize HTTP response variable
|
||||
*/
|
||||
let httpResponse = {
|
||||
success: false,
|
||||
};
|
||||
/**
|
||||
* Check for local DB settings
|
||||
*
|
||||
* @description Look for local db settings in `.env` file and by pass the http request if available
|
||||
*/
|
||||
const { DSQL_DB_HOST, DSQL_DB_USERNAME, DSQL_DB_PASSWORD, DSQL_DB_NAME } = process.env;
|
||||
if ((DSQL_DB_HOST === null || DSQL_DB_HOST === void 0 ? void 0 : DSQL_DB_HOST.match(/./)) &&
|
||||
(DSQL_DB_USERNAME === null || DSQL_DB_USERNAME === void 0 ? void 0 : DSQL_DB_USERNAME.match(/./)) &&
|
||||
(DSQL_DB_PASSWORD === null || DSQL_DB_PASSWORD === void 0 ? void 0 : DSQL_DB_PASSWORD.match(/./)) &&
|
||||
(DSQL_DB_NAME === null || DSQL_DB_NAME === void 0 ? void 0 : DSQL_DB_NAME.match(/./)) &&
|
||||
global.DSQL_USE_LOCAL) {
|
||||
let dbSchema;
|
||||
try {
|
||||
const localDbSchemaPath = path.resolve(process.cwd(), "dsql.schema.json");
|
||||
dbSchema = JSON.parse(fs.readFileSync(localDbSchemaPath, "utf8"));
|
||||
}
|
||||
catch (error) { }
|
||||
httpResponse = await apiLoginUser({
|
||||
database: database || process.env.DSQL_DB_NAME || "",
|
||||
email: payload.email,
|
||||
username: payload.username,
|
||||
password: payload.password,
|
||||
skipPassword,
|
||||
encryptionKey: finalEncryptionKey,
|
||||
additionalFields,
|
||||
email_login,
|
||||
email_login_code,
|
||||
email_login_field: emailLoginTempCodeFieldName,
|
||||
token,
|
||||
dbUserId,
|
||||
debug,
|
||||
});
|
||||
}
|
||||
else {
|
||||
httpResponse = await new Promise((resolve, reject) => {
|
||||
const reqPayload = {
|
||||
encryptionKey: finalEncryptionKey,
|
||||
payload,
|
||||
database,
|
||||
additionalFields,
|
||||
email_login,
|
||||
email_login_code,
|
||||
email_login_field: emailLoginTempCodeFieldName,
|
||||
token,
|
||||
dbUserId,
|
||||
debug,
|
||||
});
|
||||
}
|
||||
else {
|
||||
httpResponse = yield new Promise((resolve, reject) => {
|
||||
const reqPayload = {
|
||||
encryptionKey: finalEncryptionKey,
|
||||
payload,
|
||||
database,
|
||||
additionalFields,
|
||||
email_login,
|
||||
email_login_code,
|
||||
email_login_field: emailLoginTempCodeFieldName,
|
||||
token,
|
||||
skipPassword: skipPassword,
|
||||
dbUserId: dbUserId || 0,
|
||||
};
|
||||
const reqPayloadJSON = JSON.stringify(reqPayload);
|
||||
const httpsRequest = scheme.request({
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Content-Length": Buffer.from(reqPayloadJSON).length,
|
||||
Authorization: key ||
|
||||
process.env.DSQL_FULL_ACCESS_API_KEY ||
|
||||
process.env.DSQL_API_KEY,
|
||||
},
|
||||
port,
|
||||
hostname: host,
|
||||
path: `/api/user/${user_id || grabedHostNames.user_id}/login-user`,
|
||||
}, (res) => {
|
||||
var str = "";
|
||||
res.on("data", function (chunk) {
|
||||
str += chunk;
|
||||
});
|
||||
res.on("end", function () {
|
||||
resolve(JSON.parse(str));
|
||||
});
|
||||
res.on("error", (err) => {
|
||||
reject(err);
|
||||
});
|
||||
skipPassword: skipPassword,
|
||||
dbUserId: dbUserId || 0,
|
||||
};
|
||||
const reqPayloadJSON = JSON.stringify(reqPayload);
|
||||
const httpsRequest = scheme.request({
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Content-Length": Buffer.from(reqPayloadJSON).length,
|
||||
Authorization: key ||
|
||||
process.env.DSQL_FULL_ACCESS_API_KEY ||
|
||||
process.env.DSQL_API_KEY,
|
||||
},
|
||||
port,
|
||||
hostname: host,
|
||||
path: `/api/user/${user_id || grabedHostNames.user_id}/login-user`,
|
||||
}, (res) => {
|
||||
var str = "";
|
||||
res.on("data", function (chunk) {
|
||||
str += chunk;
|
||||
});
|
||||
res.on("end", function () {
|
||||
resolve(JSON.parse(str));
|
||||
});
|
||||
res.on("error", (err) => {
|
||||
reject(err);
|
||||
});
|
||||
httpsRequest.write(reqPayloadJSON);
|
||||
httpsRequest.end();
|
||||
});
|
||||
httpsRequest.write(reqPayloadJSON);
|
||||
httpsRequest.end();
|
||||
});
|
||||
}
|
||||
if (debug) {
|
||||
debugFn(httpResponse, "httpResponse");
|
||||
}
|
||||
if (httpResponse === null || httpResponse === void 0 ? void 0 : httpResponse.success) {
|
||||
let encryptedPayload = encrypt({
|
||||
data: JSON.stringify(httpResponse.payload),
|
||||
encryptionKey: finalEncryptionKey,
|
||||
encryptionSalt: finalEncryptionSalt,
|
||||
});
|
||||
try {
|
||||
if (token && encryptedPayload)
|
||||
httpResponse["token"] = encryptedPayload;
|
||||
}
|
||||
catch (error) {
|
||||
(_a = global.ERROR_CALLBACK) === null || _a === void 0 ? void 0 : _a.call(global, `Login User HTTP Response Error`, error);
|
||||
}
|
||||
const cookieNames = getAuthCookieNames({
|
||||
database,
|
||||
userId: grabedHostNames.user_id,
|
||||
});
|
||||
if (httpResponse.csrf && !skipWriteAuthFile) {
|
||||
writeAuthFile(httpResponse.csrf, JSON.stringify(httpResponse.payload), cleanupTokens && ((_b = httpResponse.payload) === null || _b === void 0 ? void 0 : _b.id)
|
||||
? { userId: httpResponse.payload.id }
|
||||
: undefined);
|
||||
}
|
||||
httpResponse["cookieNames"] = cookieNames;
|
||||
httpResponse["key"] = String(encryptedPayload);
|
||||
const authKeyName = cookieNames.keyCookieName;
|
||||
const csrfName = cookieNames.csrfCookieName;
|
||||
if (debug) {
|
||||
debugFn(httpResponse, "httpResponse");
|
||||
debugFn(authKeyName, "authKeyName");
|
||||
debugFn(csrfName, "csrfName");
|
||||
debugFn(encryptedPayload, "encryptedPayload");
|
||||
}
|
||||
if (httpResponse === null || httpResponse === void 0 ? void 0 : httpResponse.success) {
|
||||
let encryptedPayload = (0, encrypt_1.default)({
|
||||
data: JSON.stringify(httpResponse.payload),
|
||||
encryptionKey: finalEncryptionKey,
|
||||
encryptionSalt: finalEncryptionSalt,
|
||||
});
|
||||
try {
|
||||
if (token && encryptedPayload)
|
||||
httpResponse["token"] = encryptedPayload;
|
||||
}
|
||||
catch (error) {
|
||||
(_b = global.ERROR_CALLBACK) === null || _b === void 0 ? void 0 : _b.call(global, `Login User HTTP Response Error`, error);
|
||||
}
|
||||
const cookieNames = (0, get_auth_cookie_names_1.default)({
|
||||
database,
|
||||
userId: grabedHostNames.user_id,
|
||||
});
|
||||
if (httpResponse.csrf && !skipWriteAuthFile) {
|
||||
(0, write_auth_files_1.writeAuthFile)(httpResponse.csrf, JSON.stringify(httpResponse.payload), cleanupTokens && ((_c = httpResponse.payload) === null || _c === void 0 ? void 0 : _c.id)
|
||||
? { userId: httpResponse.payload.id }
|
||||
: undefined);
|
||||
}
|
||||
httpResponse["cookieNames"] = cookieNames;
|
||||
httpResponse["key"] = String(encryptedPayload);
|
||||
const authKeyName = cookieNames.keyCookieName;
|
||||
const csrfName = cookieNames.csrfCookieName;
|
||||
if (debug) {
|
||||
debugFn(authKeyName, "authKeyName");
|
||||
debugFn(csrfName, "csrfName");
|
||||
debugFn(encryptedPayload, "encryptedPayload");
|
||||
}
|
||||
response === null || response === void 0 ? void 0 : response.setHeader("Set-Cookie", [
|
||||
`${authKeyName}=${encryptedPayload};samesite=strict;path=/;HttpOnly=true;Expires=${COOKIE_EXPIRY_DATE}${secureCookie ? ";Secure=true" : ""}`,
|
||||
`${csrfName}=${(_d = httpResponse.payload) === null || _d === void 0 ? void 0 : _d.csrf_k};samesite=strict;path=/;HttpOnly=true;Expires=${COOKIE_EXPIRY_DATE}`,
|
||||
]);
|
||||
if (debug) {
|
||||
debugFn("Response Sent!");
|
||||
}
|
||||
response === null || response === void 0 ? void 0 : response.setHeader("Set-Cookie", [
|
||||
`${authKeyName}=${encryptedPayload};samesite=strict;path=/;HttpOnly=true;Expires=${COOKIE_EXPIRY_DATE}${secureCookie ? ";Secure=true" : ""}`,
|
||||
`${csrfName}=${(_c = httpResponse.payload) === null || _c === void 0 ? void 0 : _c.csrf_k};samesite=strict;path=/;HttpOnly=true;Expires=${COOKIE_EXPIRY_DATE}`,
|
||||
]);
|
||||
if (debug) {
|
||||
debugFn("Response Sent!");
|
||||
}
|
||||
return httpResponse;
|
||||
});
|
||||
}
|
||||
return httpResponse;
|
||||
}
|
||||
|
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";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = logoutUser;
|
||||
const get_auth_cookie_names_1 = __importDefault(require("../../functions/backend/cookies/get-auth-cookie-names"));
|
||||
const decrypt_1 = __importDefault(require("../../functions/dsql/decrypt"));
|
||||
const ejson_1 = __importDefault(require("../../utils/ejson"));
|
||||
const write_auth_files_1 = require("../../functions/backend/auth/write-auth-files");
|
||||
const parseCookies_1 = __importDefault(require("../../utils/backend/parseCookies"));
|
||||
const grab_host_names_1 = __importDefault(require("../../utils/grab-host-names"));
|
||||
const debug_log_1 = __importDefault(require("../../utils/logging/debug-log"));
|
||||
import getAuthCookieNames from "../../functions/backend/cookies/get-auth-cookie-names";
|
||||
import decrypt from "../../functions/dsql/decrypt";
|
||||
import EJSON from "../../utils/ejson";
|
||||
import { deleteAuthFile } from "../../functions/backend/auth/write-auth-files";
|
||||
import parseCookies from "../../utils/backend/parseCookies";
|
||||
import grabHostNames from "../../utils/grab-host-names";
|
||||
import debugLog from "../../utils/logging/debug-log";
|
||||
/**
|
||||
* # Logout user
|
||||
*/
|
||||
function logoutUser({ response, database, dsqlUserId, encryptedUserString, request, cookieString, debug, }) {
|
||||
export default function logoutUser({ response, database, dsqlUserId, encryptedUserString, request, cookieString, debug, }) {
|
||||
var _a;
|
||||
/**
|
||||
* Check Encryption Keys
|
||||
@ -22,13 +16,13 @@ function logoutUser({ response, database, dsqlUserId, encryptedUserString, reque
|
||||
* @description Check Encryption Keys
|
||||
*/
|
||||
try {
|
||||
const { user_id } = (0, grab_host_names_1.default)({ userId: dsqlUserId });
|
||||
const cookieNames = (0, get_auth_cookie_names_1.default)({
|
||||
const { user_id } = grabHostNames({ userId: dsqlUserId });
|
||||
const cookieNames = getAuthCookieNames({
|
||||
database,
|
||||
userId: user_id,
|
||||
});
|
||||
function debugFn(log, label) {
|
||||
(0, debug_log_1.default)({ log, addTime: true, title: "logoutUser", label });
|
||||
debugLog({ log, addTime: true, title: "logoutUser", label });
|
||||
}
|
||||
if (debug) {
|
||||
debugFn(cookieNames, "cookieNames");
|
||||
@ -39,16 +33,16 @@ function logoutUser({ response, database, dsqlUserId, encryptedUserString, reque
|
||||
const decryptedUserJSON = (() => {
|
||||
try {
|
||||
if (request) {
|
||||
const cookiesObject = (0, parseCookies_1.default)({
|
||||
const cookiesObject = parseCookies({
|
||||
request,
|
||||
cookieString,
|
||||
});
|
||||
return (0, decrypt_1.default)({
|
||||
return decrypt({
|
||||
encryptedString: cookiesObject[authKeyName],
|
||||
});
|
||||
}
|
||||
else if (encryptedUserString) {
|
||||
return (0, decrypt_1.default)({
|
||||
return decrypt({
|
||||
encryptedString: encryptedUserString,
|
||||
});
|
||||
}
|
||||
@ -66,7 +60,7 @@ function logoutUser({ response, database, dsqlUserId, encryptedUserString, reque
|
||||
}
|
||||
if (!decryptedUserJSON)
|
||||
throw new Error("Invalid User");
|
||||
const userObject = ejson_1.default.parse(decryptedUserJSON);
|
||||
const userObject = EJSON.parse(decryptedUserJSON);
|
||||
if (!(userObject === null || userObject === void 0 ? void 0 : userObject.csrf_k))
|
||||
throw new Error("Invalid User. Please check key");
|
||||
response === null || response === void 0 ? void 0 : response.setHeader("Set-Cookie", [
|
||||
@ -75,7 +69,7 @@ function logoutUser({ response, database, dsqlUserId, encryptedUserString, reque
|
||||
`${oneTimeCodeName}=null;max-age=0`,
|
||||
]);
|
||||
const csrf = userObject.csrf_k;
|
||||
(0, write_auth_files_1.deleteAuthFile)(csrf);
|
||||
deleteAuthFile(csrf);
|
||||
return {
|
||||
success: true,
|
||||
msg: "User Logged Out",
|
||||
|
331
dist/package-shared/actions/users/reauth-user.js
vendored
331
dist/package-shared/actions/users/reauth-user.js
vendored
@ -1,179 +1,162 @@
|
||||
"use strict";
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = reauthUser;
|
||||
const user_auth_1 = __importDefault(require("./user-auth"));
|
||||
const grab_host_names_1 = __importDefault(require("../../utils/grab-host-names"));
|
||||
const login_user_1 = __importDefault(require("./login-user"));
|
||||
import userAuth from "./user-auth";
|
||||
import grabHostNames from "../../utils/grab-host-names";
|
||||
import loginUser from "./login-user";
|
||||
/**
|
||||
* # Reauthorize User
|
||||
*/
|
||||
function reauthUser(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ key, database, response, request, level, encryptionKey, encryptionSalt, additionalFields, encryptedUserString, user_id, secureCookie, }) {
|
||||
var _b;
|
||||
/**
|
||||
* Check Encryption Keys
|
||||
*
|
||||
* @description Check Encryption Keys
|
||||
*/
|
||||
const grabedHostNames = (0, grab_host_names_1.default)();
|
||||
// const { host, port, scheme } = grabedHostNames;
|
||||
// const COOKIE_EXPIRY_DATE = grabCookieExpiryDate();
|
||||
const finalEncryptionKey = encryptionKey || process.env.DSQL_ENCRYPTION_PASSWORD;
|
||||
const finalEncryptionSalt = encryptionSalt || process.env.DSQL_ENCRYPTION_SALT;
|
||||
const existingUser = (0, user_auth_1.default)({
|
||||
database,
|
||||
encryptionKey: finalEncryptionKey,
|
||||
encryptionSalt: finalEncryptionSalt,
|
||||
level,
|
||||
request,
|
||||
encryptedUserString,
|
||||
});
|
||||
if (!((_b = existingUser === null || existingUser === void 0 ? void 0 : existingUser.payload) === null || _b === void 0 ? void 0 : _b.id)) {
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: "Cookie Credentials Invalid",
|
||||
};
|
||||
}
|
||||
return yield (0, login_user_1.default)({
|
||||
database: database || "",
|
||||
payload: {
|
||||
email: existingUser.payload.email,
|
||||
},
|
||||
additionalFields,
|
||||
skipPassword: true,
|
||||
response,
|
||||
request,
|
||||
user_id,
|
||||
secureCookie,
|
||||
key,
|
||||
});
|
||||
/**
|
||||
* Initialize HTTP response variable
|
||||
*/
|
||||
let httpResponse;
|
||||
/**
|
||||
* Check for local DB settings
|
||||
*
|
||||
* @description Look for local db settings in `.env` file and by pass the http request if available
|
||||
*/
|
||||
// const { DSQL_DB_HOST, DSQL_DB_USERNAME, DSQL_DB_PASSWORD, DSQL_DB_NAME } =
|
||||
// process.env;
|
||||
// if (
|
||||
// DSQL_DB_HOST?.match(/./) &&
|
||||
// DSQL_DB_USERNAME?.match(/./) &&
|
||||
// DSQL_DB_PASSWORD?.match(/./) &&
|
||||
// DSQL_DB_NAME?.match(/./) &&
|
||||
// global.DSQL_USE_LOCAL
|
||||
// ) {
|
||||
// let dbSchema: import("../../types").DSQL_DatabaseSchemaType | undefined;
|
||||
// try {
|
||||
// const localDbSchemaPath = path.resolve(
|
||||
// process.cwd(),
|
||||
// "dsql.schema.json"
|
||||
// );
|
||||
// dbSchema = JSON.parse(fs.readFileSync(localDbSchemaPath, "utf8"));
|
||||
// } catch (error) {}
|
||||
// httpResponse = await apiReauthUser({
|
||||
// existingUser: existingUser.payload,
|
||||
// additionalFields,
|
||||
// });
|
||||
// } else {
|
||||
// /**
|
||||
// * Make https request
|
||||
// *
|
||||
// * @description make a request to datasquirel.com
|
||||
// */
|
||||
// httpResponse = (await new Promise((resolve, reject) => {
|
||||
// const reqPayload = JSON.stringify({
|
||||
// existingUser: existingUser.payload,
|
||||
// database,
|
||||
// additionalFields,
|
||||
// });
|
||||
// const httpsRequest = scheme.request(
|
||||
// {
|
||||
// method: "POST",
|
||||
// headers: {
|
||||
// "Content-Type": "application/json",
|
||||
// "Content-Length": Buffer.from(reqPayload).length,
|
||||
// Authorization:
|
||||
// key ||
|
||||
// process.env.DSQL_FULL_ACCESS_API_KEY ||
|
||||
// process.env.DSQL_API_KEY,
|
||||
// },
|
||||
// port,
|
||||
// hostname: host,
|
||||
// path: `/api/user/${
|
||||
// user_id || grabedHostNames.user_id
|
||||
// }/reauth-user`,
|
||||
// },
|
||||
// /**
|
||||
// * Callback Function
|
||||
// *
|
||||
// * @description https request callback
|
||||
// */
|
||||
// (response) => {
|
||||
// var str = "";
|
||||
// response.on("data", function (chunk) {
|
||||
// str += chunk;
|
||||
// });
|
||||
// response.on("end", function () {
|
||||
// resolve(JSON.parse(str));
|
||||
// });
|
||||
// response.on("error", (err) => {
|
||||
// reject(err);
|
||||
// });
|
||||
// }
|
||||
// );
|
||||
// httpsRequest.write(reqPayload);
|
||||
// httpsRequest.end();
|
||||
// })) as APILoginFunctionReturn;
|
||||
// }
|
||||
// /**
|
||||
// * Make https request
|
||||
// *
|
||||
// * @description make a request to datasquirel.com
|
||||
// */
|
||||
// if (httpResponse?.success) {
|
||||
// let encryptedPayload = encrypt({
|
||||
// data: JSON.stringify(httpResponse.payload),
|
||||
// encryptionKey: finalEncryptionKey,
|
||||
// encryptionSalt: finalEncryptionSalt,
|
||||
// });
|
||||
// const cookieNames = getAuthCookieNames({
|
||||
// database,
|
||||
// userId: user_id || grabedHostNames.user_id,
|
||||
// });
|
||||
// httpResponse["cookieNames"] = cookieNames;
|
||||
// httpResponse["key"] = String(encryptedPayload);
|
||||
// const authKeyName = cookieNames.keyCookieName;
|
||||
// const csrfName = cookieNames.csrfCookieName;
|
||||
// response?.setHeader("Set-Cookie", [
|
||||
// `${authKeyName}=${encryptedPayload};samesite=strict;path=/;HttpOnly=true;Expires=${COOKIE_EXPIRY_DATE}${
|
||||
// secureCookie ? ";Secure=true" : ""
|
||||
// }`,
|
||||
// `${csrfName}=${httpResponse.payload?.csrf_k};samesite=strict;path=/;HttpOnly=true;Expires=${COOKIE_EXPIRY_DATE}`,
|
||||
// ]);
|
||||
// if (httpResponse.csrf) {
|
||||
// deleteAuthFile(String(existingUser.payload.csrf_k));
|
||||
// writeAuthFile(
|
||||
// httpResponse.csrf,
|
||||
// JSON.stringify(httpResponse.payload)
|
||||
// );
|
||||
// }
|
||||
// }
|
||||
// return httpResponse;
|
||||
export default async function reauthUser({ key, database, response, request, level, encryptionKey, encryptionSalt, additionalFields, encryptedUserString, user_id, secureCookie, }) {
|
||||
var _a;
|
||||
/**
|
||||
* Check Encryption Keys
|
||||
*
|
||||
* @description Check Encryption Keys
|
||||
*/
|
||||
const grabedHostNames = grabHostNames();
|
||||
// const { host, port, scheme } = grabedHostNames;
|
||||
// const COOKIE_EXPIRY_DATE = grabCookieExpiryDate();
|
||||
const finalEncryptionKey = encryptionKey || process.env.DSQL_ENCRYPTION_PASSWORD;
|
||||
const finalEncryptionSalt = encryptionSalt || process.env.DSQL_ENCRYPTION_SALT;
|
||||
const existingUser = userAuth({
|
||||
database,
|
||||
encryptionKey: finalEncryptionKey,
|
||||
encryptionSalt: finalEncryptionSalt,
|
||||
level,
|
||||
request,
|
||||
encryptedUserString,
|
||||
});
|
||||
if (!((_a = existingUser === null || existingUser === void 0 ? void 0 : existingUser.payload) === null || _a === void 0 ? void 0 : _a.id)) {
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: "Cookie Credentials Invalid",
|
||||
};
|
||||
}
|
||||
return await loginUser({
|
||||
database: database || "",
|
||||
payload: {
|
||||
email: existingUser.payload.email,
|
||||
},
|
||||
additionalFields,
|
||||
skipPassword: true,
|
||||
response,
|
||||
request,
|
||||
user_id,
|
||||
secureCookie,
|
||||
key,
|
||||
});
|
||||
/**
|
||||
* Initialize HTTP response variable
|
||||
*/
|
||||
let httpResponse;
|
||||
/**
|
||||
* Check for local DB settings
|
||||
*
|
||||
* @description Look for local db settings in `.env` file and by pass the http request if available
|
||||
*/
|
||||
// const { DSQL_DB_HOST, DSQL_DB_USERNAME, DSQL_DB_PASSWORD, DSQL_DB_NAME } =
|
||||
// process.env;
|
||||
// if (
|
||||
// DSQL_DB_HOST?.match(/./) &&
|
||||
// DSQL_DB_USERNAME?.match(/./) &&
|
||||
// DSQL_DB_PASSWORD?.match(/./) &&
|
||||
// DSQL_DB_NAME?.match(/./) &&
|
||||
// global.DSQL_USE_LOCAL
|
||||
// ) {
|
||||
// let dbSchema: import("../../types").DSQL_DatabaseSchemaType | undefined;
|
||||
// try {
|
||||
// const localDbSchemaPath = path.resolve(
|
||||
// process.cwd(),
|
||||
// "dsql.schema.json"
|
||||
// );
|
||||
// dbSchema = JSON.parse(fs.readFileSync(localDbSchemaPath, "utf8"));
|
||||
// } catch (error) {}
|
||||
// httpResponse = await apiReauthUser({
|
||||
// existingUser: existingUser.payload,
|
||||
// additionalFields,
|
||||
// });
|
||||
// } else {
|
||||
// /**
|
||||
// * Make https request
|
||||
// *
|
||||
// * @description make a request to datasquirel.com
|
||||
// */
|
||||
// httpResponse = (await new Promise((resolve, reject) => {
|
||||
// const reqPayload = JSON.stringify({
|
||||
// existingUser: existingUser.payload,
|
||||
// database,
|
||||
// additionalFields,
|
||||
// });
|
||||
// const httpsRequest = scheme.request(
|
||||
// {
|
||||
// method: "POST",
|
||||
// headers: {
|
||||
// "Content-Type": "application/json",
|
||||
// "Content-Length": Buffer.from(reqPayload).length,
|
||||
// Authorization:
|
||||
// key ||
|
||||
// process.env.DSQL_FULL_ACCESS_API_KEY ||
|
||||
// process.env.DSQL_API_KEY,
|
||||
// },
|
||||
// port,
|
||||
// hostname: host,
|
||||
// path: `/api/user/${
|
||||
// user_id || grabedHostNames.user_id
|
||||
// }/reauth-user`,
|
||||
// },
|
||||
// /**
|
||||
// * Callback Function
|
||||
// *
|
||||
// * @description https request callback
|
||||
// */
|
||||
// (response) => {
|
||||
// var str = "";
|
||||
// response.on("data", function (chunk) {
|
||||
// str += chunk;
|
||||
// });
|
||||
// response.on("end", function () {
|
||||
// resolve(JSON.parse(str));
|
||||
// });
|
||||
// response.on("error", (err) => {
|
||||
// reject(err);
|
||||
// });
|
||||
// }
|
||||
// );
|
||||
// httpsRequest.write(reqPayload);
|
||||
// httpsRequest.end();
|
||||
// })) as APILoginFunctionReturn;
|
||||
// }
|
||||
// /**
|
||||
// * Make https request
|
||||
// *
|
||||
// * @description make a request to datasquirel.com
|
||||
// */
|
||||
// if (httpResponse?.success) {
|
||||
// let encryptedPayload = encrypt({
|
||||
// data: JSON.stringify(httpResponse.payload),
|
||||
// encryptionKey: finalEncryptionKey,
|
||||
// encryptionSalt: finalEncryptionSalt,
|
||||
// });
|
||||
// const cookieNames = getAuthCookieNames({
|
||||
// database,
|
||||
// userId: user_id || grabedHostNames.user_id,
|
||||
// });
|
||||
// httpResponse["cookieNames"] = cookieNames;
|
||||
// httpResponse["key"] = String(encryptedPayload);
|
||||
// const authKeyName = cookieNames.keyCookieName;
|
||||
// const csrfName = cookieNames.csrfCookieName;
|
||||
// response?.setHeader("Set-Cookie", [
|
||||
// `${authKeyName}=${encryptedPayload};samesite=strict;path=/;HttpOnly=true;Expires=${COOKIE_EXPIRY_DATE}${
|
||||
// secureCookie ? ";Secure=true" : ""
|
||||
// }`,
|
||||
// `${csrfName}=${httpResponse.payload?.csrf_k};samesite=strict;path=/;HttpOnly=true;Expires=${COOKIE_EXPIRY_DATE}`,
|
||||
// ]);
|
||||
// if (httpResponse.csrf) {
|
||||
// deleteAuthFile(String(existingUser.payload.csrf_k));
|
||||
// writeAuthFile(
|
||||
// httpResponse.csrf,
|
||||
// JSON.stringify(httpResponse.payload)
|
||||
// );
|
||||
// }
|
||||
// }
|
||||
// return httpResponse;
|
||||
}
|
||||
|
@ -19,5 +19,5 @@ type Param = {
|
||||
/**
|
||||
* # Send Email Code to a User
|
||||
*/
|
||||
export default function sendEmailCode({ key, email, database, temp_code_field_name, mail_domain, mail_password, mail_username, mail_port, sender, user_id, response, extraCookies, }: Param): Promise<SendOneTimeCodeEmailResponse>;
|
||||
export default function sendEmailCode(params: Param): Promise<SendOneTimeCodeEmailResponse>;
|
||||
export {};
|
||||
|
184
dist/package-shared/actions/users/send-email-code.js
vendored
184
dist/package-shared/actions/users/send-email-code.js
vendored
@ -1,120 +1,104 @@
|
||||
"use strict";
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = sendEmailCode;
|
||||
const fs_1 = __importDefault(require("fs"));
|
||||
const path_1 = __importDefault(require("path"));
|
||||
const grab_host_names_1 = __importDefault(require("../../utils/grab-host-names"));
|
||||
const api_send_email_code_1 = __importDefault(require("../../functions/api/users/api-send-email-code"));
|
||||
import fs from "fs";
|
||||
import path from "path";
|
||||
import grabHostNames from "../../utils/grab-host-names";
|
||||
import apiSendEmailCode from "../../functions/api/users/api-send-email-code";
|
||||
/**
|
||||
* # Send Email Code to a User
|
||||
*/
|
||||
function sendEmailCode(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ key, email, database, temp_code_field_name, mail_domain, mail_password, mail_username, mail_port, sender, user_id, response, extraCookies, }) {
|
||||
const grabedHostNames = (0, grab_host_names_1.default)();
|
||||
const { host, port, scheme } = grabedHostNames;
|
||||
const defaultTempLoginFieldName = "temp_login_code";
|
||||
const emailLoginTempCodeFieldName = temp_code_field_name
|
||||
? temp_code_field_name
|
||||
: defaultTempLoginFieldName;
|
||||
const emailHtml = `<p>Please use this code to login</p>\n<h2>{{code}}</h2>\n<p>Please note that this code expires after 15 minutes</p>`;
|
||||
export default async function sendEmailCode(params) {
|
||||
const { key, email, database, temp_code_field_name, mail_domain, mail_password, mail_username, mail_port, sender, user_id, response, extraCookies, } = params;
|
||||
const grabedHostNames = grabHostNames();
|
||||
const { host, port, scheme } = grabedHostNames;
|
||||
const defaultTempLoginFieldName = "temp_login_code";
|
||||
const emailLoginTempCodeFieldName = temp_code_field_name
|
||||
? temp_code_field_name
|
||||
: defaultTempLoginFieldName;
|
||||
const emailHtml = `<p>Please use this code to login</p>\n<h2>{{code}}</h2>\n<p>Please note that this code expires after 15 minutes</p>`;
|
||||
/**
|
||||
* Check for local DB settings
|
||||
*
|
||||
* @description Look for local db settings in `.env` file and by pass the http request if available
|
||||
*/
|
||||
const { DSQL_DB_HOST, DSQL_DB_USERNAME, DSQL_DB_PASSWORD, DSQL_DB_NAME } = process.env;
|
||||
if ((DSQL_DB_HOST === null || DSQL_DB_HOST === void 0 ? void 0 : DSQL_DB_HOST.match(/./)) &&
|
||||
(DSQL_DB_USERNAME === null || DSQL_DB_USERNAME === void 0 ? void 0 : DSQL_DB_USERNAME.match(/./)) &&
|
||||
(DSQL_DB_PASSWORD === null || DSQL_DB_PASSWORD === void 0 ? void 0 : DSQL_DB_PASSWORD.match(/./)) &&
|
||||
(DSQL_DB_NAME === null || DSQL_DB_NAME === void 0 ? void 0 : DSQL_DB_NAME.match(/./)) &&
|
||||
global.DSQL_USE_LOCAL) {
|
||||
/** @type {import("../../types").DSQL_DatabaseSchemaType | undefined} */
|
||||
let dbSchema;
|
||||
try {
|
||||
const localDbSchemaPath = path.resolve(process.cwd(), "dsql.schema.json");
|
||||
dbSchema = JSON.parse(fs.readFileSync(localDbSchemaPath, "utf8"));
|
||||
}
|
||||
catch (error) { }
|
||||
return await apiSendEmailCode({
|
||||
database: DSQL_DB_NAME,
|
||||
email,
|
||||
email_login_field: emailLoginTempCodeFieldName,
|
||||
html: emailHtml,
|
||||
mail_domain,
|
||||
mail_password,
|
||||
mail_port,
|
||||
mail_username,
|
||||
sender,
|
||||
response,
|
||||
extraCookies,
|
||||
});
|
||||
}
|
||||
else {
|
||||
/**
|
||||
* Check for local DB settings
|
||||
* Make https request
|
||||
*
|
||||
* @description Look for local db settings in `.env` file and by pass the http request if available
|
||||
* @description make a request to datasquirel.com
|
||||
*
|
||||
* @type {import("../../types").SendOneTimeCodeEmailResponse}
|
||||
*/
|
||||
const { DSQL_DB_HOST, DSQL_DB_USERNAME, DSQL_DB_PASSWORD, DSQL_DB_NAME } = process.env;
|
||||
if ((DSQL_DB_HOST === null || DSQL_DB_HOST === void 0 ? void 0 : DSQL_DB_HOST.match(/./)) &&
|
||||
(DSQL_DB_USERNAME === null || DSQL_DB_USERNAME === void 0 ? void 0 : DSQL_DB_USERNAME.match(/./)) &&
|
||||
(DSQL_DB_PASSWORD === null || DSQL_DB_PASSWORD === void 0 ? void 0 : DSQL_DB_PASSWORD.match(/./)) &&
|
||||
(DSQL_DB_NAME === null || DSQL_DB_NAME === void 0 ? void 0 : DSQL_DB_NAME.match(/./)) &&
|
||||
global.DSQL_USE_LOCAL) {
|
||||
/** @type {import("../../types").DSQL_DatabaseSchemaType | undefined} */
|
||||
let dbSchema;
|
||||
try {
|
||||
const localDbSchemaPath = path_1.default.resolve(process.cwd(), "dsql.schema.json");
|
||||
dbSchema = JSON.parse(fs_1.default.readFileSync(localDbSchemaPath, "utf8"));
|
||||
}
|
||||
catch (error) { }
|
||||
return yield (0, api_send_email_code_1.default)({
|
||||
database: DSQL_DB_NAME,
|
||||
const httpResponse = await new Promise((resolve, reject) => {
|
||||
const reqPayload = JSON.stringify({
|
||||
email,
|
||||
database,
|
||||
email_login_field: emailLoginTempCodeFieldName,
|
||||
html: emailHtml,
|
||||
mail_domain,
|
||||
mail_password,
|
||||
mail_port,
|
||||
mail_username,
|
||||
mail_port,
|
||||
sender,
|
||||
response,
|
||||
extraCookies,
|
||||
html: emailHtml,
|
||||
});
|
||||
}
|
||||
else {
|
||||
const httpsRequest = scheme.request({
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Content-Length": Buffer.from(reqPayload).length,
|
||||
Authorization: key ||
|
||||
process.env.DSQL_FULL_ACCESS_API_KEY ||
|
||||
process.env.DSQL_API_KEY,
|
||||
},
|
||||
port,
|
||||
hostname: host,
|
||||
path: `/api/user/${user_id || grabedHostNames.user_id}/send-email-code`,
|
||||
},
|
||||
/**
|
||||
* Make https request
|
||||
* Callback Function
|
||||
*
|
||||
* @description make a request to datasquirel.com
|
||||
*
|
||||
* @type {import("../../types").SendOneTimeCodeEmailResponse}
|
||||
* @description https request callback
|
||||
*/
|
||||
const httpResponse = yield new Promise((resolve, reject) => {
|
||||
const reqPayload = JSON.stringify({
|
||||
email,
|
||||
database,
|
||||
email_login_field: emailLoginTempCodeFieldName,
|
||||
mail_domain,
|
||||
mail_password,
|
||||
mail_username,
|
||||
mail_port,
|
||||
sender,
|
||||
html: emailHtml,
|
||||
(res) => {
|
||||
var str = "";
|
||||
res.on("data", function (chunk) {
|
||||
str += chunk;
|
||||
});
|
||||
const httpsRequest = scheme.request({
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Content-Length": Buffer.from(reqPayload).length,
|
||||
Authorization: key ||
|
||||
process.env.DSQL_FULL_ACCESS_API_KEY ||
|
||||
process.env.DSQL_API_KEY,
|
||||
},
|
||||
port,
|
||||
hostname: host,
|
||||
path: `/api/user/${user_id || grabedHostNames.user_id}/send-email-code`,
|
||||
},
|
||||
/**
|
||||
* Callback Function
|
||||
*
|
||||
* @description https request callback
|
||||
*/
|
||||
(res) => {
|
||||
var str = "";
|
||||
res.on("data", function (chunk) {
|
||||
str += chunk;
|
||||
});
|
||||
res.on("end", function () {
|
||||
resolve(JSON.parse(str));
|
||||
});
|
||||
res.on("error", (err) => {
|
||||
reject(err);
|
||||
});
|
||||
res.on("end", function () {
|
||||
resolve(JSON.parse(str));
|
||||
});
|
||||
res.on("error", (err) => {
|
||||
reject(err);
|
||||
});
|
||||
httpsRequest.write(reqPayload);
|
||||
httpsRequest.end();
|
||||
});
|
||||
return httpResponse;
|
||||
}
|
||||
});
|
||||
httpsRequest.write(reqPayload);
|
||||
httpsRequest.end();
|
||||
});
|
||||
return httpResponse;
|
||||
}
|
||||
}
|
||||
|
@ -1,173 +1,156 @@
|
||||
"use strict";
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = githubAuth;
|
||||
const fs_1 = __importDefault(require("fs"));
|
||||
const path_1 = __importDefault(require("path"));
|
||||
const encrypt_1 = __importDefault(require("../../../functions/dsql/encrypt"));
|
||||
const grab_host_names_1 = __importDefault(require("../../../utils/grab-host-names"));
|
||||
const api_github_login_1 = __importDefault(require("../../../functions/api/users/social/api-github-login"));
|
||||
const grab_cookie_expirt_date_1 = __importDefault(require("../../../utils/grab-cookie-expirt-date"));
|
||||
import fs from "fs";
|
||||
import path from "path";
|
||||
import encrypt from "../../../functions/dsql/encrypt";
|
||||
import grabHostNames from "../../../utils/grab-host-names";
|
||||
import apiGithubLogin from "../../../functions/api/users/social/api-github-login";
|
||||
import grabCookieExpiryDate from "../../../utils/grab-cookie-expirt-date";
|
||||
/**
|
||||
* # SERVER FUNCTION: Login with google Function
|
||||
*/
|
||||
function githubAuth(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ key, code, email, database, clientId, clientSecret, response, encryptionKey, encryptionSalt, additionalFields, user_id, additionalData, secureCookie, }) {
|
||||
/**
|
||||
* Check inputs
|
||||
*
|
||||
* @description Check inputs
|
||||
*/
|
||||
const grabedHostNames = (0, grab_host_names_1.default)();
|
||||
const { host, port, scheme } = grabedHostNames;
|
||||
const COOKIE_EXPIRY_DATE = (0, grab_cookie_expirt_date_1.default)();
|
||||
if (!code || (code === null || code === void 0 ? void 0 : code.match(/ /))) {
|
||||
return {
|
||||
success: false,
|
||||
user: null,
|
||||
msg: "Please enter Github Access Token",
|
||||
};
|
||||
export default async function githubAuth({ key, code, email, database, clientId, clientSecret, response, encryptionKey, encryptionSalt, additionalFields, user_id, additionalData, secureCookie, }) {
|
||||
/**
|
||||
* Check inputs
|
||||
*
|
||||
* @description Check inputs
|
||||
*/
|
||||
const grabedHostNames = grabHostNames();
|
||||
const { host, port, scheme } = grabedHostNames;
|
||||
const COOKIE_EXPIRY_DATE = grabCookieExpiryDate();
|
||||
if (!code || (code === null || code === void 0 ? void 0 : code.match(/ /))) {
|
||||
return {
|
||||
success: false,
|
||||
user: null,
|
||||
msg: "Please enter Github Access Token",
|
||||
};
|
||||
}
|
||||
if (!database || (database === null || database === void 0 ? void 0 : database.match(/ /))) {
|
||||
return {
|
||||
success: false,
|
||||
user: null,
|
||||
msg: "Please provide database slug name you want to access",
|
||||
};
|
||||
}
|
||||
if (!clientId || (clientId === null || clientId === void 0 ? void 0 : clientId.match(/ /))) {
|
||||
return {
|
||||
success: false,
|
||||
user: null,
|
||||
msg: "Please enter Github OAUTH client ID",
|
||||
};
|
||||
}
|
||||
/**
|
||||
* Initialize HTTP response variable
|
||||
*/
|
||||
let httpResponse;
|
||||
/**
|
||||
* Check for local DB settings
|
||||
*
|
||||
* @description Look for local db settings in `.env` file and by pass the http request if available
|
||||
*/
|
||||
const { DSQL_DB_HOST, DSQL_DB_USERNAME, DSQL_DB_PASSWORD, DSQL_DB_NAME, DSQL_KEY, DSQL_REF_DB_NAME, DSQL_FULL_SYNC, } = process.env;
|
||||
if ((DSQL_DB_HOST === null || DSQL_DB_HOST === void 0 ? void 0 : DSQL_DB_HOST.match(/./)) &&
|
||||
(DSQL_DB_USERNAME === null || DSQL_DB_USERNAME === void 0 ? void 0 : DSQL_DB_USERNAME.match(/./)) &&
|
||||
(DSQL_DB_PASSWORD === null || DSQL_DB_PASSWORD === void 0 ? void 0 : DSQL_DB_PASSWORD.match(/./)) &&
|
||||
(DSQL_DB_NAME === null || DSQL_DB_NAME === void 0 ? void 0 : DSQL_DB_NAME.match(/./))) {
|
||||
/** @type {import("../../../types").DSQL_DatabaseSchemaType | undefined | undefined} */
|
||||
let dbSchema;
|
||||
try {
|
||||
const localDbSchemaPath = path.resolve(process.cwd(), "dsql.schema.json");
|
||||
dbSchema = JSON.parse(fs.readFileSync(localDbSchemaPath, "utf8"));
|
||||
}
|
||||
if (!database || (database === null || database === void 0 ? void 0 : database.match(/ /))) {
|
||||
return {
|
||||
success: false,
|
||||
user: null,
|
||||
msg: "Please provide database slug name you want to access",
|
||||
};
|
||||
}
|
||||
if (!clientId || (clientId === null || clientId === void 0 ? void 0 : clientId.match(/ /))) {
|
||||
return {
|
||||
success: false,
|
||||
user: null,
|
||||
msg: "Please enter Github OAUTH client ID",
|
||||
};
|
||||
}
|
||||
/**
|
||||
* Initialize HTTP response variable
|
||||
*/
|
||||
let httpResponse;
|
||||
/**
|
||||
* Check for local DB settings
|
||||
*
|
||||
* @description Look for local db settings in `.env` file and by pass the http request if available
|
||||
*/
|
||||
const { DSQL_DB_HOST, DSQL_DB_USERNAME, DSQL_DB_PASSWORD, DSQL_DB_NAME, DSQL_KEY, DSQL_REF_DB_NAME, DSQL_FULL_SYNC, } = process.env;
|
||||
if ((DSQL_DB_HOST === null || DSQL_DB_HOST === void 0 ? void 0 : DSQL_DB_HOST.match(/./)) &&
|
||||
(DSQL_DB_USERNAME === null || DSQL_DB_USERNAME === void 0 ? void 0 : DSQL_DB_USERNAME.match(/./)) &&
|
||||
(DSQL_DB_PASSWORD === null || DSQL_DB_PASSWORD === void 0 ? void 0 : DSQL_DB_PASSWORD.match(/./)) &&
|
||||
(DSQL_DB_NAME === null || DSQL_DB_NAME === void 0 ? void 0 : DSQL_DB_NAME.match(/./))) {
|
||||
/** @type {import("../../../types").DSQL_DatabaseSchemaType | undefined | undefined} */
|
||||
let dbSchema;
|
||||
try {
|
||||
const localDbSchemaPath = path_1.default.resolve(process.cwd(), "dsql.schema.json");
|
||||
dbSchema = JSON.parse(fs_1.default.readFileSync(localDbSchemaPath, "utf8"));
|
||||
}
|
||||
catch (error) { }
|
||||
httpResponse = yield (0, api_github_login_1.default)({
|
||||
code,
|
||||
email: email || undefined,
|
||||
clientId,
|
||||
clientSecret,
|
||||
additionalFields,
|
||||
database: DSQL_DB_NAME,
|
||||
additionalData,
|
||||
});
|
||||
}
|
||||
else {
|
||||
/**
|
||||
* Make https request
|
||||
*
|
||||
* @description make a request to datasquirel.com
|
||||
* @type {FunctionReturn} - Https response object
|
||||
*/
|
||||
httpResponse = (yield new Promise((resolve, reject) => {
|
||||
const reqPayload = JSON.stringify({
|
||||
code,
|
||||
email,
|
||||
clientId,
|
||||
clientSecret,
|
||||
database,
|
||||
additionalFields,
|
||||
additionalData,
|
||||
});
|
||||
const httpsRequest = scheme.request({
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Content-Length": Buffer.from(reqPayload).length,
|
||||
Authorization: key ||
|
||||
process.env.DSQL_FULL_ACCESS_API_KEY ||
|
||||
process.env.DSQL_API_KEY,
|
||||
},
|
||||
port,
|
||||
hostname: host,
|
||||
path: `/api/user/${user_id || grabedHostNames.user_id}/github-login`,
|
||||
},
|
||||
/**
|
||||
* Callback Function
|
||||
*
|
||||
* @description https request callback
|
||||
*/
|
||||
(response) => {
|
||||
var str = "";
|
||||
response.on("data", function (chunk) {
|
||||
str += chunk;
|
||||
});
|
||||
response.on("end", function () {
|
||||
var _a;
|
||||
try {
|
||||
resolve(JSON.parse(str));
|
||||
}
|
||||
catch (error) {
|
||||
(_a = global.ERROR_CALLBACK) === null || _a === void 0 ? void 0 : _a.call(global, `Github Auth Error`, error);
|
||||
resolve({
|
||||
success: false,
|
||||
user: null,
|
||||
msg: "Something went wrong",
|
||||
});
|
||||
}
|
||||
});
|
||||
response.on("error", (err) => {
|
||||
reject(err);
|
||||
});
|
||||
});
|
||||
httpsRequest.write(reqPayload);
|
||||
httpsRequest.end();
|
||||
}));
|
||||
}
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
catch (error) { }
|
||||
httpResponse = await apiGithubLogin({
|
||||
code,
|
||||
email: email || undefined,
|
||||
clientId,
|
||||
clientSecret,
|
||||
additionalFields,
|
||||
database: DSQL_DB_NAME,
|
||||
additionalData,
|
||||
});
|
||||
}
|
||||
else {
|
||||
/**
|
||||
* Make https request
|
||||
*
|
||||
* @description make a request to datasquirel.com
|
||||
* @type {FunctionReturn} - Https response object
|
||||
*/
|
||||
if ((httpResponse === null || httpResponse === void 0 ? void 0 : httpResponse.success) && (httpResponse === null || httpResponse === void 0 ? void 0 : httpResponse.user)) {
|
||||
let encryptedPayload = (0, encrypt_1.default)({
|
||||
data: JSON.stringify(httpResponse.user),
|
||||
encryptionKey,
|
||||
encryptionSalt,
|
||||
httpResponse = (await new Promise((resolve, reject) => {
|
||||
const reqPayload = JSON.stringify({
|
||||
code,
|
||||
email,
|
||||
clientId,
|
||||
clientSecret,
|
||||
database,
|
||||
additionalFields,
|
||||
additionalData,
|
||||
});
|
||||
const { user, dsqlUserId } = httpResponse;
|
||||
const authKeyName = `datasquirel_${dsqlUserId}_${database}_auth_key`;
|
||||
const csrfName = `datasquirel_${dsqlUserId}_${database}_csrf`;
|
||||
response.setHeader("Set-Cookie", [
|
||||
`${authKeyName}=${encryptedPayload};samesite=strict;path=/;HttpOnly=true;Expires=${COOKIE_EXPIRY_DATE}${secureCookie ? ";Secure=true" : ""}`,
|
||||
`${csrfName}=${user.csrf_k};samesite=strict;path=/;HttpOnly=true;Expires=${COOKIE_EXPIRY_DATE}`,
|
||||
]);
|
||||
}
|
||||
return httpResponse;
|
||||
});
|
||||
const httpsRequest = scheme.request({
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Content-Length": Buffer.from(reqPayload).length,
|
||||
Authorization: key ||
|
||||
process.env.DSQL_FULL_ACCESS_API_KEY ||
|
||||
process.env.DSQL_API_KEY,
|
||||
},
|
||||
port,
|
||||
hostname: host,
|
||||
path: `/api/user/${user_id || grabedHostNames.user_id}/github-login`,
|
||||
},
|
||||
/**
|
||||
* Callback Function
|
||||
*
|
||||
* @description https request callback
|
||||
*/
|
||||
(response) => {
|
||||
var str = "";
|
||||
response.on("data", function (chunk) {
|
||||
str += chunk;
|
||||
});
|
||||
response.on("end", function () {
|
||||
var _a;
|
||||
try {
|
||||
resolve(JSON.parse(str));
|
||||
}
|
||||
catch (error) {
|
||||
(_a = global.ERROR_CALLBACK) === null || _a === void 0 ? void 0 : _a.call(global, `Github Auth Error`, error);
|
||||
resolve({
|
||||
success: false,
|
||||
user: null,
|
||||
msg: "Something went wrong",
|
||||
});
|
||||
}
|
||||
});
|
||||
response.on("error", (err) => {
|
||||
reject(err);
|
||||
});
|
||||
});
|
||||
httpsRequest.write(reqPayload);
|
||||
httpsRequest.end();
|
||||
}));
|
||||
}
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
/**
|
||||
* Make https request
|
||||
*
|
||||
* @description make a request to datasquirel.com
|
||||
*/
|
||||
if ((httpResponse === null || httpResponse === void 0 ? void 0 : httpResponse.success) && (httpResponse === null || httpResponse === void 0 ? void 0 : httpResponse.user)) {
|
||||
let encryptedPayload = encrypt({
|
||||
data: JSON.stringify(httpResponse.user),
|
||||
encryptionKey,
|
||||
encryptionSalt,
|
||||
});
|
||||
const { user, dsqlUserId } = httpResponse;
|
||||
const authKeyName = `datasquirel_${dsqlUserId}_${database}_auth_key`;
|
||||
const csrfName = `datasquirel_${dsqlUserId}_${database}_csrf`;
|
||||
response.setHeader("Set-Cookie", [
|
||||
`${authKeyName}=${encryptedPayload};samesite=strict;path=/;HttpOnly=true;Expires=${COOKIE_EXPIRY_DATE}${secureCookie ? ";Secure=true" : ""}`,
|
||||
`${csrfName}=${user.csrf_k};samesite=strict;path=/;HttpOnly=true;Expires=${COOKIE_EXPIRY_DATE}`,
|
||||
]);
|
||||
}
|
||||
return httpResponse;
|
||||
}
|
||||
|
@ -1,161 +1,144 @@
|
||||
"use strict";
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = googleAuth;
|
||||
const encrypt_1 = __importDefault(require("../../../functions/dsql/encrypt"));
|
||||
const grab_host_names_1 = __importDefault(require("../../../utils/grab-host-names"));
|
||||
const api_google_login_1 = __importDefault(require("../../../functions/api/users/social/api-google-login"));
|
||||
const get_auth_cookie_names_1 = __importDefault(require("../../../functions/backend/cookies/get-auth-cookie-names"));
|
||||
const write_auth_files_1 = require("../../../functions/backend/auth/write-auth-files");
|
||||
const grab_cookie_expirt_date_1 = __importDefault(require("../../../utils/grab-cookie-expirt-date"));
|
||||
import encrypt from "../../../functions/dsql/encrypt";
|
||||
import grabHostNames from "../../../utils/grab-host-names";
|
||||
import apiGoogleLogin from "../../../functions/api/users/social/api-google-login";
|
||||
import getAuthCookieNames from "../../../functions/backend/cookies/get-auth-cookie-names";
|
||||
import { writeAuthFile } from "../../../functions/backend/auth/write-auth-files";
|
||||
import grabCookieExpiryDate from "../../../utils/grab-cookie-expirt-date";
|
||||
/**
|
||||
* # SERVER FUNCTION: Login with google Function
|
||||
*/
|
||||
function googleAuth(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ key, token, database, response, encryptionKey, encryptionSalt, additionalFields, additionalData, apiUserID, debug, secureCookie, loginOnly, }) {
|
||||
var _b;
|
||||
const grabedHostNames = (0, grab_host_names_1.default)({
|
||||
userId: apiUserID || process.env.DSQL_API_USER_ID,
|
||||
});
|
||||
const { host, port, scheme, user_id } = grabedHostNames;
|
||||
const COOKIE_EXPIRY_DATE = (0, grab_cookie_expirt_date_1.default)();
|
||||
const finalEncryptionKey = encryptionKey || process.env.DSQL_ENCRYPTION_PASSWORD;
|
||||
const finalEncryptionSalt = encryptionSalt || process.env.DSQL_ENCRYPTION_SALT;
|
||||
if (!(finalEncryptionKey === null || finalEncryptionKey === void 0 ? void 0 : finalEncryptionKey.match(/.{8,}/))) {
|
||||
console.log("Encryption key is invalid");
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: "Encryption key is invalid",
|
||||
};
|
||||
}
|
||||
if (!(finalEncryptionSalt === null || finalEncryptionSalt === void 0 ? void 0 : finalEncryptionSalt.match(/.{8,}/))) {
|
||||
console.log("Encryption salt is invalid");
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: "Encryption salt is invalid",
|
||||
};
|
||||
}
|
||||
/**
|
||||
* Check inputs
|
||||
*
|
||||
* @description Check inputs
|
||||
*/
|
||||
if (!token || (token === null || token === void 0 ? void 0 : token.match(/ /))) {
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: "Please enter Google Access Token",
|
||||
};
|
||||
}
|
||||
/**
|
||||
* Initialize HTTP response variable
|
||||
*/
|
||||
let httpResponse = {
|
||||
export default async function googleAuth({ key, token, database, response, encryptionKey, encryptionSalt, additionalFields, additionalData, apiUserID, debug, secureCookie, loginOnly, }) {
|
||||
var _a;
|
||||
const grabedHostNames = grabHostNames({
|
||||
userId: apiUserID || process.env.DSQL_API_USER_ID,
|
||||
});
|
||||
const { host, port, scheme, user_id } = grabedHostNames;
|
||||
const COOKIE_EXPIRY_DATE = grabCookieExpiryDate();
|
||||
const finalEncryptionKey = encryptionKey || process.env.DSQL_ENCRYPTION_PASSWORD;
|
||||
const finalEncryptionSalt = encryptionSalt || process.env.DSQL_ENCRYPTION_SALT;
|
||||
if (!(finalEncryptionKey === null || finalEncryptionKey === void 0 ? void 0 : finalEncryptionKey.match(/.{8,}/))) {
|
||||
console.log("Encryption key is invalid");
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: "Encryption key is invalid",
|
||||
};
|
||||
/**
|
||||
* Check for local DB settings
|
||||
*
|
||||
* @description Look for local db settings in `.env` file and by pass the http request if available
|
||||
*/
|
||||
const { DSQL_DB_HOST, DSQL_DB_USERNAME, DSQL_DB_PASSWORD, DSQL_DB_NAME } = process.env;
|
||||
if ((DSQL_DB_HOST === null || DSQL_DB_HOST === void 0 ? void 0 : DSQL_DB_HOST.match(/./)) &&
|
||||
(DSQL_DB_USERNAME === null || DSQL_DB_USERNAME === void 0 ? void 0 : DSQL_DB_USERNAME.match(/./)) &&
|
||||
(DSQL_DB_PASSWORD === null || DSQL_DB_PASSWORD === void 0 ? void 0 : DSQL_DB_PASSWORD.match(/./)) &&
|
||||
(DSQL_DB_NAME === null || DSQL_DB_NAME === void 0 ? void 0 : DSQL_DB_NAME.match(/./)) &&
|
||||
global.DSQL_USE_LOCAL) {
|
||||
if (debug) {
|
||||
console.log(`Google login with Local Paradigm ...`);
|
||||
}
|
||||
httpResponse = yield (0, api_google_login_1.default)({
|
||||
}
|
||||
if (!(finalEncryptionSalt === null || finalEncryptionSalt === void 0 ? void 0 : finalEncryptionSalt.match(/.{8,}/))) {
|
||||
console.log("Encryption salt is invalid");
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: "Encryption salt is invalid",
|
||||
};
|
||||
}
|
||||
/**
|
||||
* Check inputs
|
||||
*
|
||||
* @description Check inputs
|
||||
*/
|
||||
if (!token || (token === null || token === void 0 ? void 0 : token.match(/ /))) {
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: "Please enter Google Access Token",
|
||||
};
|
||||
}
|
||||
/**
|
||||
* Initialize HTTP response variable
|
||||
*/
|
||||
let httpResponse = {
|
||||
success: false,
|
||||
};
|
||||
/**
|
||||
* Check for local DB settings
|
||||
*
|
||||
* @description Look for local db settings in `.env` file and by pass the http request if available
|
||||
*/
|
||||
const { DSQL_DB_HOST, DSQL_DB_USERNAME, DSQL_DB_PASSWORD, DSQL_DB_NAME } = process.env;
|
||||
if ((DSQL_DB_HOST === null || DSQL_DB_HOST === void 0 ? void 0 : DSQL_DB_HOST.match(/./)) &&
|
||||
(DSQL_DB_USERNAME === null || DSQL_DB_USERNAME === void 0 ? void 0 : DSQL_DB_USERNAME.match(/./)) &&
|
||||
(DSQL_DB_PASSWORD === null || DSQL_DB_PASSWORD === void 0 ? void 0 : DSQL_DB_PASSWORD.match(/./)) &&
|
||||
(DSQL_DB_NAME === null || DSQL_DB_NAME === void 0 ? void 0 : DSQL_DB_NAME.match(/./)) &&
|
||||
global.DSQL_USE_LOCAL) {
|
||||
if (debug) {
|
||||
console.log(`Google login with Local Paradigm ...`);
|
||||
}
|
||||
httpResponse = await apiGoogleLogin({
|
||||
token,
|
||||
additionalFields,
|
||||
additionalData,
|
||||
debug,
|
||||
});
|
||||
}
|
||||
else {
|
||||
httpResponse = await new Promise((resolve, reject) => {
|
||||
const reqPayload = JSON.stringify({
|
||||
token,
|
||||
database,
|
||||
additionalFields,
|
||||
additionalData,
|
||||
debug,
|
||||
});
|
||||
}
|
||||
else {
|
||||
httpResponse = yield new Promise((resolve, reject) => {
|
||||
const reqPayload = JSON.stringify({
|
||||
token,
|
||||
database,
|
||||
additionalFields,
|
||||
additionalData,
|
||||
const httpsRequest = scheme.request({
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Content-Length": Buffer.from(reqPayload).length,
|
||||
Authorization: key ||
|
||||
process.env.DSQL_FULL_ACCESS_API_KEY ||
|
||||
process.env.DSQL_API_KEY,
|
||||
},
|
||||
port,
|
||||
hostname: host,
|
||||
path: `/api/user/${apiUserID || grabedHostNames.user_id}/google-login`,
|
||||
},
|
||||
/**
|
||||
* Callback Function
|
||||
*
|
||||
* @description https request callback
|
||||
*/
|
||||
(response) => {
|
||||
var str = "";
|
||||
response.on("data", function (chunk) {
|
||||
str += chunk;
|
||||
});
|
||||
const httpsRequest = scheme.request({
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Content-Length": Buffer.from(reqPayload).length,
|
||||
Authorization: key ||
|
||||
process.env.DSQL_FULL_ACCESS_API_KEY ||
|
||||
process.env.DSQL_API_KEY,
|
||||
},
|
||||
port,
|
||||
hostname: host,
|
||||
path: `/api/user/${apiUserID || grabedHostNames.user_id}/google-login`,
|
||||
},
|
||||
/**
|
||||
* Callback Function
|
||||
*
|
||||
* @description https request callback
|
||||
*/
|
||||
(response) => {
|
||||
var str = "";
|
||||
response.on("data", function (chunk) {
|
||||
str += chunk;
|
||||
});
|
||||
response.on("end", function () {
|
||||
resolve(JSON.parse(str));
|
||||
});
|
||||
response.on("error", (err) => {
|
||||
reject(err);
|
||||
});
|
||||
response.on("end", function () {
|
||||
resolve(JSON.parse(str));
|
||||
});
|
||||
response.on("error", (err) => {
|
||||
reject(err);
|
||||
});
|
||||
httpsRequest.write(reqPayload);
|
||||
httpsRequest.end();
|
||||
});
|
||||
httpsRequest.write(reqPayload);
|
||||
httpsRequest.end();
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Make https request
|
||||
*
|
||||
* @description make a request to datasquirel.com
|
||||
*/
|
||||
if ((httpResponse === null || httpResponse === void 0 ? void 0 : httpResponse.success) && (httpResponse === null || httpResponse === void 0 ? void 0 : httpResponse.payload)) {
|
||||
let encryptedPayload = encrypt({
|
||||
data: JSON.stringify(httpResponse.payload),
|
||||
encryptionKey: finalEncryptionKey,
|
||||
encryptionSalt: finalEncryptionSalt,
|
||||
});
|
||||
const cookieNames = getAuthCookieNames({
|
||||
database,
|
||||
userId: user_id,
|
||||
});
|
||||
if (httpResponse.csrf) {
|
||||
writeAuthFile(httpResponse.csrf, JSON.stringify(httpResponse.payload));
|
||||
}
|
||||
/**
|
||||
* Make https request
|
||||
*
|
||||
* @description make a request to datasquirel.com
|
||||
*/
|
||||
if ((httpResponse === null || httpResponse === void 0 ? void 0 : httpResponse.success) && (httpResponse === null || httpResponse === void 0 ? void 0 : httpResponse.payload)) {
|
||||
let encryptedPayload = (0, encrypt_1.default)({
|
||||
data: JSON.stringify(httpResponse.payload),
|
||||
encryptionKey: finalEncryptionKey,
|
||||
encryptionSalt: finalEncryptionSalt,
|
||||
});
|
||||
const cookieNames = (0, get_auth_cookie_names_1.default)({
|
||||
database,
|
||||
userId: user_id,
|
||||
});
|
||||
if (httpResponse.csrf) {
|
||||
(0, write_auth_files_1.writeAuthFile)(httpResponse.csrf, JSON.stringify(httpResponse.payload));
|
||||
}
|
||||
httpResponse["cookieNames"] = cookieNames;
|
||||
httpResponse["key"] = String(encryptedPayload);
|
||||
const authKeyName = cookieNames.keyCookieName;
|
||||
const csrfName = cookieNames.csrfCookieName;
|
||||
response === null || response === void 0 ? void 0 : response.setHeader("Set-Cookie", [
|
||||
`${authKeyName}=${encryptedPayload};samesite=strict;path=/;HttpOnly=true;;Expires=${COOKIE_EXPIRY_DATE}${secureCookie ? ";Secure=true" : ""}`,
|
||||
`${csrfName}=${(_b = httpResponse.payload) === null || _b === void 0 ? void 0 : _b.csrf_k};samesite=strict;path=/;HttpOnly=true;;Expires=${COOKIE_EXPIRY_DATE}`,
|
||||
]);
|
||||
}
|
||||
return httpResponse;
|
||||
});
|
||||
httpResponse["cookieNames"] = cookieNames;
|
||||
httpResponse["key"] = String(encryptedPayload);
|
||||
const authKeyName = cookieNames.keyCookieName;
|
||||
const csrfName = cookieNames.csrfCookieName;
|
||||
response === null || response === void 0 ? void 0 : response.setHeader("Set-Cookie", [
|
||||
`${authKeyName}=${encryptedPayload};samesite=strict;path=/;HttpOnly=true;;Expires=${COOKIE_EXPIRY_DATE}${secureCookie ? ";Secure=true" : ""}`,
|
||||
`${csrfName}=${(_a = httpResponse.payload) === null || _a === void 0 ? void 0 : _a.csrf_k};samesite=strict;path=/;HttpOnly=true;;Expires=${COOKIE_EXPIRY_DATE}`,
|
||||
]);
|
||||
}
|
||||
return httpResponse;
|
||||
}
|
||||
|
165
dist/package-shared/actions/users/update-user.js
vendored
165
dist/package-shared/actions/users/update-user.js
vendored
@ -1,98 +1,81 @@
|
||||
"use strict";
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = updateUser;
|
||||
const path_1 = __importDefault(require("path"));
|
||||
const fs_1 = __importDefault(require("fs"));
|
||||
const grab_host_names_1 = __importDefault(require("../../utils/grab-host-names"));
|
||||
const api_update_user_1 = __importDefault(require("../../functions/api/users/api-update-user"));
|
||||
import path from "path";
|
||||
import fs from "fs";
|
||||
import grabHostNames from "../../utils/grab-host-names";
|
||||
import apiUpdateUser from "../../functions/api/users/api-update-user";
|
||||
/**
|
||||
* # Update User
|
||||
*/
|
||||
function updateUser(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ key, payload, database, user_id, updatedUserId, }) {
|
||||
/**
|
||||
* Check for local DB settings
|
||||
*
|
||||
* @description Look for local db settings in `.env` file and by pass the http request if available
|
||||
*/
|
||||
const { DSQL_DB_HOST, DSQL_DB_USERNAME, DSQL_DB_PASSWORD, DSQL_DB_NAME } = process.env;
|
||||
const grabedHostNames = (0, grab_host_names_1.default)();
|
||||
const { host, port, scheme } = grabedHostNames;
|
||||
if ((DSQL_DB_HOST === null || DSQL_DB_HOST === void 0 ? void 0 : DSQL_DB_HOST.match(/./)) &&
|
||||
(DSQL_DB_USERNAME === null || DSQL_DB_USERNAME === void 0 ? void 0 : DSQL_DB_USERNAME.match(/./)) &&
|
||||
(DSQL_DB_PASSWORD === null || DSQL_DB_PASSWORD === void 0 ? void 0 : DSQL_DB_PASSWORD.match(/./)) &&
|
||||
(DSQL_DB_NAME === null || DSQL_DB_NAME === void 0 ? void 0 : DSQL_DB_NAME.match(/./)) &&
|
||||
global.DSQL_USE_LOCAL) {
|
||||
/** @type {import("../../types").DSQL_DatabaseSchemaType | undefined} */
|
||||
let dbSchema;
|
||||
try {
|
||||
const localDbSchemaPath = path_1.default.resolve(process.cwd(), "dsql.schema.json");
|
||||
dbSchema = JSON.parse(fs_1.default.readFileSync(localDbSchemaPath, "utf8"));
|
||||
}
|
||||
catch (error) { }
|
||||
return yield (0, api_update_user_1.default)({
|
||||
payload: payload,
|
||||
dbFullName: DSQL_DB_NAME,
|
||||
updatedUserId,
|
||||
dbSchema,
|
||||
});
|
||||
export default async function updateUser({ key, payload, database, user_id, updatedUserId, }) {
|
||||
/**
|
||||
* Check for local DB settings
|
||||
*
|
||||
* @description Look for local db settings in `.env` file and by pass the http request if available
|
||||
*/
|
||||
const { DSQL_DB_HOST, DSQL_DB_USERNAME, DSQL_DB_PASSWORD, DSQL_DB_NAME } = process.env;
|
||||
const grabedHostNames = grabHostNames();
|
||||
const { host, port, scheme } = grabedHostNames;
|
||||
if ((DSQL_DB_HOST === null || DSQL_DB_HOST === void 0 ? void 0 : DSQL_DB_HOST.match(/./)) &&
|
||||
(DSQL_DB_USERNAME === null || DSQL_DB_USERNAME === void 0 ? void 0 : DSQL_DB_USERNAME.match(/./)) &&
|
||||
(DSQL_DB_PASSWORD === null || DSQL_DB_PASSWORD === void 0 ? void 0 : DSQL_DB_PASSWORD.match(/./)) &&
|
||||
(DSQL_DB_NAME === null || DSQL_DB_NAME === void 0 ? void 0 : DSQL_DB_NAME.match(/./)) &&
|
||||
global.DSQL_USE_LOCAL) {
|
||||
/** @type {import("../../types").DSQL_DatabaseSchemaType | undefined} */
|
||||
let dbSchema;
|
||||
try {
|
||||
const localDbSchemaPath = path.resolve(process.cwd(), "dsql.schema.json");
|
||||
dbSchema = JSON.parse(fs.readFileSync(localDbSchemaPath, "utf8"));
|
||||
}
|
||||
/**
|
||||
* Make https request
|
||||
*
|
||||
* @description make a request to datasquirel.com
|
||||
*/
|
||||
const httpResponse = yield new Promise((resolve, reject) => {
|
||||
const reqPayload = JSON.stringify({
|
||||
payload,
|
||||
database,
|
||||
updatedUserId,
|
||||
});
|
||||
const httpsRequest = scheme.request({
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Content-Length": Buffer.from(reqPayload).length,
|
||||
Authorization: process.env.DSQL_FULL_ACCESS_API_KEY ||
|
||||
process.env.DSQL_API_KEY ||
|
||||
key,
|
||||
},
|
||||
port,
|
||||
hostname: host,
|
||||
path: `/api/user/${user_id || grabedHostNames.user_id}/update-user`,
|
||||
},
|
||||
/**
|
||||
* Callback Function
|
||||
*
|
||||
* @description https request callback
|
||||
*/
|
||||
(response) => {
|
||||
var str = "";
|
||||
response.on("data", function (chunk) {
|
||||
str += chunk;
|
||||
});
|
||||
response.on("end", function () {
|
||||
resolve(JSON.parse(str));
|
||||
});
|
||||
response.on("error", (err) => {
|
||||
reject(err);
|
||||
});
|
||||
});
|
||||
httpsRequest.write(reqPayload);
|
||||
httpsRequest.end();
|
||||
catch (error) { }
|
||||
return await apiUpdateUser({
|
||||
payload: payload,
|
||||
dbFullName: DSQL_DB_NAME,
|
||||
updatedUserId,
|
||||
dbSchema,
|
||||
});
|
||||
return httpResponse;
|
||||
}
|
||||
/**
|
||||
* Make https request
|
||||
*
|
||||
* @description make a request to datasquirel.com
|
||||
*/
|
||||
const httpResponse = await new Promise((resolve, reject) => {
|
||||
const reqPayload = JSON.stringify({
|
||||
payload,
|
||||
database,
|
||||
updatedUserId,
|
||||
});
|
||||
const httpsRequest = scheme.request({
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Content-Length": Buffer.from(reqPayload).length,
|
||||
Authorization: process.env.DSQL_FULL_ACCESS_API_KEY ||
|
||||
process.env.DSQL_API_KEY ||
|
||||
key,
|
||||
},
|
||||
port,
|
||||
hostname: host,
|
||||
path: `/api/user/${user_id || grabedHostNames.user_id}/update-user`,
|
||||
},
|
||||
/**
|
||||
* Callback Function
|
||||
*
|
||||
* @description https request callback
|
||||
*/
|
||||
(response) => {
|
||||
var str = "";
|
||||
response.on("data", function (chunk) {
|
||||
str += chunk;
|
||||
});
|
||||
response.on("end", function () {
|
||||
resolve(JSON.parse(str));
|
||||
});
|
||||
response.on("error", (err) => {
|
||||
reject(err);
|
||||
});
|
||||
});
|
||||
httpsRequest.write(reqPayload);
|
||||
httpsRequest.end();
|
||||
});
|
||||
return httpResponse;
|
||||
}
|
||||
|
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";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = userAuth;
|
||||
const decrypt_1 = __importDefault(require("../../functions/dsql/decrypt"));
|
||||
const get_auth_cookie_names_1 = __importDefault(require("../../functions/backend/cookies/get-auth-cookie-names"));
|
||||
const write_auth_files_1 = require("../../functions/backend/auth/write-auth-files");
|
||||
const parseCookies_1 = __importDefault(require("../../utils/backend/parseCookies"));
|
||||
const get_csrf_header_name_1 = __importDefault(require("../../actions/get-csrf-header-name"));
|
||||
const grab_host_names_1 = __importDefault(require("../../utils/grab-host-names"));
|
||||
const debug_log_1 = __importDefault(require("../../utils/logging/debug-log"));
|
||||
import decrypt from "../../functions/dsql/decrypt";
|
||||
import getAuthCookieNames from "../../functions/backend/cookies/get-auth-cookie-names";
|
||||
import { checkAuthFile } from "../../functions/backend/auth/write-auth-files";
|
||||
import parseCookies from "../../utils/backend/parseCookies";
|
||||
import getCsrfHeaderName from "../../actions/get-csrf-header-name";
|
||||
import grabHostNames from "../../utils/grab-host-names";
|
||||
import debugLog from "../../utils/logging/debug-log";
|
||||
const minuteInMilliseconds = 60000;
|
||||
const hourInMilliseconds = minuteInMilliseconds * 60;
|
||||
const dayInMilliseconds = hourInMilliseconds * 24;
|
||||
@ -23,28 +17,28 @@ const yearInMilliseconds = dayInMilliseconds * 365;
|
||||
* @description This Function takes in a request object and returns a user object
|
||||
* with the user's data
|
||||
*/
|
||||
function userAuth({ request, req, encryptionKey, encryptionSalt, level, database, dsqlUserId, encryptedUserString, expiry = weekInMilliseconds, cookieString, csrfHeaderName, debug, skipFileCheck, }) {
|
||||
export default function userAuth({ request, req, encryptionKey, encryptionSalt, level, database, dsqlUserId, encryptedUserString, expiry = weekInMilliseconds, cookieString, csrfHeaderName, debug, skipFileCheck, }) {
|
||||
var _a;
|
||||
try {
|
||||
const finalRequest = req || request;
|
||||
const { user_id } = (0, grab_host_names_1.default)({ userId: dsqlUserId });
|
||||
const cookies = (0, parseCookies_1.default)({
|
||||
const { user_id } = grabHostNames({ userId: dsqlUserId });
|
||||
const cookies = parseCookies({
|
||||
request: finalRequest,
|
||||
cookieString,
|
||||
});
|
||||
if (debug) {
|
||||
(0, debug_log_1.default)({
|
||||
debugLog({
|
||||
log: cookies,
|
||||
addTime: true,
|
||||
label: "userAuth:cookies",
|
||||
});
|
||||
}
|
||||
const keyNames = (0, get_auth_cookie_names_1.default)({
|
||||
const keyNames = getAuthCookieNames({
|
||||
userId: user_id,
|
||||
database: database || process.env.DSQL_DB_NAME,
|
||||
});
|
||||
if (debug) {
|
||||
(0, debug_log_1.default)({
|
||||
debugLog({
|
||||
log: keyNames,
|
||||
addTime: true,
|
||||
label: "userAuth:keyNames",
|
||||
@ -54,7 +48,7 @@ function userAuth({ request, req, encryptionKey, encryptionSalt, level, database
|
||||
? encryptedUserString
|
||||
: cookies[keyNames.keyCookieName];
|
||||
if (debug) {
|
||||
(0, debug_log_1.default)({
|
||||
debugLog({
|
||||
log: key,
|
||||
addTime: true,
|
||||
label: "userAuth:key",
|
||||
@ -65,13 +59,13 @@ function userAuth({ request, req, encryptionKey, encryptionSalt, level, database
|
||||
*
|
||||
* @description Grab the payload
|
||||
*/
|
||||
let userPayloadJSON = (0, decrypt_1.default)({
|
||||
let userPayloadJSON = decrypt({
|
||||
encryptedString: key,
|
||||
encryptionKey,
|
||||
encryptionSalt,
|
||||
});
|
||||
if (debug) {
|
||||
(0, debug_log_1.default)({
|
||||
debugLog({
|
||||
log: userPayloadJSON,
|
||||
addTime: true,
|
||||
label: "userAuth:userPayloadJSON",
|
||||
@ -92,7 +86,7 @@ function userAuth({ request, req, encryptionKey, encryptionSalt, level, database
|
||||
}
|
||||
let userObject = JSON.parse(userPayloadJSON);
|
||||
if (debug) {
|
||||
(0, debug_log_1.default)({
|
||||
debugLog({
|
||||
log: userObject,
|
||||
addTime: true,
|
||||
label: "userAuth:userObject",
|
||||
@ -106,7 +100,7 @@ function userAuth({ request, req, encryptionKey, encryptionSalt, level, database
|
||||
cookieNames: keyNames,
|
||||
};
|
||||
}
|
||||
if (!skipFileCheck && !(0, write_auth_files_1.checkAuthFile)(userObject.csrf_k)) {
|
||||
if (!skipFileCheck && !checkAuthFile(userObject.csrf_k)) {
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
@ -120,7 +114,7 @@ function userAuth({ request, req, encryptionKey, encryptionSalt, level, database
|
||||
* @description Grab the payload
|
||||
*/
|
||||
if ((level === null || level === void 0 ? void 0 : level.match(/deep/i)) && finalRequest) {
|
||||
const finalCsrfHeaderName = csrfHeaderName || (0, get_csrf_header_name_1.default)();
|
||||
const finalCsrfHeaderName = csrfHeaderName || getCsrfHeaderName();
|
||||
if (finalRequest.headers[finalCsrfHeaderName] !== userObject.csrf_k) {
|
||||
return {
|
||||
success: false,
|
||||
|
@ -1,49 +1,32 @@
|
||||
"use strict";
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = validateTempEmailCode;
|
||||
const get_auth_cookie_names_1 = __importDefault(require("../../functions/backend/cookies/get-auth-cookie-names"));
|
||||
const parseCookies_1 = __importDefault(require("../../utils/backend/parseCookies"));
|
||||
const decrypt_1 = __importDefault(require("../../functions/dsql/decrypt"));
|
||||
const ejson_1 = __importDefault(require("../../utils/ejson"));
|
||||
import getAuthCookieNames from "../../functions/backend/cookies/get-auth-cookie-names";
|
||||
import parseCookies from "../../utils/backend/parseCookies";
|
||||
import decrypt from "../../functions/dsql/decrypt";
|
||||
import EJSON from "../../utils/ejson";
|
||||
/**
|
||||
* # Verify the temp email code sent to the user's email address
|
||||
*/
|
||||
function validateTempEmailCode(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ request, email, cookieString, }) {
|
||||
var _b;
|
||||
try {
|
||||
const keyNames = (0, get_auth_cookie_names_1.default)();
|
||||
const oneTimeCodeCookieName = keyNames.oneTimeCodeName;
|
||||
const cookies = (0, parseCookies_1.default)({ request, cookieString });
|
||||
const encryptedOneTimeCode = cookies[oneTimeCodeCookieName];
|
||||
const encryptedPayload = (0, decrypt_1.default)({
|
||||
encryptedString: encryptedOneTimeCode,
|
||||
});
|
||||
const payload = ejson_1.default.parse(encryptedPayload);
|
||||
if ((payload === null || payload === void 0 ? void 0 : payload.email) && !email) {
|
||||
return payload;
|
||||
}
|
||||
if ((payload === null || payload === void 0 ? void 0 : payload.email) && payload.email === email) {
|
||||
return payload;
|
||||
}
|
||||
return null;
|
||||
export default async function validateTempEmailCode({ request, email, cookieString, }) {
|
||||
var _a;
|
||||
try {
|
||||
const keyNames = getAuthCookieNames();
|
||||
const oneTimeCodeCookieName = keyNames.oneTimeCodeName;
|
||||
const cookies = parseCookies({ request, cookieString });
|
||||
const encryptedOneTimeCode = cookies[oneTimeCodeCookieName];
|
||||
const encryptedPayload = decrypt({
|
||||
encryptedString: encryptedOneTimeCode,
|
||||
});
|
||||
const payload = EJSON.parse(encryptedPayload);
|
||||
if ((payload === null || payload === void 0 ? void 0 : payload.email) && !email) {
|
||||
return payload;
|
||||
}
|
||||
catch (error) {
|
||||
(_b = global.ERROR_CALLBACK) === null || _b === void 0 ? void 0 : _b.call(global, `Validate Temp Email Code Error`, error);
|
||||
console.log("validateTempEmailCode error:", error.message);
|
||||
return null;
|
||||
if ((payload === null || payload === void 0 ? void 0 : payload.email) && payload.email === email) {
|
||||
return payload;
|
||||
}
|
||||
});
|
||||
return null;
|
||||
}
|
||||
catch (error) {
|
||||
(_a = global.ERROR_CALLBACK) === null || _a === void 0 ? void 0 : _a.call(global, `Validate Temp Email Code Error`, error);
|
||||
console.log("validateTempEmailCode error:", error.message);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
@ -1,16 +1,10 @@
|
||||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = validateToken;
|
||||
const decrypt_1 = __importDefault(require("../../functions/dsql/decrypt"));
|
||||
import decrypt from "../../functions/dsql/decrypt";
|
||||
/**
|
||||
* Validate Token
|
||||
* ======================================
|
||||
* @description This Function takes in a encrypted token and returns a user object
|
||||
*/
|
||||
function validateToken({ token, encryptionKey, encryptionSalt, }) {
|
||||
export default function validateToken({ token, encryptionKey, encryptionSalt, }) {
|
||||
var _a;
|
||||
try {
|
||||
/**
|
||||
@ -24,7 +18,7 @@ function validateToken({ token, encryptionKey, encryptionSalt, }) {
|
||||
*
|
||||
* @description Grab the payload
|
||||
*/
|
||||
let userPayload = (0, decrypt_1.default)({
|
||||
let userPayload = decrypt({
|
||||
encryptedString: key,
|
||||
encryptionKey,
|
||||
encryptionSalt,
|
||||
|
21
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",
|
||||
"decimals": "1-4"
|
||||
},
|
||||
{
|
||||
"title": "OPTIONS",
|
||||
"name": "VARCHAR",
|
||||
"value": "250",
|
||||
"argument": true,
|
||||
"description": "This is a custom field which is a varchar under the hood",
|
||||
"maxValue": 255
|
||||
},
|
||||
{
|
||||
"title": "UUID",
|
||||
"name": "UUID",
|
||||
|
8
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,
|
||||
};
|
||||
}
|
||||
}
|
158
dist/package-shared/functions/api/query/get.js
vendored
158
dist/package-shared/functions/api/query/get.js
vendored
@ -1,94 +1,74 @@
|
||||
"use strict";
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = apiGet;
|
||||
const lodash_1 = __importDefault(require("lodash"));
|
||||
const serverError_1 = __importDefault(require("../../backend/serverError"));
|
||||
const runQuery_1 = __importDefault(require("../../backend/db/runQuery"));
|
||||
const grab_query_and_values_1 = __importDefault(require("../../../utils/grab-query-and-values"));
|
||||
import _ from "lodash";
|
||||
import serverError from "../../backend/serverError";
|
||||
import runQuery from "../../backend/db/runQuery";
|
||||
import apiGetGrabQueryAndValues from "../../../utils/grab-query-and-values";
|
||||
/**
|
||||
* # Get Function FOr API
|
||||
*/
|
||||
function apiGet(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ query, dbFullName, queryValues, tableName, dbSchema, debug, dbContext, forceLocal, }) {
|
||||
var _b, _c;
|
||||
const queryAndValues = (0, grab_query_and_values_1.default)({
|
||||
query,
|
||||
values: queryValues,
|
||||
});
|
||||
if (typeof query == "string" && query.match(/^alter|^delete|^create/i)) {
|
||||
return { success: false, msg: "Wrong Input." };
|
||||
}
|
||||
let results;
|
||||
try {
|
||||
let { result, error } = yield (0, runQuery_1.default)({
|
||||
dbFullName: dbFullName,
|
||||
query: queryAndValues.query,
|
||||
queryValuesArray: queryAndValues.values,
|
||||
readOnly: true,
|
||||
dbSchema,
|
||||
tableName,
|
||||
dbContext,
|
||||
debug,
|
||||
forceLocal,
|
||||
});
|
||||
if (debug && global.DSQL_USE_LOCAL) {
|
||||
console.log("apiGet:result", result);
|
||||
console.log("apiGet:error", error);
|
||||
}
|
||||
let tableSchema;
|
||||
if (dbSchema) {
|
||||
const targetTable = (_b = dbSchema.tables) === null || _b === void 0 ? void 0 : _b.find((table) => table.tableName === tableName);
|
||||
if (targetTable) {
|
||||
const clonedTargetTable = lodash_1.default.cloneDeep(targetTable);
|
||||
delete clonedTargetTable.childTable;
|
||||
delete clonedTargetTable.childTableDbFullName;
|
||||
delete clonedTargetTable.childTableName;
|
||||
delete clonedTargetTable.childrenTables;
|
||||
delete clonedTargetTable.updateData;
|
||||
delete clonedTargetTable.tableNameOld;
|
||||
delete clonedTargetTable.indexes;
|
||||
tableSchema = clonedTargetTable;
|
||||
}
|
||||
}
|
||||
if (error)
|
||||
throw error;
|
||||
if (result.error)
|
||||
throw new Error(result.error);
|
||||
results = result;
|
||||
const resObject = {
|
||||
success: true,
|
||||
payload: results,
|
||||
schema: tableName && tableSchema ? tableSchema : undefined,
|
||||
};
|
||||
return resObject;
|
||||
}
|
||||
catch (error) {
|
||||
(0, serverError_1.default)({
|
||||
component: "/api/query/get/lines-85-94",
|
||||
message: error.message,
|
||||
});
|
||||
(_c = global.ERROR_CALLBACK) === null || _c === void 0 ? void 0 : _c.call(global, `API Get Error`, error);
|
||||
if (debug && global.DSQL_USE_LOCAL) {
|
||||
console.log("apiGet:error", error.message);
|
||||
console.log("queryAndValues", queryAndValues);
|
||||
}
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
error: error.message,
|
||||
};
|
||||
}
|
||||
export default async function apiGet({ query, dbFullName, queryValues, tableName, dbSchema, debug, dbContext, forceLocal, }) {
|
||||
var _a, _b;
|
||||
const queryAndValues = apiGetGrabQueryAndValues({
|
||||
query,
|
||||
values: queryValues,
|
||||
});
|
||||
if (typeof query == "string" && query.match(/^alter|^delete|^create/i)) {
|
||||
return { success: false, msg: "Wrong Input." };
|
||||
}
|
||||
let results;
|
||||
try {
|
||||
let { result, error } = await runQuery({
|
||||
dbFullName: dbFullName,
|
||||
query: queryAndValues.query,
|
||||
queryValuesArray: queryAndValues.values,
|
||||
readOnly: true,
|
||||
dbSchema,
|
||||
tableName,
|
||||
dbContext,
|
||||
debug,
|
||||
forceLocal,
|
||||
});
|
||||
if (debug && global.DSQL_USE_LOCAL) {
|
||||
console.log("apiGet:result", result);
|
||||
console.log("apiGet:error", error);
|
||||
}
|
||||
let tableSchema;
|
||||
if (dbSchema) {
|
||||
const targetTable = (_a = dbSchema.tables) === null || _a === void 0 ? void 0 : _a.find((table) => table.tableName === tableName);
|
||||
if (targetTable) {
|
||||
const clonedTargetTable = _.cloneDeep(targetTable);
|
||||
delete clonedTargetTable.childTable;
|
||||
delete clonedTargetTable.childrenTables;
|
||||
delete clonedTargetTable.updateData;
|
||||
delete clonedTargetTable.indexes;
|
||||
tableSchema = clonedTargetTable;
|
||||
}
|
||||
}
|
||||
if (error)
|
||||
throw error;
|
||||
if (result.error)
|
||||
throw new Error(result.error);
|
||||
results = result;
|
||||
const resObject = {
|
||||
success: true,
|
||||
payload: results,
|
||||
schema: tableName && tableSchema ? tableSchema : undefined,
|
||||
};
|
||||
return resObject;
|
||||
}
|
||||
catch (error) {
|
||||
serverError({
|
||||
component: "/api/query/get/lines-85-94",
|
||||
message: error.message,
|
||||
});
|
||||
(_b = global.ERROR_CALLBACK) === null || _b === void 0 ? void 0 : _b.call(global, `API Get Error`, error);
|
||||
if (debug && global.DSQL_USE_LOCAL) {
|
||||
console.log("apiGet:error", error.message);
|
||||
console.log("queryAndValues", queryAndValues);
|
||||
}
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
error: error.message,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
166
dist/package-shared/functions/api/query/post.js
vendored
166
dist/package-shared/functions/api/query/post.js
vendored
@ -1,100 +1,80 @@
|
||||
"use strict";
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = apiPost;
|
||||
const lodash_1 = __importDefault(require("lodash"));
|
||||
const serverError_1 = __importDefault(require("../../backend/serverError"));
|
||||
const runQuery_1 = __importDefault(require("../../backend/db/runQuery"));
|
||||
const debug_log_1 = __importDefault(require("../../../utils/logging/debug-log"));
|
||||
import _ from "lodash";
|
||||
import serverError from "../../backend/serverError";
|
||||
import runQuery from "../../backend/db/runQuery";
|
||||
import debugLog from "../../../utils/logging/debug-log";
|
||||
/**
|
||||
* # Post Function For API
|
||||
*/
|
||||
function apiPost(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ query, dbFullName, queryValues, tableName, dbSchema, dbContext, forceLocal, debug, }) {
|
||||
var _b, _c;
|
||||
if (typeof query === "string" && (query === null || query === void 0 ? void 0 : query.match(/^create |^alter |^drop /i))) {
|
||||
return { success: false, msg: "Wrong Input" };
|
||||
}
|
||||
if (typeof query === "object" &&
|
||||
((_b = query === null || query === void 0 ? void 0 : query.action) === null || _b === void 0 ? void 0 : _b.match(/^create |^alter |^drop /i))) {
|
||||
return { success: false, msg: "Wrong Input" };
|
||||
}
|
||||
let results;
|
||||
/**
|
||||
* Create new user folder and file
|
||||
*
|
||||
* @description Create new user folder and file
|
||||
*/
|
||||
try {
|
||||
let { result, error } = yield (0, runQuery_1.default)({
|
||||
dbFullName: dbFullName,
|
||||
query: query,
|
||||
dbSchema: dbSchema,
|
||||
queryValuesArray: queryValues,
|
||||
tableName,
|
||||
dbContext,
|
||||
forceLocal,
|
||||
debug,
|
||||
export default async function apiPost({ query, dbFullName, queryValues, tableName, dbSchema, dbContext, forceLocal, debug, }) {
|
||||
var _a, _b;
|
||||
if (typeof query === "string" && (query === null || query === void 0 ? void 0 : query.match(/^create |^alter |^drop /i))) {
|
||||
return { success: false, msg: "Wrong Input" };
|
||||
}
|
||||
if (typeof query === "object" &&
|
||||
((_a = query === null || query === void 0 ? void 0 : query.action) === null || _a === void 0 ? void 0 : _a.match(/^create |^alter |^drop /i))) {
|
||||
return { success: false, msg: "Wrong Input" };
|
||||
}
|
||||
let results;
|
||||
/**
|
||||
* Create new user folder and file
|
||||
*
|
||||
* @description Create new user folder and file
|
||||
*/
|
||||
try {
|
||||
let { result, error } = await runQuery({
|
||||
dbFullName,
|
||||
query,
|
||||
dbSchema,
|
||||
queryValuesArray: queryValues,
|
||||
tableName,
|
||||
dbContext,
|
||||
forceLocal,
|
||||
debug,
|
||||
});
|
||||
if (debug) {
|
||||
debugLog({
|
||||
log: result,
|
||||
addTime: true,
|
||||
label: "result",
|
||||
});
|
||||
if (debug) {
|
||||
(0, debug_log_1.default)({
|
||||
log: result,
|
||||
addTime: true,
|
||||
label: "result",
|
||||
});
|
||||
(0, debug_log_1.default)({
|
||||
log: query,
|
||||
addTime: true,
|
||||
label: "query",
|
||||
});
|
||||
}
|
||||
results = result;
|
||||
if (error)
|
||||
throw new Error(error);
|
||||
let tableSchema;
|
||||
if (dbSchema) {
|
||||
const targetTable = dbSchema.tables.find((table) => table.tableName === tableName);
|
||||
if (targetTable) {
|
||||
const clonedTargetTable = lodash_1.default.cloneDeep(targetTable);
|
||||
delete clonedTargetTable.childTable;
|
||||
delete clonedTargetTable.childTableDbFullName;
|
||||
delete clonedTargetTable.childTableName;
|
||||
delete clonedTargetTable.childrenTables;
|
||||
delete clonedTargetTable.updateData;
|
||||
delete clonedTargetTable.tableNameOld;
|
||||
delete clonedTargetTable.indexes;
|
||||
tableSchema = clonedTargetTable;
|
||||
}
|
||||
}
|
||||
return {
|
||||
success: true,
|
||||
payload: results,
|
||||
error: error,
|
||||
schema: tableName && tableSchema ? tableSchema : undefined,
|
||||
};
|
||||
}
|
||||
catch (error) {
|
||||
(0, serverError_1.default)({
|
||||
component: "/api/query/post/lines-132-142",
|
||||
message: error.message,
|
||||
debugLog({
|
||||
log: query,
|
||||
addTime: true,
|
||||
label: "query",
|
||||
});
|
||||
(_c = global.ERROR_CALLBACK) === null || _c === void 0 ? void 0 : _c.call(global, `API Post Error`, error);
|
||||
return {
|
||||
success: false,
|
||||
payload: results,
|
||||
error: error.message,
|
||||
};
|
||||
}
|
||||
});
|
||||
results = result;
|
||||
if (error)
|
||||
throw new Error(error);
|
||||
let tableSchema;
|
||||
if (dbSchema) {
|
||||
const targetTable = dbSchema.tables.find((table) => table.tableName === tableName);
|
||||
if (targetTable) {
|
||||
const clonedTargetTable = _.cloneDeep(targetTable);
|
||||
delete clonedTargetTable.childTable;
|
||||
delete clonedTargetTable.childrenTables;
|
||||
delete clonedTargetTable.updateData;
|
||||
delete clonedTargetTable.indexes;
|
||||
tableSchema = clonedTargetTable;
|
||||
}
|
||||
}
|
||||
return {
|
||||
success: true,
|
||||
payload: results,
|
||||
error: error,
|
||||
schema: tableName && tableSchema ? tableSchema : undefined,
|
||||
};
|
||||
}
|
||||
catch (error) {
|
||||
serverError({
|
||||
component: "/api/query/post/lines-132-142",
|
||||
message: error.message,
|
||||
});
|
||||
(_b = global.ERROR_CALLBACK) === null || _b === void 0 ? void 0 : _b.call(global, `API Post Error`, error);
|
||||
return {
|
||||
success: false,
|
||||
payload: results,
|
||||
error: error.message,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
@ -1,35 +1,19 @@
|
||||
"use strict";
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = facebookLogin;
|
||||
const DB_HANDLER_1 = __importDefault(require("../../../utils/backend/global-db/DB_HANDLER"));
|
||||
const serverError_1 = __importDefault(require("../../backend/serverError"));
|
||||
const hashPassword_1 = __importDefault(require("../../dsql/hashPassword"));
|
||||
import DB_HANDLER from "../../../utils/backend/global-db/DB_HANDLER";
|
||||
import serverError from "../../backend/serverError";
|
||||
import hashPassword from "../../dsql/hashPassword";
|
||||
/**
|
||||
* # Facebook Login
|
||||
*/
|
||||
function facebookLogin(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ usertype, body, }) {
|
||||
try {
|
||||
const foundUser = yield (0, DB_HANDLER_1.default)(`SELECT * FROM users WHERE email='${body.facebookUserEmail}' AND social_login='1'`);
|
||||
if (foundUser && foundUser[0]) {
|
||||
return foundUser[0];
|
||||
}
|
||||
let socialHashedPassword = (0, hashPassword_1.default)({
|
||||
password: body.facebookUserId,
|
||||
});
|
||||
let newUser = yield (0, DB_HANDLER_1.default)(`INSERT INTO ${usertype} (
|
||||
export default async function facebookLogin({ usertype, body, }) {
|
||||
try {
|
||||
const foundUser = await DB_HANDLER(`SELECT * FROM users WHERE email='${body.facebookUserEmail}' AND social_login='1'`);
|
||||
if (foundUser && foundUser[0]) {
|
||||
return foundUser[0];
|
||||
}
|
||||
let socialHashedPassword = hashPassword({
|
||||
password: body.facebookUserId,
|
||||
});
|
||||
let newUser = await DB_HANDLER(`INSERT INTO ${usertype} (
|
||||
first_name,
|
||||
last_name,
|
||||
social_platform,
|
||||
@ -49,8 +33,8 @@ function facebookLogin(_a) {
|
||||
'${body.facebookUserLastName}',
|
||||
'facebook',
|
||||
'facebook_${body.facebookUserEmail
|
||||
? body.facebookUserEmail.replace(/@.*/, "")
|
||||
: body.facebookUserFirstName.toLowerCase()}',
|
||||
? body.facebookUserEmail.replace(/@.*/, "")
|
||||
: body.facebookUserFirstName.toLowerCase()}',
|
||||
'${body.facebookUserEmail}',
|
||||
'${body.facebookUserImage}',
|
||||
'${body.facebookUserImage}',
|
||||
@ -62,17 +46,16 @@ function facebookLogin(_a) {
|
||||
'${Date()}',
|
||||
'${Date.now()}'
|
||||
)`);
|
||||
const newFoundUser = yield (0, DB_HANDLER_1.default)(`SELECT * FROM ${usertype} WHERE id='${newUser.insertId}'`);
|
||||
}
|
||||
catch ( /** @type {any} */error) {
|
||||
(0, serverError_1.default)({
|
||||
component: "functions/backend/facebookLogin",
|
||||
message: error.message,
|
||||
});
|
||||
}
|
||||
return {
|
||||
isFacebookAuthValid: false,
|
||||
newFoundUser: null,
|
||||
};
|
||||
});
|
||||
const newFoundUser = await DB_HANDLER(`SELECT * FROM ${usertype} WHERE id='${newUser.insertId}'`);
|
||||
}
|
||||
catch ( /** @type {any} */error) {
|
||||
serverError({
|
||||
component: "functions/backend/facebookLogin",
|
||||
message: error.message,
|
||||
});
|
||||
}
|
||||
return {
|
||||
isFacebookAuthValid: false,
|
||||
newFoundUser: null,
|
||||
};
|
||||
}
|
||||
|
@ -1,62 +1,45 @@
|
||||
"use strict";
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = githubLogin;
|
||||
const DB_HANDLER_1 = __importDefault(require("../../../utils/backend/global-db/DB_HANDLER"));
|
||||
const httpsRequest_1 = __importDefault(require("../../backend/httpsRequest"));
|
||||
import DB_HANDLER from "../../../utils/backend/global-db/DB_HANDLER";
|
||||
import httpsRequest from "../../backend/httpsRequest";
|
||||
/**
|
||||
* # Login/signup a github user
|
||||
*/
|
||||
function githubLogin(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ code, clientId, clientSecret, }) {
|
||||
let gitHubUser;
|
||||
try {
|
||||
const response = yield (0, httpsRequest_1.default)({
|
||||
method: "POST",
|
||||
hostname: "github.com",
|
||||
path: `/login/oauth/access_token?client_id=${clientId}&client_secret=${clientSecret}&code=${code}`,
|
||||
headers: {
|
||||
Accept: "application/json",
|
||||
"User-Agent": "*",
|
||||
},
|
||||
scheme: "https",
|
||||
});
|
||||
const accessTokenObject = JSON.parse(response);
|
||||
if (!(accessTokenObject === null || accessTokenObject === void 0 ? void 0 : accessTokenObject.access_token)) {
|
||||
return gitHubUser;
|
||||
}
|
||||
const userDataResponse = yield (0, httpsRequest_1.default)({
|
||||
method: "GET",
|
||||
hostname: "api.github.com",
|
||||
path: "/user",
|
||||
headers: {
|
||||
Authorization: `Bearer ${accessTokenObject.access_token}`,
|
||||
"User-Agent": "*",
|
||||
},
|
||||
scheme: "https",
|
||||
});
|
||||
gitHubUser = JSON.parse(userDataResponse);
|
||||
if (!(gitHubUser === null || gitHubUser === void 0 ? void 0 : gitHubUser.email) && gitHubUser) {
|
||||
const existingGithubUser = yield (0, DB_HANDLER_1.default)(`SELECT email FROM users WHERE social_login='1' AND social_platform='github' AND social_id='${gitHubUser.id}'`);
|
||||
if (existingGithubUser && existingGithubUser[0]) {
|
||||
gitHubUser.email = existingGithubUser[0].email;
|
||||
}
|
||||
export default async function githubLogin({ code, clientId, clientSecret, }) {
|
||||
let gitHubUser;
|
||||
try {
|
||||
const response = await httpsRequest({
|
||||
method: "POST",
|
||||
hostname: "github.com",
|
||||
path: `/login/oauth/access_token?client_id=${clientId}&client_secret=${clientSecret}&code=${code}`,
|
||||
headers: {
|
||||
Accept: "application/json",
|
||||
"User-Agent": "*",
|
||||
},
|
||||
scheme: "https",
|
||||
});
|
||||
const accessTokenObject = JSON.parse(response);
|
||||
if (!(accessTokenObject === null || accessTokenObject === void 0 ? void 0 : accessTokenObject.access_token)) {
|
||||
return gitHubUser;
|
||||
}
|
||||
const userDataResponse = await httpsRequest({
|
||||
method: "GET",
|
||||
hostname: "api.github.com",
|
||||
path: "/user",
|
||||
headers: {
|
||||
Authorization: `Bearer ${accessTokenObject.access_token}`,
|
||||
"User-Agent": "*",
|
||||
},
|
||||
scheme: "https",
|
||||
});
|
||||
gitHubUser = JSON.parse(userDataResponse);
|
||||
if (!(gitHubUser === null || gitHubUser === void 0 ? void 0 : gitHubUser.email) && gitHubUser) {
|
||||
const existingGithubUser = await DB_HANDLER(`SELECT email FROM users WHERE social_login='1' AND social_platform='github' AND social_id='${gitHubUser.id}'`);
|
||||
if (existingGithubUser && existingGithubUser[0]) {
|
||||
gitHubUser.email = existingGithubUser[0].email;
|
||||
}
|
||||
}
|
||||
catch ( /** @type {any} */error) {
|
||||
console.log("ERROR in githubLogin.ts backend function =>", error.message);
|
||||
}
|
||||
return gitHubUser;
|
||||
});
|
||||
}
|
||||
catch ( /** @type {any} */error) {
|
||||
console.log("ERROR in githubLogin.ts backend function =>", error.message);
|
||||
}
|
||||
return gitHubUser;
|
||||
}
|
||||
|
@ -1,82 +1,66 @@
|
||||
"use strict";
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = googleLogin;
|
||||
const google_auth_library_1 = require("google-auth-library");
|
||||
const serverError_1 = __importDefault(require("../../backend/serverError"));
|
||||
const DB_HANDLER_1 = __importDefault(require("../../../utils/backend/global-db/DB_HANDLER"));
|
||||
const hashPassword_1 = __importDefault(require("../../dsql/hashPassword"));
|
||||
import { OAuth2Client } from "google-auth-library";
|
||||
import serverError from "../../backend/serverError";
|
||||
import DB_HANDLER from "../../../utils/backend/global-db/DB_HANDLER";
|
||||
import hashPassword from "../../dsql/hashPassword";
|
||||
/**
|
||||
* # Google Login
|
||||
*/
|
||||
function googleLogin(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ usertype, foundUser, isSocialValidated, isUserValid, reqBody, serverRes, loginFailureReason, }) {
|
||||
var _b, _c;
|
||||
const client = new google_auth_library_1.OAuth2Client(process.env.DSQL_GOOGLE_CLIENT_ID);
|
||||
let isGoogleAuthValid = false;
|
||||
let newFoundUser = null;
|
||||
export default async function googleLogin({ usertype, foundUser, isSocialValidated, isUserValid, reqBody, serverRes, loginFailureReason, }) {
|
||||
var _a, _b;
|
||||
const client = new OAuth2Client(process.env.DSQL_GOOGLE_CLIENT_ID);
|
||||
let isGoogleAuthValid = false;
|
||||
let newFoundUser = null;
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
try {
|
||||
const ticket = await client.verifyIdToken({
|
||||
idToken: reqBody.token,
|
||||
audience: process.env.DSQL_GOOGLE_CLIENT_ID, // Specify the CLIENT_ID of the app that accesses the backend
|
||||
// Or, if multiple clients access the backend:
|
||||
//[CLIENT_ID_1, CLIENT_ID_2, CLIENT_ID_3]
|
||||
});
|
||||
const payload = ticket.getPayload();
|
||||
const userid = payload === null || payload === void 0 ? void 0 : payload["sub"];
|
||||
if (!payload)
|
||||
throw new Error("Google login failed. Credentials invalid");
|
||||
isUserValid = Boolean(payload.email_verified);
|
||||
if (!isUserValid || !payload || !payload.email_verified)
|
||||
return;
|
||||
serverRes.isUserValid = payload.email_verified;
|
||||
isSocialValidated = payload.email_verified;
|
||||
isGoogleAuthValid = payload.email_verified;
|
||||
////// If request specified a G Suite domain:
|
||||
////// const domain = payload['hd'];
|
||||
let socialHashedPassword = hashPassword({
|
||||
password: payload.at_hash || "",
|
||||
});
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
try {
|
||||
const ticket = yield client.verifyIdToken({
|
||||
idToken: reqBody.token,
|
||||
audience: process.env.DSQL_GOOGLE_CLIENT_ID, // Specify the CLIENT_ID of the app that accesses the backend
|
||||
// Or, if multiple clients access the backend:
|
||||
//[CLIENT_ID_1, CLIENT_ID_2, CLIENT_ID_3]
|
||||
});
|
||||
const payload = ticket.getPayload();
|
||||
const userid = payload === null || payload === void 0 ? void 0 : payload["sub"];
|
||||
if (!payload)
|
||||
throw new Error("Google login failed. Credentials invalid");
|
||||
isUserValid = Boolean(payload.email_verified);
|
||||
if (!isUserValid || !payload || !payload.email_verified)
|
||||
return;
|
||||
serverRes.isUserValid = payload.email_verified;
|
||||
isSocialValidated = payload.email_verified;
|
||||
isGoogleAuthValid = payload.email_verified;
|
||||
////// If request specified a G Suite domain:
|
||||
////// const domain = payload['hd'];
|
||||
let socialHashedPassword = (0, hashPassword_1.default)({
|
||||
password: payload.at_hash || "",
|
||||
});
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
let existinEmail = yield (0, DB_HANDLER_1.default)(`SELECT * FROM ${usertype} WHERE email='${payload.email}' AND social_login!='1' AND social_platform!='google'`);
|
||||
if (existinEmail && existinEmail[0]) {
|
||||
loginFailureReason = "Email Exists Already";
|
||||
isGoogleAuthValid = false;
|
||||
return {
|
||||
isGoogleAuthValid: isGoogleAuthValid,
|
||||
newFoundUser: newFoundUser,
|
||||
loginFailureReason: loginFailureReason,
|
||||
};
|
||||
}
|
||||
////////////////////////////////////////
|
||||
foundUser = yield (0, DB_HANDLER_1.default)(`SELECT * FROM ${usertype} WHERE email='${payload.email}' AND social_login='1' AND social_platform='google'`);
|
||||
if (foundUser && foundUser[0]) {
|
||||
newFoundUser = foundUser;
|
||||
return {
|
||||
isGoogleAuthValid: isGoogleAuthValid,
|
||||
newFoundUser: newFoundUser,
|
||||
};
|
||||
}
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
let newUser = yield (0, DB_HANDLER_1.default)(`INSERT INTO ${usertype} (
|
||||
let existinEmail = await DB_HANDLER(`SELECT * FROM ${usertype} WHERE email='${payload.email}' AND social_login!='1' AND social_platform!='google'`);
|
||||
if (existinEmail && existinEmail[0]) {
|
||||
loginFailureReason = "Email Exists Already";
|
||||
isGoogleAuthValid = false;
|
||||
return {
|
||||
isGoogleAuthValid: isGoogleAuthValid,
|
||||
newFoundUser: newFoundUser,
|
||||
loginFailureReason: loginFailureReason,
|
||||
};
|
||||
}
|
||||
////////////////////////////////////////
|
||||
foundUser = await DB_HANDLER(`SELECT * FROM ${usertype} WHERE email='${payload.email}' AND social_login='1' AND social_platform='google'`);
|
||||
if (foundUser && foundUser[0]) {
|
||||
newFoundUser = foundUser;
|
||||
return {
|
||||
isGoogleAuthValid: isGoogleAuthValid,
|
||||
newFoundUser: newFoundUser,
|
||||
};
|
||||
}
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
let newUser = await DB_HANDLER(`INSERT INTO ${usertype} (
|
||||
first_name,
|
||||
last_name,
|
||||
social_platform,
|
||||
@ -95,7 +79,7 @@ function googleLogin(_a) {
|
||||
'${payload.given_name}',
|
||||
'${payload.family_name}',
|
||||
'google',
|
||||
'google_${(_b = payload.email) === null || _b === void 0 ? void 0 : _b.replace(/@.*/, "")}',
|
||||
'google_${(_a = payload.email) === null || _a === void 0 ? void 0 : _a.replace(/@.*/, "")}',
|
||||
'${payload.sub}',
|
||||
'${payload.email}',
|
||||
'${payload.picture}',
|
||||
@ -107,18 +91,17 @@ function googleLogin(_a) {
|
||||
'${Date()}',
|
||||
'${Date.now()}'
|
||||
)`);
|
||||
newFoundUser = yield (0, DB_HANDLER_1.default)(`SELECT * FROM ${usertype} WHERE id='${newUser.insertId}'`);
|
||||
}
|
||||
catch (error) {
|
||||
(0, serverError_1.default)({
|
||||
component: "googleLogin",
|
||||
message: error.message,
|
||||
});
|
||||
(_c = global.ERROR_CALLBACK) === null || _c === void 0 ? void 0 : _c.call(global, `Google Login Error`, error);
|
||||
loginFailureReason = error;
|
||||
isUserValid = false;
|
||||
isSocialValidated = false;
|
||||
}
|
||||
return { isGoogleAuthValid: isGoogleAuthValid, newFoundUser: newFoundUser };
|
||||
});
|
||||
newFoundUser = await DB_HANDLER(`SELECT * FROM ${usertype} WHERE id='${newUser.insertId}'`);
|
||||
}
|
||||
catch (error) {
|
||||
serverError({
|
||||
component: "googleLogin",
|
||||
message: error.message,
|
||||
});
|
||||
(_b = global.ERROR_CALLBACK) === null || _b === void 0 ? void 0 : _b.call(global, `Google Login Error`, error);
|
||||
loginFailureReason = error;
|
||||
isUserValid = false;
|
||||
isSocialValidated = false;
|
||||
}
|
||||
return { isGoogleAuthValid: isGoogleAuthValid, newFoundUser: newFoundUser };
|
||||
}
|
||||
|
@ -1,217 +1,201 @@
|
||||
"use strict";
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = handleSocialDb;
|
||||
const fs_1 = __importDefault(require("fs"));
|
||||
const handleNodemailer_1 = __importDefault(require("../../backend/handleNodemailer"));
|
||||
const path_1 = __importDefault(require("path"));
|
||||
const addMariadbUser_1 = __importDefault(require("../../backend/addMariadbUser"));
|
||||
const varDatabaseDbHandler_1 = __importDefault(require("../../backend/varDatabaseDbHandler"));
|
||||
const encrypt_1 = __importDefault(require("../../dsql/encrypt"));
|
||||
const addDbEntry_1 = __importDefault(require("../../backend/db/addDbEntry"));
|
||||
const loginSocialUser_1 = __importDefault(require("./loginSocialUser"));
|
||||
import fs from "fs";
|
||||
import handleNodemailer from "../../backend/handleNodemailer";
|
||||
import path from "path";
|
||||
import addMariadbUser from "../../backend/addMariadbUser";
|
||||
import varDatabaseDbHandler from "../../backend/varDatabaseDbHandler";
|
||||
import encrypt from "../../dsql/encrypt";
|
||||
import addDbEntry from "../../backend/db/addDbEntry";
|
||||
import loginSocialUser from "./loginSocialUser";
|
||||
import grabDirNames from "../../../utils/backend/names/grab-dir-names";
|
||||
/**
|
||||
* # Handle Social DB
|
||||
*/
|
||||
function handleSocialDb(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ database, email, social_platform, payload, invitation, supEmail, additionalFields, debug, loginOnly, }) {
|
||||
var _b;
|
||||
try {
|
||||
const finalDbName = global.DSQL_USE_LOCAL
|
||||
? undefined
|
||||
: database
|
||||
? database
|
||||
: "datasquirel";
|
||||
const dbAppend = global.DSQL_USE_LOCAL ? "" : `${finalDbName}.`;
|
||||
const existingSocialUserQUery = `SELECT * FROM ${dbAppend}users WHERE email = ? AND social_login='1' AND social_platform = ? `;
|
||||
const existingSocialUserValues = [email, social_platform];
|
||||
if (debug) {
|
||||
console.log("handleSocialDb:existingSocialUserQUery", existingSocialUserQUery);
|
||||
console.log("handleSocialDb:existingSocialUserValues", existingSocialUserValues);
|
||||
}
|
||||
let existingSocialUser = yield (0, varDatabaseDbHandler_1.default)({
|
||||
database: finalDbName,
|
||||
queryString: existingSocialUserQUery,
|
||||
queryValuesArray: existingSocialUserValues,
|
||||
debug,
|
||||
});
|
||||
if (debug) {
|
||||
console.log("handleSocialDb:existingSocialUser", existingSocialUser);
|
||||
}
|
||||
if (existingSocialUser === null || existingSocialUser === void 0 ? void 0 : existingSocialUser[0]) {
|
||||
return yield (0, loginSocialUser_1.default)({
|
||||
user: existingSocialUser[0],
|
||||
social_platform,
|
||||
invitation,
|
||||
database: finalDbName,
|
||||
additionalFields,
|
||||
debug,
|
||||
});
|
||||
}
|
||||
else if (loginOnly) {
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: "User Does not Exist",
|
||||
};
|
||||
}
|
||||
const finalEmail = email ? email : supEmail ? supEmail : null;
|
||||
if (!finalEmail) {
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: "No Email Present",
|
||||
};
|
||||
}
|
||||
const existingEmailOnlyQuery = `SELECT * FROM ${dbAppend}users WHERE email='${finalEmail}'`;
|
||||
if (debug) {
|
||||
console.log("handleSocialDb:existingEmailOnlyQuery", existingEmailOnlyQuery);
|
||||
}
|
||||
let existingEmailOnly = yield (0, varDatabaseDbHandler_1.default)({
|
||||
database: finalDbName,
|
||||
queryString: existingEmailOnlyQuery,
|
||||
debug,
|
||||
});
|
||||
if (debug) {
|
||||
console.log("handleSocialDb:existingEmailOnly", existingEmailOnly);
|
||||
}
|
||||
if (existingEmailOnly === null || existingEmailOnly === void 0 ? void 0 : existingEmailOnly[0]) {
|
||||
return yield (0, loginSocialUser_1.default)({
|
||||
user: existingEmailOnly[0],
|
||||
social_platform,
|
||||
invitation,
|
||||
database: finalDbName,
|
||||
additionalFields,
|
||||
debug,
|
||||
});
|
||||
}
|
||||
else if (loginOnly) {
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: "Social Account Creation Not allowed",
|
||||
};
|
||||
}
|
||||
const socialHashedPassword = (0, encrypt_1.default)({
|
||||
data: email,
|
||||
});
|
||||
const data = {
|
||||
social_login: "1",
|
||||
verification_status: supEmail ? "0" : "1",
|
||||
password: socialHashedPassword,
|
||||
};
|
||||
Object.keys(payload).forEach((key) => {
|
||||
data[key] = payload[key];
|
||||
});
|
||||
const newUser = yield (0, addDbEntry_1.default)({
|
||||
dbContext: finalDbName ? "Dsql User" : undefined,
|
||||
paradigm: finalDbName ? "Full Access" : undefined,
|
||||
dbFullName: finalDbName,
|
||||
tableName: "users",
|
||||
duplicateColumnName: "email",
|
||||
duplicateColumnValue: finalEmail,
|
||||
data: Object.assign(Object.assign({}, data), { email: finalEmail }),
|
||||
});
|
||||
if (newUser === null || newUser === void 0 ? void 0 : newUser.insertId) {
|
||||
if (!database) {
|
||||
/**
|
||||
* Add a Mariadb User for this User
|
||||
*/
|
||||
yield (0, addMariadbUser_1.default)({ userId: newUser.insertId });
|
||||
}
|
||||
const newUserQueriedQuery = `SELECT * FROM ${dbAppend}users WHERE id='${newUser.insertId}'`;
|
||||
const newUserQueried = yield (0, varDatabaseDbHandler_1.default)({
|
||||
database: finalDbName,
|
||||
queryString: newUserQueriedQuery,
|
||||
debug,
|
||||
});
|
||||
if (!newUserQueried || !newUserQueried[0])
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: "User Insertion Failed!",
|
||||
};
|
||||
if (supEmail && (database === null || database === void 0 ? void 0 : database.match(/^datasquirel$/))) {
|
||||
/**
|
||||
* Send email Verification
|
||||
*
|
||||
* @description Send verification email to newly created agent
|
||||
*/
|
||||
let generatedToken = (0, encrypt_1.default)({
|
||||
data: JSON.stringify({
|
||||
id: newUser.insertId,
|
||||
email: supEmail,
|
||||
dateCode: Date.now(),
|
||||
}),
|
||||
});
|
||||
(0, handleNodemailer_1.default)({
|
||||
to: supEmail,
|
||||
subject: "Verify Email Address",
|
||||
text: "Please click the link to verify your email address",
|
||||
html: fs_1.default
|
||||
.readFileSync("./email/send-email-verification-link.html", "utf8")
|
||||
.replace(/{{host}}/, process.env.DSQL_HOST || "")
|
||||
.replace(/{{token}}/, generatedToken || ""),
|
||||
}).then(() => { });
|
||||
}
|
||||
const STATIC_ROOT = process.env.DSQL_STATIC_SERVER_DIR;
|
||||
if (!STATIC_ROOT) {
|
||||
console.log("Static File ENV not Found!");
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: "Static File ENV not Found!",
|
||||
};
|
||||
}
|
||||
/**
|
||||
* Create new user folder and file
|
||||
*
|
||||
* @description Create new user folder and file
|
||||
*/
|
||||
if (!database || (database === null || database === void 0 ? void 0 : database.match(/^datasquirel$/))) {
|
||||
let newUserSchemaFolderPath = `${process.env.DSQL_USER_DB_SCHEMA_PATH}/user-${newUser.insertId}`;
|
||||
let newUserMediaFolderPath = path_1.default.join(STATIC_ROOT, `images/user-images/user-${newUser.insertId}`);
|
||||
fs_1.default.mkdirSync(newUserSchemaFolderPath);
|
||||
fs_1.default.mkdirSync(newUserMediaFolderPath);
|
||||
fs_1.default.writeFileSync(`${newUserSchemaFolderPath}/main.json`, JSON.stringify([]), "utf8");
|
||||
}
|
||||
return yield (0, loginSocialUser_1.default)({
|
||||
user: newUserQueried[0],
|
||||
social_platform,
|
||||
invitation,
|
||||
database: finalDbName,
|
||||
additionalFields,
|
||||
debug,
|
||||
});
|
||||
}
|
||||
else {
|
||||
console.log("Social User Failed to insert in 'handleSocialDb.ts' backend function =>", newUser);
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: "Social User Failed to insert in 'handleSocialDb.ts' backend function",
|
||||
};
|
||||
}
|
||||
export default async function handleSocialDb({ database, email, social_platform, payload, invitation, supEmail, additionalFields, debug, loginOnly, }) {
|
||||
var _a, _b;
|
||||
try {
|
||||
const finalDbName = global.DSQL_USE_LOCAL
|
||||
? undefined
|
||||
: database
|
||||
? database
|
||||
: "datasquirel";
|
||||
const dbAppend = global.DSQL_USE_LOCAL ? "" : `${finalDbName}.`;
|
||||
const existingSocialUserQUery = `SELECT * FROM ${dbAppend}users WHERE email = ? AND social_login='1' AND social_platform = ? `;
|
||||
const existingSocialUserValues = [email, social_platform];
|
||||
if (debug) {
|
||||
console.log("handleSocialDb:existingSocialUserQUery", existingSocialUserQUery);
|
||||
console.log("handleSocialDb:existingSocialUserValues", existingSocialUserValues);
|
||||
}
|
||||
catch (error) {
|
||||
console.log("ERROR in 'handleSocialDb.ts' backend function =>", error.message);
|
||||
(_b = global.ERROR_CALLBACK) === null || _b === void 0 ? void 0 : _b.call(global, `Handle Social DB Error`, error);
|
||||
let existingSocialUser = await varDatabaseDbHandler({
|
||||
database: finalDbName,
|
||||
queryString: existingSocialUserQUery,
|
||||
queryValuesArray: existingSocialUserValues,
|
||||
debug,
|
||||
});
|
||||
if (debug) {
|
||||
console.log("handleSocialDb:existingSocialUser", existingSocialUser);
|
||||
}
|
||||
if (existingSocialUser === null || existingSocialUser === void 0 ? void 0 : existingSocialUser[0]) {
|
||||
return await loginSocialUser({
|
||||
user: existingSocialUser[0],
|
||||
social_platform,
|
||||
invitation,
|
||||
database: finalDbName,
|
||||
additionalFields,
|
||||
debug,
|
||||
});
|
||||
}
|
||||
else if (loginOnly) {
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: error.message,
|
||||
msg: "User Does not Exist",
|
||||
};
|
||||
}
|
||||
});
|
||||
const finalEmail = email ? email : supEmail ? supEmail : null;
|
||||
if (!finalEmail) {
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: "No Email Present",
|
||||
};
|
||||
}
|
||||
const existingEmailOnlyQuery = `SELECT * FROM ${dbAppend}users WHERE email='${finalEmail}'`;
|
||||
if (debug) {
|
||||
console.log("handleSocialDb:existingEmailOnlyQuery", existingEmailOnlyQuery);
|
||||
}
|
||||
let existingEmailOnly = await varDatabaseDbHandler({
|
||||
database: finalDbName,
|
||||
queryString: existingEmailOnlyQuery,
|
||||
debug,
|
||||
});
|
||||
if (debug) {
|
||||
console.log("handleSocialDb:existingEmailOnly", existingEmailOnly);
|
||||
}
|
||||
if (existingEmailOnly === null || existingEmailOnly === void 0 ? void 0 : existingEmailOnly[0]) {
|
||||
return await loginSocialUser({
|
||||
user: existingEmailOnly[0],
|
||||
social_platform,
|
||||
invitation,
|
||||
database: finalDbName,
|
||||
additionalFields,
|
||||
debug,
|
||||
});
|
||||
}
|
||||
else if (loginOnly) {
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: "Social Account Creation Not allowed",
|
||||
};
|
||||
}
|
||||
const socialHashedPassword = encrypt({
|
||||
data: email,
|
||||
});
|
||||
const data = {
|
||||
social_login: "1",
|
||||
verification_status: supEmail ? "0" : "1",
|
||||
password: socialHashedPassword,
|
||||
};
|
||||
Object.keys(payload).forEach((key) => {
|
||||
data[key] = payload[key];
|
||||
});
|
||||
const newUser = await addDbEntry({
|
||||
dbContext: finalDbName ? "Dsql User" : undefined,
|
||||
paradigm: finalDbName ? "Full Access" : undefined,
|
||||
dbFullName: finalDbName,
|
||||
tableName: "users",
|
||||
duplicateColumnName: "email",
|
||||
duplicateColumnValue: finalEmail,
|
||||
data: Object.assign(Object.assign({}, data), { email: finalEmail }),
|
||||
});
|
||||
if ((_a = newUser === null || newUser === void 0 ? void 0 : newUser.payload) === null || _a === void 0 ? void 0 : _a.insertId) {
|
||||
if (!database) {
|
||||
/**
|
||||
* Add a Mariadb User for this User
|
||||
*/
|
||||
await addMariadbUser({ userId: newUser.payload.insertId });
|
||||
}
|
||||
const newUserQueriedQuery = `SELECT * FROM ${dbAppend}users WHERE id='${newUser.payload.insertId}'`;
|
||||
const newUserQueried = await varDatabaseDbHandler({
|
||||
database: finalDbName,
|
||||
queryString: newUserQueriedQuery,
|
||||
debug,
|
||||
});
|
||||
if (!newUserQueried || !newUserQueried[0])
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: "User Insertion Failed!",
|
||||
};
|
||||
if (supEmail && (database === null || database === void 0 ? void 0 : database.match(/^datasquirel$/))) {
|
||||
/**
|
||||
* Send email Verification
|
||||
*
|
||||
* @description Send verification email to newly created agent
|
||||
*/
|
||||
let generatedToken = encrypt({
|
||||
data: JSON.stringify({
|
||||
id: newUser.payload.insertId,
|
||||
email: supEmail,
|
||||
dateCode: Date.now(),
|
||||
}),
|
||||
});
|
||||
handleNodemailer({
|
||||
to: supEmail,
|
||||
subject: "Verify Email Address",
|
||||
text: "Please click the link to verify your email address",
|
||||
html: fs
|
||||
.readFileSync("./email/send-email-verification-link.html", "utf8")
|
||||
.replace(/{{host}}/, process.env.DSQL_HOST || "")
|
||||
.replace(/{{token}}/, generatedToken || ""),
|
||||
}).then(() => { });
|
||||
}
|
||||
const { STATIC_ROOT } = grabDirNames();
|
||||
if (!STATIC_ROOT) {
|
||||
console.log("Static File ENV not Found!");
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: "Static File ENV not Found!",
|
||||
};
|
||||
}
|
||||
/**
|
||||
* Create new user folder and file
|
||||
*
|
||||
* @description Create new user folder and file
|
||||
*/
|
||||
if (!database || (database === null || database === void 0 ? void 0 : database.match(/^datasquirel$/))) {
|
||||
let newUserSchemaFolderPath = `${process.env.DSQL_USER_DB_SCHEMA_PATH}/user-${newUser.payload.insertId}`;
|
||||
let newUserMediaFolderPath = path.join(STATIC_ROOT, `images/user-images/user-${newUser.payload.insertId}`);
|
||||
fs.mkdirSync(newUserSchemaFolderPath);
|
||||
fs.mkdirSync(newUserMediaFolderPath);
|
||||
fs.writeFileSync(`${newUserSchemaFolderPath}/main.json`, JSON.stringify([]), "utf8");
|
||||
}
|
||||
return await loginSocialUser({
|
||||
user: newUserQueried[0],
|
||||
social_platform,
|
||||
invitation,
|
||||
database: finalDbName,
|
||||
additionalFields,
|
||||
debug,
|
||||
});
|
||||
}
|
||||
else {
|
||||
console.log("Social User Failed to insert in 'handleSocialDb.ts' backend function =>", newUser);
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: "Social User Failed to insert in 'handleSocialDb.ts' backend function",
|
||||
};
|
||||
}
|
||||
}
|
||||
catch (error) {
|
||||
console.log("ERROR in 'handleSocialDb.ts' backend function =>", error.message);
|
||||
(_b = global.ERROR_CALLBACK) === null || _b === void 0 ? void 0 : _b.call(global, `Handle Social DB Error`, error);
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: error.message,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
@ -1,81 +1,64 @@
|
||||
"use strict";
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = loginSocialUser;
|
||||
const addAdminUserOnLogin_1 = __importDefault(require("../../backend/addAdminUserOnLogin"));
|
||||
const varDatabaseDbHandler_1 = __importDefault(require("../../backend/varDatabaseDbHandler"));
|
||||
import addAdminUserOnLogin from "../../backend/addAdminUserOnLogin";
|
||||
import varDatabaseDbHandler from "../../backend/varDatabaseDbHandler";
|
||||
/**
|
||||
* Function to login social user
|
||||
* ==============================================================================
|
||||
* @description This function logs in the user after 'handleSocialDb' function finishes
|
||||
* the user creation or confirmation process
|
||||
*/
|
||||
function loginSocialUser(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ user, social_platform, invitation, database, additionalFields, debug, }) {
|
||||
const finalDbName = database ? database : "datasquirel";
|
||||
const dbAppend = database ? `\`${finalDbName}\`.` : "";
|
||||
const foundUserQuery = `SELECT * FROM ${dbAppend}\`users\` WHERE email=?`;
|
||||
const foundUserValues = [user.email];
|
||||
const foundUser = yield (0, varDatabaseDbHandler_1.default)({
|
||||
database: finalDbName,
|
||||
queryString: foundUserQuery,
|
||||
queryValuesArray: foundUserValues,
|
||||
debug,
|
||||
});
|
||||
if (!(foundUser === null || foundUser === void 0 ? void 0 : foundUser[0]))
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: "Couldn't find Social User.",
|
||||
};
|
||||
let csrfKey = Math.random().toString(36).substring(2) +
|
||||
"-" +
|
||||
Math.random().toString(36).substring(2);
|
||||
let userPayload = {
|
||||
id: foundUser[0].id,
|
||||
uuid: foundUser[0].uuid,
|
||||
first_name: foundUser[0].first_name,
|
||||
last_name: foundUser[0].last_name,
|
||||
username: foundUser[0].username,
|
||||
user_type: foundUser[0].user_type,
|
||||
email: foundUser[0].email,
|
||||
social_id: foundUser[0].social_id,
|
||||
image: foundUser[0].image,
|
||||
image_thumbnail: foundUser[0].image_thumbnail,
|
||||
verification_status: foundUser[0].verification_status,
|
||||
social_login: foundUser[0].social_login,
|
||||
social_platform: foundUser[0].social_platform,
|
||||
csrf_k: csrfKey,
|
||||
logged_in_status: true,
|
||||
date: Date.now(),
|
||||
};
|
||||
if (additionalFields === null || additionalFields === void 0 ? void 0 : additionalFields[0]) {
|
||||
additionalFields.forEach((key) => {
|
||||
userPayload[key] = foundUser[0][key];
|
||||
});
|
||||
}
|
||||
if (invitation && (!database || (database === null || database === void 0 ? void 0 : database.match(/^datasquirel$/)))) {
|
||||
(0, addAdminUserOnLogin_1.default)({
|
||||
query: invitation,
|
||||
user: userPayload,
|
||||
});
|
||||
}
|
||||
let result = {
|
||||
success: true,
|
||||
payload: userPayload,
|
||||
csrf: csrfKey,
|
||||
};
|
||||
return result;
|
||||
export default async function loginSocialUser({ user, social_platform, invitation, database, additionalFields, debug, }) {
|
||||
const finalDbName = database ? database : "datasquirel";
|
||||
const dbAppend = database ? `\`${finalDbName}\`.` : "";
|
||||
const foundUserQuery = `SELECT * FROM ${dbAppend}\`users\` WHERE email=?`;
|
||||
const foundUserValues = [user.email];
|
||||
const foundUser = await varDatabaseDbHandler({
|
||||
database: finalDbName,
|
||||
queryString: foundUserQuery,
|
||||
queryValuesArray: foundUserValues,
|
||||
debug,
|
||||
});
|
||||
if (!(foundUser === null || foundUser === void 0 ? void 0 : foundUser[0]))
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: "Couldn't find Social User.",
|
||||
};
|
||||
let csrfKey = Math.random().toString(36).substring(2) +
|
||||
"-" +
|
||||
Math.random().toString(36).substring(2);
|
||||
let userPayload = {
|
||||
id: foundUser[0].id,
|
||||
uuid: foundUser[0].uuid,
|
||||
first_name: foundUser[0].first_name,
|
||||
last_name: foundUser[0].last_name,
|
||||
username: foundUser[0].username,
|
||||
user_type: foundUser[0].user_type,
|
||||
email: foundUser[0].email,
|
||||
social_id: foundUser[0].social_id,
|
||||
image: foundUser[0].image,
|
||||
image_thumbnail: foundUser[0].image_thumbnail,
|
||||
verification_status: foundUser[0].verification_status,
|
||||
social_login: foundUser[0].social_login,
|
||||
social_platform: foundUser[0].social_platform,
|
||||
csrf_k: csrfKey,
|
||||
logged_in_status: true,
|
||||
date: Date.now(),
|
||||
};
|
||||
if (additionalFields === null || additionalFields === void 0 ? void 0 : additionalFields[0]) {
|
||||
additionalFields.forEach((key) => {
|
||||
userPayload[key] = foundUser[0][key];
|
||||
});
|
||||
}
|
||||
if (invitation && (!database || (database === null || database === void 0 ? void 0 : database.match(/^datasquirel$/)))) {
|
||||
addAdminUserOnLogin({
|
||||
query: invitation,
|
||||
user: userPayload,
|
||||
});
|
||||
}
|
||||
let result = {
|
||||
success: true,
|
||||
payload: userPayload,
|
||||
csrf: csrfKey,
|
||||
};
|
||||
return result;
|
||||
}
|
||||
|
@ -20,6 +20,6 @@ export default function apiCreateUser({ encryptionKey, payload, database, userId
|
||||
} | {
|
||||
success: boolean;
|
||||
msg: string;
|
||||
sqlResult: import("../../../types").PostInsertReturn | null;
|
||||
sqlResult: import("../../../types").APIResponseObject<import("../../../types").PostInsertReturn>;
|
||||
payload: null;
|
||||
}>;
|
||||
|
@ -1,143 +1,140 @@
|
||||
"use strict";
|
||||
// @ts-check
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = apiCreateUser;
|
||||
const addUsersTableToDb_1 = __importDefault(require("../../backend/addUsersTableToDb"));
|
||||
const addDbEntry_1 = __importDefault(require("../../backend/db/addDbEntry"));
|
||||
const updateUsersTableSchema_1 = __importDefault(require("../../backend/updateUsersTableSchema"));
|
||||
const varDatabaseDbHandler_1 = __importDefault(require("../../backend/varDatabaseDbHandler"));
|
||||
const hashPassword_1 = __importDefault(require("../../dsql/hashPassword"));
|
||||
const validate_email_1 = __importDefault(require("../../email/fns/validate-email"));
|
||||
import { findDbNameInSchemaDir } from "../../../shell/createDbFromSchema/grab-required-database-schemas";
|
||||
import addUsersTableToDb from "../../backend/addUsersTableToDb";
|
||||
import addDbEntry from "../../backend/db/addDbEntry";
|
||||
import updateUsersTableSchema from "../../backend/updateUsersTableSchema";
|
||||
import varDatabaseDbHandler from "../../backend/varDatabaseDbHandler";
|
||||
import hashPassword from "../../dsql/hashPassword";
|
||||
import validateEmail from "../../email/fns/validate-email";
|
||||
/**
|
||||
* # API Create User
|
||||
*/
|
||||
function apiCreateUser(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ encryptionKey, payload, database, userId, }) {
|
||||
const dbFullName = database;
|
||||
const API_USER_ID = userId || process.env.DSQL_API_USER_ID;
|
||||
const finalEncryptionKey = encryptionKey || process.env.DSQL_ENCRYPTION_PASSWORD;
|
||||
if (!finalEncryptionKey) {
|
||||
return {
|
||||
success: false,
|
||||
msg: "No encryption key provided",
|
||||
payload: null,
|
||||
};
|
||||
}
|
||||
if (!(finalEncryptionKey === null || finalEncryptionKey === void 0 ? void 0 : finalEncryptionKey.match(/.{8,}/))) {
|
||||
return {
|
||||
success: false,
|
||||
msg: "Encryption key must be at least 8 characters long",
|
||||
payload: null,
|
||||
};
|
||||
}
|
||||
const hashedPassword = (0, hashPassword_1.default)({
|
||||
encryptionKey: finalEncryptionKey,
|
||||
password: String(payload.password),
|
||||
export default async function apiCreateUser({ encryptionKey, payload, database, userId, }) {
|
||||
var _a;
|
||||
const dbFullName = database;
|
||||
const API_USER_ID = userId || process.env.DSQL_API_USER_ID;
|
||||
const finalEncryptionKey = encryptionKey || process.env.DSQL_ENCRYPTION_PASSWORD;
|
||||
if (!finalEncryptionKey) {
|
||||
return {
|
||||
success: false,
|
||||
msg: "No encryption key provided",
|
||||
payload: null,
|
||||
};
|
||||
}
|
||||
if (!(finalEncryptionKey === null || finalEncryptionKey === void 0 ? void 0 : finalEncryptionKey.match(/.{8,}/))) {
|
||||
return {
|
||||
success: false,
|
||||
msg: "Encryption key must be at least 8 characters long",
|
||||
payload: null,
|
||||
};
|
||||
}
|
||||
const targetDbSchema = findDbNameInSchemaDir({
|
||||
dbName: dbFullName,
|
||||
userId,
|
||||
});
|
||||
if (!(targetDbSchema === null || targetDbSchema === void 0 ? void 0 : targetDbSchema.id)) {
|
||||
return {
|
||||
success: false,
|
||||
msg: "targetDbSchema not found",
|
||||
payload: null,
|
||||
};
|
||||
}
|
||||
const hashedPassword = hashPassword({
|
||||
encryptionKey: finalEncryptionKey,
|
||||
password: String(payload.password),
|
||||
});
|
||||
payload.password = hashedPassword;
|
||||
const fieldsQuery = `SHOW COLUMNS FROM ${dbFullName}.users`;
|
||||
let fields = await varDatabaseDbHandler({
|
||||
queryString: fieldsQuery,
|
||||
database: dbFullName,
|
||||
});
|
||||
if (!(fields === null || fields === void 0 ? void 0 : fields[0])) {
|
||||
const newTable = await addUsersTableToDb({
|
||||
userId: Number(API_USER_ID),
|
||||
database: dbFullName,
|
||||
payload: payload,
|
||||
dbId: targetDbSchema.id,
|
||||
});
|
||||
payload.password = hashedPassword;
|
||||
const fieldsQuery = `SHOW COLUMNS FROM ${dbFullName}.users`;
|
||||
let fields = yield (0, varDatabaseDbHandler_1.default)({
|
||||
fields = await varDatabaseDbHandler({
|
||||
queryString: fieldsQuery,
|
||||
database: dbFullName,
|
||||
});
|
||||
if (!(fields === null || fields === void 0 ? void 0 : fields[0])) {
|
||||
const newTable = yield (0, addUsersTableToDb_1.default)({
|
||||
}
|
||||
if (!(fields === null || fields === void 0 ? void 0 : fields[0])) {
|
||||
return {
|
||||
success: false,
|
||||
msg: "Could not create users table",
|
||||
};
|
||||
}
|
||||
const fieldsTitles = fields.map((fieldObject) => fieldObject.Field);
|
||||
let invalidField = null;
|
||||
for (let i = 0; i < Object.keys(payload).length; i++) {
|
||||
const key = Object.keys(payload)[i];
|
||||
if (!fieldsTitles.includes(key)) {
|
||||
await updateUsersTableSchema({
|
||||
userId: Number(API_USER_ID),
|
||||
database: dbFullName,
|
||||
payload: payload,
|
||||
});
|
||||
fields = yield (0, varDatabaseDbHandler_1.default)({
|
||||
queryString: fieldsQuery,
|
||||
database: dbFullName,
|
||||
newPayload: {
|
||||
[key]: payload[key],
|
||||
},
|
||||
dbId: targetDbSchema.id,
|
||||
});
|
||||
}
|
||||
if (!(fields === null || fields === void 0 ? void 0 : fields[0])) {
|
||||
return {
|
||||
success: false,
|
||||
msg: "Could not create users table",
|
||||
};
|
||||
}
|
||||
const fieldsTitles = fields.map((fieldObject) => fieldObject.Field);
|
||||
let invalidField = null;
|
||||
for (let i = 0; i < Object.keys(payload).length; i++) {
|
||||
const key = Object.keys(payload)[i];
|
||||
if (!fieldsTitles.includes(key)) {
|
||||
yield (0, updateUsersTableSchema_1.default)({
|
||||
userId: Number(API_USER_ID),
|
||||
database: dbFullName,
|
||||
newPayload: {
|
||||
[key]: payload[key],
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
if (invalidField) {
|
||||
return {
|
||||
success: false,
|
||||
msg: `${invalidField} is not a valid field!`,
|
||||
};
|
||||
}
|
||||
const existingUserQuery = `SELECT * FROM ${dbFullName}.users WHERE email = ?${payload.username ? " OR username = ?" : ""}`;
|
||||
const existingUserValues = payload.username
|
||||
? [payload.email, payload.username]
|
||||
: [payload.email];
|
||||
const existingUser = yield (0, varDatabaseDbHandler_1.default)({
|
||||
queryString: existingUserQuery,
|
||||
queryValuesArray: existingUserValues,
|
||||
}
|
||||
if (invalidField) {
|
||||
return {
|
||||
success: false,
|
||||
msg: `${invalidField} is not a valid field!`,
|
||||
};
|
||||
}
|
||||
const existingUserQuery = `SELECT * FROM ${dbFullName}.users WHERE email = ?${payload.username ? " OR username = ?" : ""}`;
|
||||
const existingUserValues = payload.username
|
||||
? [payload.email, payload.username]
|
||||
: [payload.email];
|
||||
const existingUser = await varDatabaseDbHandler({
|
||||
queryString: existingUserQuery,
|
||||
queryValuesArray: existingUserValues,
|
||||
database: dbFullName,
|
||||
});
|
||||
if (existingUser === null || existingUser === void 0 ? void 0 : existingUser[0]) {
|
||||
return {
|
||||
success: false,
|
||||
msg: "User Already Exists",
|
||||
payload: null,
|
||||
};
|
||||
}
|
||||
const isEmailValid = await validateEmail({ email: payload.email });
|
||||
if (!isEmailValid.isValid) {
|
||||
return {
|
||||
success: false,
|
||||
msg: isEmailValid.message,
|
||||
payload: null,
|
||||
};
|
||||
}
|
||||
const addUser = await addDbEntry({
|
||||
dbFullName: dbFullName,
|
||||
tableName: "users",
|
||||
data: Object.assign(Object.assign({}, payload), { image: process.env.DSQL_DEFAULT_USER_IMAGE ||
|
||||
"/images/user-preset.png", image_thumbnail: process.env.DSQL_DEFAULT_USER_IMAGE ||
|
||||
"/images/user-preset-thumbnail.png" }),
|
||||
});
|
||||
if ((_a = addUser === null || addUser === void 0 ? void 0 : addUser.payload) === null || _a === void 0 ? void 0 : _a.insertId) {
|
||||
const newlyAddedUserQuery = `SELECT id,uuid,first_name,last_name,email,username,image,image_thumbnail,verification_status FROM ${dbFullName}.users WHERE id='${addUser.payload.insertId}'`;
|
||||
const newlyAddedUser = await varDatabaseDbHandler({
|
||||
queryString: newlyAddedUserQuery,
|
||||
database: dbFullName,
|
||||
});
|
||||
if (existingUser === null || existingUser === void 0 ? void 0 : existingUser[0]) {
|
||||
return {
|
||||
success: false,
|
||||
msg: "User Already Exists",
|
||||
payload: null,
|
||||
};
|
||||
}
|
||||
const isEmailValid = yield (0, validate_email_1.default)({ email: payload.email });
|
||||
if (!isEmailValid.isValid) {
|
||||
return {
|
||||
success: false,
|
||||
msg: isEmailValid.message,
|
||||
payload: null,
|
||||
};
|
||||
}
|
||||
const addUser = yield (0, addDbEntry_1.default)({
|
||||
dbFullName: dbFullName,
|
||||
tableName: "users",
|
||||
data: Object.assign(Object.assign({}, payload), { image: process.env.DSQL_DEFAULT_USER_IMAGE ||
|
||||
"/images/user-preset.png", image_thumbnail: process.env.DSQL_DEFAULT_USER_IMAGE ||
|
||||
"/images/user-preset-thumbnail.png" }),
|
||||
});
|
||||
if (addUser === null || addUser === void 0 ? void 0 : addUser.insertId) {
|
||||
const newlyAddedUserQuery = `SELECT id,uuid,first_name,last_name,email,username,image,image_thumbnail,verification_status FROM ${dbFullName}.users WHERE id='${addUser.insertId}'`;
|
||||
const newlyAddedUser = yield (0, varDatabaseDbHandler_1.default)({
|
||||
queryString: newlyAddedUserQuery,
|
||||
database: dbFullName,
|
||||
});
|
||||
return {
|
||||
success: true,
|
||||
payload: newlyAddedUser[0],
|
||||
};
|
||||
}
|
||||
else {
|
||||
return {
|
||||
success: false,
|
||||
msg: "Could not create user",
|
||||
sqlResult: addUser,
|
||||
payload: null,
|
||||
};
|
||||
}
|
||||
});
|
||||
return {
|
||||
success: true,
|
||||
payload: newlyAddedUser[0],
|
||||
};
|
||||
}
|
||||
else {
|
||||
return {
|
||||
success: false,
|
||||
msg: "Could not create user",
|
||||
sqlResult: addUser,
|
||||
payload: null,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
@ -1,48 +1,31 @@
|
||||
"use strict";
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = apiDeleteUser;
|
||||
const deleteDbEntry_1 = __importDefault(require("../../backend/db/deleteDbEntry"));
|
||||
const varDatabaseDbHandler_1 = __importDefault(require("../../backend/varDatabaseDbHandler"));
|
||||
import deleteDbEntry from "../../backend/db/deleteDbEntry";
|
||||
import varDatabaseDbHandler from "../../backend/varDatabaseDbHandler";
|
||||
/**
|
||||
* # Update API User Function
|
||||
*/
|
||||
function apiDeleteUser(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ dbFullName, deletedUserId, }) {
|
||||
const existingUserQuery = `SELECT * FROM ${dbFullName}.users WHERE id = ?`;
|
||||
const existingUserValues = [deletedUserId];
|
||||
const existingUser = yield (0, varDatabaseDbHandler_1.default)({
|
||||
queryString: existingUserQuery,
|
||||
queryValuesArray: existingUserValues,
|
||||
database: dbFullName,
|
||||
});
|
||||
if (!(existingUser === null || existingUser === void 0 ? void 0 : existingUser[0])) {
|
||||
return {
|
||||
success: false,
|
||||
msg: "User not found",
|
||||
};
|
||||
}
|
||||
const deleteUser = yield (0, deleteDbEntry_1.default)({
|
||||
dbContext: "Dsql User",
|
||||
dbFullName,
|
||||
tableName: "users",
|
||||
identifierColumnName: "id",
|
||||
identifierValue: deletedUserId,
|
||||
});
|
||||
return {
|
||||
success: true,
|
||||
result: deleteUser,
|
||||
};
|
||||
export default async function apiDeleteUser({ dbFullName, deletedUserId, }) {
|
||||
const existingUserQuery = `SELECT * FROM ${dbFullName}.users WHERE id = ?`;
|
||||
const existingUserValues = [deletedUserId];
|
||||
const existingUser = await varDatabaseDbHandler({
|
||||
queryString: existingUserQuery,
|
||||
queryValuesArray: existingUserValues,
|
||||
database: dbFullName,
|
||||
});
|
||||
if (!(existingUser === null || existingUser === void 0 ? void 0 : existingUser[0])) {
|
||||
return {
|
||||
success: false,
|
||||
msg: "User not found",
|
||||
};
|
||||
}
|
||||
const deleteUser = await deleteDbEntry({
|
||||
dbContext: "Dsql User",
|
||||
dbFullName,
|
||||
tableName: "users",
|
||||
identifierColumnName: "id",
|
||||
identifierValue: deletedUserId,
|
||||
});
|
||||
return {
|
||||
success: true,
|
||||
result: deleteUser,
|
||||
};
|
||||
}
|
||||
|
@ -1,41 +1,24 @@
|
||||
"use strict";
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = apiGetUser;
|
||||
const varDatabaseDbHandler_1 = __importDefault(require("../../backend/varDatabaseDbHandler"));
|
||||
import varDatabaseDbHandler from "../../backend/varDatabaseDbHandler";
|
||||
/**
|
||||
* # API Get User
|
||||
*/
|
||||
function apiGetUser(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ fields, dbFullName, userId, }) {
|
||||
const finalDbName = dbFullName.replace(/[^a-z0-9_]/g, "");
|
||||
const query = `SELECT ${fields.join(",")} FROM ${finalDbName}.users WHERE id=?`;
|
||||
const API_USER_ID = userId || process.env.DSQL_API_USER_ID;
|
||||
let foundUser = yield (0, varDatabaseDbHandler_1.default)({
|
||||
queryString: query,
|
||||
queryValuesArray: [API_USER_ID],
|
||||
database: finalDbName,
|
||||
});
|
||||
if (!foundUser || !foundUser[0]) {
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
};
|
||||
}
|
||||
return {
|
||||
success: true,
|
||||
payload: foundUser[0],
|
||||
};
|
||||
export default async function apiGetUser({ fields, dbFullName, userId, }) {
|
||||
const finalDbName = dbFullName.replace(/[^a-z0-9_]/g, "");
|
||||
const query = `SELECT ${fields.join(",")} FROM ${finalDbName}.users WHERE id=?`;
|
||||
const API_USER_ID = userId || process.env.DSQL_API_USER_ID;
|
||||
let foundUser = await varDatabaseDbHandler({
|
||||
queryString: query,
|
||||
queryValuesArray: [API_USER_ID],
|
||||
database: finalDbName,
|
||||
});
|
||||
if (!foundUser || !foundUser[0]) {
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
};
|
||||
}
|
||||
return {
|
||||
success: true,
|
||||
payload: foundUser[0],
|
||||
};
|
||||
}
|
||||
|
298
dist/package-shared/functions/api/users/api-login.js
vendored
298
dist/package-shared/functions/api/users/api-login.js
vendored
@ -1,162 +1,154 @@
|
||||
"use strict";
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = apiLoginUser;
|
||||
const grab_db_full_name_1 = __importDefault(require("../../../utils/grab-db-full-name"));
|
||||
const varDatabaseDbHandler_1 = __importDefault(require("../../backend/varDatabaseDbHandler"));
|
||||
const hashPassword_1 = __importDefault(require("../../dsql/hashPassword"));
|
||||
import grabDbFullName from "../../../utils/grab-db-full-name";
|
||||
import varDatabaseDbHandler from "../../backend/varDatabaseDbHandler";
|
||||
import hashPassword from "../../dsql/hashPassword";
|
||||
/**
|
||||
* # API Login
|
||||
*/
|
||||
function apiLoginUser(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ encryptionKey, email, username, password, database, additionalFields, email_login, email_login_code, email_login_field, skipPassword, social, dbUserId, debug, }) {
|
||||
const dbFullName = (0, grab_db_full_name_1.default)({ dbName: database, userId: dbUserId });
|
||||
const dbAppend = global.DSQL_USE_LOCAL ? "" : `${dbFullName}.`;
|
||||
/**
|
||||
* Check input validity
|
||||
*
|
||||
* @description Check input validity
|
||||
*/
|
||||
if ((email === null || email === void 0 ? void 0 : email.match(/ /)) ||
|
||||
(username && (username === null || username === void 0 ? void 0 : username.match(/ /))) ||
|
||||
(password && (password === null || password === void 0 ? void 0 : password.match(/ /)))) {
|
||||
return {
|
||||
success: false,
|
||||
msg: "Invalid Email/Password format",
|
||||
};
|
||||
}
|
||||
/**
|
||||
* Password hash
|
||||
*
|
||||
* @description Password hash
|
||||
*/
|
||||
let hashedPassword = password
|
||||
? (0, hashPassword_1.default)({
|
||||
encryptionKey: encryptionKey,
|
||||
password: password,
|
||||
})
|
||||
: null;
|
||||
export default async function apiLoginUser({ encryptionKey, email, username, password, database, additionalFields, email_login, email_login_code, email_login_field, skipPassword, social, dbUserId, debug, }) {
|
||||
const dbFullName = grabDbFullName({ dbName: database, userId: dbUserId });
|
||||
if (!dbFullName) {
|
||||
console.log(`Database Full Name couldn't be grabbed`);
|
||||
return {
|
||||
success: false,
|
||||
msg: `Database Full Name couldn't be grabbed`,
|
||||
};
|
||||
}
|
||||
const dbAppend = global.DSQL_USE_LOCAL ? "" : `${dbFullName}.`;
|
||||
/**
|
||||
* Check input validity
|
||||
*
|
||||
* @description Check input validity
|
||||
*/
|
||||
if ((email === null || email === void 0 ? void 0 : email.match(/ /)) ||
|
||||
(username && (username === null || username === void 0 ? void 0 : username.match(/ /))) ||
|
||||
(password && (password === null || password === void 0 ? void 0 : password.match(/ /)))) {
|
||||
return {
|
||||
success: false,
|
||||
msg: "Invalid Email/Password format",
|
||||
};
|
||||
}
|
||||
/**
|
||||
* Password hash
|
||||
*
|
||||
* @description Password hash
|
||||
*/
|
||||
let hashedPassword = password
|
||||
? hashPassword({
|
||||
encryptionKey: encryptionKey,
|
||||
password: password,
|
||||
})
|
||||
: null;
|
||||
if (debug) {
|
||||
console.log("apiLoginUser:database:", dbFullName);
|
||||
console.log("apiLoginUser:Finding User ...");
|
||||
}
|
||||
let foundUser = await varDatabaseDbHandler({
|
||||
queryString: `SELECT * FROM ${dbAppend}users WHERE email = ? OR username = ?`,
|
||||
queryValuesArray: [email, username],
|
||||
database: dbFullName,
|
||||
debug,
|
||||
});
|
||||
if (debug) {
|
||||
console.log("apiLoginUser:foundUser:", foundUser);
|
||||
}
|
||||
if ((!foundUser || !foundUser[0]) && !social)
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: "No user found",
|
||||
};
|
||||
let isPasswordCorrect = false;
|
||||
if (debug) {
|
||||
console.log("apiLoginUser:isPasswordCorrect:", isPasswordCorrect);
|
||||
}
|
||||
if ((foundUser === null || foundUser === void 0 ? void 0 : foundUser[0]) && !email_login && skipPassword) {
|
||||
isPasswordCorrect = true;
|
||||
}
|
||||
else if ((foundUser === null || foundUser === void 0 ? void 0 : foundUser[0]) && !email_login) {
|
||||
if (debug) {
|
||||
console.log("apiLoginUser:database:", dbFullName);
|
||||
console.log("apiLoginUser:Finding User ...");
|
||||
console.log("apiLoginUser:hashedPassword:", hashedPassword);
|
||||
console.log("apiLoginUser:foundUser[0].password:", foundUser[0].password);
|
||||
}
|
||||
let foundUser = yield (0, varDatabaseDbHandler_1.default)({
|
||||
queryString: `SELECT * FROM ${dbAppend}users WHERE email = ? OR username = ?`,
|
||||
isPasswordCorrect = hashedPassword === foundUser[0].password;
|
||||
}
|
||||
else if (foundUser &&
|
||||
foundUser[0] &&
|
||||
email_login &&
|
||||
email_login_code &&
|
||||
email_login_field) {
|
||||
const tempCode = foundUser[0][email_login_field];
|
||||
if (debug) {
|
||||
console.log("apiLoginUser:tempCode:", tempCode);
|
||||
}
|
||||
if (!tempCode)
|
||||
throw new Error("No code Found!");
|
||||
const tempCodeArray = tempCode.split("-");
|
||||
const [code, codeDate] = tempCodeArray;
|
||||
const millisecond15mins = 1000 * 60 * 15;
|
||||
if (Date.now() - Number(codeDate) > millisecond15mins) {
|
||||
throw new Error("Code Expired");
|
||||
}
|
||||
isPasswordCorrect = code === email_login_code;
|
||||
}
|
||||
let socialUserValid = false;
|
||||
if (!isPasswordCorrect && !socialUserValid) {
|
||||
return {
|
||||
success: false,
|
||||
msg: "Wrong password, no social login validity",
|
||||
payload: null,
|
||||
};
|
||||
}
|
||||
if (debug) {
|
||||
console.log("apiLoginUser:isPasswordCorrect:", isPasswordCorrect);
|
||||
console.log("apiLoginUser:email_login:", email_login);
|
||||
}
|
||||
if (isPasswordCorrect && email_login) {
|
||||
const resetTempCode = await varDatabaseDbHandler({
|
||||
queryString: `UPDATE ${dbAppend}users SET ${email_login_field} = '' WHERE email = ? OR username = ?`,
|
||||
queryValuesArray: [email, username],
|
||||
database: dbFullName,
|
||||
debug,
|
||||
});
|
||||
if (debug) {
|
||||
console.log("apiLoginUser:foundUser:", foundUser);
|
||||
}
|
||||
if ((!foundUser || !foundUser[0]) && !social)
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: "No user found",
|
||||
};
|
||||
let isPasswordCorrect = false;
|
||||
if (debug) {
|
||||
console.log("apiLoginUser:isPasswordCorrect:", isPasswordCorrect);
|
||||
}
|
||||
if ((foundUser === null || foundUser === void 0 ? void 0 : foundUser[0]) && !email_login && skipPassword) {
|
||||
isPasswordCorrect = true;
|
||||
}
|
||||
else if ((foundUser === null || foundUser === void 0 ? void 0 : foundUser[0]) && !email_login) {
|
||||
if (debug) {
|
||||
console.log("apiLoginUser:hashedPassword:", hashedPassword);
|
||||
console.log("apiLoginUser:foundUser[0].password:", foundUser[0].password);
|
||||
}
|
||||
isPasswordCorrect = hashedPassword === foundUser[0].password;
|
||||
}
|
||||
else if (foundUser &&
|
||||
foundUser[0] &&
|
||||
email_login &&
|
||||
email_login_code &&
|
||||
email_login_field) {
|
||||
const tempCode = foundUser[0][email_login_field];
|
||||
if (debug) {
|
||||
console.log("apiLoginUser:tempCode:", tempCode);
|
||||
}
|
||||
if (!tempCode)
|
||||
throw new Error("No code Found!");
|
||||
const tempCodeArray = tempCode.split("-");
|
||||
const [code, codeDate] = tempCodeArray;
|
||||
const millisecond15mins = 1000 * 60 * 15;
|
||||
if (Date.now() - Number(codeDate) > millisecond15mins) {
|
||||
throw new Error("Code Expired");
|
||||
}
|
||||
isPasswordCorrect = code === email_login_code;
|
||||
}
|
||||
let socialUserValid = false;
|
||||
if (!isPasswordCorrect && !socialUserValid) {
|
||||
return {
|
||||
success: false,
|
||||
msg: "Wrong password, no social login validity",
|
||||
payload: null,
|
||||
};
|
||||
}
|
||||
if (debug) {
|
||||
console.log("apiLoginUser:isPasswordCorrect:", isPasswordCorrect);
|
||||
console.log("apiLoginUser:email_login:", email_login);
|
||||
}
|
||||
if (isPasswordCorrect && email_login) {
|
||||
const resetTempCode = yield (0, varDatabaseDbHandler_1.default)({
|
||||
queryString: `UPDATE ${dbAppend}users SET ${email_login_field} = '' WHERE email = ? OR username = ?`,
|
||||
queryValuesArray: [email, username],
|
||||
database: dbFullName,
|
||||
});
|
||||
}
|
||||
let csrfKey = Math.random().toString(36).substring(2) +
|
||||
"-" +
|
||||
Math.random().toString(36).substring(2);
|
||||
let userPayload = {
|
||||
id: foundUser[0].id,
|
||||
first_name: foundUser[0].first_name,
|
||||
last_name: foundUser[0].last_name,
|
||||
username: foundUser[0].username,
|
||||
email: foundUser[0].email,
|
||||
phone: foundUser[0].phone,
|
||||
social_id: foundUser[0].social_id,
|
||||
image: foundUser[0].image,
|
||||
image_thumbnail: foundUser[0].image_thumbnail,
|
||||
verification_status: foundUser[0].verification_status,
|
||||
social_login: foundUser[0].social_login,
|
||||
social_platform: foundUser[0].social_platform,
|
||||
csrf_k: csrfKey,
|
||||
more_data: foundUser[0].more_user_data,
|
||||
logged_in_status: true,
|
||||
date: Date.now(),
|
||||
};
|
||||
if (debug) {
|
||||
console.log("apiLoginUser:userPayload:", userPayload);
|
||||
console.log("apiLoginUser:Sending Response Object ...");
|
||||
}
|
||||
const resposeObject = {
|
||||
success: true,
|
||||
msg: "Login Successful",
|
||||
payload: userPayload,
|
||||
userId: foundUser[0].id,
|
||||
csrf: csrfKey,
|
||||
};
|
||||
if (additionalFields &&
|
||||
Array.isArray(additionalFields) &&
|
||||
additionalFields.length > 0) {
|
||||
additionalFields.forEach((key) => {
|
||||
userPayload[key] = foundUser[0][key];
|
||||
});
|
||||
}
|
||||
return resposeObject;
|
||||
});
|
||||
}
|
||||
let csrfKey = Math.random().toString(36).substring(2) +
|
||||
"-" +
|
||||
Math.random().toString(36).substring(2);
|
||||
let userPayload = {
|
||||
id: foundUser[0].id,
|
||||
uid: foundUser[0].uid,
|
||||
uuid: foundUser[0].uuid,
|
||||
first_name: foundUser[0].first_name,
|
||||
last_name: foundUser[0].last_name,
|
||||
username: foundUser[0].username,
|
||||
email: foundUser[0].email,
|
||||
phone: foundUser[0].phone,
|
||||
social_id: foundUser[0].social_id,
|
||||
image: foundUser[0].image,
|
||||
image_thumbnail: foundUser[0].image_thumbnail,
|
||||
verification_status: foundUser[0].verification_status,
|
||||
social_login: foundUser[0].social_login,
|
||||
social_platform: foundUser[0].social_platform,
|
||||
csrf_k: csrfKey,
|
||||
more_data: foundUser[0].more_user_data,
|
||||
logged_in_status: true,
|
||||
date: Date.now(),
|
||||
};
|
||||
if (debug) {
|
||||
console.log("apiLoginUser:userPayload:", userPayload);
|
||||
console.log("apiLoginUser:Sending Response Object ...");
|
||||
}
|
||||
const resposeObject = {
|
||||
success: true,
|
||||
msg: "Login Successful",
|
||||
payload: userPayload,
|
||||
userId: foundUser[0].id,
|
||||
csrf: csrfKey,
|
||||
};
|
||||
if (additionalFields &&
|
||||
Array.isArray(additionalFields) &&
|
||||
additionalFields.length > 0) {
|
||||
additionalFields.forEach((key) => {
|
||||
userPayload[key] = foundUser[0][key];
|
||||
});
|
||||
}
|
||||
return resposeObject;
|
||||
}
|
||||
|
@ -1,75 +1,58 @@
|
||||
"use strict";
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = apiReauthUser;
|
||||
const varDatabaseDbHandler_1 = __importDefault(require("../../backend/varDatabaseDbHandler"));
|
||||
import varDatabaseDbHandler from "../../backend/varDatabaseDbHandler";
|
||||
/**
|
||||
* # Re-authenticate API user
|
||||
*/
|
||||
function apiReauthUser(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ existingUser, database, additionalFields, }) {
|
||||
const dbAppend = global.DSQL_USE_LOCAL
|
||||
? ""
|
||||
: database
|
||||
? `${database}.`
|
||||
: "";
|
||||
let foundUser = (existingUser === null || existingUser === void 0 ? void 0 : existingUser.id) && existingUser.id.toString().match(/./)
|
||||
? yield (0, varDatabaseDbHandler_1.default)({
|
||||
queryString: `SELECT * FROM ${dbAppend}users WHERE id=?`,
|
||||
queryValuesArray: [existingUser.id.toString()],
|
||||
database,
|
||||
})
|
||||
: null;
|
||||
if (!foundUser || !foundUser[0])
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: "No user found",
|
||||
};
|
||||
let csrfKey = Math.random().toString(36).substring(2) +
|
||||
"-" +
|
||||
Math.random().toString(36).substring(2);
|
||||
let userPayload = {
|
||||
id: foundUser[0].id,
|
||||
first_name: foundUser[0].first_name,
|
||||
last_name: foundUser[0].last_name,
|
||||
username: foundUser[0].username,
|
||||
email: foundUser[0].email,
|
||||
phone: foundUser[0].phone,
|
||||
social_id: foundUser[0].social_id,
|
||||
image: foundUser[0].image,
|
||||
image_thumbnail: foundUser[0].image_thumbnail,
|
||||
verification_status: foundUser[0].verification_status,
|
||||
social_login: foundUser[0].social_login,
|
||||
social_platform: foundUser[0].social_platform,
|
||||
csrf_k: csrfKey,
|
||||
more_data: foundUser[0].more_user_data,
|
||||
logged_in_status: true,
|
||||
date: Date.now(),
|
||||
};
|
||||
if (additionalFields &&
|
||||
Array.isArray(additionalFields) &&
|
||||
additionalFields.length > 0) {
|
||||
additionalFields.forEach((key) => {
|
||||
userPayload[key] = foundUser[0][key];
|
||||
});
|
||||
}
|
||||
export default async function apiReauthUser({ existingUser, database, additionalFields, }) {
|
||||
const dbAppend = global.DSQL_USE_LOCAL
|
||||
? ""
|
||||
: database
|
||||
? `${database}.`
|
||||
: "";
|
||||
let foundUser = (existingUser === null || existingUser === void 0 ? void 0 : existingUser.id) && existingUser.id.toString().match(/./)
|
||||
? await varDatabaseDbHandler({
|
||||
queryString: `SELECT * FROM ${dbAppend}users WHERE id=?`,
|
||||
queryValuesArray: [existingUser.id.toString()],
|
||||
database,
|
||||
})
|
||||
: null;
|
||||
if (!foundUser || !foundUser[0])
|
||||
return {
|
||||
success: true,
|
||||
msg: "Login Successful",
|
||||
payload: userPayload,
|
||||
csrf: csrfKey,
|
||||
success: false,
|
||||
payload: null,
|
||||
msg: "No user found",
|
||||
};
|
||||
});
|
||||
let csrfKey = Math.random().toString(36).substring(2) +
|
||||
"-" +
|
||||
Math.random().toString(36).substring(2);
|
||||
let userPayload = {
|
||||
id: foundUser[0].id,
|
||||
first_name: foundUser[0].first_name,
|
||||
last_name: foundUser[0].last_name,
|
||||
username: foundUser[0].username,
|
||||
email: foundUser[0].email,
|
||||
phone: foundUser[0].phone,
|
||||
social_id: foundUser[0].social_id,
|
||||
image: foundUser[0].image,
|
||||
image_thumbnail: foundUser[0].image_thumbnail,
|
||||
verification_status: foundUser[0].verification_status,
|
||||
social_login: foundUser[0].social_login,
|
||||
social_platform: foundUser[0].social_platform,
|
||||
csrf_k: csrfKey,
|
||||
more_data: foundUser[0].more_user_data,
|
||||
logged_in_status: true,
|
||||
date: Date.now(),
|
||||
};
|
||||
if (additionalFields &&
|
||||
Array.isArray(additionalFields) &&
|
||||
additionalFields.length > 0) {
|
||||
additionalFields.forEach((key) => {
|
||||
userPayload[key] = foundUser[0][key];
|
||||
});
|
||||
}
|
||||
return {
|
||||
success: true,
|
||||
msg: "Login Successful",
|
||||
payload: userPayload,
|
||||
csrf: csrfKey,
|
||||
};
|
||||
}
|
||||
|
@ -1,132 +1,115 @@
|
||||
"use strict";
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = apiSendEmailCode;
|
||||
const varDatabaseDbHandler_1 = __importDefault(require("../../backend/varDatabaseDbHandler"));
|
||||
const nodemailer_1 = __importDefault(require("nodemailer"));
|
||||
const get_auth_cookie_names_1 = __importDefault(require("../../backend/cookies/get-auth-cookie-names"));
|
||||
const encrypt_1 = __importDefault(require("../../dsql/encrypt"));
|
||||
const serialize_cookies_1 = __importDefault(require("../../../utils/serialize-cookies"));
|
||||
import varDatabaseDbHandler from "../../backend/varDatabaseDbHandler";
|
||||
import nodemailer from "nodemailer";
|
||||
import getAuthCookieNames from "../../backend/cookies/get-auth-cookie-names";
|
||||
import encrypt from "../../dsql/encrypt";
|
||||
import serializeCookies from "../../../utils/serialize-cookies";
|
||||
/**
|
||||
* # Send Email Login Code
|
||||
*/
|
||||
function apiSendEmailCode(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ email, database, email_login_field, mail_domain, mail_port, sender, mail_username, mail_password, html, response, extraCookies, }) {
|
||||
if (email === null || email === void 0 ? void 0 : email.match(/ /)) {
|
||||
return {
|
||||
success: false,
|
||||
msg: "Invalid Email/Password format",
|
||||
};
|
||||
export default async function apiSendEmailCode({ email, database, email_login_field, mail_domain, mail_port, sender, mail_username, mail_password, html, response, extraCookies, }) {
|
||||
if (email === null || email === void 0 ? void 0 : email.match(/ /)) {
|
||||
return {
|
||||
success: false,
|
||||
msg: "Invalid Email/Password format",
|
||||
};
|
||||
}
|
||||
const createdAt = Date.now();
|
||||
const foundUserQuery = `SELECT * FROM ${database}.users WHERE email = ?`;
|
||||
const foundUserValues = [email];
|
||||
let foundUser = await varDatabaseDbHandler({
|
||||
queryString: foundUserQuery,
|
||||
queryValuesArray: foundUserValues,
|
||||
database,
|
||||
});
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
if (!foundUser || !foundUser[0]) {
|
||||
return {
|
||||
success: false,
|
||||
msg: "No user found",
|
||||
};
|
||||
}
|
||||
function generateCode() {
|
||||
const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
|
||||
let code = "";
|
||||
for (let i = 0; i < 8; i++) {
|
||||
code += chars[Math.floor(Math.random() * chars.length)];
|
||||
}
|
||||
const createdAt = Date.now();
|
||||
const foundUserQuery = `SELECT * FROM ${database}.users WHERE email = ?`;
|
||||
const foundUserValues = [email];
|
||||
let foundUser = yield (0, varDatabaseDbHandler_1.default)({
|
||||
queryString: foundUserQuery,
|
||||
queryValuesArray: foundUserValues,
|
||||
return code;
|
||||
}
|
||||
if ((foundUser === null || foundUser === void 0 ? void 0 : foundUser[0]) && email_login_field) {
|
||||
const tempCode = generateCode();
|
||||
let transporter = nodemailer.createTransport({
|
||||
host: mail_domain || process.env.DSQL_MAIL_HOST,
|
||||
port: mail_port
|
||||
? mail_port
|
||||
: process.env.DSQL_MAIL_PORT
|
||||
? Number(process.env.DSQL_MAIL_PORT)
|
||||
: 465,
|
||||
secure: true,
|
||||
auth: {
|
||||
user: mail_username || process.env.DSQL_MAIL_EMAIL,
|
||||
pass: mail_password || process.env.DSQL_MAIL_PASSWORD,
|
||||
},
|
||||
});
|
||||
let mailObject = {};
|
||||
mailObject["from"] = `"Datasquirel SSO" <${sender || "support@datasquirel.com"}>`;
|
||||
mailObject["sender"] = sender || "support@datasquirel.com";
|
||||
mailObject["to"] = email;
|
||||
mailObject["subject"] = "One Time Login Code";
|
||||
mailObject["html"] = html.replace(/{{code}}/, tempCode);
|
||||
const info = await transporter.sendMail(mailObject);
|
||||
if (!(info === null || info === void 0 ? void 0 : info.accepted))
|
||||
throw new Error("Mail not Sent!");
|
||||
const setTempCodeQuery = `UPDATE ${database}.users SET ${email_login_field} = ? WHERE email = ?`;
|
||||
const setTempCodeValues = [tempCode + `-${createdAt}`, email];
|
||||
let setTempCode = await varDatabaseDbHandler({
|
||||
queryString: setTempCodeQuery,
|
||||
queryValuesArray: setTempCodeValues,
|
||||
database,
|
||||
});
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
if (!foundUser || !foundUser[0]) {
|
||||
return {
|
||||
success: false,
|
||||
msg: "No user found",
|
||||
};
|
||||
}
|
||||
function generateCode() {
|
||||
const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
|
||||
let code = "";
|
||||
for (let i = 0; i < 8; i++) {
|
||||
code += chars[Math.floor(Math.random() * chars.length)];
|
||||
/** @type {import("../../../types").SendOneTimeCodeEmailResponse} */
|
||||
const resObject = {
|
||||
success: true,
|
||||
code: tempCode,
|
||||
email: email,
|
||||
createdAt,
|
||||
msg: "Success",
|
||||
};
|
||||
if (response) {
|
||||
const cookieKeyNames = getAuthCookieNames();
|
||||
const oneTimeCodeCookieName = cookieKeyNames.oneTimeCodeName;
|
||||
const encryptedPayload = encrypt({
|
||||
data: JSON.stringify(resObject),
|
||||
});
|
||||
if (!encryptedPayload) {
|
||||
throw new Error("apiSendEmailCode Error: Failed to encrypt payload");
|
||||
}
|
||||
return code;
|
||||
}
|
||||
if ((foundUser === null || foundUser === void 0 ? void 0 : foundUser[0]) && email_login_field) {
|
||||
const tempCode = generateCode();
|
||||
let transporter = nodemailer_1.default.createTransport({
|
||||
host: mail_domain || process.env.DSQL_MAIL_HOST,
|
||||
port: mail_port
|
||||
? mail_port
|
||||
: process.env.DSQL_MAIL_PORT
|
||||
? Number(process.env.DSQL_MAIL_PORT)
|
||||
: 465,
|
||||
/** @type {import("../../../../package-shared/types").CookieObject} */
|
||||
const oneTimeCookieObject = {
|
||||
name: oneTimeCodeCookieName,
|
||||
value: encryptedPayload,
|
||||
sameSite: "Strict",
|
||||
path: "/",
|
||||
httpOnly: true,
|
||||
secure: true,
|
||||
auth: {
|
||||
user: mail_username || process.env.DSQL_MAIL_EMAIL,
|
||||
pass: mail_password || process.env.DSQL_MAIL_PASSWORD,
|
||||
},
|
||||
});
|
||||
let mailObject = {};
|
||||
mailObject["from"] = `"Datasquirel SSO" <${sender || "support@datasquirel.com"}>`;
|
||||
mailObject["sender"] = sender || "support@datasquirel.com";
|
||||
mailObject["to"] = email;
|
||||
mailObject["subject"] = "One Time Login Code";
|
||||
mailObject["html"] = html.replace(/{{code}}/, tempCode);
|
||||
const info = yield transporter.sendMail(mailObject);
|
||||
if (!(info === null || info === void 0 ? void 0 : info.accepted))
|
||||
throw new Error("Mail not Sent!");
|
||||
const setTempCodeQuery = `UPDATE ${database}.users SET ${email_login_field} = ? WHERE email = ?`;
|
||||
const setTempCodeValues = [tempCode + `-${createdAt}`, email];
|
||||
let setTempCode = yield (0, varDatabaseDbHandler_1.default)({
|
||||
queryString: setTempCodeQuery,
|
||||
queryValuesArray: setTempCodeValues,
|
||||
database,
|
||||
});
|
||||
/** @type {import("../../../types").SendOneTimeCodeEmailResponse} */
|
||||
const resObject = {
|
||||
success: true,
|
||||
code: tempCode,
|
||||
email: email,
|
||||
createdAt,
|
||||
msg: "Success",
|
||||
};
|
||||
if (response) {
|
||||
const cookieKeyNames = (0, get_auth_cookie_names_1.default)();
|
||||
const oneTimeCodeCookieName = cookieKeyNames.oneTimeCodeName;
|
||||
const encryptedPayload = (0, encrypt_1.default)({
|
||||
data: JSON.stringify(resObject),
|
||||
});
|
||||
if (!encryptedPayload) {
|
||||
throw new Error("apiSendEmailCode Error: Failed to encrypt payload");
|
||||
}
|
||||
/** @type {import("../../../../package-shared/types").CookieObject} */
|
||||
const oneTimeCookieObject = {
|
||||
name: oneTimeCodeCookieName,
|
||||
value: encryptedPayload,
|
||||
sameSite: "Strict",
|
||||
path: "/",
|
||||
httpOnly: true,
|
||||
secure: true,
|
||||
};
|
||||
/** @type {import("../../../../package-shared/types").CookieObject[]} */
|
||||
const cookiesObjectArray = extraCookies
|
||||
? [...extraCookies, oneTimeCookieObject]
|
||||
: [oneTimeCookieObject];
|
||||
const serializedCookies = (0, serialize_cookies_1.default)({
|
||||
cookies: cookiesObjectArray,
|
||||
});
|
||||
response.setHeader("Set-Cookie", serializedCookies);
|
||||
}
|
||||
return resObject;
|
||||
/** @type {import("../../../../package-shared/types").CookieObject[]} */
|
||||
const cookiesObjectArray = extraCookies
|
||||
? [...extraCookies, oneTimeCookieObject]
|
||||
: [oneTimeCookieObject];
|
||||
const serializedCookies = serializeCookies({
|
||||
cookies: cookiesObjectArray,
|
||||
});
|
||||
response.setHeader("Set-Cookie", serializedCookies);
|
||||
}
|
||||
else {
|
||||
return {
|
||||
success: false,
|
||||
msg: "Invalid Email/Password format",
|
||||
};
|
||||
}
|
||||
});
|
||||
return resObject;
|
||||
}
|
||||
else {
|
||||
return {
|
||||
success: false,
|
||||
msg: "Invalid Email/Password format",
|
||||
};
|
||||
}
|
||||
}
|
||||
|
@ -1,81 +1,64 @@
|
||||
"use strict";
|
||||
// @ts-check
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = apiUpdateUser;
|
||||
const updateDbEntry_1 = __importDefault(require("../../backend/db/updateDbEntry"));
|
||||
const encrypt_1 = __importDefault(require("../../dsql/encrypt"));
|
||||
const hashPassword_1 = __importDefault(require("../../dsql/hashPassword"));
|
||||
const varDatabaseDbHandler_1 = __importDefault(require("../../backend/varDatabaseDbHandler"));
|
||||
import updateDbEntry from "../../backend/db/updateDbEntry";
|
||||
import encrypt from "../../dsql/encrypt";
|
||||
import hashPassword from "../../dsql/hashPassword";
|
||||
import varDatabaseDbHandler from "../../backend/varDatabaseDbHandler";
|
||||
/**
|
||||
* # Update API User Function
|
||||
*/
|
||||
function apiUpdateUser(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ payload, dbFullName, updatedUserId, dbSchema, }) {
|
||||
const existingUserQuery = `SELECT * FROM ${dbFullName}.users WHERE id = ?`;
|
||||
const existingUserValues = [updatedUserId];
|
||||
const existingUser = yield (0, varDatabaseDbHandler_1.default)({
|
||||
queryString: existingUserQuery,
|
||||
queryValuesArray: existingUserValues,
|
||||
database: dbFullName,
|
||||
});
|
||||
if (!(existingUser === null || existingUser === void 0 ? void 0 : existingUser[0])) {
|
||||
return {
|
||||
success: false,
|
||||
msg: "User not found",
|
||||
};
|
||||
}
|
||||
const data = (() => {
|
||||
const reqBodyKeys = Object.keys(payload);
|
||||
const targetTableSchema = (() => {
|
||||
var _a;
|
||||
try {
|
||||
const targetDatabaseSchema = (_a = dbSchema === null || dbSchema === void 0 ? void 0 : dbSchema.tables) === null || _a === void 0 ? void 0 : _a.find((tbl) => tbl.tableName == "users");
|
||||
return targetDatabaseSchema;
|
||||
}
|
||||
catch (error) {
|
||||
return undefined;
|
||||
}
|
||||
})();
|
||||
/** @type {any} */
|
||||
const finalData = {};
|
||||
reqBodyKeys.forEach((key) => {
|
||||
var _a;
|
||||
const targetFieldSchema = (_a = targetTableSchema === null || targetTableSchema === void 0 ? void 0 : targetTableSchema.fields) === null || _a === void 0 ? void 0 : _a.find((field) => field.fieldName == key);
|
||||
if (key === null || key === void 0 ? void 0 : key.match(/^date_|^id$|^uuid$/))
|
||||
return;
|
||||
let value = payload[key];
|
||||
if (targetFieldSchema === null || targetFieldSchema === void 0 ? void 0 : targetFieldSchema.encrypted) {
|
||||
value = (0, encrypt_1.default)({ data: value });
|
||||
}
|
||||
finalData[key] = value;
|
||||
});
|
||||
if (finalData.password && typeof finalData.password == "string") {
|
||||
finalData.password = (0, hashPassword_1.default)({ password: finalData.password });
|
||||
}
|
||||
return finalData;
|
||||
})();
|
||||
const updateUser = yield (0, updateDbEntry_1.default)({
|
||||
dbFullName,
|
||||
tableName: "users",
|
||||
identifierColumnName: "id",
|
||||
identifierValue: updatedUserId,
|
||||
data: data,
|
||||
});
|
||||
return {
|
||||
success: true,
|
||||
payload: updateUser,
|
||||
};
|
||||
export default async function apiUpdateUser({ payload, dbFullName, updatedUserId, dbSchema, }) {
|
||||
const existingUserQuery = `SELECT * FROM ${dbFullName}.users WHERE id = ?`;
|
||||
const existingUserValues = [updatedUserId];
|
||||
const existingUser = await varDatabaseDbHandler({
|
||||
queryString: existingUserQuery,
|
||||
queryValuesArray: existingUserValues,
|
||||
database: dbFullName,
|
||||
});
|
||||
if (!(existingUser === null || existingUser === void 0 ? void 0 : existingUser[0])) {
|
||||
return {
|
||||
success: false,
|
||||
msg: "User not found",
|
||||
};
|
||||
}
|
||||
const data = (() => {
|
||||
const reqBodyKeys = Object.keys(payload);
|
||||
const targetTableSchema = (() => {
|
||||
var _a;
|
||||
try {
|
||||
const targetDatabaseSchema = (_a = dbSchema === null || dbSchema === void 0 ? void 0 : dbSchema.tables) === null || _a === void 0 ? void 0 : _a.find((tbl) => tbl.tableName == "users");
|
||||
return targetDatabaseSchema;
|
||||
}
|
||||
catch (error) {
|
||||
return undefined;
|
||||
}
|
||||
})();
|
||||
/** @type {any} */
|
||||
const finalData = {};
|
||||
reqBodyKeys.forEach((key) => {
|
||||
var _a;
|
||||
const targetFieldSchema = (_a = targetTableSchema === null || targetTableSchema === void 0 ? void 0 : targetTableSchema.fields) === null || _a === void 0 ? void 0 : _a.find((field) => field.fieldName == key);
|
||||
if (key === null || key === void 0 ? void 0 : key.match(/^date_|^id$|^uuid$/))
|
||||
return;
|
||||
let value = payload[key];
|
||||
if (targetFieldSchema === null || targetFieldSchema === void 0 ? void 0 : targetFieldSchema.encrypted) {
|
||||
value = encrypt({ data: value });
|
||||
}
|
||||
finalData[key] = value;
|
||||
});
|
||||
if (finalData.password && typeof finalData.password == "string") {
|
||||
finalData.password = hashPassword({ password: finalData.password });
|
||||
}
|
||||
return finalData;
|
||||
})();
|
||||
const updateUser = await updateDbEntry({
|
||||
dbFullName,
|
||||
tableName: "users",
|
||||
identifierColumnName: "id",
|
||||
identifierValue: updatedUserId,
|
||||
data: data,
|
||||
});
|
||||
return {
|
||||
success: true,
|
||||
payload: updateUser,
|
||||
};
|
||||
}
|
||||
|
@ -1,18 +1,12 @@
|
||||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = encryptReserPasswordUrl;
|
||||
const ejson_1 = __importDefault(require("../../../../../utils/ejson"));
|
||||
const encrypt_1 = __importDefault(require("../../../../dsql/encrypt"));
|
||||
function encryptReserPasswordUrl({ email, encryptionKey, encryptionSalt, }) {
|
||||
import EJSON from "../../../../../utils/ejson";
|
||||
import encrypt from "../../../../dsql/encrypt";
|
||||
export default function encryptReserPasswordUrl({ email, encryptionKey, encryptionSalt, }) {
|
||||
const encryptObject = {
|
||||
email,
|
||||
createdAt: Date.now(),
|
||||
};
|
||||
const encryptStr = (0, encrypt_1.default)({
|
||||
data: ejson_1.default.stringify(encryptObject),
|
||||
const encryptStr = encrypt({
|
||||
data: EJSON.stringify(encryptObject),
|
||||
encryptionKey,
|
||||
encryptionSalt,
|
||||
});
|
||||
|
@ -1,52 +1,36 @@
|
||||
"use strict";
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = apiSendResetPasswordLink;
|
||||
const grab_db_full_name_1 = __importDefault(require("../../../../utils/grab-db-full-name"));
|
||||
const varDatabaseDbHandler_1 = __importDefault(require("../../../backend/varDatabaseDbHandler"));
|
||||
import grabDbFullName from "../../../../utils/grab-db-full-name";
|
||||
import varDatabaseDbHandler from "../../../backend/varDatabaseDbHandler";
|
||||
/**
|
||||
* # API Login
|
||||
*/
|
||||
function apiSendResetPasswordLink(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ database, email, dbUserId, debug, }) {
|
||||
const dbFullName = (0, grab_db_full_name_1.default)({ dbName: database, userId: dbUserId });
|
||||
/**
|
||||
* Check input validity
|
||||
*
|
||||
* @description Check input validity
|
||||
*/
|
||||
if (email === null || email === void 0 ? void 0 : email.match(/ /)) {
|
||||
return {
|
||||
success: false,
|
||||
msg: "Invalid Email/Password format",
|
||||
};
|
||||
}
|
||||
let foundUser = yield (0, varDatabaseDbHandler_1.default)({
|
||||
queryString: `SELECT * FROM ${dbFullName}.users WHERE email = ? OR username = ?`,
|
||||
queryValuesArray: [email, email],
|
||||
database: dbFullName,
|
||||
debug,
|
||||
});
|
||||
if (debug) {
|
||||
console.log("apiSendResetPassword:foundUser:", foundUser);
|
||||
}
|
||||
const targetUser = foundUser === null || foundUser === void 0 ? void 0 : foundUser[0];
|
||||
if (!targetUser)
|
||||
return {
|
||||
success: false,
|
||||
msg: "No user found",
|
||||
};
|
||||
return { success: true };
|
||||
export default async function apiSendResetPasswordLink({ database, email, dbUserId, debug, }) {
|
||||
const dbFullName = grabDbFullName({ dbName: database, userId: dbUserId });
|
||||
if (!dbFullName) {
|
||||
return {
|
||||
success: false,
|
||||
msg: `Couldn't get database full name`,
|
||||
};
|
||||
}
|
||||
if (email === null || email === void 0 ? void 0 : email.match(/ /)) {
|
||||
return {
|
||||
success: false,
|
||||
msg: "Invalid Email/Password format",
|
||||
};
|
||||
}
|
||||
let foundUser = await varDatabaseDbHandler({
|
||||
queryString: `SELECT * FROM ${dbFullName}.users WHERE email = ? OR username = ?`,
|
||||
queryValuesArray: [email, email],
|
||||
database: dbFullName,
|
||||
debug,
|
||||
});
|
||||
if (debug) {
|
||||
console.log("apiSendResetPassword:foundUser:", foundUser);
|
||||
}
|
||||
const targetUser = foundUser === null || foundUser === void 0 ? void 0 : foundUser[0];
|
||||
if (!targetUser)
|
||||
return {
|
||||
success: false,
|
||||
msg: "No user found",
|
||||
};
|
||||
return { success: true };
|
||||
}
|
||||
|
@ -1,88 +1,71 @@
|
||||
"use strict";
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = apiGithubLogin;
|
||||
const handleSocialDb_1 = __importDefault(require("../../social-login/handleSocialDb"));
|
||||
const githubLogin_1 = __importDefault(require("../../social-login/githubLogin"));
|
||||
const camelJoinedtoCamelSpace_1 = __importDefault(require("../../../../utils/camelJoinedtoCamelSpace"));
|
||||
import handleSocialDb from "../../social-login/handleSocialDb";
|
||||
import githubLogin from "../../social-login/githubLogin";
|
||||
import camelJoinedtoCamelSpace from "../../../../utils/camelJoinedtoCamelSpace";
|
||||
/**
|
||||
* # API Login with Github
|
||||
*/
|
||||
function apiGithubLogin(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ code, clientId, clientSecret, database, additionalFields, email, additionalData, }) {
|
||||
if (!code || !clientId || !clientSecret || !database) {
|
||||
return {
|
||||
success: false,
|
||||
msg: "Missing query params",
|
||||
};
|
||||
}
|
||||
if (typeof code !== "string" ||
|
||||
typeof clientId !== "string" ||
|
||||
typeof clientSecret !== "string" ||
|
||||
typeof database !== "string") {
|
||||
return {
|
||||
success: false,
|
||||
msg: "Wrong Parameters",
|
||||
};
|
||||
}
|
||||
/**
|
||||
* Create new user folder and file
|
||||
*
|
||||
* @description Create new user folder and file
|
||||
*/
|
||||
const gitHubUser = yield (0, githubLogin_1.default)({
|
||||
code: code,
|
||||
clientId: clientId,
|
||||
clientSecret: clientSecret,
|
||||
});
|
||||
if (!gitHubUser) {
|
||||
return {
|
||||
success: false,
|
||||
msg: "No github user returned",
|
||||
};
|
||||
}
|
||||
const socialId = gitHubUser.name || gitHubUser.id || gitHubUser.login;
|
||||
const targetName = gitHubUser.name || gitHubUser.login;
|
||||
const nameArray = (targetName === null || targetName === void 0 ? void 0 : targetName.match(/ /))
|
||||
? targetName === null || targetName === void 0 ? void 0 : targetName.split(" ")
|
||||
: (targetName === null || targetName === void 0 ? void 0 : targetName.match(/\-/))
|
||||
? targetName === null || targetName === void 0 ? void 0 : targetName.split("-")
|
||||
: [targetName];
|
||||
let payload = {
|
||||
email: gitHubUser.email,
|
||||
first_name: (0, camelJoinedtoCamelSpace_1.default)(nameArray[0]),
|
||||
last_name: (0, camelJoinedtoCamelSpace_1.default)(nameArray[1]),
|
||||
social_id: socialId,
|
||||
social_platform: "github",
|
||||
image: gitHubUser.avatar_url,
|
||||
image_thumbnail: gitHubUser.avatar_url,
|
||||
username: "github-user-" + socialId,
|
||||
export default async function apiGithubLogin({ code, clientId, clientSecret, database, additionalFields, email, additionalData, }) {
|
||||
if (!code || !clientId || !clientSecret || !database) {
|
||||
return {
|
||||
success: false,
|
||||
msg: "Missing query params",
|
||||
};
|
||||
if (additionalData) {
|
||||
payload = Object.assign(Object.assign({}, payload), additionalData);
|
||||
}
|
||||
const loggedInGithubUser = yield (0, handleSocialDb_1.default)({
|
||||
database,
|
||||
email: gitHubUser.email,
|
||||
payload,
|
||||
social_platform: "github",
|
||||
supEmail: email,
|
||||
additionalFields,
|
||||
});
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
return Object.assign({}, loggedInGithubUser);
|
||||
}
|
||||
if (typeof code !== "string" ||
|
||||
typeof clientId !== "string" ||
|
||||
typeof clientSecret !== "string" ||
|
||||
typeof database !== "string") {
|
||||
return {
|
||||
success: false,
|
||||
msg: "Wrong Parameters",
|
||||
};
|
||||
}
|
||||
/**
|
||||
* Create new user folder and file
|
||||
*
|
||||
* @description Create new user folder and file
|
||||
*/
|
||||
const gitHubUser = await githubLogin({
|
||||
code: code,
|
||||
clientId: clientId,
|
||||
clientSecret: clientSecret,
|
||||
});
|
||||
if (!gitHubUser) {
|
||||
return {
|
||||
success: false,
|
||||
msg: "No github user returned",
|
||||
};
|
||||
}
|
||||
const socialId = gitHubUser.name || gitHubUser.id || gitHubUser.login;
|
||||
const targetName = gitHubUser.name || gitHubUser.login;
|
||||
const nameArray = (targetName === null || targetName === void 0 ? void 0 : targetName.match(/ /))
|
||||
? targetName === null || targetName === void 0 ? void 0 : targetName.split(" ")
|
||||
: (targetName === null || targetName === void 0 ? void 0 : targetName.match(/\-/))
|
||||
? targetName === null || targetName === void 0 ? void 0 : targetName.split("-")
|
||||
: [targetName];
|
||||
let payload = {
|
||||
email: gitHubUser.email,
|
||||
first_name: camelJoinedtoCamelSpace(nameArray[0]),
|
||||
last_name: camelJoinedtoCamelSpace(nameArray[1]),
|
||||
social_id: socialId,
|
||||
social_platform: "github",
|
||||
image: gitHubUser.avatar_url,
|
||||
image_thumbnail: gitHubUser.avatar_url,
|
||||
username: "github-user-" + socialId,
|
||||
};
|
||||
if (additionalData) {
|
||||
payload = Object.assign(Object.assign({}, payload), additionalData);
|
||||
}
|
||||
const loggedInGithubUser = await handleSocialDb({
|
||||
database,
|
||||
email: gitHubUser.email,
|
||||
payload,
|
||||
social_platform: "github",
|
||||
supEmail: email,
|
||||
additionalFields,
|
||||
});
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
return Object.assign({}, loggedInGithubUser);
|
||||
}
|
||||
|
@ -1,89 +1,72 @@
|
||||
"use strict";
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = apiGoogleLogin;
|
||||
const https_1 = __importDefault(require("https"));
|
||||
const handleSocialDb_1 = __importDefault(require("../../social-login/handleSocialDb"));
|
||||
const ejson_1 = __importDefault(require("../../../../utils/ejson"));
|
||||
import https from "https";
|
||||
import handleSocialDb from "../../social-login/handleSocialDb";
|
||||
import EJSON from "../../../../utils/ejson";
|
||||
/**
|
||||
* # API google login
|
||||
*/
|
||||
function apiGoogleLogin(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ token, database, additionalFields, additionalData, debug, loginOnly, }) {
|
||||
try {
|
||||
const gUser = yield new Promise((resolve, reject) => {
|
||||
https_1.default
|
||||
.request({
|
||||
method: "GET",
|
||||
hostname: "www.googleapis.com",
|
||||
path: "/oauth2/v3/userinfo",
|
||||
headers: {
|
||||
Authorization: `Bearer ${token}`,
|
||||
},
|
||||
}, (res) => {
|
||||
let data = "";
|
||||
res.on("data", (chunk) => {
|
||||
data += chunk;
|
||||
});
|
||||
res.on("end", () => {
|
||||
resolve(ejson_1.default.parse(data));
|
||||
});
|
||||
})
|
||||
.end();
|
||||
});
|
||||
if (!(gUser === null || gUser === void 0 ? void 0 : gUser.email_verified))
|
||||
throw new Error("No Google User.");
|
||||
/**
|
||||
* Create new user folder and file
|
||||
*
|
||||
* @description Create new user folder and file
|
||||
*/
|
||||
const { given_name, family_name, email, sub, picture } = gUser;
|
||||
let payloadObject = {
|
||||
email: email,
|
||||
first_name: given_name,
|
||||
last_name: family_name,
|
||||
social_id: sub,
|
||||
social_platform: "google",
|
||||
image: picture,
|
||||
image_thumbnail: picture,
|
||||
username: `google-user-${sub}`,
|
||||
};
|
||||
if (additionalData) {
|
||||
payloadObject = Object.assign(Object.assign({}, payloadObject), additionalData);
|
||||
}
|
||||
const loggedInGoogleUser = yield (0, handleSocialDb_1.default)({
|
||||
database,
|
||||
email: email || "",
|
||||
payload: payloadObject,
|
||||
social_platform: "google",
|
||||
additionalFields,
|
||||
debug,
|
||||
loginOnly,
|
||||
});
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
return Object.assign({}, loggedInGoogleUser);
|
||||
export default async function apiGoogleLogin({ token, database, additionalFields, additionalData, debug, loginOnly, }) {
|
||||
try {
|
||||
const gUser = await new Promise((resolve, reject) => {
|
||||
https
|
||||
.request({
|
||||
method: "GET",
|
||||
hostname: "www.googleapis.com",
|
||||
path: "/oauth2/v3/userinfo",
|
||||
headers: {
|
||||
Authorization: `Bearer ${token}`,
|
||||
},
|
||||
}, (res) => {
|
||||
let data = "";
|
||||
res.on("data", (chunk) => {
|
||||
data += chunk;
|
||||
});
|
||||
res.on("end", () => {
|
||||
resolve(EJSON.parse(data));
|
||||
});
|
||||
})
|
||||
.end();
|
||||
});
|
||||
if (!(gUser === null || gUser === void 0 ? void 0 : gUser.email_verified))
|
||||
throw new Error("No Google User.");
|
||||
/**
|
||||
* Create new user folder and file
|
||||
*
|
||||
* @description Create new user folder and file
|
||||
*/
|
||||
const { given_name, family_name, email, sub, picture } = gUser;
|
||||
let payloadObject = {
|
||||
email: email,
|
||||
first_name: given_name,
|
||||
last_name: family_name,
|
||||
social_id: sub,
|
||||
social_platform: "google",
|
||||
image: picture,
|
||||
image_thumbnail: picture,
|
||||
username: `google-user-${sub}`,
|
||||
};
|
||||
if (additionalData) {
|
||||
payloadObject = Object.assign(Object.assign({}, payloadObject), additionalData);
|
||||
}
|
||||
catch ( /** @type {any} */error) {
|
||||
console.log(`api-google-login.ts ERROR: ${error.message}`);
|
||||
return {
|
||||
success: false,
|
||||
payload: undefined,
|
||||
msg: error.message,
|
||||
};
|
||||
}
|
||||
});
|
||||
const loggedInGoogleUser = await handleSocialDb({
|
||||
database,
|
||||
email: email || "",
|
||||
payload: payloadObject,
|
||||
social_platform: "google",
|
||||
additionalFields,
|
||||
debug,
|
||||
loginOnly,
|
||||
});
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
return Object.assign({}, loggedInGoogleUser);
|
||||
}
|
||||
catch ( /** @type {any} */error) {
|
||||
console.log(`api-google-login.ts ERROR: ${error.message}`);
|
||||
return {
|
||||
success: false,
|
||||
payload: undefined,
|
||||
msg: error.message,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
@ -1,22 +1,7 @@
|
||||
"use strict";
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = addAdminUserOnLogin;
|
||||
const serverError_1 = __importDefault(require("./serverError"));
|
||||
const DB_HANDLER_1 = __importDefault(require("../../utils/backend/global-db/DB_HANDLER"));
|
||||
const addDbEntry_1 = __importDefault(require("./db/addDbEntry"));
|
||||
const LOCAL_DB_HANDLER_1 = __importDefault(require("../../utils/backend/global-db/LOCAL_DB_HANDLER"));
|
||||
import serverError from "./serverError";
|
||||
import DB_HANDLER from "../../utils/backend/global-db/DB_HANDLER";
|
||||
import addDbEntry from "./db/addDbEntry";
|
||||
import LOCAL_DB_HANDLER from "../../utils/backend/global-db/LOCAL_DB_HANDLER";
|
||||
/**
|
||||
* Add Admin User on Login
|
||||
* ==============================================================================
|
||||
@ -25,88 +10,86 @@ const LOCAL_DB_HANDLER_1 = __importDefault(require("../../utils/backend/global-d
|
||||
* admin user. This fires when the invited user has been logged in or a new account
|
||||
* has been created for the invited user
|
||||
*/
|
||||
function addAdminUserOnLogin(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ query, user, }) {
|
||||
var _b;
|
||||
try {
|
||||
const finalDbHandler = global.DSQL_USE_LOCAL
|
||||
? LOCAL_DB_HANDLER_1.default
|
||||
: DB_HANDLER_1.default;
|
||||
const { invite, database_access, priviledge, email } = query;
|
||||
const lastInviteTimeQuery = `SELECT date_created_code FROM invitations WHERE inviting_user_id=? AND invited_user_email=?`;
|
||||
const lastInviteTimeValues = [invite, email];
|
||||
const lastInviteTimeArray = yield finalDbHandler(lastInviteTimeQuery, lastInviteTimeValues);
|
||||
if (!lastInviteTimeArray || !lastInviteTimeArray[0]) {
|
||||
throw new Error("No Invitation Found");
|
||||
export default async function addAdminUserOnLogin({ query, user, }) {
|
||||
var _a;
|
||||
try {
|
||||
const finalDbHandler = global.DSQL_USE_LOCAL
|
||||
? LOCAL_DB_HANDLER
|
||||
: DB_HANDLER;
|
||||
const { invite, database_access, priviledge, email } = query;
|
||||
const lastInviteTimeQuery = `SELECT date_created_code FROM invitations WHERE inviting_user_id=? AND invited_user_email=?`;
|
||||
const lastInviteTimeValues = [invite, email];
|
||||
const lastInviteTimeArray = await finalDbHandler(lastInviteTimeQuery, lastInviteTimeValues);
|
||||
if (!lastInviteTimeArray || !lastInviteTimeArray[0]) {
|
||||
throw new Error("No Invitation Found");
|
||||
}
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
const invitingUserDbQuery = `SELECT first_name,last_name,email FROM users WHERE id=?`;
|
||||
const invitingUserDbValues = [invite];
|
||||
const invitingUserDb = await finalDbHandler(invitingUserDbQuery, invitingUserDbValues);
|
||||
if (invitingUserDb === null || invitingUserDb === void 0 ? void 0 : invitingUserDb[0]) {
|
||||
const existingUserUser = await finalDbHandler(`SELECT email FROM user_users WHERE user_id=? AND invited_user_id=? AND user_type='admin' AND email=?`, [invite, user.id, email]);
|
||||
if (existingUserUser === null || existingUserUser === void 0 ? void 0 : existingUserUser[0]) {
|
||||
console.log("User already added");
|
||||
}
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
const invitingUserDbQuery = `SELECT first_name,last_name,email FROM users WHERE id=?`;
|
||||
const invitingUserDbValues = [invite];
|
||||
const invitingUserDb = yield finalDbHandler(invitingUserDbQuery, invitingUserDbValues);
|
||||
if (invitingUserDb === null || invitingUserDb === void 0 ? void 0 : invitingUserDb[0]) {
|
||||
const existingUserUser = yield finalDbHandler(`SELECT email FROM user_users WHERE user_id=? AND invited_user_id=? AND user_type='admin' AND email=?`, [invite, user.id, email]);
|
||||
if (existingUserUser === null || existingUserUser === void 0 ? void 0 : existingUserUser[0]) {
|
||||
console.log("User already added");
|
||||
}
|
||||
else {
|
||||
(0, addDbEntry_1.default)({
|
||||
dbFullName: "datasquirel",
|
||||
tableName: "user_users",
|
||||
data: {
|
||||
user_id: invite,
|
||||
invited_user_id: user.id,
|
||||
database_access: database_access,
|
||||
first_name: user.first_name,
|
||||
last_name: user.last_name,
|
||||
phone: user.phone,
|
||||
email: user.email,
|
||||
username: user.username,
|
||||
user_type: "admin",
|
||||
user_priviledge: priviledge,
|
||||
image: user.image,
|
||||
image_thumbnail: user.image_thumbnail,
|
||||
},
|
||||
});
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
const dbTableData = yield finalDbHandler(`SELECT db_tables_data FROM invitations WHERE inviting_user_id=? AND invited_user_email=?`, [invite, email]);
|
||||
const clearEntries = yield finalDbHandler(`DELETE FROM delegated_user_tables WHERE root_user_id=? AND delegated_user_id=?`, [invite, user.id]);
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
if (dbTableData && dbTableData[0]) {
|
||||
const dbTableEntries = dbTableData[0].db_tables_data.split("|");
|
||||
for (let i = 0; i < dbTableEntries.length; i++) {
|
||||
const dbTableEntry = dbTableEntries[i];
|
||||
const dbTableEntryArray = dbTableEntry.split("-");
|
||||
const [db_slug, table_slug] = dbTableEntryArray;
|
||||
const newEntry = yield (0, addDbEntry_1.default)({
|
||||
dbFullName: "datasquirel",
|
||||
tableName: "delegated_user_tables",
|
||||
data: {
|
||||
delegated_user_id: user.id,
|
||||
root_user_id: invite,
|
||||
database: db_slug,
|
||||
table: table_slug,
|
||||
priviledge: priviledge,
|
||||
},
|
||||
});
|
||||
}
|
||||
else {
|
||||
addDbEntry({
|
||||
dbFullName: "datasquirel",
|
||||
tableName: "user_users",
|
||||
data: {
|
||||
user_id: invite,
|
||||
invited_user_id: user.id,
|
||||
database_access: database_access,
|
||||
first_name: user.first_name,
|
||||
last_name: user.last_name,
|
||||
phone: user.phone,
|
||||
email: user.email,
|
||||
username: user.username,
|
||||
user_type: "admin",
|
||||
user_priviledge: priviledge,
|
||||
image: user.image,
|
||||
image_thumbnail: user.image_thumbnail,
|
||||
},
|
||||
});
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
const dbTableData = await finalDbHandler(`SELECT db_tables_data FROM invitations WHERE inviting_user_id=? AND invited_user_email=?`, [invite, email]);
|
||||
const clearEntries = await finalDbHandler(`DELETE FROM delegated_user_tables WHERE root_user_id=? AND delegated_user_id=?`, [invite, user.id]);
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
if (dbTableData && dbTableData[0]) {
|
||||
const dbTableEntries = dbTableData[0].db_tables_data.split("|");
|
||||
for (let i = 0; i < dbTableEntries.length; i++) {
|
||||
const dbTableEntry = dbTableEntries[i];
|
||||
const dbTableEntryArray = dbTableEntry.split("-");
|
||||
const [db_slug, table_slug] = dbTableEntryArray;
|
||||
const newEntry = await addDbEntry({
|
||||
dbFullName: "datasquirel",
|
||||
tableName: "delegated_user_tables",
|
||||
data: {
|
||||
delegated_user_id: user.id,
|
||||
root_user_id: invite,
|
||||
database: db_slug,
|
||||
table: table_slug,
|
||||
priviledge: priviledge,
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
const inviteAccepted = yield finalDbHandler(`UPDATE invitations SET invitation_status='Accepted' WHERE inviting_user_id=? AND invited_user_email=?`, [invite, email]);
|
||||
}
|
||||
const inviteAccepted = await finalDbHandler(`UPDATE invitations SET invitation_status='Accepted' WHERE inviting_user_id=? AND invited_user_email=?`, [invite, email]);
|
||||
}
|
||||
catch (error) {
|
||||
(_b = global.ERROR_CALLBACK) === null || _b === void 0 ? void 0 : _b.call(global, `Add Admin User On Login Error`, error);
|
||||
(0, serverError_1.default)({
|
||||
component: "addAdminUserOnLogin",
|
||||
message: error.message,
|
||||
user: user,
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
catch (error) {
|
||||
(_a = global.ERROR_CALLBACK) === null || _a === void 0 ? void 0 : _a.call(global, `Add Admin User On Login Error`, error);
|
||||
serverError({
|
||||
component: "addAdminUserOnLogin",
|
||||
message: error.message,
|
||||
user: user,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
@ -1,70 +1,54 @@
|
||||
"use strict";
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = addMariadbUser;
|
||||
const generate_password_1 = __importDefault(require("generate-password"));
|
||||
const DB_HANDLER_1 = __importDefault(require("../../utils/backend/global-db/DB_HANDLER"));
|
||||
const NO_DB_HANDLER_1 = __importDefault(require("../../utils/backend/global-db/NO_DB_HANDLER"));
|
||||
const addDbEntry_1 = __importDefault(require("./db/addDbEntry"));
|
||||
const encrypt_1 = __importDefault(require("../dsql/encrypt"));
|
||||
const LOCAL_DB_HANDLER_1 = __importDefault(require("../../utils/backend/global-db/LOCAL_DB_HANDLER"));
|
||||
import generator from "generate-password";
|
||||
import DB_HANDLER from "../../utils/backend/global-db/DB_HANDLER";
|
||||
import NO_DB_HANDLER from "../../utils/backend/global-db/NO_DB_HANDLER";
|
||||
import addDbEntry from "./db/addDbEntry";
|
||||
import encrypt from "../dsql/encrypt";
|
||||
import LOCAL_DB_HANDLER from "../../utils/backend/global-db/LOCAL_DB_HANDLER";
|
||||
import grabSQLKeyName from "../../utils/grab-sql-key-name";
|
||||
/**
|
||||
* # Add Mariadb User
|
||||
*/
|
||||
function addMariadbUser(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ userId }) {
|
||||
try {
|
||||
const defaultMariadbUserHost = process.env.DSQL_DB_HOST || "127.0.0.1";
|
||||
const username = `dsql_user_${userId}`;
|
||||
const password = generate_password_1.default.generate({
|
||||
length: 16,
|
||||
numbers: true,
|
||||
symbols: true,
|
||||
uppercase: true,
|
||||
exclude: "*#.'`\"",
|
||||
});
|
||||
const encryptedPassword = (0, encrypt_1.default)({ data: password });
|
||||
const createMariadbUsersQuery = `CREATE USER IF NOT EXISTS '${username}'@'127.0.0.1' IDENTIFIED BY '${password}'`;
|
||||
if (global.DSQL_USE_LOCAL) {
|
||||
yield (0, LOCAL_DB_HANDLER_1.default)(createMariadbUsersQuery);
|
||||
}
|
||||
else {
|
||||
yield (0, NO_DB_HANDLER_1.default)(createMariadbUsersQuery);
|
||||
}
|
||||
const updateUserQuery = `UPDATE users SET mariadb_user = ?, mariadb_host = '127.0.0.1', mariadb_pass = ? WHERE id = ?`;
|
||||
const updateUserValues = [username, encryptedPassword, userId];
|
||||
const updateUser = global.DSQL_USE_LOCAL
|
||||
? yield (0, LOCAL_DB_HANDLER_1.default)(updateUserQuery, updateUserValues)
|
||||
: yield (0, DB_HANDLER_1.default)(updateUserQuery, updateUserValues);
|
||||
const addMariadbUser = yield (0, addDbEntry_1.default)({
|
||||
tableName: "mariadb_users",
|
||||
data: {
|
||||
user_id: userId,
|
||||
username,
|
||||
host: defaultMariadbUserHost,
|
||||
password: encryptedPassword,
|
||||
primary: "1",
|
||||
grants: '[{"database":"*","table":"*","privileges":["ALL"]}]',
|
||||
},
|
||||
dbContext: "Master",
|
||||
});
|
||||
console.log(`User ${userId} SQL credentials successfully added.`);
|
||||
export default async function addMariadbUser({ userId }) {
|
||||
try {
|
||||
const defaultMariadbUserHost = process.env.DSQL_DB_HOST || "127.0.0.1";
|
||||
const username = grabSQLKeyName({ type: "user", userId });
|
||||
const password = generator.generate({
|
||||
length: 16,
|
||||
numbers: true,
|
||||
symbols: true,
|
||||
uppercase: true,
|
||||
exclude: "*#.'`\"",
|
||||
});
|
||||
const encryptedPassword = encrypt({ data: password });
|
||||
const createMariadbUsersQuery = `CREATE USER IF NOT EXISTS '${username}'@'127.0.0.1' IDENTIFIED BY '${password}'`;
|
||||
if (global.DSQL_USE_LOCAL) {
|
||||
await LOCAL_DB_HANDLER(createMariadbUsersQuery);
|
||||
}
|
||||
catch ( /** @type {any} */error) {
|
||||
console.log(`Error in adding SQL user in 'addMariadbUser' function =>`, error.message);
|
||||
else {
|
||||
await NO_DB_HANDLER(createMariadbUsersQuery);
|
||||
}
|
||||
});
|
||||
const updateUserQuery = `UPDATE users SET mariadb_user = ?, mariadb_host = '127.0.0.1', mariadb_pass = ? WHERE id = ?`;
|
||||
const updateUserValues = [username, encryptedPassword, userId];
|
||||
const updateUser = global.DSQL_USE_LOCAL
|
||||
? await LOCAL_DB_HANDLER(updateUserQuery, updateUserValues)
|
||||
: await DB_HANDLER(updateUserQuery, updateUserValues);
|
||||
const addMariadbUser = await addDbEntry({
|
||||
tableName: "mariadb_users",
|
||||
data: {
|
||||
user_id: userId,
|
||||
username,
|
||||
host: defaultMariadbUserHost,
|
||||
password: encryptedPassword,
|
||||
primary: "1",
|
||||
grants: '[{"database":"*","table":"*","privileges":["ALL"]}]',
|
||||
},
|
||||
dbContext: "Master",
|
||||
});
|
||||
console.log(`User ${userId} SQL credentials successfully added.`);
|
||||
}
|
||||
catch ( /** @type {any} */error) {
|
||||
console.log(`Error in adding SQL user in 'addMariadbUser' function =>`, error.message);
|
||||
}
|
||||
}
|
||||
////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////
|
||||
|
@ -4,9 +4,10 @@ type Param = {
|
||||
payload?: {
|
||||
[s: string]: any;
|
||||
};
|
||||
dbId: string | number;
|
||||
};
|
||||
/**
|
||||
* # Add User Table to Database
|
||||
*/
|
||||
export default function addUsersTableToDb({ userId, database, payload, }: Param): Promise<any>;
|
||||
export default function addUsersTableToDb({ userId, database, payload, dbId, }: Param): Promise<any>;
|
||||
export {};
|
||||
|
@ -1,81 +1,63 @@
|
||||
"use strict";
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = addUsersTableToDb;
|
||||
const serverError_1 = __importDefault(require("./serverError"));
|
||||
const DB_HANDLER_1 = __importDefault(require("../../utils/backend/global-db/DB_HANDLER"));
|
||||
const grabUserSchemaData_1 = __importDefault(require("./grabUserSchemaData"));
|
||||
const setUserSchemaData_1 = __importDefault(require("./setUserSchemaData"));
|
||||
const addDbEntry_1 = __importDefault(require("./db/addDbEntry"));
|
||||
const createDbFromSchema_1 = __importDefault(require("../../shell/createDbFromSchema"));
|
||||
const LOCAL_DB_HANDLER_1 = __importDefault(require("../../utils/backend/global-db/LOCAL_DB_HANDLER"));
|
||||
const grabNewUsersTableSchema_1 = __importDefault(require("./grabNewUsersTableSchema"));
|
||||
import serverError from "./serverError";
|
||||
import DB_HANDLER from "../../utils/backend/global-db/DB_HANDLER";
|
||||
import addDbEntry from "./db/addDbEntry";
|
||||
import createDbFromSchema from "../../shell/createDbFromSchema";
|
||||
import LOCAL_DB_HANDLER from "../../utils/backend/global-db/LOCAL_DB_HANDLER";
|
||||
import grabNewUsersTableSchema from "./grabNewUsersTableSchema";
|
||||
import { grabPrimaryRequiredDbSchema, writeUpdatedDbSchema, } from "../../shell/createDbFromSchema/grab-required-database-schemas";
|
||||
/**
|
||||
* # Add User Table to Database
|
||||
*/
|
||||
function addUsersTableToDb(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ userId, database, payload, }) {
|
||||
try {
|
||||
const dbFullName = database;
|
||||
const userPreset = (0, grabNewUsersTableSchema_1.default)({ payload });
|
||||
if (!userPreset)
|
||||
throw new Error("Couldn't Get User Preset!");
|
||||
const userSchemaData = (0, grabUserSchemaData_1.default)({ userId });
|
||||
if (!userSchemaData)
|
||||
throw new Error("User schema data not found!");
|
||||
let targetDatabase = userSchemaData.find((db) => db.dbFullName === database);
|
||||
if (!targetDatabase) {
|
||||
throw new Error("Couldn't Find Target Database!");
|
||||
}
|
||||
let existingTableIndex = targetDatabase === null || targetDatabase === void 0 ? void 0 : targetDatabase.tables.findIndex((table) => table.tableName === "users");
|
||||
if (typeof existingTableIndex == "number" && existingTableIndex > 0) {
|
||||
targetDatabase.tables[existingTableIndex] = userPreset;
|
||||
}
|
||||
else {
|
||||
targetDatabase.tables.push(userPreset);
|
||||
}
|
||||
(0, setUserSchemaData_1.default)({ schemaData: userSchemaData, userId });
|
||||
const targetDb = global.DSQL_USE_LOCAL
|
||||
? yield (0, LOCAL_DB_HANDLER_1.default)(`SELECT id FROM user_databases WHERE user_id=? AND db_slug=?`, [userId, database])
|
||||
: yield (0, DB_HANDLER_1.default)(`SELECT id FROM user_databases WHERE user_id=? AND db_slug=?`, [userId, database]);
|
||||
if (targetDb === null || targetDb === void 0 ? void 0 : targetDb[0]) {
|
||||
const newTableEntry = yield (0, addDbEntry_1.default)({
|
||||
dbFullName: "datasquirel",
|
||||
tableName: "user_database_tables",
|
||||
data: {
|
||||
user_id: userId,
|
||||
db_id: targetDb[0].id,
|
||||
db_slug: targetDatabase.dbSlug,
|
||||
table_name: "Users",
|
||||
table_slug: "users",
|
||||
},
|
||||
});
|
||||
}
|
||||
const dbShellUpdate = yield (0, createDbFromSchema_1.default)({
|
||||
userId,
|
||||
targetDatabase: dbFullName,
|
||||
});
|
||||
return `Done!`;
|
||||
export default async function addUsersTableToDb({ userId, database, payload, dbId, }) {
|
||||
try {
|
||||
const dbFullName = database;
|
||||
const userPreset = grabNewUsersTableSchema({ payload });
|
||||
if (!userPreset)
|
||||
throw new Error("Couldn't Get User Preset!");
|
||||
let targetDatabase = grabPrimaryRequiredDbSchema({
|
||||
dbId,
|
||||
userId,
|
||||
});
|
||||
if (!targetDatabase) {
|
||||
throw new Error("Couldn't Find Target Database!");
|
||||
}
|
||||
catch ( /** @type {any} */error) {
|
||||
console.log(`addUsersTableToDb.ts ERROR: ${error.message}`);
|
||||
(0, serverError_1.default)({
|
||||
component: "addUsersTableToDb",
|
||||
message: error.message,
|
||||
user: { id: userId },
|
||||
});
|
||||
return error.message;
|
||||
let existingTableIndex = targetDatabase === null || targetDatabase === void 0 ? void 0 : targetDatabase.tables.findIndex((table) => table.tableName === "users");
|
||||
if (typeof existingTableIndex == "number" && existingTableIndex > 0) {
|
||||
targetDatabase.tables[existingTableIndex] = userPreset;
|
||||
}
|
||||
});
|
||||
else {
|
||||
targetDatabase.tables.push(userPreset);
|
||||
}
|
||||
writeUpdatedDbSchema({ dbSchema: targetDatabase, userId });
|
||||
const targetDb = global.DSQL_USE_LOCAL
|
||||
? await LOCAL_DB_HANDLER(`SELECT id FROM user_databases WHERE user_id=? AND db_slug=?`, [userId, database])
|
||||
: await DB_HANDLER(`SELECT id FROM user_databases WHERE user_id=? AND db_slug=?`, [userId, database]);
|
||||
if (targetDb === null || targetDb === void 0 ? void 0 : targetDb[0]) {
|
||||
const newTableEntry = await addDbEntry({
|
||||
dbFullName: "datasquirel",
|
||||
tableName: "user_database_tables",
|
||||
data: {
|
||||
user_id: userId,
|
||||
db_id: targetDb[0].id,
|
||||
db_slug: targetDatabase.dbSlug,
|
||||
table_name: "Users",
|
||||
table_slug: "users",
|
||||
},
|
||||
});
|
||||
}
|
||||
const dbShellUpdate = await createDbFromSchema({
|
||||
userId,
|
||||
targetDatabase: dbFullName,
|
||||
});
|
||||
return `Done!`;
|
||||
}
|
||||
catch ( /** @type {any} */error) {
|
||||
console.log(`addUsersTableToDb.ts ERROR: ${error.message}`);
|
||||
serverError({
|
||||
component: "addUsersTableToDb",
|
||||
message: error.message,
|
||||
user: { id: userId },
|
||||
});
|
||||
return error.message;
|
||||
}
|
||||
}
|
||||
|
@ -1,6 +1,4 @@
|
||||
import { CheckApiCredentialsFn } from "../../types";
|
||||
export {};
|
||||
/**
|
||||
* # 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