Refactor Code to typescript
This commit is contained in:
parent
549d0abc02
commit
eb0992f28d
7
client/auth/github/getAccessToken.d.ts
vendored
7
client/auth/github/getAccessToken.d.ts
vendored
@ -1,7 +0,0 @@
|
|||||||
declare function _exports({ clientId, redirectUrl, setLoading, scopes }: {
|
|
||||||
clientId: string;
|
|
||||||
redirectUrl: string;
|
|
||||||
setLoading?: (arg0: boolean) => void;
|
|
||||||
scopes?: string[];
|
|
||||||
}): void;
|
|
||||||
export = _exports;
|
|
@ -1,36 +0,0 @@
|
|||||||
// @ts-check
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Login with Github Function
|
|
||||||
* ===============================================================================
|
|
||||||
* @description This function uses github api to login a user with datasquirel
|
|
||||||
*
|
|
||||||
* @async
|
|
||||||
*
|
|
||||||
* @param {object} params - Single object passed
|
|
||||||
* @param {string} params.clientId - Github app client ID: {@link https://datasquirel.com/docs}
|
|
||||||
* @param {string} params.redirectUrl - Github Redirect URL as listed in your oauth app settings: {@link https://datasquirel.com/docs}
|
|
||||||
* @param {function(boolean): void} [params.setLoading] - React setState Function: sets whether the google login button is ready or not
|
|
||||||
* @param {string[]} [params.scopes] - Scopes to be requested from the user
|
|
||||||
*
|
|
||||||
* @returns {void} - Return
|
|
||||||
*/
|
|
||||||
module.exports = function getAccessToken({ clientId, redirectUrl, setLoading, scopes }) {
|
|
||||||
/**
|
|
||||||
* == Initialize
|
|
||||||
*
|
|
||||||
* @description Initialize
|
|
||||||
*/
|
|
||||||
if (setLoading) setLoading(true);
|
|
||||||
|
|
||||||
const scopeString = scopes ? scopes.join("%20") : "read:user";
|
|
||||||
const fetchUrl = `https://github.com/login/oauth/authorize?client_id=${clientId}&scope=${scopeString}&redirect_uri=${redirectUrl}`;
|
|
||||||
window.location.assign(fetchUrl);
|
|
||||||
|
|
||||||
//////////////////////////////////////////////////////////////////////////////////
|
|
||||||
//////////////////////////////////////////////////////////////////////////////////
|
|
||||||
//////////////////////////////////////////////////////////////////////////////////
|
|
||||||
//////////////////////////////////////////////////////////////////////////////////
|
|
||||||
//////////////////////////////////////////////////////////////////////////////////
|
|
||||||
//////////////////////////////////////////////////////////////////////////////////
|
|
||||||
};
|
|
24
client/auth/github/getAccessToken.ts
Normal file
24
client/auth/github/getAccessToken.ts
Normal file
@ -0,0 +1,24 @@
|
|||||||
|
type Param = {
|
||||||
|
clientId: string;
|
||||||
|
redirectUrl: string;
|
||||||
|
setLoading?: (arg0: boolean) => void;
|
||||||
|
scopes?: string[];
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Login with Github Function
|
||||||
|
* ===============================================================================
|
||||||
|
* @description This function uses github api to login a user with datasquirel
|
||||||
|
*/
|
||||||
|
export default function getAccessToken({
|
||||||
|
clientId,
|
||||||
|
redirectUrl,
|
||||||
|
setLoading,
|
||||||
|
scopes,
|
||||||
|
}: Param): void {
|
||||||
|
if (setLoading) setLoading(true);
|
||||||
|
|
||||||
|
const scopeString = scopes ? scopes.join("%20") : "read:user";
|
||||||
|
const fetchUrl = `https://github.com/login/oauth/authorize?client_id=${clientId}&scope=${scopeString}&redirect_uri=${redirectUrl}`;
|
||||||
|
window.location.assign(fetchUrl);
|
||||||
|
}
|
19
client/auth/google/getAccessToken.d.ts
vendored
19
client/auth/google/getAccessToken.d.ts
vendored
@ -1,19 +0,0 @@
|
|||||||
declare namespace _exports {
|
|
||||||
export { GoogleGetAccessTokenFunctionParams };
|
|
||||||
}
|
|
||||||
declare function _exports(params: GoogleGetAccessTokenFunctionParams): Promise<string>;
|
|
||||||
export = _exports;
|
|
||||||
type GoogleGetAccessTokenFunctionParams = {
|
|
||||||
/**
|
|
||||||
* - Google app client ID: {@link https://datasquirel.com/docs}
|
|
||||||
*/
|
|
||||||
clientId: string;
|
|
||||||
/**
|
|
||||||
* - Whether to trigger Google signing popup or not: {@link https://datasquirel.com/docs}
|
|
||||||
*/
|
|
||||||
triggerPrompt?: boolean;
|
|
||||||
/**
|
|
||||||
* - React setState Function: sets whether the google login button is ready or not
|
|
||||||
*/
|
|
||||||
setLoading?: React.Dispatch<React.SetStateAction<boolean>>;
|
|
||||||
};
|
|
@ -1,33 +1,22 @@
|
|||||||
// @ts-check
|
interface GoogleGetAccessTokenFunctionParams {
|
||||||
|
clientId: string;
|
||||||
|
triggerPrompt?: boolean;
|
||||||
|
setLoading?: React.Dispatch<React.SetStateAction<boolean>>;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
let interval: any;
|
||||||
* @typedef {object} GoogleGetAccessTokenFunctionParams
|
|
||||||
* @property {string} clientId - Google app client ID: {@link https://datasquirel.com/docs}
|
|
||||||
* @property {boolean} [triggerPrompt] - Whether to trigger Google signing popup or not: {@link https://datasquirel.com/docs}
|
|
||||||
* @property {React.Dispatch<React.SetStateAction<boolean>>} [setLoading] - React setState Function: sets whether the google login button is ready or not
|
|
||||||
*
|
|
||||||
*/
|
|
||||||
|
|
||||||
/** @type {any} */
|
|
||||||
let interval;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Login with Google Function
|
* Login with Google Function
|
||||||
* ===============================================================================
|
* ===============================================================================
|
||||||
* @description This function uses google identity api to login a user with datasquirel
|
* @description This function uses google identity api to login a user with datasquirel
|
||||||
*
|
|
||||||
* @async
|
|
||||||
*
|
|
||||||
* @requires script "https://accounts.google.com/gsi/client" async script added to head
|
|
||||||
*
|
|
||||||
* @param {GoogleGetAccessTokenFunctionParams} params - Single object passed
|
|
||||||
|
|
||||||
* @returns {Promise<string>} - Access Token String
|
|
||||||
*/
|
*/
|
||||||
module.exports = async function getAccessToken(params) {
|
export default async function getAccessToken(
|
||||||
|
params: GoogleGetAccessTokenFunctionParams
|
||||||
|
): Promise<string> {
|
||||||
params.setLoading?.(true);
|
params.setLoading?.(true);
|
||||||
|
|
||||||
const response = await new Promise((resolve, reject) => {
|
const response = (await new Promise((resolve, reject) => {
|
||||||
interval = setInterval(() => {
|
interval = setInterval(() => {
|
||||||
// @ts-ignore
|
// @ts-ignore
|
||||||
let google = window.google;
|
let google = window.google;
|
||||||
@ -37,20 +26,22 @@ module.exports = async function getAccessToken(params) {
|
|||||||
resolve(googleLogin({ ...params, google }));
|
resolve(googleLogin({ ...params, google }));
|
||||||
}
|
}
|
||||||
}, 500);
|
}, 500);
|
||||||
});
|
})) as any;
|
||||||
|
|
||||||
params.setLoading?.(false);
|
params.setLoading?.(false);
|
||||||
|
|
||||||
return response;
|
return response;
|
||||||
};
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* # Google Login Function
|
* # Google Login Function
|
||||||
*
|
|
||||||
* @param {GoogleGetAccessTokenFunctionParams & { google: any }} params
|
|
||||||
* @returns
|
|
||||||
*/
|
*/
|
||||||
function googleLogin({ google, clientId, setLoading, triggerPrompt }) {
|
export function googleLogin({
|
||||||
|
google,
|
||||||
|
clientId,
|
||||||
|
setLoading,
|
||||||
|
triggerPrompt,
|
||||||
|
}: GoogleGetAccessTokenFunctionParams & { google: any }) {
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
setLoading?.(false);
|
setLoading?.(false);
|
||||||
}, 3000);
|
}, 3000);
|
||||||
@ -60,7 +51,9 @@ function googleLogin({ google, clientId, setLoading, triggerPrompt }) {
|
|||||||
* # Callback Function
|
* # Callback Function
|
||||||
* @param {import("../../../package-shared/types").GoogleAccessTokenObject} response
|
* @param {import("../../../package-shared/types").GoogleAccessTokenObject} response
|
||||||
*/
|
*/
|
||||||
function handleCredentialResponse(response) {
|
function handleCredentialResponse(
|
||||||
|
response: import("../../../package-shared/types").GoogleAccessTokenObject
|
||||||
|
) {
|
||||||
resolve(response.access_token);
|
resolve(response.access_token);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -81,7 +74,9 @@ function googleLogin({ google, clientId, setLoading, triggerPrompt }) {
|
|||||||
* ========================================================
|
* ========================================================
|
||||||
* @param {import("../../../package-shared/types").GoogleIdentityPromptNotification} notification
|
* @param {import("../../../package-shared/types").GoogleIdentityPromptNotification} notification
|
||||||
*/
|
*/
|
||||||
function triggerGooglePromptCallback(notification) {
|
function triggerGooglePromptCallback(
|
||||||
|
notification: import("../../../package-shared/types").GoogleIdentityPromptNotification
|
||||||
|
) {
|
||||||
console.log(notification);
|
console.log(notification);
|
||||||
}
|
}
|
||||||
});
|
});
|
2
client/auth/logout.d.ts
vendored
2
client/auth/logout.d.ts
vendored
@ -1,2 +0,0 @@
|
|||||||
declare function _exports(params: object | null): Promise<boolean>;
|
|
||||||
export = _exports;
|
|
@ -1,146 +0,0 @@
|
|||||||
/**
|
|
||||||
* Type Definitions
|
|
||||||
* ===============================================================================
|
|
||||||
*/
|
|
||||||
|
|
||||||
const parseClientCookies = require("../utils/parseClientCookies");
|
|
||||||
|
|
||||||
//////////////////////////////////////////////////////////////////////////////////
|
|
||||||
//////////////////////////////////////////////////////////////////////////////////
|
|
||||||
//////////////////////////////////////////////////////////////////////////////////
|
|
||||||
//////////////////////////////////////////////////////////////////////////////////
|
|
||||||
//////////////////////////////////////////////////////////////////////////////////
|
|
||||||
//////////////////////////////////////////////////////////////////////////////////
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Login with Google Function
|
|
||||||
* ===============================================================================
|
|
||||||
* @description This function uses google identity api to login a user with datasquirel
|
|
||||||
*
|
|
||||||
* @async
|
|
||||||
*
|
|
||||||
* @param {object|null} params - Single object passed
|
|
||||||
* @param {string|null} params.googleClientId - Google client Id if applicable
|
|
||||||
*
|
|
||||||
* @requires localStorageUser - a "user" JSON string stored in local storage with all
|
|
||||||
* the necessary user data gotten from the server
|
|
||||||
*
|
|
||||||
* @returns {Promise<boolean>} - Return
|
|
||||||
*/
|
|
||||||
module.exports = async function logout(params) {
|
|
||||||
/**
|
|
||||||
* == Initialize
|
|
||||||
*
|
|
||||||
* @description Initialize
|
|
||||||
*/
|
|
||||||
const localUser = localStorage.getItem("user");
|
|
||||||
let targetUser;
|
|
||||||
|
|
||||||
try {
|
|
||||||
targetUser = JSON.parse(localUser);
|
|
||||||
} catch (error) {
|
|
||||||
console.log(error);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!targetUser) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
////////////////////////////////////////
|
|
||||||
////////////////////////////////////////
|
|
||||||
////////////////////////////////////////
|
|
||||||
|
|
||||||
const cookies = parseClientCookies();
|
|
||||||
const socialId = 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("csrf");
|
|
||||||
|
|
||||||
document.cookie = `datasquirel_social_id=null;samesite=strict;path=/`;
|
|
||||||
|
|
||||||
////////////////////////////////////////
|
|
||||||
////////////////////////////////////////
|
|
||||||
////////////////////////////////////////
|
|
||||||
|
|
||||||
const response = await new Promise((resolve, reject) => {
|
|
||||||
//////////////////////////////////////////////////////////////////////////////////
|
|
||||||
//////////////////////////////////////////////////////////////////////////////////
|
|
||||||
//////////////////////////////////////////////////////////////////////////////////
|
|
||||||
//////////////////////////////////////////////////////////////////////////////////
|
|
||||||
//////////////////////////////////////////////////////////////////////////////////
|
|
||||||
//////////////////////////////////////////////////////////////////////////////////
|
|
||||||
|
|
||||||
if (socialId && !socialId?.match(/^null$/i)) {
|
|
||||||
const googleClientId = 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) {
|
|
||||||
if (google) {
|
|
||||||
////////////////////////////////////////
|
|
||||||
////////////////////////////////////////
|
|
||||||
////////////////////////////////////////
|
|
||||||
|
|
||||||
google.accounts.id.initialize({
|
|
||||||
client_id: googleClientId,
|
|
||||||
});
|
|
||||||
|
|
||||||
google.accounts.id.revoke(socialId, (done) => {
|
|
||||||
console.log(done.error);
|
|
||||||
|
|
||||||
resolve(true);
|
|
||||||
});
|
|
||||||
|
|
||||||
////////////////////////////////////////
|
|
||||||
////////////////////////////////////////
|
|
||||||
////////////////////////////////////////
|
|
||||||
}
|
|
||||||
};
|
|
||||||
} else {
|
|
||||||
resolve(true);
|
|
||||||
}
|
|
||||||
|
|
||||||
////////////////////////////////////////
|
|
||||||
////////////////////////////////////////
|
|
||||||
////////////////////////////////////////
|
|
||||||
} else {
|
|
||||||
resolve(true);
|
|
||||||
}
|
|
||||||
|
|
||||||
//////////////////////////////////////////////////////////////////////////////////
|
|
||||||
//////////////////////////////////////////////////////////////////////////////////
|
|
||||||
//////////////////////////////////////////////////////////////////////////////////
|
|
||||||
//////////////////////////////////////////////////////////////////////////////////
|
|
||||||
//////////////////////////////////////////////////////////////////////////////////
|
|
||||||
//////////////////////////////////////////////////////////////////////////////////
|
|
||||||
});
|
|
||||||
|
|
||||||
//////////////////////////////////////////////////////////////////////////////////
|
|
||||||
//////////////////////////////////////////////////////////////////////////////////
|
|
||||||
//////////////////////////////////////////////////////////////////////////////////
|
|
||||||
//////////////////////////////////////////////////////////////////////////////////
|
|
||||||
//////////////////////////////////////////////////////////////////////////////////
|
|
||||||
//////////////////////////////////////////////////////////////////////////////////
|
|
||||||
|
|
||||||
return response;
|
|
||||||
|
|
||||||
//////////////////////////////////////////////////////////////////////////////////
|
|
||||||
//////////////////////////////////////////////////////////////////////////////////
|
|
||||||
//////////////////////////////////////////////////////////////////////////////////
|
|
||||||
//////////////////////////////////////////////////////////////////////////////////
|
|
||||||
//////////////////////////////////////////////////////////////////////////////////
|
|
||||||
//////////////////////////////////////////////////////////////////////////////////
|
|
||||||
};
|
|
103
client/auth/logout.ts
Normal file
103
client/auth/logout.ts
Normal file
@ -0,0 +1,103 @@
|
|||||||
|
import parseClientCookies from "../utils/parseClientCookies";
|
||||||
|
/**
|
||||||
|
* Login with Google Function
|
||||||
|
* ===============================================================================
|
||||||
|
* @description This function uses google identity api to login a user with datasquirel
|
||||||
|
*/
|
||||||
|
export default async function logout(
|
||||||
|
params: { [s: string]: any } | null
|
||||||
|
): Promise<boolean> {
|
||||||
|
try {
|
||||||
|
const localUser = localStorage.getItem("user");
|
||||||
|
let targetUser;
|
||||||
|
|
||||||
|
try {
|
||||||
|
targetUser = JSON.parse(localUser || "");
|
||||||
|
} catch (error) {
|
||||||
|
console.log(error);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!targetUser) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
////////////////////////////////////////
|
||||||
|
////////////////////////////////////////
|
||||||
|
////////////////////////////////////////
|
||||||
|
|
||||||
|
const cookies = parseClientCookies();
|
||||||
|
const socialId =
|
||||||
|
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("csrf");
|
||||||
|
|
||||||
|
document.cookie = `datasquirel_social_id=null;samesite=strict;path=/`;
|
||||||
|
|
||||||
|
////////////////////////////////////////
|
||||||
|
////////////////////////////////////////
|
||||||
|
////////////////////////////////////////
|
||||||
|
|
||||||
|
const response: boolean = await new Promise((resolve, reject) => {
|
||||||
|
if (socialId && !socialId?.match(/^null$/i)) {
|
||||||
|
const googleClientId = 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: any) => {
|
||||||
|
console.log(done.error);
|
||||||
|
resolve(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
////////////////////////////////////////
|
||||||
|
////////////////////////////////////////
|
||||||
|
////////////////////////////////////////
|
||||||
|
}
|
||||||
|
};
|
||||||
|
} else {
|
||||||
|
resolve(true);
|
||||||
|
}
|
||||||
|
|
||||||
|
////////////////////////////////////////
|
||||||
|
////////////////////////////////////////
|
||||||
|
////////////////////////////////////////
|
||||||
|
} else {
|
||||||
|
resolve(true);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
return response;
|
||||||
|
} catch (error) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
5
client/fetch/index.d.ts
vendored
5
client/fetch/index.d.ts
vendored
@ -1,5 +0,0 @@
|
|||||||
export = clientFetch;
|
|
||||||
declare function clientFetch(url: string, options?: import("../../package-shared/types").FetchApiOptions, csrf?: boolean): Promise<any>;
|
|
||||||
declare namespace clientFetch {
|
|
||||||
export { clientFetch as fetchApi };
|
|
||||||
}
|
|
@ -1,95 +0,0 @@
|
|||||||
// @ts-check
|
|
||||||
|
|
||||||
const _ = require("lodash");
|
|
||||||
|
|
||||||
/** @type {import("../../package-shared/types").FetchApiFn} */
|
|
||||||
async function clientFetch(url, options, csrf) {
|
|
||||||
let data;
|
|
||||||
let finalUrl = url;
|
|
||||||
|
|
||||||
if (typeof options === "string") {
|
|
||||||
try {
|
|
||||||
let fetchData;
|
|
||||||
|
|
||||||
switch (options) {
|
|
||||||
case "post":
|
|
||||||
fetchData = await fetch(finalUrl, {
|
|
||||||
method: options,
|
|
||||||
headers: {
|
|
||||||
"Content-Type": "application/json",
|
|
||||||
},
|
|
||||||
});
|
|
||||||
data = await fetchData.json();
|
|
||||||
break;
|
|
||||||
|
|
||||||
default:
|
|
||||||
fetchData = await fetch(finalUrl);
|
|
||||||
data = await fetchData.json();
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
} catch (/** @type {any} */ error) {
|
|
||||||
console.log("FetchAPI error #1:", error.message);
|
|
||||||
data = null;
|
|
||||||
}
|
|
||||||
} else if (typeof options === "object") {
|
|
||||||
try {
|
|
||||||
let fetchData;
|
|
||||||
|
|
||||||
if (options.query) {
|
|
||||||
let pathSuffix = "";
|
|
||||||
pathSuffix += "?";
|
|
||||||
const queryString = Object.keys(options.query)
|
|
||||||
?.map((queryKey) => {
|
|
||||||
if (!options.query?.[queryKey]) return undefined;
|
|
||||||
if (typeof options.query[queryKey] == "object") {
|
|
||||||
return `${queryKey}=${JSON.stringify(
|
|
||||||
options.query[queryKey]
|
|
||||||
)}`;
|
|
||||||
}
|
|
||||||
return `${queryKey}=${options.query[queryKey]}`;
|
|
||||||
})
|
|
||||||
.filter((prt) => prt)
|
|
||||||
.join("&");
|
|
||||||
pathSuffix += queryString;
|
|
||||||
finalUrl += pathSuffix;
|
|
||||||
delete options.query;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (options.body && typeof options.body === "object") {
|
|
||||||
let oldOptionsBody = _.cloneDeep(options.body);
|
|
||||||
options.body = JSON.stringify(oldOptionsBody);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (options.headers) {
|
|
||||||
/** @type {any} */
|
|
||||||
const finalOptions = { ...options };
|
|
||||||
|
|
||||||
fetchData = await fetch(finalUrl, finalOptions);
|
|
||||||
} else {
|
|
||||||
fetchData = await fetch(finalUrl, {
|
|
||||||
...options,
|
|
||||||
headers: {
|
|
||||||
"Content-Type": "application/json",
|
|
||||||
},
|
|
||||||
});
|
|
||||||
}
|
|
||||||
data = await fetchData.json();
|
|
||||||
} catch (/** @type {any} */ error) {
|
|
||||||
console.log("FetchAPI error #2:", error.message);
|
|
||||||
data = null;
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
try {
|
|
||||||
let fetchData = await fetch(finalUrl);
|
|
||||||
data = await fetchData.json();
|
|
||||||
} catch (/** @type {any} */ error) {
|
|
||||||
console.log("FetchAPI error #3:", error.message);
|
|
||||||
data = null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return data;
|
|
||||||
}
|
|
||||||
|
|
||||||
module.exports = clientFetch;
|
|
||||||
exports.fetchApi = clientFetch;
|
|
113
client/fetch/index.ts
Normal file
113
client/fetch/index.ts
Normal file
@ -0,0 +1,113 @@
|
|||||||
|
import _ from "lodash";
|
||||||
|
|
||||||
|
type FetchApiOptions = {
|
||||||
|
method:
|
||||||
|
| "POST"
|
||||||
|
| "GET"
|
||||||
|
| "DELETE"
|
||||||
|
| "PUT"
|
||||||
|
| "PATCH"
|
||||||
|
| "post"
|
||||||
|
| "get"
|
||||||
|
| "delete"
|
||||||
|
| "put"
|
||||||
|
| "patch";
|
||||||
|
body?: object | string;
|
||||||
|
headers?: FetchHeader;
|
||||||
|
};
|
||||||
|
|
||||||
|
type FetchHeader = HeadersInit & {
|
||||||
|
[key: string]: string | null;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type FetchApiReturn = {
|
||||||
|
success: boolean;
|
||||||
|
payload: any;
|
||||||
|
msg?: string;
|
||||||
|
[key: string]: any;
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* # Fetch API
|
||||||
|
*/
|
||||||
|
export default async function fetchApi(
|
||||||
|
url: string,
|
||||||
|
options?: FetchApiOptions,
|
||||||
|
csrf?: boolean,
|
||||||
|
/** Key to use to grab local Storage csrf value. */
|
||||||
|
localStorageCSRFKey?: string
|
||||||
|
): Promise<any> {
|
||||||
|
let data;
|
||||||
|
|
||||||
|
const csrfValue = localStorage.getItem(localStorageCSRFKey || "csrf");
|
||||||
|
|
||||||
|
let finalHeaders = {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
} as FetchHeader;
|
||||||
|
|
||||||
|
if (csrf && csrfValue) {
|
||||||
|
finalHeaders[`'${csrfValue.replace(/\"/g, "")}'`] = "true";
|
||||||
|
}
|
||||||
|
|
||||||
|
if (typeof options === "string") {
|
||||||
|
try {
|
||||||
|
let fetchData;
|
||||||
|
|
||||||
|
switch (options) {
|
||||||
|
case "post":
|
||||||
|
fetchData = await fetch(url, {
|
||||||
|
method: options,
|
||||||
|
headers: finalHeaders,
|
||||||
|
} as RequestInit);
|
||||||
|
data = fetchData.json();
|
||||||
|
break;
|
||||||
|
|
||||||
|
default:
|
||||||
|
fetchData = await fetch(url);
|
||||||
|
data = fetchData.json();
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
} catch (error: any) {
|
||||||
|
console.log("FetchAPI error #1:", error.message);
|
||||||
|
data = null;
|
||||||
|
}
|
||||||
|
} 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);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (options.headers) {
|
||||||
|
options.headers = _.merge(options.headers, finalHeaders);
|
||||||
|
|
||||||
|
const finalOptions: any = { ...options };
|
||||||
|
fetchData = await fetch(url, finalOptions);
|
||||||
|
} else {
|
||||||
|
const finalOptions = {
|
||||||
|
...options,
|
||||||
|
headers: finalHeaders,
|
||||||
|
} as RequestInit;
|
||||||
|
|
||||||
|
fetchData = await fetch(url, finalOptions);
|
||||||
|
}
|
||||||
|
|
||||||
|
data = fetchData.json();
|
||||||
|
} catch (error: any) {
|
||||||
|
console.log("FetchAPI error #2:", error.message);
|
||||||
|
data = null;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
try {
|
||||||
|
let fetchData = await fetch(url);
|
||||||
|
data = await fetchData.json();
|
||||||
|
} catch (error: any) {
|
||||||
|
console.log("FetchAPI error #3:", error.message);
|
||||||
|
data = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return data;
|
||||||
|
}
|
38
client/index.d.ts
vendored
38
client/index.d.ts
vendored
@ -1,38 +0,0 @@
|
|||||||
export namespace media {
|
|
||||||
export { imageInputToBase64 };
|
|
||||||
export { imageInputFileToBase64 };
|
|
||||||
export { inputFileToBase64 };
|
|
||||||
}
|
|
||||||
export namespace auth {
|
|
||||||
export namespace google {
|
|
||||||
export { getAccessToken };
|
|
||||||
}
|
|
||||||
export namespace github {
|
|
||||||
export { getGithubAccessToken as getAccessToken };
|
|
||||||
}
|
|
||||||
export { logout };
|
|
||||||
}
|
|
||||||
export namespace fetch {
|
|
||||||
export { fetchApi };
|
|
||||||
export { clientFetch };
|
|
||||||
}
|
|
||||||
export namespace utils {
|
|
||||||
export { serializeQuery };
|
|
||||||
export { serializeCookies };
|
|
||||||
export { EJSON };
|
|
||||||
export { numberfy };
|
|
||||||
export { slugify };
|
|
||||||
}
|
|
||||||
import imageInputToBase64 = require("./media/imageInputToBase64");
|
|
||||||
import imageInputFileToBase64 = require("./media/imageInputFileToBase64");
|
|
||||||
import inputFileToBase64 = require("./media/inputFileToBase64");
|
|
||||||
import getAccessToken = require("./auth/google/getAccessToken");
|
|
||||||
import getGithubAccessToken = require("./auth/github/getAccessToken");
|
|
||||||
import logout = require("./auth/logout");
|
|
||||||
import { fetchApi } from "./fetch";
|
|
||||||
import clientFetch = require("./fetch");
|
|
||||||
import serializeQuery = require("../package-shared/utils/serialize-query");
|
|
||||||
import serializeCookies = require("../package-shared/utils/serialize-cookies");
|
|
||||||
import EJSON = require("../package-shared/utils/ejson");
|
|
||||||
import numberfy = require("../package-shared/utils/numberfy");
|
|
||||||
import slugify = require("../package-shared/utils/slugify");
|
|
@ -1,67 +0,0 @@
|
|||||||
// @ts-check
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Imports
|
|
||||||
*/
|
|
||||||
const imageInputFileToBase64 = require("./media/imageInputFileToBase64");
|
|
||||||
const imageInputToBase64 = require("./media/imageInputToBase64");
|
|
||||||
const inputFileToBase64 = require("./media/inputFileToBase64");
|
|
||||||
const getAccessToken = require("./auth/google/getAccessToken");
|
|
||||||
const getGithubAccessToken = require("./auth/github/getAccessToken");
|
|
||||||
const logout = require("./auth/logout");
|
|
||||||
const { fetchApi } = require("./fetch");
|
|
||||||
const clientFetch = require("./fetch");
|
|
||||||
const serializeQuery = require("../package-shared/utils/serialize-query");
|
|
||||||
const serializeCookies = require("../package-shared/utils/serialize-cookies");
|
|
||||||
const EJSON = require("../package-shared/utils/ejson");
|
|
||||||
const numberfy = require("../package-shared/utils/numberfy");
|
|
||||||
const slugify = require("../package-shared/utils/slugify");
|
|
||||||
|
|
||||||
////////////////////////////////////////
|
|
||||||
////////////////////////////////////////
|
|
||||||
////////////////////////////////////////
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Media Functions Object
|
|
||||||
*/
|
|
||||||
const media = {
|
|
||||||
imageInputToBase64: imageInputToBase64,
|
|
||||||
imageInputFileToBase64: imageInputFileToBase64,
|
|
||||||
inputFileToBase64: inputFileToBase64,
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* User Auth Object
|
|
||||||
*/
|
|
||||||
const auth = {
|
|
||||||
google: {
|
|
||||||
getAccessToken: getAccessToken,
|
|
||||||
},
|
|
||||||
github: {
|
|
||||||
getAccessToken: getGithubAccessToken,
|
|
||||||
},
|
|
||||||
logout: logout,
|
|
||||||
};
|
|
||||||
|
|
||||||
const utils = {
|
|
||||||
serializeQuery,
|
|
||||||
serializeCookies,
|
|
||||||
EJSON,
|
|
||||||
numberfy,
|
|
||||||
slugify,
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Fetch
|
|
||||||
*/
|
|
||||||
const fetch = {
|
|
||||||
fetchApi,
|
|
||||||
clientFetch,
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Main Export
|
|
||||||
*/
|
|
||||||
const datasquirelClient = { media, auth, fetch, utils };
|
|
||||||
|
|
||||||
module.exports = datasquirelClient;
|
|
62
client/index.ts
Normal file
62
client/index.ts
Normal file
@ -0,0 +1,62 @@
|
|||||||
|
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";
|
||||||
|
|
||||||
|
////////////////////////////////////////
|
||||||
|
////////////////////////////////////////
|
||||||
|
////////////////////////////////////////
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Media Functions Object
|
||||||
|
*/
|
||||||
|
const media = {
|
||||||
|
imageInputToBase64: imageInputToBase64,
|
||||||
|
imageInputFileToBase64: imageInputFileToBase64,
|
||||||
|
inputFileToBase64: inputFileToBase64,
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* User Auth Object
|
||||||
|
*/
|
||||||
|
const auth = {
|
||||||
|
google: {
|
||||||
|
getAccessToken: getAccessToken,
|
||||||
|
},
|
||||||
|
github: {
|
||||||
|
getAccessToken: getGithubAccessToken,
|
||||||
|
},
|
||||||
|
logout: logout,
|
||||||
|
};
|
||||||
|
|
||||||
|
const utils = {
|
||||||
|
serializeQuery,
|
||||||
|
serializeCookies,
|
||||||
|
EJSON,
|
||||||
|
numberfy,
|
||||||
|
slugify,
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Fetch
|
||||||
|
*/
|
||||||
|
const fetch = {
|
||||||
|
fetchApi,
|
||||||
|
clientFetch,
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Main Export
|
||||||
|
*/
|
||||||
|
const datasquirelClient = { media, auth, fetch, utils };
|
||||||
|
|
||||||
|
export default datasquirelClient;
|
8
client/media/imageInputFileToBase64.d.ts
vendored
8
client/media/imageInputFileToBase64.d.ts
vendored
@ -1,8 +0,0 @@
|
|||||||
declare function _exports({ imageInputFile, maxWidth, imagePreviewNode, }: {
|
|
||||||
imageInputFile: {
|
|
||||||
name: string;
|
|
||||||
};
|
|
||||||
maxWidth?: number;
|
|
||||||
imagePreviewNode?: HTMLImageElement;
|
|
||||||
}): Promise<any>;
|
|
||||||
export = _exports;
|
|
@ -1,22 +1,19 @@
|
|||||||
|
import { ImageInputFileToBase64FunctionReturn } from "../../package-shared/types";
|
||||||
|
|
||||||
|
type Param = {
|
||||||
|
imageInputFile: File;
|
||||||
|
maxWidth?: number;
|
||||||
|
imagePreviewNode?: HTMLImageElement;
|
||||||
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* ==============================================================================
|
* # Image input File top Base64
|
||||||
* Main Function
|
|
||||||
* ==============================================================================
|
|
||||||
* @async
|
|
||||||
*
|
|
||||||
* @param {{
|
|
||||||
* imageInputFile: { name:string },
|
|
||||||
* maxWidth?: number,
|
|
||||||
* imagePreviewNode?: HTMLImageElement,
|
|
||||||
* }} params - Single object passed
|
|
||||||
*
|
|
||||||
* @returns { Promise<import("../../types/general.td").ImageInputFileToBase64FunctionReturn> } - Return Object
|
|
||||||
*/
|
*/
|
||||||
module.exports = async function imageInputFileToBase64({
|
export default async function imageInputFileToBase64({
|
||||||
imageInputFile,
|
imageInputFile,
|
||||||
maxWidth,
|
maxWidth,
|
||||||
imagePreviewNode,
|
imagePreviewNode,
|
||||||
}) {
|
}: Param): Promise<ImageInputFileToBase64FunctionReturn> {
|
||||||
/**
|
/**
|
||||||
* Make https request
|
* Make https request
|
||||||
*
|
*
|
||||||
@ -24,15 +21,15 @@ module.exports = async function imageInputFileToBase64({
|
|||||||
*/
|
*/
|
||||||
try {
|
try {
|
||||||
let imageName = imageInputFile.name.replace(/\..*/, "");
|
let imageName = imageInputFile.name.replace(/\..*/, "");
|
||||||
let imageDataBase64;
|
let imageDataBase64: string | undefined;
|
||||||
let imageSize;
|
let imageSize: number | undefined;
|
||||||
let canvas = document.createElement("canvas");
|
let canvas = document.createElement("canvas");
|
||||||
|
|
||||||
const MIME_TYPE = imageInputFile.type;
|
const MIME_TYPE = imageInputFile.type;
|
||||||
const QUALITY = 0.95;
|
const QUALITY = 0.95;
|
||||||
const MAX_WIDTH = maxWidth ? maxWidth : null;
|
const MAX_WIDTH = maxWidth ? maxWidth : null;
|
||||||
|
|
||||||
const file = imageInputFile; // get the file
|
const file = imageInputFile;
|
||||||
const blobURL = URL.createObjectURL(file);
|
const blobURL = URL.createObjectURL(file);
|
||||||
const img = new Image();
|
const img = new Image();
|
||||||
|
|
||||||
@ -47,8 +44,9 @@ module.exports = async function imageInputFileToBase64({
|
|||||||
};
|
};
|
||||||
|
|
||||||
/** ********************* Handle new image when loaded */
|
/** ********************* Handle new image when loaded */
|
||||||
img.onload = function () {
|
img.onload = function (e) {
|
||||||
URL.revokeObjectURL(this.src);
|
const imgEl = e.target as HTMLImageElement;
|
||||||
|
URL.revokeObjectURL(imgEl.src);
|
||||||
|
|
||||||
if (MAX_WIDTH) {
|
if (MAX_WIDTH) {
|
||||||
const scaleSize = MAX_WIDTH / img.naturalWidth;
|
const scaleSize = MAX_WIDTH / img.naturalWidth;
|
||||||
@ -67,7 +65,7 @@ module.exports = async function imageInputFileToBase64({
|
|||||||
}
|
}
|
||||||
|
|
||||||
const ctx = canvas.getContext("2d");
|
const ctx = canvas.getContext("2d");
|
||||||
ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
|
ctx?.drawImage(img, 0, 0, canvas.width, canvas.height);
|
||||||
|
|
||||||
const srcEncoded = canvas.toDataURL(MIME_TYPE, QUALITY);
|
const srcEncoded = canvas.toDataURL(MIME_TYPE, QUALITY);
|
||||||
|
|
||||||
@ -82,7 +80,7 @@ module.exports = async function imageInputFileToBase64({
|
|||||||
imageSize = await new Promise((res, rej) => {
|
imageSize = await new Promise((res, rej) => {
|
||||||
canvas.toBlob(
|
canvas.toBlob(
|
||||||
(blob) => {
|
(blob) => {
|
||||||
res(blob.size);
|
res(blob?.size);
|
||||||
},
|
},
|
||||||
MIME_TYPE,
|
MIME_TYPE,
|
||||||
QUALITY
|
QUALITY
|
||||||
@ -90,23 +88,19 @@ module.exports = async function imageInputFileToBase64({
|
|||||||
});
|
});
|
||||||
|
|
||||||
return {
|
return {
|
||||||
imageBase64: imageDataBase64.replace(/.*?base64,/, ""),
|
imageBase64: imageDataBase64?.replace(/.*?base64,/, ""),
|
||||||
imageBase64Full: imageDataBase64,
|
imageBase64Full: imageDataBase64,
|
||||||
imageName: imageName,
|
imageName: imageName,
|
||||||
imageSize: imageSize,
|
imageSize: imageSize,
|
||||||
};
|
};
|
||||||
} catch (/** @type {*} */ error) {
|
} catch (error: any) {
|
||||||
console.log("Image Processing Error! =>", error.message);
|
console.log("Image Processing Error! =>", error.message);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
imageBase64: null,
|
imageBase64: undefined,
|
||||||
imageBase64Full: null,
|
imageBase64Full: undefined,
|
||||||
imageName: null,
|
imageName: undefined,
|
||||||
imageSize: null,
|
imageSize: undefined,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
};
|
}
|
||||||
|
|
||||||
/** ********************************************** */
|
|
||||||
/** ********************************************** */
|
|
||||||
/** ********************************************** */
|
|
14
client/media/imageInputToBase64.d.ts
vendored
14
client/media/imageInputToBase64.d.ts
vendored
@ -1,14 +0,0 @@
|
|||||||
declare namespace _exports {
|
|
||||||
export { FunctionReturn };
|
|
||||||
}
|
|
||||||
declare function _exports({ imageInput, maxWidth, mimeType, }: {
|
|
||||||
imageInput: HTMLInputElement;
|
|
||||||
maxWidth?: number;
|
|
||||||
mimeType?: [string];
|
|
||||||
}): Promise<FunctionReturn>;
|
|
||||||
export = _exports;
|
|
||||||
type FunctionReturn = {
|
|
||||||
imageBase64: string;
|
|
||||||
imageBase64Full: string;
|
|
||||||
imageName: string;
|
|
||||||
};
|
|
@ -1,115 +0,0 @@
|
|||||||
/**
|
|
||||||
* @typedef {{
|
|
||||||
* imageBase64: string,
|
|
||||||
* imageBase64Full: string,
|
|
||||||
* imageName: string,
|
|
||||||
* }} FunctionReturn
|
|
||||||
*/
|
|
||||||
|
|
||||||
/**
|
|
||||||
* ==============================================================================
|
|
||||||
* Main Function
|
|
||||||
* ==============================================================================
|
|
||||||
* @async
|
|
||||||
*
|
|
||||||
* @param {{
|
|
||||||
* imageInput: HTMLInputElement,
|
|
||||||
* maxWidth?: number,
|
|
||||||
* mimeType?: [string='image/jpeg']
|
|
||||||
* }} params - Single object passed
|
|
||||||
*
|
|
||||||
* @returns { Promise<FunctionReturn> } - Return Object
|
|
||||||
*/
|
|
||||||
module.exports = async function imageInputToBase64({
|
|
||||||
imageInput,
|
|
||||||
maxWidth,
|
|
||||||
mimeType,
|
|
||||||
}) {
|
|
||||||
/**
|
|
||||||
* Make https request
|
|
||||||
*
|
|
||||||
* @description make a request to datasquirel.com
|
|
||||||
*/
|
|
||||||
try {
|
|
||||||
let imagePreviewNode = document.querySelector(
|
|
||||||
`[data-imagepreview='image']`
|
|
||||||
);
|
|
||||||
let imageName = imageInput.files[0].name.replace(/\..*/, "");
|
|
||||||
let imageDataBase64;
|
|
||||||
|
|
||||||
const MIME_TYPE = mimeType ? mimeType : "image/jpeg";
|
|
||||||
const QUALITY = 0.95;
|
|
||||||
const MAX_WIDTH = maxWidth ? maxWidth : null;
|
|
||||||
|
|
||||||
const file = imageInput.files[0]; // get the file
|
|
||||||
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);
|
|
||||||
window.alert("Cannot load image!");
|
|
||||||
};
|
|
||||||
|
|
||||||
/** ********************* Handle new image when loaded */
|
|
||||||
img.onload = function () {
|
|
||||||
URL.revokeObjectURL(this.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.drawImage(img, 0, 0, canvas.width, canvas.height);
|
|
||||||
|
|
||||||
const srcEncoded = canvas.toDataURL(MIME_TYPE, QUALITY);
|
|
||||||
|
|
||||||
if (imagePreviewNode) {
|
|
||||||
document
|
|
||||||
.querySelectorAll(`[data-imagepreview='image']`)
|
|
||||||
.forEach((img) => {
|
|
||||||
img.src = srcEncoded;
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
res(srcEncoded);
|
|
||||||
};
|
|
||||||
});
|
|
||||||
|
|
||||||
return {
|
|
||||||
imageBase64: imageDataBase64.replace(/.*?base64,/, ""),
|
|
||||||
imageBase64Full: imageDataBase64,
|
|
||||||
imageName: imageName,
|
|
||||||
};
|
|
||||||
} catch (/** @type {*} */ error) {
|
|
||||||
console.log("Image Processing Error! =>", error.message);
|
|
||||||
|
|
||||||
return {
|
|
||||||
imageBase64: null,
|
|
||||||
imageBase64Full: null,
|
|
||||||
imageName: null,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
/** ********************************************** */
|
|
||||||
/** ********************************************** */
|
|
||||||
/** ********************************************** */
|
|
104
client/media/imageInputToBase64.ts
Normal file
104
client/media/imageInputToBase64.ts
Normal file
@ -0,0 +1,104 @@
|
|||||||
|
type FunctionReturn = {
|
||||||
|
imageBase64?: string;
|
||||||
|
imageBase64Full?: string;
|
||||||
|
imageName?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
type Param = {
|
||||||
|
imageInput: HTMLInputElement;
|
||||||
|
maxWidth?: number;
|
||||||
|
mimeType?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* # Image Input Element to Base 64
|
||||||
|
*/
|
||||||
|
export default async function imageInputToBase64({
|
||||||
|
imageInput,
|
||||||
|
maxWidth,
|
||||||
|
mimeType,
|
||||||
|
}: Param): Promise<FunctionReturn> {
|
||||||
|
/**
|
||||||
|
* Make https request
|
||||||
|
*
|
||||||
|
* @description make a request to datasquirel.com
|
||||||
|
*/
|
||||||
|
try {
|
||||||
|
let imagePreviewNode = document.querySelector(
|
||||||
|
`[data-imagepreview='image']`
|
||||||
|
);
|
||||||
|
let imageName = imageInput.files?.[0].name.replace(/\..*/, "");
|
||||||
|
let imageDataBase64: string | undefined;
|
||||||
|
|
||||||
|
const MIME_TYPE = mimeType ? mimeType : "image/jpeg";
|
||||||
|
const QUALITY = 0.95;
|
||||||
|
const MAX_WIDTH = maxWidth ? maxWidth : null;
|
||||||
|
|
||||||
|
const file = imageInput.files?.[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!");
|
||||||
|
};
|
||||||
|
|
||||||
|
img.onload = function (e) {
|
||||||
|
const imgEl = e.target as HTMLImageElement;
|
||||||
|
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?.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 as HTMLImageElement;
|
||||||
|
_imgEl.src = srcEncoded;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
res(srcEncoded);
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
return {
|
||||||
|
imageBase64: imageDataBase64?.replace(/.*?base64,/, ""),
|
||||||
|
imageBase64Full: imageDataBase64,
|
||||||
|
imageName: imageName,
|
||||||
|
};
|
||||||
|
} else {
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
} catch (/** @type {*} */ error: any) {
|
||||||
|
console.log("Image Processing Error! =>", error.message);
|
||||||
|
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
}
|
19
client/media/inputFileToBase64.d.ts
vendored
19
client/media/inputFileToBase64.d.ts
vendored
@ -1,19 +0,0 @@
|
|||||||
declare namespace _exports {
|
|
||||||
export { FunctionReturn };
|
|
||||||
}
|
|
||||||
declare function _exports({ inputFile, allowedRegex }: {
|
|
||||||
inputFile: {
|
|
||||||
name: string;
|
|
||||||
size: number;
|
|
||||||
type: string;
|
|
||||||
};
|
|
||||||
allowedRegex?: RegExp;
|
|
||||||
}): Promise<FunctionReturn>;
|
|
||||||
export = _exports;
|
|
||||||
type FunctionReturn = {
|
|
||||||
fileBase64: string;
|
|
||||||
fileBase64Full: string;
|
|
||||||
fileName: string;
|
|
||||||
fileSize: number;
|
|
||||||
fileType: string;
|
|
||||||
};
|
|
@ -1,96 +0,0 @@
|
|||||||
/**
|
|
||||||
* @typedef {{
|
|
||||||
* fileBase64: string,
|
|
||||||
* fileBase64Full: string,
|
|
||||||
* fileName: string,
|
|
||||||
* fileSize: number,
|
|
||||||
* fileType: string,
|
|
||||||
* }} FunctionReturn
|
|
||||||
*/
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Input File to base64
|
|
||||||
* ==============================================================================
|
|
||||||
*
|
|
||||||
* @description This function takes in a *SINGLE* input file from a HTML file input element.
|
|
||||||
* HTML file input elements usually return an array of input objects, so be sure to select the target
|
|
||||||
* file from the array.
|
|
||||||
*
|
|
||||||
* @async
|
|
||||||
*
|
|
||||||
* @param {object} params - Single object passed
|
|
||||||
* @param {object} params.inputFile - HTML input File
|
|
||||||
* @param {string} params.inputFile.name - Input File Name
|
|
||||||
* @param {number} params.inputFile.size - Input File Size in bytes
|
|
||||||
* @param {string} params.inputFile.type - Input File Type: "JPEG", "PNG", "PDF", etc. Whichever allowed regexp is provided
|
|
||||||
* @param {RegExp} [params.allowedRegex] - Regexp containing the allowed file types
|
|
||||||
*
|
|
||||||
* @returns { Promise<FunctionReturn> } - Return Object
|
|
||||||
*/
|
|
||||||
module.exports = async function inputFileToBase64({ inputFile, allowedRegex }) {
|
|
||||||
/**
|
|
||||||
* == Initialize
|
|
||||||
*
|
|
||||||
* @description Initialize
|
|
||||||
*/
|
|
||||||
const allowedTypesRegex = allowedRegex ? allowedRegex : /image\/*|\/pdf/;
|
|
||||||
|
|
||||||
if (!inputFile?.type?.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 {
|
|
||||||
fileBase64: null,
|
|
||||||
fileBase64Full: null,
|
|
||||||
fileName: inputFile.name,
|
|
||||||
fileSize: null,
|
|
||||||
fileType: null,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
/** Process File **/
|
|
||||||
let fileName = inputFile.name.replace(/\..*/, "");
|
|
||||||
|
|
||||||
/** Add source to new file **/
|
|
||||||
const fileData = await new Promise((resolve, reject) => {
|
|
||||||
var reader = new FileReader();
|
|
||||||
reader.readAsDataURL(inputFile);
|
|
||||||
reader.onload = function () {
|
|
||||||
resolve(reader.result);
|
|
||||||
};
|
|
||||||
reader.onerror = function (/** @type {*} */ error) {
|
|
||||||
console.log("Error: ", error.message);
|
|
||||||
};
|
|
||||||
});
|
|
||||||
|
|
||||||
////////////////////////////////////////
|
|
||||||
////////////////////////////////////////
|
|
||||||
////////////////////////////////////////
|
|
||||||
|
|
||||||
return {
|
|
||||||
fileBase64: fileData.replace(/.*?base64,/, ""),
|
|
||||||
fileBase64Full: fileData,
|
|
||||||
fileName: fileName,
|
|
||||||
fileSize: inputFile.size,
|
|
||||||
fileType: inputFile.type,
|
|
||||||
};
|
|
||||||
|
|
||||||
////////////////////////////////////////
|
|
||||||
////////////////////////////////////////
|
|
||||||
////////////////////////////////////////
|
|
||||||
} catch (/** @type {*} */ error) {
|
|
||||||
console.log("File Processing Error! =>", error.message);
|
|
||||||
|
|
||||||
return {
|
|
||||||
fileBase64: null,
|
|
||||||
fileBase64Full: null,
|
|
||||||
fileName: inputFile.name,
|
|
||||||
fileSize: null,
|
|
||||||
fileType: null,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
////////////////////////////////////////
|
|
||||||
////////////////////////////////////////
|
|
||||||
////////////////////////////////////////
|
|
68
client/media/inputFileToBase64.ts
Normal file
68
client/media/inputFileToBase64.ts
Normal file
@ -0,0 +1,68 @@
|
|||||||
|
type FunctionReturn = {
|
||||||
|
fileBase64?: string;
|
||||||
|
fileBase64Full?: string;
|
||||||
|
fileName?: string;
|
||||||
|
fileSize?: number;
|
||||||
|
fileType?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
type Param = {
|
||||||
|
inputFile: File;
|
||||||
|
allowedRegex?: RegExp;
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Input File to base64
|
||||||
|
* ==============================================================================
|
||||||
|
*
|
||||||
|
* @description This function takes in a *SINGLE* input file from a HTML file input element.
|
||||||
|
* HTML file input elements usually return an array of input objects, so be sure to select the target
|
||||||
|
* file from the array.
|
||||||
|
*/
|
||||||
|
export default async function inputFileToBase64({
|
||||||
|
inputFile,
|
||||||
|
allowedRegex,
|
||||||
|
}: Param): Promise<FunctionReturn> {
|
||||||
|
const allowedTypesRegex = allowedRegex ? allowedRegex : /image\/*|\/pdf/;
|
||||||
|
|
||||||
|
if (!inputFile?.type?.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: string | undefined = await new Promise(
|
||||||
|
(resolve, reject) => {
|
||||||
|
var reader = new FileReader();
|
||||||
|
reader.readAsDataURL(inputFile);
|
||||||
|
reader.onload = function () {
|
||||||
|
resolve(reader.result?.toString());
|
||||||
|
};
|
||||||
|
reader.onerror = function (/** @type {*} */ error: any) {
|
||||||
|
console.log("Error: ", error.message);
|
||||||
|
};
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
return {
|
||||||
|
fileBase64: fileData?.replace(/.*?base64,/, ""),
|
||||||
|
fileBase64Full: fileData,
|
||||||
|
fileName: fileName,
|
||||||
|
fileSize: inputFile.size,
|
||||||
|
fileType: inputFile.type,
|
||||||
|
};
|
||||||
|
} catch (error: any) {
|
||||||
|
console.log("File Processing Error! =>", error.message);
|
||||||
|
|
||||||
|
return {
|
||||||
|
fileName: inputFile.name,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
2
client/utils/parseClientCookies.d.ts
vendored
2
client/utils/parseClientCookies.d.ts
vendored
@ -1,2 +0,0 @@
|
|||||||
declare function _exports(): {} | null;
|
|
||||||
export = _exports;
|
|
@ -1,65 +0,0 @@
|
|||||||
/**
|
|
||||||
* ==============================================================================
|
|
||||||
* Imports
|
|
||||||
* ==============================================================================
|
|
||||||
*/
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Parse request cookies
|
|
||||||
* ==============================================================================
|
|
||||||
*
|
|
||||||
* @description This function takes in a request object and returns the cookies as a JS object
|
|
||||||
*
|
|
||||||
* @async
|
|
||||||
*
|
|
||||||
* @param {object} params - main params object
|
|
||||||
* @param {object} params.request - HTTPS request object
|
|
||||||
*
|
|
||||||
* @returns {{}|null}
|
|
||||||
*/
|
|
||||||
module.exports = function () {
|
|
||||||
/**
|
|
||||||
* Check inputs
|
|
||||||
*
|
|
||||||
* @description Check inputs
|
|
||||||
*/
|
|
||||||
|
|
||||||
////////////////////////////////////////
|
|
||||||
////////////////////////////////////////
|
|
||||||
////////////////////////////////////////
|
|
||||||
|
|
||||||
/** @type {string|null} */
|
|
||||||
const cookieString = document.cookie;
|
|
||||||
|
|
||||||
if (!cookieString || typeof cookieString !== "string") {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @type {string[]} */
|
|
||||||
const cookieSplitArray = cookieString.split(";");
|
|
||||||
|
|
||||||
let cookieObject = {};
|
|
||||||
|
|
||||||
cookieSplitArray.forEach((keyValueString) => {
|
|
||||||
const [key, value] = keyValueString.split("=");
|
|
||||||
if (key && typeof key == "string") {
|
|
||||||
cookieObject[key.replace(/^ +| +$/, "")] = value && typeof value == "string" ? value.replace(/^ +| +$/, "") : null;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
////////////////////////////////////////
|
|
||||||
////////////////////////////////////////
|
|
||||||
////////////////////////////////////////
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Make https request
|
|
||||||
*
|
|
||||||
* @description make a request to datasquirel.com
|
|
||||||
*/
|
|
||||||
|
|
||||||
return cookieObject;
|
|
||||||
};
|
|
||||||
|
|
||||||
////////////////////////////////////////
|
|
||||||
////////////////////////////////////////
|
|
||||||
////////////////////////////////////////
|
|
34
client/utils/parseClientCookies.ts
Normal file
34
client/utils/parseClientCookies.ts
Normal file
@ -0,0 +1,34 @@
|
|||||||
|
/**
|
||||||
|
* Parse request cookies
|
||||||
|
* ============================================================================== *
|
||||||
|
* @description This function takes in a request object and returns the cookies as a JS object
|
||||||
|
*/
|
||||||
|
export default function (): { [s: string]: any } | null {
|
||||||
|
/**
|
||||||
|
* Check inputs
|
||||||
|
*
|
||||||
|
* @description Check inputs
|
||||||
|
*/
|
||||||
|
|
||||||
|
const cookieString: string | null = document.cookie;
|
||||||
|
|
||||||
|
if (!cookieString || typeof cookieString !== "string") {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const cookieSplitArray: string[] = cookieString.split(";");
|
||||||
|
|
||||||
|
let cookieObject: { [s: string]: any } = {};
|
||||||
|
|
||||||
|
cookieSplitArray.forEach((keyValueString) => {
|
||||||
|
const [key, value] = keyValueString.split("=");
|
||||||
|
if (key && typeof key == "string") {
|
||||||
|
cookieObject[key.replace(/^ +| +$/, "")] =
|
||||||
|
value && typeof value == "string"
|
||||||
|
? value.replace(/^ +| +$/, "")
|
||||||
|
: null;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
return cookieObject;
|
||||||
|
}
|
@ -28,4 +28,4 @@ const colors = {
|
|||||||
BgGray: "\x1b[100m",
|
BgGray: "\x1b[100m",
|
||||||
};
|
};
|
||||||
|
|
||||||
module.exports = colors;
|
export default colors;
|
@ -1,17 +1,17 @@
|
|||||||
#! /usr/bin/env node
|
#! /usr/bin/env node
|
||||||
// @ts-check
|
|
||||||
|
|
||||||
const fs = require("fs");
|
import fs from "fs";
|
||||||
const path = require("path");
|
import path from "path";
|
||||||
const { execSync } = require("child_process");
|
import { execSync } from "child_process";
|
||||||
|
|
||||||
require("dotenv").config({
|
require("dotenv").config({
|
||||||
path: path.resolve(process.cwd(), ".env"),
|
path: path.resolve(process.cwd(), ".env"),
|
||||||
});
|
});
|
||||||
|
|
||||||
const datasquirel = require("../index");
|
import datasquirel from "../index";
|
||||||
const colors = require("../console-colors");
|
import colors from "../console-colors";
|
||||||
const createDbFromSchema = require("../package-shared/shell/createDbFromSchema");
|
import createDbFromSchema from "../package-shared/shell/createDbFromSchema";
|
||||||
|
import { DSQL_DatabaseSchemaType } from "../package-shared/types";
|
||||||
|
|
||||||
if (!fs.existsSync(path.resolve(process.cwd(), ".env"))) {
|
if (!fs.existsSync(path.resolve(process.cwd(), ".env"))) {
|
||||||
console.log(".env file not found");
|
console.log(".env file not found");
|
||||||
@ -45,9 +45,8 @@ if (!DSQL_PASS?.match(/./)) {
|
|||||||
|
|
||||||
const dbSchemaLocalFilePath = path.resolve(process.cwd(), "dsql.schema.json");
|
const dbSchemaLocalFilePath = path.resolve(process.cwd(), "dsql.schema.json");
|
||||||
|
|
||||||
async function run() {
|
export default async function run() {
|
||||||
/** @type {any} */
|
let schemaData: any;
|
||||||
let schemaData;
|
|
||||||
|
|
||||||
if (DSQL_KEY && DSQL_REF_DB_NAME?.match(/./)) {
|
if (DSQL_KEY && DSQL_REF_DB_NAME?.match(/./)) {
|
||||||
const dbSchemaDataResponse = await datasquirel.getSchema({
|
const dbSchemaDataResponse = await datasquirel.getSchema({
|
||||||
@ -66,8 +65,8 @@ async function run() {
|
|||||||
process.exit();
|
process.exit();
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @type {import("../package-shared/types").DSQL_DatabaseSchemaType} */ // @ts-ignore
|
let fetchedDbSchemaObject =
|
||||||
let fetchedDbSchemaObject = dbSchemaDataResponse.payload;
|
dbSchemaDataResponse.payload as DSQL_DatabaseSchemaType;
|
||||||
if (DSQL_DB_NAME) fetchedDbSchemaObject.dbFullName = DSQL_DB_NAME;
|
if (DSQL_DB_NAME) fetchedDbSchemaObject.dbFullName = DSQL_DB_NAME;
|
||||||
|
|
||||||
schemaData = [fetchedDbSchemaObject];
|
schemaData = [fetchedDbSchemaObject];
|
||||||
@ -129,8 +128,6 @@ async function run() {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
// let timeout;
|
|
||||||
|
|
||||||
let interval;
|
let interval;
|
||||||
|
|
||||||
if (fs.existsSync(dbSchemaLocalFilePath) && !DSQL_KEY?.match(/....../)) {
|
if (fs.existsSync(dbSchemaLocalFilePath) && !DSQL_KEY?.match(/....../)) {
|
@ -1,9 +1,8 @@
|
|||||||
#! /usr/bin/env node
|
#! /usr/bin/env node
|
||||||
// @ts-check
|
|
||||||
|
|
||||||
const fs = require("fs");
|
import fs from "fs";
|
||||||
const path = require("path");
|
import path from "path";
|
||||||
const { execSync } = require("child_process");
|
import { execSync } from "child_process";
|
||||||
|
|
||||||
require("dotenv").config({
|
require("dotenv").config({
|
||||||
path: path.resolve(process.cwd(), ".env"),
|
path: path.resolve(process.cwd(), ".env"),
|
||||||
@ -57,6 +56,6 @@ try {
|
|||||||
////////////////////////////////////////
|
////////////////////////////////////////
|
||||||
////////////////////////////////////////
|
////////////////////////////////////////
|
||||||
////////////////////////////////////////
|
////////////////////////////////////////
|
||||||
} catch (/** @type {*} */ error) {
|
} catch (error: any) {
|
||||||
console.log("Dump Error: ", error.message);
|
console.log("Dump Error: ", error.message);
|
||||||
}
|
}
|
75
index.d.ts
vendored
75
index.d.ts
vendored
@ -1,75 +0,0 @@
|
|||||||
import get = require("./utils/get");
|
|
||||||
import post = require("./utils/post");
|
|
||||||
export namespace media {
|
|
||||||
export { uploadImage };
|
|
||||||
export { uploadFile };
|
|
||||||
export { deleteFile };
|
|
||||||
}
|
|
||||||
export namespace user {
|
|
||||||
export { createUser };
|
|
||||||
export let deleteUser: typeof import("./users/delete-user");
|
|
||||||
export { loginUser };
|
|
||||||
export { sendEmailCode };
|
|
||||||
export { logoutUser };
|
|
||||||
export { userAuth };
|
|
||||||
export { reAuthUser };
|
|
||||||
export { updateUser };
|
|
||||||
export { getUser };
|
|
||||||
export { getToken };
|
|
||||||
export { validateToken };
|
|
||||||
export let validateTempEmailCode: typeof import("./users/validate-temp-email-code");
|
|
||||||
export namespace social {
|
|
||||||
export { loginWithGoogle };
|
|
||||||
export { loginWithGithub };
|
|
||||||
}
|
|
||||||
}
|
|
||||||
import getSchema = require("./utils/get-schema");
|
|
||||||
import datasquirelClient = require("./client");
|
|
||||||
export namespace sql {
|
|
||||||
export { sqlGenerator };
|
|
||||||
export { sqlInsertGenerator };
|
|
||||||
export { sqlDeleteGenerator };
|
|
||||||
export { trimSql as trim };
|
|
||||||
}
|
|
||||||
import parseCookies = require("./package-shared/utils/backend/parseCookies");
|
|
||||||
import httpRequest = require("./package-shared/functions/backend/httpRequest");
|
|
||||||
import uploadImage = require("./utils/upload-image");
|
|
||||||
import uploadFile = require("./utils/upload-file");
|
|
||||||
import deleteFile = require("./utils/delete-file");
|
|
||||||
import createUser = require("./users/add-user");
|
|
||||||
import loginUser = require("./users/login-user");
|
|
||||||
import sendEmailCode = require("./users/send-email-code");
|
|
||||||
import logoutUser = require("./users/logout-user");
|
|
||||||
import userAuth = require("./users/user-auth");
|
|
||||||
import reAuthUser = require("./users/reauth-user");
|
|
||||||
import updateUser = require("./users/update-user");
|
|
||||||
import getUser = require("./users/get-user");
|
|
||||||
import getToken = require("./users/get-token");
|
|
||||||
import validateToken = require("./users/validate-token");
|
|
||||||
import loginWithGoogle = require("./users/social/google-auth");
|
|
||||||
import loginWithGithub = require("./users/social/github-auth");
|
|
||||||
import sqlGenerator = require("./package-shared/functions/dsql/sql/sql-generator");
|
|
||||||
import sqlInsertGenerator = require("./package-shared/functions/dsql/sql/sql-insert-generator");
|
|
||||||
import sqlDeleteGenerator = require("./package-shared/functions/dsql/sql/sql-delete-generator");
|
|
||||||
import trimSql = require("./package-shared/utils/trim-sql");
|
|
||||||
export declare namespace utils {
|
|
||||||
export namespace crypto {
|
|
||||||
let encrypt: ({ data, encryptionKey, encryptionSalt }: {
|
|
||||||
data: string;
|
|
||||||
encryptionKey?: string;
|
|
||||||
encryptionSalt?: string;
|
|
||||||
}) => string | null;
|
|
||||||
let decrypt: ({ encryptedString, encryptionKey, encryptionSalt }: {
|
|
||||||
encryptedString: string;
|
|
||||||
encryptionKey?: string;
|
|
||||||
encryptionSalt?: string;
|
|
||||||
}) => string;
|
|
||||||
let hash: ({ password, encryptionKey }: {
|
|
||||||
password: string;
|
|
||||||
encryptionKey?: string;
|
|
||||||
}) => string;
|
|
||||||
}
|
|
||||||
export { parseCookies };
|
|
||||||
export { httpRequest };
|
|
||||||
}
|
|
||||||
export { get, post, getSchema, datasquirelClient as client };
|
|
104
index.js
104
index.js
@ -1,104 +0,0 @@
|
|||||||
// @ts-check
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Imports
|
|
||||||
*/
|
|
||||||
const get = require("./utils/get");
|
|
||||||
const post = require("./utils/post");
|
|
||||||
const getSchema = require("./utils/get-schema");
|
|
||||||
|
|
||||||
const uploadImage = require("./utils/upload-image");
|
|
||||||
const uploadFile = require("./utils/upload-file");
|
|
||||||
const deleteFile = require("./utils/delete-file");
|
|
||||||
|
|
||||||
const createUser = require("./users/add-user");
|
|
||||||
const updateUser = require("./users/update-user");
|
|
||||||
const loginUser = require("./users/login-user");
|
|
||||||
const sendEmailCode = require("./users/send-email-code");
|
|
||||||
const logoutUser = require("./users/logout-user");
|
|
||||||
|
|
||||||
const userAuth = require("./users/user-auth");
|
|
||||||
const reAuthUser = require("./users/reauth-user");
|
|
||||||
const getUser = require("./users/get-user");
|
|
||||||
|
|
||||||
const loginWithGoogle = require("./users/social/google-auth");
|
|
||||||
const loginWithGithub = require("./users/social/github-auth");
|
|
||||||
const getToken = require("./users/get-token");
|
|
||||||
const validateToken = require("./users/validate-token");
|
|
||||||
|
|
||||||
const datasquirelClient = require("./client");
|
|
||||||
const sqlGenerator = require("./package-shared/functions/dsql/sql/sql-generator");
|
|
||||||
const sqlInsertGenerator = require("./package-shared/functions/dsql/sql/sql-insert-generator");
|
|
||||||
const sqlDeleteGenerator = require("./package-shared/functions/dsql/sql/sql-delete-generator");
|
|
||||||
const trimSql = require("./package-shared/utils/trim-sql");
|
|
||||||
const parseCookies = require("./package-shared/utils/backend/parseCookies");
|
|
||||||
const httpRequest = require("./package-shared/functions/backend/httpRequest");
|
|
||||||
|
|
||||||
////////////////////////////////////////
|
|
||||||
////////////////////////////////////////
|
|
||||||
////////////////////////////////////////
|
|
||||||
|
|
||||||
/**
|
|
||||||
* User Functions Object
|
|
||||||
*/
|
|
||||||
const user = {
|
|
||||||
createUser: createUser,
|
|
||||||
deleteUser: require("./users/delete-user"),
|
|
||||||
loginUser: loginUser,
|
|
||||||
sendEmailCode: sendEmailCode,
|
|
||||||
logoutUser: logoutUser,
|
|
||||||
userAuth: userAuth,
|
|
||||||
reAuthUser: reAuthUser,
|
|
||||||
updateUser: updateUser,
|
|
||||||
getUser: getUser,
|
|
||||||
getToken: getToken,
|
|
||||||
validateToken: validateToken,
|
|
||||||
validateTempEmailCode: require("./users/validate-temp-email-code"),
|
|
||||||
social: {
|
|
||||||
loginWithGoogle: loginWithGoogle,
|
|
||||||
loginWithGithub: loginWithGithub,
|
|
||||||
},
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Media Functions Object
|
|
||||||
*/
|
|
||||||
const media = {
|
|
||||||
uploadImage: uploadImage,
|
|
||||||
uploadFile: uploadFile,
|
|
||||||
deleteFile: deleteFile,
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* SQL Utils
|
|
||||||
*/
|
|
||||||
const sql = {
|
|
||||||
sqlGenerator,
|
|
||||||
sqlInsertGenerator,
|
|
||||||
sqlDeleteGenerator,
|
|
||||||
trim: trimSql,
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Main Export
|
|
||||||
*/
|
|
||||||
const datasquirel = {
|
|
||||||
get,
|
|
||||||
post,
|
|
||||||
media,
|
|
||||||
user,
|
|
||||||
getSchema,
|
|
||||||
client: datasquirelClient,
|
|
||||||
sql,
|
|
||||||
utils: {
|
|
||||||
crypto: {
|
|
||||||
encrypt: require("./package-shared/functions/dsql/encrypt"),
|
|
||||||
decrypt: require("./package-shared/functions/dsql/decrypt"),
|
|
||||||
hash: require("./package-shared/functions/dsql/hashPassword"),
|
|
||||||
},
|
|
||||||
parseCookies,
|
|
||||||
httpRequest,
|
|
||||||
},
|
|
||||||
};
|
|
||||||
|
|
||||||
module.exports = datasquirel;
|
|
104
index.ts
Normal file
104
index.ts
Normal file
@ -0,0 +1,104 @@
|
|||||||
|
// @ts-check
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Imports
|
||||||
|
*/
|
||||||
|
import get from "./utils/get";
|
||||||
|
import post from "./utils/post";
|
||||||
|
import getSchema from "./utils/get-schema";
|
||||||
|
|
||||||
|
import uploadImage from "./utils/upload-image";
|
||||||
|
import uploadFile from "./utils/upload-file";
|
||||||
|
import deleteFile from "./utils/delete-file";
|
||||||
|
|
||||||
|
import createUser from "./users/add-user";
|
||||||
|
import updateUser from "./users/update-user";
|
||||||
|
import loginUser from "./users/login-user";
|
||||||
|
import sendEmailCode from "./users/send-email-code";
|
||||||
|
import logoutUser from "./users/logout-user";
|
||||||
|
|
||||||
|
import userAuth from "./users/user-auth";
|
||||||
|
import reAuthUser from "./users/reauth-user";
|
||||||
|
import getUser from "./users/get-user";
|
||||||
|
|
||||||
|
import loginWithGoogle from "./users/social/google-auth";
|
||||||
|
import loginWithGithub from "./users/social/github-auth";
|
||||||
|
import getToken from "./users/get-token";
|
||||||
|
import validateToken from "./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 httpRequest from "./package-shared/functions/backend/httpRequest";
|
||||||
|
|
||||||
|
////////////////////////////////////////
|
||||||
|
////////////////////////////////////////
|
||||||
|
////////////////////////////////////////
|
||||||
|
|
||||||
|
/**
|
||||||
|
* User Functions Object
|
||||||
|
*/
|
||||||
|
const user = {
|
||||||
|
createUser: createUser,
|
||||||
|
deleteUser: require("./users/delete-user"),
|
||||||
|
loginUser: loginUser,
|
||||||
|
sendEmailCode: sendEmailCode,
|
||||||
|
logoutUser: logoutUser,
|
||||||
|
userAuth: userAuth,
|
||||||
|
reAuthUser: reAuthUser,
|
||||||
|
updateUser: updateUser,
|
||||||
|
getUser: getUser,
|
||||||
|
getToken: getToken,
|
||||||
|
validateToken: validateToken,
|
||||||
|
validateTempEmailCode: require("./users/validate-temp-email-code"),
|
||||||
|
social: {
|
||||||
|
loginWithGoogle: loginWithGoogle,
|
||||||
|
loginWithGithub: loginWithGithub,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Media Functions Object
|
||||||
|
*/
|
||||||
|
const media = {
|
||||||
|
uploadImage: uploadImage,
|
||||||
|
uploadFile: uploadFile,
|
||||||
|
deleteFile: deleteFile,
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* SQL Utils
|
||||||
|
*/
|
||||||
|
const sql = {
|
||||||
|
sqlGenerator,
|
||||||
|
sqlInsertGenerator,
|
||||||
|
sqlDeleteGenerator,
|
||||||
|
trim: trimSql,
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Main Export
|
||||||
|
*/
|
||||||
|
const datasquirel = {
|
||||||
|
get,
|
||||||
|
post,
|
||||||
|
media,
|
||||||
|
user,
|
||||||
|
getSchema,
|
||||||
|
client: datasquirelClient,
|
||||||
|
sql,
|
||||||
|
utils: {
|
||||||
|
crypto: {
|
||||||
|
encrypt: require("./package-shared/functions/dsql/encrypt"),
|
||||||
|
decrypt: require("./package-shared/functions/dsql/decrypt"),
|
||||||
|
hash: require("./package-shared/functions/dsql/hashPassword"),
|
||||||
|
},
|
||||||
|
parseCookies,
|
||||||
|
httpRequest,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
export default datasquirel;
|
9
package-shared/functions/api/query/get.d.ts
vendored
9
package-shared/functions/api/query/get.d.ts
vendored
@ -1,9 +0,0 @@
|
|||||||
declare function _exports({ query, dbFullName, queryValues, tableName, dbSchema, useLocal, }: {
|
|
||||||
query: string;
|
|
||||||
queryValues?: (string | number)[];
|
|
||||||
dbFullName: string;
|
|
||||||
tableName?: string;
|
|
||||||
dbSchema?: import("../../../types").DSQL_DatabaseSchemaType;
|
|
||||||
useLocal?: boolean;
|
|
||||||
}): Promise<import("../../../types").GetReturn>;
|
|
||||||
export = _exports;
|
|
@ -1,30 +1,29 @@
|
|||||||
// @ts-check
|
// @ts-check
|
||||||
|
|
||||||
const _ = require("lodash");
|
import _ from "lodash";
|
||||||
const serverError = require("../../backend/serverError");
|
import serverError from "../../backend/serverError";
|
||||||
const runQuery = require("../../backend/db/runQuery");
|
import runQuery from "../../backend/db/runQuery";
|
||||||
|
|
||||||
|
type Param = {
|
||||||
|
query: string;
|
||||||
|
queryValues?: (string | number)[];
|
||||||
|
dbFullName: string;
|
||||||
|
tableName?: string;
|
||||||
|
dbSchema?: import("../../../types").DSQL_DatabaseSchemaType;
|
||||||
|
useLocal?: boolean;
|
||||||
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* # Get Function FOr API
|
* # Get Function FOr API
|
||||||
*
|
|
||||||
* @param {object} params
|
|
||||||
* @param {string} params.query
|
|
||||||
* @param {(string|number)[]} [params.queryValues]
|
|
||||||
* @param {string} params.dbFullName
|
|
||||||
* @param {string} [params.tableName]
|
|
||||||
* @param {import("../../../types").DSQL_DatabaseSchemaType} [params.dbSchema]
|
|
||||||
* @param {boolean} [params.useLocal]
|
|
||||||
*
|
|
||||||
* @returns {Promise<import("../../../types").GetReturn>}
|
|
||||||
*/
|
*/
|
||||||
module.exports = async function apiGet({
|
export default async function apiGet({
|
||||||
query,
|
query,
|
||||||
dbFullName,
|
dbFullName,
|
||||||
queryValues,
|
queryValues,
|
||||||
tableName,
|
tableName,
|
||||||
dbSchema,
|
dbSchema,
|
||||||
useLocal,
|
useLocal,
|
||||||
}) {
|
}: Param): Promise<import("../../../types").GetReturn> {
|
||||||
if (
|
if (
|
||||||
typeof query == "string" &&
|
typeof query == "string" &&
|
||||||
query.match(/^alter|^delete|information_schema|databases|^create/i)
|
query.match(/^alter|^delete|information_schema|databases|^create/i)
|
||||||
@ -51,7 +50,9 @@ module.exports = async function apiGet({
|
|||||||
});
|
});
|
||||||
|
|
||||||
/** @type {import("../../../types").DSQL_TableSchemaType | undefined} */
|
/** @type {import("../../../types").DSQL_TableSchemaType | undefined} */
|
||||||
let tableSchema;
|
let tableSchema:
|
||||||
|
| import("../../../types").DSQL_TableSchemaType
|
||||||
|
| undefined;
|
||||||
|
|
||||||
if (dbSchema) {
|
if (dbSchema) {
|
||||||
const targetTable = dbSchema.tables.find(
|
const targetTable = dbSchema.tables.find(
|
||||||
@ -77,14 +78,14 @@ module.exports = async function apiGet({
|
|||||||
results = result;
|
results = result;
|
||||||
|
|
||||||
/** @type {import("../../../types").GetReturn} */
|
/** @type {import("../../../types").GetReturn} */
|
||||||
const resObject = {
|
const resObject: import("../../../types").GetReturn = {
|
||||||
success: true,
|
success: true,
|
||||||
payload: results,
|
payload: results,
|
||||||
schema: tableName && tableSchema ? tableSchema : undefined,
|
schema: tableName && tableSchema ? tableSchema : undefined,
|
||||||
};
|
};
|
||||||
|
|
||||||
return resObject;
|
return resObject;
|
||||||
} catch (/** @type {any} */ error) {
|
} catch (/** @type {any} */ error: any) {
|
||||||
serverError({
|
serverError({
|
||||||
component: "/api/query/get/lines-85-94",
|
component: "/api/query/get/lines-85-94",
|
||||||
message: error.message,
|
message: error.message,
|
||||||
@ -92,4 +93,4 @@ module.exports = async function apiGet({
|
|||||||
|
|
||||||
return { success: false, payload: null, error: error.message };
|
return { success: false, payload: null, error: error.message };
|
||||||
}
|
}
|
||||||
};
|
}
|
9
package-shared/functions/api/query/post.d.ts
vendored
9
package-shared/functions/api/query/post.d.ts
vendored
@ -1,9 +0,0 @@
|
|||||||
declare function _exports({ query, dbFullName, queryValues, tableName, dbSchema, useLocal, }: {
|
|
||||||
query: any;
|
|
||||||
queryValues?: (string | number)[];
|
|
||||||
dbFullName: string;
|
|
||||||
tableName?: string;
|
|
||||||
dbSchema?: import("../../../types").DSQL_DatabaseSchemaType;
|
|
||||||
useLocal?: boolean;
|
|
||||||
}): Promise<import("../../../types").PostReturn>;
|
|
||||||
export = _exports;
|
|
@ -1,30 +1,28 @@
|
|||||||
// @ts-check
|
import _ from "lodash";
|
||||||
|
import serverError from "../../backend/serverError";
|
||||||
|
import runQuery from "../../backend/db/runQuery";
|
||||||
|
import { DSQL_DatabaseSchemaType, PostReturn } from "../../../types";
|
||||||
|
|
||||||
const _ = require("lodash");
|
type Param = {
|
||||||
const serverError = require("../../backend/serverError");
|
query: any;
|
||||||
const runQuery = require("../../backend/db/runQuery");
|
queryValues?: (string | number)[];
|
||||||
|
dbFullName: string;
|
||||||
|
tableName?: string;
|
||||||
|
dbSchema?: DSQL_DatabaseSchemaType;
|
||||||
|
useLocal?: boolean;
|
||||||
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* # Post Function For API
|
* # Post Function For API
|
||||||
*
|
|
||||||
* @param {object} params
|
|
||||||
* @param {any} params.query
|
|
||||||
* @param {(string|number)[]} [params.queryValues]
|
|
||||||
* @param {string} params.dbFullName
|
|
||||||
* @param {string} [params.tableName]
|
|
||||||
* @param {import("../../../types").DSQL_DatabaseSchemaType} [params.dbSchema]
|
|
||||||
* @param {boolean} [params.useLocal]
|
|
||||||
*
|
|
||||||
* @returns {Promise<import("../../../types").PostReturn>}
|
|
||||||
*/
|
*/
|
||||||
module.exports = async function apiPost({
|
export default async function apiPost({
|
||||||
query,
|
query,
|
||||||
dbFullName,
|
dbFullName,
|
||||||
queryValues,
|
queryValues,
|
||||||
tableName,
|
tableName,
|
||||||
dbSchema,
|
dbSchema,
|
||||||
useLocal,
|
useLocal,
|
||||||
}) {
|
}: Param): Promise<PostReturn> {
|
||||||
if (typeof query === "string" && query?.match(/^create |^alter |^drop /i)) {
|
if (typeof query === "string" && query?.match(/^create |^alter |^drop /i)) {
|
||||||
return { success: false, msg: "Wrong Input" };
|
return { success: false, msg: "Wrong Input" };
|
||||||
}
|
}
|
||||||
@ -37,7 +35,7 @@ module.exports = async function apiPost({
|
|||||||
}
|
}
|
||||||
|
|
||||||
/** @type {any} */
|
/** @type {any} */
|
||||||
let results;
|
let results: any;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Create new user folder and file
|
* Create new user folder and file
|
||||||
@ -59,7 +57,9 @@ module.exports = async function apiPost({
|
|||||||
if (error) throw error;
|
if (error) throw error;
|
||||||
|
|
||||||
/** @type {import("../../../types").DSQL_TableSchemaType | undefined} */
|
/** @type {import("../../../types").DSQL_TableSchemaType | undefined} */
|
||||||
let tableSchema;
|
let tableSchema:
|
||||||
|
| import("../../../types").DSQL_TableSchemaType
|
||||||
|
| undefined;
|
||||||
|
|
||||||
if (dbSchema) {
|
if (dbSchema) {
|
||||||
const targetTable = dbSchema.tables.find(
|
const targetTable = dbSchema.tables.find(
|
||||||
@ -76,6 +76,7 @@ module.exports = async function apiPost({
|
|||||||
delete clonedTargetTable.updateData;
|
delete clonedTargetTable.updateData;
|
||||||
delete clonedTargetTable.tableNameOld;
|
delete clonedTargetTable.tableNameOld;
|
||||||
delete clonedTargetTable.indexes;
|
delete clonedTargetTable.indexes;
|
||||||
|
|
||||||
tableSchema = clonedTargetTable;
|
tableSchema = clonedTargetTable;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -86,9 +87,7 @@ module.exports = async function apiPost({
|
|||||||
error: error,
|
error: error,
|
||||||
schema: tableName && tableSchema ? tableSchema : undefined,
|
schema: tableName && tableSchema ? tableSchema : undefined,
|
||||||
};
|
};
|
||||||
|
} catch (error: any) {
|
||||||
////////////////////////////////////////
|
|
||||||
} catch (/** @type {any} */ error) {
|
|
||||||
serverError({
|
serverError({
|
||||||
component: "/api/query/post/lines-132-142",
|
component: "/api/query/post/lines-132-142",
|
||||||
message: error.message,
|
message: error.message,
|
||||||
@ -100,4 +99,4 @@ module.exports = async function apiPost({
|
|||||||
error: error.message,
|
error: error.message,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
};
|
}
|
@ -1,128 +0,0 @@
|
|||||||
// @ts-check
|
|
||||||
|
|
||||||
/**
|
|
||||||
* ==============================================================================
|
|
||||||
* Imports
|
|
||||||
* ==============================================================================
|
|
||||||
*/
|
|
||||||
|
|
||||||
const DB_HANDLER = require("../../../utils/backend/global-db/DB_HANDLER");
|
|
||||||
const handleNodemailer = require("../../backend/handleNodemailer");
|
|
||||||
const serverError = require("../../backend/serverError");
|
|
||||||
const hashPassword = require("../../dsql/hashPassword");
|
|
||||||
|
|
||||||
//////////////////////////////////////////////////////////////////////////////////
|
|
||||||
//////////////////////////////////////////////////////////////////////////////////
|
|
||||||
//////////////////////////////////////////////////////////////////////////////////
|
|
||||||
//////////////////////////////////////////////////////////////////////////////////
|
|
||||||
//////////////////////////////////////////////////////////////////////////////////
|
|
||||||
//////////////////////////////////////////////////////////////////////////////////
|
|
||||||
|
|
||||||
/**
|
|
||||||
* ==============================================================================
|
|
||||||
* Main Function
|
|
||||||
* ==============================================================================
|
|
||||||
* @param {object} params - parameters object
|
|
||||||
* @param {any} params.body
|
|
||||||
* @param {import("../../../types").UserType} params.usertype
|
|
||||||
*/
|
|
||||||
module.exports = 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,
|
|
||||||
social_name,
|
|
||||||
email,
|
|
||||||
image,
|
|
||||||
image_thumbnail,
|
|
||||||
password,
|
|
||||||
verification_status,
|
|
||||||
social_login,
|
|
||||||
social_id,
|
|
||||||
terms_agreement,
|
|
||||||
date_created,
|
|
||||||
date_code
|
|
||||||
) VALUES (
|
|
||||||
'${body.facebookUserFirstName}',
|
|
||||||
'${body.facebookUserLastName}',
|
|
||||||
'facebook',
|
|
||||||
'facebook_${
|
|
||||||
body.facebookUserEmail
|
|
||||||
? body.facebookUserEmail.replace(/@.*/, "")
|
|
||||||
: body.facebookUserFirstName.toLowerCase()
|
|
||||||
}',
|
|
||||||
'${body.facebookUserEmail}',
|
|
||||||
'${body.facebookUserImage}',
|
|
||||||
'${body.facebookUserImage}',
|
|
||||||
'${socialHashedPassword}',
|
|
||||||
'1',
|
|
||||||
'1',
|
|
||||||
'${body.facebookUserId}',
|
|
||||||
'1',
|
|
||||||
'${Date()}',
|
|
||||||
'${Date.now()}'
|
|
||||||
)`);
|
|
||||||
|
|
||||||
const newFoundUser = await DB_HANDLER(
|
|
||||||
`SELECT * FROM ${usertype} WHERE id='${newUser.insertId}'`
|
|
||||||
);
|
|
||||||
|
|
||||||
////////////////////////////////////////////////
|
|
||||||
////////////////////////////////////////////////
|
|
||||||
////////////////////////////////////////////////
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Send email notifications to admin
|
|
||||||
*
|
|
||||||
* @description Send verification email to newly created agent
|
|
||||||
*/
|
|
||||||
// handleNodemailer({
|
|
||||||
// to: "",
|
|
||||||
// subject: "New Registered Buyer",
|
|
||||||
// text: "We have a new registered Buyer from facebook",
|
|
||||||
// html: `
|
|
||||||
// <h2>${newFoundUser[0].first_name} ${newFoundUser[0].last_name} just registered from facebook.</h2>
|
|
||||||
// <p>We have a new buyer registration</p>
|
|
||||||
// <div>Name: <b>${newFoundUser[0].first_name} ${newFoundUser[0].last_name}</b></div>
|
|
||||||
// <div>Email: <b>${newFoundUser[0].email}</b></div>
|
|
||||||
// <div>Site: <b>${process.env.DSQL_DB_HOST}</b></div>
|
|
||||||
// `,
|
|
||||||
// }).catch((error) => {
|
|
||||||
// console.log(
|
|
||||||
// "error in mail notification for new Facebook user =>",
|
|
||||||
// error.message
|
|
||||||
// );
|
|
||||||
// });
|
|
||||||
} catch (/** @type {any} */ error) {
|
|
||||||
serverError({
|
|
||||||
component: "functions/backend/facebookLogin",
|
|
||||||
message: error.message,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
|
||||||
isFacebookAuthValid: false,
|
|
||||||
newFoundUser: null,
|
|
||||||
};
|
|
||||||
};
|
|
80
package-shared/functions/api/social-login/facebookLogin.ts
Executable file
80
package-shared/functions/api/social-login/facebookLogin.ts
Executable file
@ -0,0 +1,80 @@
|
|||||||
|
import { UserType } from "../../../types";
|
||||||
|
import DB_HANDLER from "../../../utils/backend/global-db/DB_HANDLER";
|
||||||
|
import handleNodemailer from "../../backend/handleNodemailer";
|
||||||
|
import serverError from "../../backend/serverError";
|
||||||
|
import hashPassword from "../../dsql/hashPassword";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* # Facebook Login
|
||||||
|
*/
|
||||||
|
export default async function facebookLogin({
|
||||||
|
usertype,
|
||||||
|
body,
|
||||||
|
}: {
|
||||||
|
body: any;
|
||||||
|
usertype: UserType;
|
||||||
|
}) {
|
||||||
|
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,
|
||||||
|
social_name,
|
||||||
|
email,
|
||||||
|
image,
|
||||||
|
image_thumbnail,
|
||||||
|
password,
|
||||||
|
verification_status,
|
||||||
|
social_login,
|
||||||
|
social_id,
|
||||||
|
terms_agreement,
|
||||||
|
date_created,
|
||||||
|
date_code
|
||||||
|
) VALUES (
|
||||||
|
'${body.facebookUserFirstName}',
|
||||||
|
'${body.facebookUserLastName}',
|
||||||
|
'facebook',
|
||||||
|
'facebook_${
|
||||||
|
body.facebookUserEmail
|
||||||
|
? body.facebookUserEmail.replace(/@.*/, "")
|
||||||
|
: body.facebookUserFirstName.toLowerCase()
|
||||||
|
}',
|
||||||
|
'${body.facebookUserEmail}',
|
||||||
|
'${body.facebookUserImage}',
|
||||||
|
'${body.facebookUserImage}',
|
||||||
|
'${socialHashedPassword}',
|
||||||
|
'1',
|
||||||
|
'1',
|
||||||
|
'${body.facebookUserId}',
|
||||||
|
'1',
|
||||||
|
'${Date()}',
|
||||||
|
'${Date.now()}'
|
||||||
|
)`);
|
||||||
|
|
||||||
|
const newFoundUser = await DB_HANDLER(
|
||||||
|
`SELECT * FROM ${usertype} WHERE id='${newUser.insertId}'`
|
||||||
|
);
|
||||||
|
} catch (/** @type {any} */ error: any) {
|
||||||
|
serverError({
|
||||||
|
component: "functions/backend/facebookLogin",
|
||||||
|
message: error.message,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
isFacebookAuthValid: false,
|
||||||
|
newFoundUser: null,
|
||||||
|
};
|
||||||
|
}
|
@ -1,135 +0,0 @@
|
|||||||
declare namespace _exports {
|
|
||||||
export { GithubUserPayload };
|
|
||||||
}
|
|
||||||
declare function _exports({ code, clientId, clientSecret }: {
|
|
||||||
code: string;
|
|
||||||
clientId: string;
|
|
||||||
clientSecret: string;
|
|
||||||
}): Promise<GithubUserPayload | null | undefined>;
|
|
||||||
export = _exports;
|
|
||||||
type GithubUserPayload = {
|
|
||||||
/**
|
|
||||||
* - Full name merged eg. "JohnDoe"
|
|
||||||
*/
|
|
||||||
login: string;
|
|
||||||
/**
|
|
||||||
* - github user id
|
|
||||||
*/
|
|
||||||
id: number;
|
|
||||||
/**
|
|
||||||
* - Some other id
|
|
||||||
*/
|
|
||||||
node_id: string;
|
|
||||||
/**
|
|
||||||
* - profile picture
|
|
||||||
*/
|
|
||||||
avatar_url: string;
|
|
||||||
/**
|
|
||||||
* - some other id
|
|
||||||
*/
|
|
||||||
gravatar_id: string;
|
|
||||||
/**
|
|
||||||
* - Github user URL
|
|
||||||
*/
|
|
||||||
url: string;
|
|
||||||
/**
|
|
||||||
* - User html URL - whatever that means
|
|
||||||
*/
|
|
||||||
html_url: string;
|
|
||||||
/**
|
|
||||||
* - Followers URL
|
|
||||||
*/
|
|
||||||
followers_url: string;
|
|
||||||
/**
|
|
||||||
* - Following URL
|
|
||||||
*/
|
|
||||||
following_url: string;
|
|
||||||
/**
|
|
||||||
* - Gists URL
|
|
||||||
*/
|
|
||||||
gists_url: string;
|
|
||||||
/**
|
|
||||||
* - Starred URL
|
|
||||||
*/
|
|
||||||
starred_url: string;
|
|
||||||
/**
|
|
||||||
* - Subscriptions URL
|
|
||||||
*/
|
|
||||||
subscriptions_url: string;
|
|
||||||
/**
|
|
||||||
* - Organizations URL
|
|
||||||
*/
|
|
||||||
organizations_url: string;
|
|
||||||
/**
|
|
||||||
* - Repositories URL
|
|
||||||
*/
|
|
||||||
repos_url: string;
|
|
||||||
/**
|
|
||||||
* - Received Events URL
|
|
||||||
*/
|
|
||||||
received_events_url: string;
|
|
||||||
/**
|
|
||||||
* - Common value => "User"
|
|
||||||
*/
|
|
||||||
type: string;
|
|
||||||
/**
|
|
||||||
* - Is site admin or not? Boolean
|
|
||||||
*/
|
|
||||||
site_admin: boolean;
|
|
||||||
/**
|
|
||||||
* - More like "username"
|
|
||||||
*/
|
|
||||||
name: string;
|
|
||||||
/**
|
|
||||||
* - User company
|
|
||||||
*/
|
|
||||||
company: string;
|
|
||||||
/**
|
|
||||||
* - User blog URL
|
|
||||||
*/
|
|
||||||
blog: string;
|
|
||||||
/**
|
|
||||||
* - User Location
|
|
||||||
*/
|
|
||||||
location: string;
|
|
||||||
/**
|
|
||||||
* - User Email
|
|
||||||
*/
|
|
||||||
email: string;
|
|
||||||
/**
|
|
||||||
* - Is user hireable
|
|
||||||
*/
|
|
||||||
hireable: string;
|
|
||||||
/**
|
|
||||||
* - User bio
|
|
||||||
*/
|
|
||||||
bio: string;
|
|
||||||
/**
|
|
||||||
* - User twitter username
|
|
||||||
*/
|
|
||||||
twitter_username: string;
|
|
||||||
/**
|
|
||||||
* - Number of public repositories
|
|
||||||
*/
|
|
||||||
public_repos: number;
|
|
||||||
/**
|
|
||||||
* - Number of public gists
|
|
||||||
*/
|
|
||||||
public_gists: number;
|
|
||||||
/**
|
|
||||||
* - Number of followers
|
|
||||||
*/
|
|
||||||
followers: number;
|
|
||||||
/**
|
|
||||||
* - Number of following
|
|
||||||
*/
|
|
||||||
following: number;
|
|
||||||
/**
|
|
||||||
* - Date created
|
|
||||||
*/
|
|
||||||
created_at: string;
|
|
||||||
/**
|
|
||||||
* - Date updated
|
|
||||||
*/
|
|
||||||
updated_at: string;
|
|
||||||
};
|
|
@ -1,160 +0,0 @@
|
|||||||
// @ts-check
|
|
||||||
|
|
||||||
const DB_HANDLER = require("../../../utils/backend/global-db/DB_HANDLER");
|
|
||||||
const httpsRequest = require("../../backend/httpsRequest");
|
|
||||||
|
|
||||||
//////////////////////////////////////////////////////////////////////////////////
|
|
||||||
//////////////////////////////////////////////////////////////////////////////////
|
|
||||||
//////////////////////////////////////////////////////////////////////////////////
|
|
||||||
//////////////////////////////////////////////////////////////////////////////////
|
|
||||||
//////////////////////////////////////////////////////////////////////////////////
|
|
||||||
//////////////////////////////////////////////////////////////////////////////////
|
|
||||||
|
|
||||||
/**
|
|
||||||
*
|
|
||||||
* @typedef {object} GithubUserPayload
|
|
||||||
* @property {string} login - Full name merged eg. "JohnDoe"
|
|
||||||
* @property {number} id - github user id
|
|
||||||
* @property {string} node_id - Some other id
|
|
||||||
* @property {string} avatar_url - profile picture
|
|
||||||
* @property {string} gravatar_id - some other id
|
|
||||||
* @property {string} url - Github user URL
|
|
||||||
* @property {string} html_url - User html URL - whatever that means
|
|
||||||
* @property {string} followers_url - Followers URL
|
|
||||||
* @property {string} following_url - Following URL
|
|
||||||
* @property {string} gists_url - Gists URL
|
|
||||||
* @property {string} starred_url - Starred URL
|
|
||||||
* @property {string} subscriptions_url - Subscriptions URL
|
|
||||||
* @property {string} organizations_url - Organizations URL
|
|
||||||
* @property {string} repos_url - Repositories URL
|
|
||||||
* @property {string} received_events_url - Received Events URL
|
|
||||||
* @property {string} type - Common value => "User"
|
|
||||||
* @property {boolean} site_admin - Is site admin or not? Boolean
|
|
||||||
* @property {string} name - More like "username"
|
|
||||||
* @property {string} company - User company
|
|
||||||
* @property {string} blog - User blog URL
|
|
||||||
* @property {string} location - User Location
|
|
||||||
* @property {string} email - User Email
|
|
||||||
* @property {string} hireable - Is user hireable
|
|
||||||
* @property {string} bio - User bio
|
|
||||||
* @property {string} twitter_username - User twitter username
|
|
||||||
* @property {number} public_repos - Number of public repositories
|
|
||||||
* @property {number} public_gists - Number of public gists
|
|
||||||
* @property {number} followers - Number of followers
|
|
||||||
* @property {number} following - Number of following
|
|
||||||
* @property {string} created_at - Date created
|
|
||||||
* @property {string} updated_at - Date updated
|
|
||||||
*/
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Login/signup a github user
|
|
||||||
* ==============================================================================
|
|
||||||
* @async
|
|
||||||
*
|
|
||||||
* @param {Object} params - foundUser if any
|
|
||||||
* @param {string} params.code - github auth token
|
|
||||||
* @param {string} params.clientId - github client Id
|
|
||||||
* @param {string} params.clientSecret - github client Secret
|
|
||||||
*
|
|
||||||
* @returns {Promise<GithubUserPayload|null|undefined>}
|
|
||||||
*/
|
|
||||||
module.exports = async function githubLogin({ code, clientId, clientSecret }) {
|
|
||||||
/** @type {GithubUserPayload | undefined} */
|
|
||||||
let gitHubUser;
|
|
||||||
|
|
||||||
////////////////////////////////////////////////
|
|
||||||
////////////////////////////////////////////////
|
|
||||||
////////////////////////////////////////////////
|
|
||||||
|
|
||||||
try {
|
|
||||||
/**
|
|
||||||
* Create new user folder and file
|
|
||||||
*
|
|
||||||
* @description Create new user folder and file
|
|
||||||
*/
|
|
||||||
// const response = await fetch(`https://github.com/login/oauth/access_token?client_id=${process.env.DSQL_GITHUB_ID}`);
|
|
||||||
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",
|
|
||||||
});
|
|
||||||
|
|
||||||
// `https://github.com/login/oauth/access_token?client_id=${process.env.DSQL_GITHUB_ID}&client_secret=${process.env.DSQL_GITHUB_SECRET}&code=${code}`,
|
|
||||||
// body: JSON.stringify({
|
|
||||||
// client_id: process.env.DSQL_GITHUB_ID,
|
|
||||||
// client_secret: process.env.DSQL_GITHUB_SECRET,
|
|
||||||
// code: code,
|
|
||||||
// }),
|
|
||||||
|
|
||||||
const accessTokenObject = JSON.parse(response);
|
|
||||||
|
|
||||||
if (!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?.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.js backend function =>",
|
|
||||||
error.message
|
|
||||||
);
|
|
||||||
|
|
||||||
// serverError({
|
|
||||||
// component: "/api/social-login/github-auth/catch-error",
|
|
||||||
// message: error.message,
|
|
||||||
// user: user,
|
|
||||||
// });
|
|
||||||
|
|
||||||
////////////////////////////////////////////////
|
|
||||||
////////////////////////////////////////////////
|
|
||||||
////////////////////////////////////////////////
|
|
||||||
}
|
|
||||||
|
|
||||||
////////////////////////////////////////////////
|
|
||||||
////////////////////////////////////////////////
|
|
||||||
////////////////////////////////////////////////
|
|
||||||
|
|
||||||
return gitHubUser;
|
|
||||||
};
|
|
102
package-shared/functions/api/social-login/githubLogin.ts
Executable file
102
package-shared/functions/api/social-login/githubLogin.ts
Executable file
@ -0,0 +1,102 @@
|
|||||||
|
import DB_HANDLER from "../../../utils/backend/global-db/DB_HANDLER";
|
||||||
|
import httpsRequest from "../../backend/httpsRequest";
|
||||||
|
|
||||||
|
export interface GithubUserPayload {
|
||||||
|
login: string;
|
||||||
|
id: number;
|
||||||
|
node_id: string;
|
||||||
|
avatar_url: string;
|
||||||
|
gravatar_id: string;
|
||||||
|
url: string;
|
||||||
|
html_url: string;
|
||||||
|
followers_url: string;
|
||||||
|
following_url: string;
|
||||||
|
gists_url: string;
|
||||||
|
starred_url: string;
|
||||||
|
subscriptions_url: string;
|
||||||
|
organizations_url: string;
|
||||||
|
repos_url: string;
|
||||||
|
received_events_url: string;
|
||||||
|
type: string;
|
||||||
|
site_admin: boolean;
|
||||||
|
name: string;
|
||||||
|
company: string;
|
||||||
|
blog: string;
|
||||||
|
location: string;
|
||||||
|
email: string;
|
||||||
|
hireable: string;
|
||||||
|
bio: string;
|
||||||
|
twitter_username: string;
|
||||||
|
public_repos: number;
|
||||||
|
public_gists: number;
|
||||||
|
followers: number;
|
||||||
|
following: number;
|
||||||
|
created_at: string;
|
||||||
|
updated_at: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
type Param = {
|
||||||
|
code: string;
|
||||||
|
clientId: string;
|
||||||
|
clientSecret: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* # Login/signup a github user
|
||||||
|
*/
|
||||||
|
export default async function githubLogin({
|
||||||
|
code,
|
||||||
|
clientId,
|
||||||
|
clientSecret,
|
||||||
|
}: Param): Promise<GithubUserPayload | null | undefined> {
|
||||||
|
let gitHubUser: GithubUserPayload | undefined;
|
||||||
|
|
||||||
|
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 as string);
|
||||||
|
|
||||||
|
if (!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 as string);
|
||||||
|
|
||||||
|
if (!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: any) {
|
||||||
|
console.log(
|
||||||
|
"ERROR in githubLogin.js backend function =>",
|
||||||
|
error.message
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return gitHubUser;
|
||||||
|
}
|
@ -1,44 +1,23 @@
|
|||||||
// @ts-check
|
import fs from "fs";
|
||||||
|
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";
|
||||||
|
|
||||||
|
type Param = {
|
||||||
|
usertype: string;
|
||||||
|
foundUser: any;
|
||||||
|
isSocialValidated: boolean;
|
||||||
|
isUserValid: boolean;
|
||||||
|
reqBody: any;
|
||||||
|
serverRes: any;
|
||||||
|
loginFailureReason: any;
|
||||||
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* ==============================================================================
|
* # Google Login
|
||||||
* Imports
|
|
||||||
* ==============================================================================
|
|
||||||
*/
|
*/
|
||||||
const fs = require("fs");
|
export default async function googleLogin({
|
||||||
|
|
||||||
////////////////////////////////////////////////
|
|
||||||
////////////////////////////////////////////////
|
|
||||||
////////////////////////////////////////////////
|
|
||||||
|
|
||||||
const { OAuth2Client } = require("google-auth-library");
|
|
||||||
|
|
||||||
const serverError = require("../../backend/serverError");
|
|
||||||
const { ServerResponse } = require("http");
|
|
||||||
const DB_HANDLER = require("../../../utils/backend/global-db/DB_HANDLER");
|
|
||||||
const hashPassword = require("../../dsql/hashPassword");
|
|
||||||
|
|
||||||
//////////////////////////////////////////////////////////////////////////////////
|
|
||||||
//////////////////////////////////////////////////////////////////////////////////
|
|
||||||
//////////////////////////////////////////////////////////////////////////////////
|
|
||||||
//////////////////////////////////////////////////////////////////////////////////
|
|
||||||
//////////////////////////////////////////////////////////////////////////////////
|
|
||||||
//////////////////////////////////////////////////////////////////////////////////
|
|
||||||
|
|
||||||
/**
|
|
||||||
* ==============================================================================
|
|
||||||
* Main Function
|
|
||||||
* ==============================================================================
|
|
||||||
* @param {Object} params
|
|
||||||
* @param {string} params.usertype
|
|
||||||
* @param {any} params.foundUser
|
|
||||||
* @param {boolean} params.isSocialValidated
|
|
||||||
* @param {boolean} params.isUserValid
|
|
||||||
* @param {any} params.reqBody
|
|
||||||
* @param {any} params.serverRes
|
|
||||||
* @param {any} params.loginFailureReason
|
|
||||||
*/
|
|
||||||
module.exports = async function googleLogin({
|
|
||||||
usertype,
|
usertype,
|
||||||
foundUser,
|
foundUser,
|
||||||
isSocialValidated,
|
isSocialValidated,
|
||||||
@ -46,7 +25,7 @@ module.exports = async function googleLogin({
|
|||||||
reqBody,
|
reqBody,
|
||||||
serverRes,
|
serverRes,
|
||||||
loginFailureReason,
|
loginFailureReason,
|
||||||
}) {
|
}: Param) {
|
||||||
const client = new OAuth2Client(
|
const client = new OAuth2Client(
|
||||||
process.env.NEXT_PUBLIC_DSQL_GOOGLE_CLIENT_ID
|
process.env.NEXT_PUBLIC_DSQL_GOOGLE_CLIENT_ID
|
||||||
);
|
);
|
||||||
@ -156,11 +135,7 @@ module.exports = async function googleLogin({
|
|||||||
newFoundUser = await DB_HANDLER(
|
newFoundUser = await DB_HANDLER(
|
||||||
`SELECT * FROM ${usertype} WHERE id='${newUser.insertId}'`
|
`SELECT * FROM ${usertype} WHERE id='${newUser.insertId}'`
|
||||||
);
|
);
|
||||||
|
} catch (error: any) {
|
||||||
////////////////////////////////////////////////
|
|
||||||
////////////////////////////////////////////////
|
|
||||||
////////////////////////////////////////////////
|
|
||||||
} catch (/** @type {any} */ error) {
|
|
||||||
serverError({
|
serverError({
|
||||||
component: "googleLogin",
|
component: "googleLogin",
|
||||||
message: error.message,
|
message: error.message,
|
||||||
@ -172,9 +147,5 @@ module.exports = async function googleLogin({
|
|||||||
isSocialValidated = false;
|
isSocialValidated = false;
|
||||||
}
|
}
|
||||||
|
|
||||||
////////////////////////////////////////////////
|
|
||||||
////////////////////////////////////////////////
|
|
||||||
////////////////////////////////////////////////
|
|
||||||
|
|
||||||
return { isGoogleAuthValid: isGoogleAuthValid, newFoundUser: newFoundUser };
|
return { isGoogleAuthValid: isGoogleAuthValid, newFoundUser: newFoundUser };
|
||||||
};
|
}
|
@ -1,2 +0,0 @@
|
|||||||
declare const _exports: import("../../../types").HandleSocialDbFunction;
|
|
||||||
export = _exports;
|
|
@ -1,18 +1,20 @@
|
|||||||
// @ts-check
|
import fs from "fs";
|
||||||
|
import handleNodemailer from "../../backend/handleNodemailer";
|
||||||
const fs = require("fs");
|
import path from "path";
|
||||||
const handleNodemailer = require("../../backend/handleNodemailer");
|
import addMariadbUser from "../../backend/addMariadbUser";
|
||||||
const path = require("path");
|
import varDatabaseDbHandler from "../../backend/varDatabaseDbHandler";
|
||||||
const addMariadbUser = require("../../backend/addMariadbUser");
|
import encrypt from "../../dsql/encrypt";
|
||||||
const varDatabaseDbHandler = require("../../backend/varDatabaseDbHandler");
|
import addDbEntry from "../../backend/db/addDbEntry";
|
||||||
const encrypt = require("../../dsql/encrypt");
|
import loginSocialUser from "./loginSocialUser";
|
||||||
const addDbEntry = require("../../backend/db/addDbEntry");
|
import {
|
||||||
const loginSocialUser = require("./loginSocialUser");
|
APILoginFunctionReturn,
|
||||||
|
HandleSocialDbFunctionParams,
|
||||||
|
} from "../../../types";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @type {import("../../../types").HandleSocialDbFunction}
|
* # Handle Social DB
|
||||||
*/
|
*/
|
||||||
module.exports = async function handleSocialDb({
|
export default async function handleSocialDb({
|
||||||
database,
|
database,
|
||||||
social_id,
|
social_id,
|
||||||
email,
|
email,
|
||||||
@ -22,7 +24,7 @@ module.exports = async function handleSocialDb({
|
|||||||
supEmail,
|
supEmail,
|
||||||
additionalFields,
|
additionalFields,
|
||||||
useLocal,
|
useLocal,
|
||||||
}) {
|
}: HandleSocialDbFunctionParams): Promise<APILoginFunctionReturn> {
|
||||||
try {
|
try {
|
||||||
const existingSocialIdUserQuery = `SELECT * FROM users WHERE social_id = ? AND social_login='1' AND social_platform = ? `;
|
const existingSocialIdUserQuery = `SELECT * FROM users WHERE social_id = ? AND social_login='1' AND social_platform = ? `;
|
||||||
const existingSocialIdUserValues = [
|
const existingSocialIdUserValues = [
|
||||||
@ -99,8 +101,7 @@ module.exports = async function handleSocialDb({
|
|||||||
data: social_id.toString(),
|
data: social_id.toString(),
|
||||||
});
|
});
|
||||||
|
|
||||||
/** @type {any} */
|
const data: { [k: string]: any } = {
|
||||||
const data = {
|
|
||||||
social_login: "1",
|
social_login: "1",
|
||||||
verification_status: supEmail ? "0" : "1",
|
verification_status: supEmail ? "0" : "1",
|
||||||
password: socialHashedPassword,
|
password: socialHashedPassword,
|
||||||
@ -173,7 +174,7 @@ module.exports = async function handleSocialDb({
|
|||||||
)
|
)
|
||||||
.replace(/{{host}}/, process.env.DSQL_HOST || "")
|
.replace(/{{host}}/, process.env.DSQL_HOST || "")
|
||||||
.replace(/{{token}}/, generatedToken || ""),
|
.replace(/{{token}}/, generatedToken || ""),
|
||||||
}).then((mail) => {});
|
}).then(() => {});
|
||||||
}
|
}
|
||||||
|
|
||||||
const STATIC_ROOT = process.env.DSQL_STATIC_SERVER_DIR;
|
const STATIC_ROOT = process.env.DSQL_STATIC_SERVER_DIR;
|
||||||
@ -230,7 +231,7 @@ module.exports = async function handleSocialDb({
|
|||||||
msg: "Social User Failed to insert in 'handleSocialDb.js' backend function",
|
msg: "Social User Failed to insert in 'handleSocialDb.js' backend function",
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
} catch (/** @type {any} */ error) {
|
} catch (error: any) {
|
||||||
console.log(
|
console.log(
|
||||||
"ERROR in 'handleSocialDb.js' backend function =>",
|
"ERROR in 'handleSocialDb.js' backend function =>",
|
||||||
error.message
|
error.message
|
||||||
@ -242,4 +243,4 @@ module.exports = async function handleSocialDb({
|
|||||||
msg: error.message,
|
msg: error.message,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
};
|
}
|
@ -1,37 +0,0 @@
|
|||||||
export = loginSocialUser;
|
|
||||||
/**
|
|
||||||
* Function to login social user
|
|
||||||
* ==============================================================================
|
|
||||||
* @description This function logs in the user after 'handleSocialDb' function finishes
|
|
||||||
* the user creation or confirmation process
|
|
||||||
*
|
|
||||||
* @async
|
|
||||||
*
|
|
||||||
* @param {object} params - function parameters inside an object
|
|
||||||
* @param {{
|
|
||||||
* first_name: string,
|
|
||||||
* last_name: string,
|
|
||||||
* email: string,
|
|
||||||
* social_id: string|number,
|
|
||||||
* }} params.user - user object
|
|
||||||
* @param {string} params.social_platform - Whether its "google" or "facebook" or "github"
|
|
||||||
* @param {any} [params.invitation] - A query object if user was invited
|
|
||||||
* @param {string} [params.database] - Target Database
|
|
||||||
* @param {string[]} [params.additionalFields] - Additional fields to be added to the user payload
|
|
||||||
* @param {boolean} [params.useLocal]
|
|
||||||
*
|
|
||||||
* @returns {Promise<import("../../../types").APILoginFunctionReturn>}
|
|
||||||
*/
|
|
||||||
declare function loginSocialUser({ user, social_platform, invitation, database, additionalFields, useLocal, }: {
|
|
||||||
user: {
|
|
||||||
first_name: string;
|
|
||||||
last_name: string;
|
|
||||||
email: string;
|
|
||||||
social_id: string | number;
|
|
||||||
};
|
|
||||||
social_platform: string;
|
|
||||||
invitation?: any;
|
|
||||||
database?: string;
|
|
||||||
additionalFields?: string[];
|
|
||||||
useLocal?: boolean;
|
|
||||||
}): Promise<import("../../../types").APILoginFunctionReturn>;
|
|
@ -1,42 +1,35 @@
|
|||||||
// @ts-check
|
import addAdminUserOnLogin from "../../backend/addAdminUserOnLogin";
|
||||||
|
import varDatabaseDbHandler from "../../backend/varDatabaseDbHandler";
|
||||||
|
import { APILoginFunctionReturn } from "../../../types";
|
||||||
|
|
||||||
const addAdminUserOnLogin = require("../../backend/addAdminUserOnLogin");
|
type Param = {
|
||||||
const { ServerResponse } = require("http");
|
user: {
|
||||||
const varDatabaseDbHandler = require("../../backend/varDatabaseDbHandler");
|
first_name: string;
|
||||||
const encrypt = require("../../dsql/encrypt");
|
last_name: string;
|
||||||
const getAuthCookieNames = require("../../backend/cookies/get-auth-cookie-names");
|
email: string;
|
||||||
|
social_id: string | number;
|
||||||
|
};
|
||||||
|
social_platform: string;
|
||||||
|
invitation?: any;
|
||||||
|
database?: string;
|
||||||
|
additionalFields?: string[];
|
||||||
|
useLocal?: boolean;
|
||||||
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Function to login social user
|
* Function to login social user
|
||||||
* ==============================================================================
|
* ==============================================================================
|
||||||
* @description This function logs in the user after 'handleSocialDb' function finishes
|
* @description This function logs in the user after 'handleSocialDb' function finishes
|
||||||
* the user creation or confirmation process
|
* the user creation or confirmation process
|
||||||
*
|
|
||||||
* @async
|
|
||||||
*
|
|
||||||
* @param {object} params - function parameters inside an object
|
|
||||||
* @param {{
|
|
||||||
* first_name: string,
|
|
||||||
* last_name: string,
|
|
||||||
* email: string,
|
|
||||||
* social_id: string|number,
|
|
||||||
* }} params.user - user object
|
|
||||||
* @param {string} params.social_platform - Whether its "google" or "facebook" or "github"
|
|
||||||
* @param {any} [params.invitation] - A query object if user was invited
|
|
||||||
* @param {string} [params.database] - Target Database
|
|
||||||
* @param {string[]} [params.additionalFields] - Additional fields to be added to the user payload
|
|
||||||
* @param {boolean} [params.useLocal]
|
|
||||||
*
|
|
||||||
* @returns {Promise<import("../../../types").APILoginFunctionReturn>}
|
|
||||||
*/
|
*/
|
||||||
async function loginSocialUser({
|
export default async function loginSocialUser({
|
||||||
user,
|
user,
|
||||||
social_platform,
|
social_platform,
|
||||||
invitation,
|
invitation,
|
||||||
database,
|
database,
|
||||||
additionalFields,
|
additionalFields,
|
||||||
useLocal,
|
useLocal,
|
||||||
}) {
|
}: Param): Promise<APILoginFunctionReturn> {
|
||||||
const foundUserQuery = `SELECT * FROM users WHERE email=? AND social_id=? AND social_platform=?`;
|
const foundUserQuery = `SELECT * FROM users WHERE email=? AND social_id=? AND social_platform=?`;
|
||||||
const foundUserValues = [user.email, user.social_id, social_platform];
|
const foundUserValues = [user.email, user.social_id, social_platform];
|
||||||
|
|
||||||
@ -59,7 +52,7 @@ async function loginSocialUser({
|
|||||||
Math.random().toString(36).substring(2);
|
Math.random().toString(36).substring(2);
|
||||||
|
|
||||||
/** @type {import("../../../types").DATASQUIREL_LoggedInUser} */
|
/** @type {import("../../../types").DATASQUIREL_LoggedInUser} */
|
||||||
let userPayload = {
|
let userPayload: import("../../../types").DATASQUIREL_LoggedInUser = {
|
||||||
id: foundUser[0].id,
|
id: foundUser[0].id,
|
||||||
first_name: foundUser[0].first_name,
|
first_name: foundUser[0].first_name,
|
||||||
last_name: foundUser[0].last_name,
|
last_name: foundUser[0].last_name,
|
||||||
@ -92,7 +85,7 @@ async function loginSocialUser({
|
|||||||
}
|
}
|
||||||
|
|
||||||
/** @type {import("../../../types").APILoginFunctionReturn} */
|
/** @type {import("../../../types").APILoginFunctionReturn} */
|
||||||
let result = {
|
let result: import("../../../types").APILoginFunctionReturn = {
|
||||||
success: true,
|
success: true,
|
||||||
payload: userPayload,
|
payload: userPayload,
|
||||||
csrf: csrfKey,
|
csrf: csrfKey,
|
||||||
@ -100,5 +93,3 @@ async function loginSocialUser({
|
|||||||
|
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports = loginSocialUser;
|
|
@ -1,2 +0,0 @@
|
|||||||
declare const _exports: import("../../../types").APICreateUserFunction;
|
|
||||||
export = _exports;
|
|
@ -1,19 +1,22 @@
|
|||||||
// @ts-check
|
// @ts-check
|
||||||
|
|
||||||
const addUsersTableToDb = require("../../backend/addUsersTableToDb");
|
import { APICreateUserFunctionParams } from "../../../types";
|
||||||
const addDbEntry = require("../../backend/db/addDbEntry");
|
import addUsersTableToDb from "../../backend/addUsersTableToDb";
|
||||||
const updateUsersTableSchema = require("../../backend/updateUsersTableSchema");
|
import addDbEntry from "../../backend/db/addDbEntry";
|
||||||
const varDatabaseDbHandler = require("../../backend/varDatabaseDbHandler");
|
import updateUsersTableSchema from "../../backend/updateUsersTableSchema";
|
||||||
const hashPassword = require("../../dsql/hashPassword");
|
import varDatabaseDbHandler from "../../backend/varDatabaseDbHandler";
|
||||||
|
import hashPassword from "../../dsql/hashPassword";
|
||||||
|
|
||||||
/** @type {import("../../../types").APICreateUserFunction} */
|
/**
|
||||||
module.exports = async function apiCreateUser({
|
* # API Create User
|
||||||
|
*/
|
||||||
|
export default async function apiCreateUser({
|
||||||
encryptionKey,
|
encryptionKey,
|
||||||
payload,
|
payload,
|
||||||
database,
|
database,
|
||||||
userId,
|
userId,
|
||||||
useLocal,
|
useLocal,
|
||||||
}) {
|
}: APICreateUserFunctionParams) {
|
||||||
const dbFullName = database;
|
const dbFullName = database;
|
||||||
const API_USER_ID = userId || process.env.DSQL_API_USER_ID;
|
const API_USER_ID = userId || process.env.DSQL_API_USER_ID;
|
||||||
|
|
||||||
@ -73,9 +76,7 @@ module.exports = async function apiCreateUser({
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
const fieldsTitles = fields.map(
|
const fieldsTitles = fields.map((fieldObject: any) => fieldObject.Field);
|
||||||
(/** @type {any} */ fieldObject) => fieldObject.Field
|
|
||||||
);
|
|
||||||
|
|
||||||
let invalidField = null;
|
let invalidField = null;
|
||||||
|
|
||||||
@ -159,4 +160,4 @@ module.exports = async function apiCreateUser({
|
|||||||
payload: null,
|
payload: null,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
};
|
}
|
@ -1,10 +0,0 @@
|
|||||||
declare function _exports({ dbFullName, deletedUserId, useLocal, }: {
|
|
||||||
dbFullName: string;
|
|
||||||
deletedUserId: string | number;
|
|
||||||
useLocal?: boolean;
|
|
||||||
}): Promise<{
|
|
||||||
success: boolean;
|
|
||||||
result?: any;
|
|
||||||
msg?: string;
|
|
||||||
}>;
|
|
||||||
export = _exports;
|
|
@ -1,23 +1,21 @@
|
|||||||
// @ts-check
|
import deleteDbEntry from "../../backend/db/deleteDbEntry";
|
||||||
|
import varDatabaseDbHandler from "../../backend/varDatabaseDbHandler";
|
||||||
|
|
||||||
const deleteDbEntry = require("../../backend/db/deleteDbEntry");
|
type Param = {
|
||||||
const varDatabaseDbHandler = require("../../backend/varDatabaseDbHandler");
|
dbFullName: string;
|
||||||
|
deletedUserId: string | number;
|
||||||
|
useLocal?: boolean;
|
||||||
|
};
|
||||||
|
type Return = { success: boolean; result?: any; msg?: string };
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* # Update API User Function
|
* # Update API User Function
|
||||||
*
|
|
||||||
* @param {object} params
|
|
||||||
* @param {string} params.dbFullName
|
|
||||||
* @param {string | number} params.deletedUserId
|
|
||||||
* @param {boolean} [params.useLocal]
|
|
||||||
*
|
|
||||||
* @returns {Promise<{ success: boolean, result?: any, msg?: string }>}
|
|
||||||
*/
|
*/
|
||||||
module.exports = async function apiDeleteUser({
|
export default async function apiDeleteUser({
|
||||||
dbFullName,
|
dbFullName,
|
||||||
deletedUserId,
|
deletedUserId,
|
||||||
useLocal,
|
useLocal,
|
||||||
}) {
|
}: Param): Promise<Return> {
|
||||||
const existingUserQuery = `SELECT * FROM users WHERE id = ?`;
|
const existingUserQuery = `SELECT * FROM users WHERE id = ?`;
|
||||||
const existingUserValues = [deletedUserId];
|
const existingUserValues = [deletedUserId];
|
||||||
|
|
||||||
@ -49,4 +47,4 @@ module.exports = async function apiDeleteUser({
|
|||||||
success: true,
|
success: true,
|
||||||
result: deleteUser,
|
result: deleteUser,
|
||||||
};
|
};
|
||||||
};
|
}
|
@ -1,2 +0,0 @@
|
|||||||
declare const _exports: import("../../../types").APIGetUserFunction;
|
|
||||||
export = _exports;
|
|
@ -1,14 +1,18 @@
|
|||||||
// @ts-check
|
import {
|
||||||
|
APIGetUserFunctionParams,
|
||||||
|
GetUserFunctionReturn,
|
||||||
|
} from "../../../types";
|
||||||
|
import varDatabaseDbHandler from "../../backend/varDatabaseDbHandler";
|
||||||
|
|
||||||
const varDatabaseDbHandler = require("../../backend/varDatabaseDbHandler");
|
/**
|
||||||
|
* # API Get User
|
||||||
/** @type {import("../../../types").APIGetUserFunction} */
|
*/
|
||||||
module.exports = async function apiGetUser({
|
export default async function apiGetUser({
|
||||||
fields,
|
fields,
|
||||||
dbFullName,
|
dbFullName,
|
||||||
userId,
|
userId,
|
||||||
useLocal,
|
useLocal,
|
||||||
}) {
|
}: APIGetUserFunctionParams): Promise<GetUserFunctionReturn> {
|
||||||
const query = `SELECT ${fields.join(",")} FROM users WHERE id=?`;
|
const query = `SELECT ${fields.join(",")} FROM users WHERE id=?`;
|
||||||
const API_USER_ID = userId || process.env.DSQL_API_USER_ID;
|
const API_USER_ID = userId || process.env.DSQL_API_USER_ID;
|
||||||
|
|
||||||
@ -30,4 +34,4 @@ module.exports = async function apiGetUser({
|
|||||||
success: true,
|
success: true,
|
||||||
payload: foundUser[0],
|
payload: foundUser[0],
|
||||||
};
|
};
|
||||||
};
|
}
|
@ -1,2 +0,0 @@
|
|||||||
declare const _exports: import("../../../types").APILoginFunction;
|
|
||||||
export = _exports;
|
|
@ -1,10 +1,15 @@
|
|||||||
// @ts-check
|
import {
|
||||||
|
APILoginFunctionParams,
|
||||||
|
APILoginFunctionReturn,
|
||||||
|
DATASQUIREL_LoggedInUser,
|
||||||
|
} from "../../../types";
|
||||||
|
import varDatabaseDbHandler from "../../backend/varDatabaseDbHandler";
|
||||||
|
import hashPassword from "../../dsql/hashPassword";
|
||||||
|
|
||||||
const varDatabaseDbHandler = require("../../backend/varDatabaseDbHandler");
|
/**
|
||||||
const hashPassword = require("../../dsql/hashPassword");
|
* # API Login
|
||||||
|
*/
|
||||||
/** @type {import("../../../types").APILoginFunction} */
|
export default async function apiLoginUser({
|
||||||
module.exports = async function apiLoginUser({
|
|
||||||
encryptionKey,
|
encryptionKey,
|
||||||
email,
|
email,
|
||||||
username,
|
username,
|
||||||
@ -18,7 +23,7 @@ module.exports = async function apiLoginUser({
|
|||||||
skipPassword,
|
skipPassword,
|
||||||
social,
|
social,
|
||||||
useLocal,
|
useLocal,
|
||||||
}) {
|
}: APILoginFunctionParams): Promise<APILoginFunctionReturn> {
|
||||||
const dbFullName = database;
|
const dbFullName = database;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -115,8 +120,7 @@ module.exports = async function apiLoginUser({
|
|||||||
"-" +
|
"-" +
|
||||||
Math.random().toString(36).substring(2);
|
Math.random().toString(36).substring(2);
|
||||||
|
|
||||||
/** @type {import("../../../types").DATASQUIREL_LoggedInUser} */
|
let userPayload: DATASQUIREL_LoggedInUser = {
|
||||||
let userPayload = {
|
|
||||||
id: foundUser[0].id,
|
id: foundUser[0].id,
|
||||||
first_name: foundUser[0].first_name,
|
first_name: foundUser[0].first_name,
|
||||||
last_name: foundUser[0].last_name,
|
last_name: foundUser[0].last_name,
|
||||||
@ -135,14 +139,10 @@ module.exports = async function apiLoginUser({
|
|||||||
date: Date.now(),
|
date: Date.now(),
|
||||||
};
|
};
|
||||||
|
|
||||||
/** @type {import("../../../types").APILoginFunctionReturn} */
|
const resposeObject: APILoginFunctionReturn = {
|
||||||
const resposeObject = {
|
|
||||||
success: true,
|
success: true,
|
||||||
msg: "Login Successful",
|
msg: "Login Successful",
|
||||||
payload:
|
payload: userPayload,
|
||||||
/** @type {import("../../../types").DATASQUIREL_LoggedInUser} */ (
|
|
||||||
userPayload
|
|
||||||
),
|
|
||||||
userId: foundUser[0].id,
|
userId: foundUser[0].id,
|
||||||
csrf: csrfKey,
|
csrf: csrfKey,
|
||||||
};
|
};
|
||||||
@ -158,4 +158,4 @@ module.exports = async function apiLoginUser({
|
|||||||
}
|
}
|
||||||
|
|
||||||
return resposeObject;
|
return resposeObject;
|
||||||
};
|
}
|
@ -1,9 +0,0 @@
|
|||||||
declare function _exports({ existingUser, database, additionalFields, useLocal, }: {
|
|
||||||
existingUser: {
|
|
||||||
[x: string]: any;
|
|
||||||
};
|
|
||||||
database?: string;
|
|
||||||
additionalFields?: string[];
|
|
||||||
useLocal?: boolean;
|
|
||||||
}): Promise<import("../../../types").APILoginFunctionReturn>;
|
|
||||||
export = _exports;
|
|
@ -1,25 +1,22 @@
|
|||||||
// @ts-check
|
import { APILoginFunctionReturn } from "../../../types";
|
||||||
|
import varDatabaseDbHandler from "../../backend/varDatabaseDbHandler";
|
||||||
|
|
||||||
const LOCAL_DB_HANDLER = require("../../../utils/backend/global-db/LOCAL_DB_HANDLER");
|
type Param = {
|
||||||
const varDatabaseDbHandler = require("../../backend/varDatabaseDbHandler");
|
existingUser: { [s: string]: any };
|
||||||
const nodemailer = require("nodemailer");
|
database?: string;
|
||||||
|
additionalFields?: string[];
|
||||||
|
useLocal?: boolean;
|
||||||
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* # Re-authenticate API user
|
* # Re-authenticate API user
|
||||||
* @param {object} param
|
|
||||||
* @param {Object<string, any>} param.existingUser
|
|
||||||
* @param {string} [param.database]
|
|
||||||
* @param {string[]} [param.additionalFields]
|
|
||||||
* @param {boolean} [param.useLocal]
|
|
||||||
*
|
|
||||||
* @returns {Promise<import("../../../types").APILoginFunctionReturn>}
|
|
||||||
*/
|
*/
|
||||||
module.exports = async function apiReauthUser({
|
export default async function apiReauthUser({
|
||||||
existingUser,
|
existingUser,
|
||||||
database,
|
database,
|
||||||
additionalFields,
|
additionalFields,
|
||||||
useLocal,
|
useLocal,
|
||||||
}) {
|
}: Param): Promise<APILoginFunctionReturn> {
|
||||||
let foundUser =
|
let foundUser =
|
||||||
existingUser?.id && existingUser.id.toString().match(/./)
|
existingUser?.id && existingUser.id.toString().match(/./)
|
||||||
? await varDatabaseDbHandler({
|
? await varDatabaseDbHandler({
|
||||||
@ -30,10 +27,6 @@ module.exports = async function apiReauthUser({
|
|||||||
})
|
})
|
||||||
: null;
|
: null;
|
||||||
|
|
||||||
////////////////////////////////////////
|
|
||||||
////////////////////////////////////////
|
|
||||||
////////////////////////////////////////
|
|
||||||
|
|
||||||
if (!foundUser || !foundUser[0])
|
if (!foundUser || !foundUser[0])
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
@ -41,17 +34,13 @@ module.exports = async function apiReauthUser({
|
|||||||
msg: "No user found",
|
msg: "No user found",
|
||||||
};
|
};
|
||||||
|
|
||||||
////////////////////////////////////////
|
|
||||||
////////////////////////////////////////
|
|
||||||
////////////////////////////////////////
|
|
||||||
|
|
||||||
let csrfKey =
|
let csrfKey =
|
||||||
Math.random().toString(36).substring(2) +
|
Math.random().toString(36).substring(2) +
|
||||||
"-" +
|
"-" +
|
||||||
Math.random().toString(36).substring(2);
|
Math.random().toString(36).substring(2);
|
||||||
|
|
||||||
/** @type {import("../../../types").DATASQUIREL_LoggedInUser} */
|
/** @type {import("../../../types").DATASQUIREL_LoggedInUser} */
|
||||||
let userPayload = {
|
let userPayload: import("../../../types").DATASQUIREL_LoggedInUser = {
|
||||||
id: foundUser[0].id,
|
id: foundUser[0].id,
|
||||||
first_name: foundUser[0].first_name,
|
first_name: foundUser[0].first_name,
|
||||||
last_name: foundUser[0].last_name,
|
last_name: foundUser[0].last_name,
|
||||||
@ -80,15 +69,10 @@ module.exports = async function apiReauthUser({
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
////////////////////////////////////////
|
|
||||||
////////////////////////////////////////
|
|
||||||
////////////////////////////////////////
|
|
||||||
|
|
||||||
/** ********************* Send Response */
|
|
||||||
return {
|
return {
|
||||||
success: true,
|
success: true,
|
||||||
msg: "Login Successful",
|
msg: "Login Successful",
|
||||||
payload: userPayload,
|
payload: userPayload,
|
||||||
csrf: csrfKey,
|
csrf: csrfKey,
|
||||||
};
|
};
|
||||||
};
|
}
|
@ -1,18 +0,0 @@
|
|||||||
declare function _exports({ email, database, email_login_field, mail_domain, mail_port, sender, mail_username, mail_password, html, useLocal, response, extraCookies, }: {
|
|
||||||
email: string;
|
|
||||||
database: string;
|
|
||||||
email_login_field?: string;
|
|
||||||
mail_domain?: string;
|
|
||||||
mail_port?: number;
|
|
||||||
sender?: string;
|
|
||||||
mail_username?: string;
|
|
||||||
mail_password?: string;
|
|
||||||
html: string;
|
|
||||||
useLocal?: boolean;
|
|
||||||
response?: http.ServerResponse & {
|
|
||||||
[x: string]: any;
|
|
||||||
};
|
|
||||||
extraCookies?: import("../../../../package-shared/types").CookieObject[];
|
|
||||||
}): Promise<import("../../../types").SendOneTimeCodeEmailResponse>;
|
|
||||||
export = _exports;
|
|
||||||
import http = require("http");
|
|
@ -1,32 +1,30 @@
|
|||||||
// @ts-check
|
import varDatabaseDbHandler from "../../backend/varDatabaseDbHandler";
|
||||||
|
import nodemailer, { SendMailOptions } from "nodemailer";
|
||||||
|
import http from "http";
|
||||||
|
import getAuthCookieNames from "../../backend/cookies/get-auth-cookie-names";
|
||||||
|
import encrypt from "../../dsql/encrypt";
|
||||||
|
import serializeCookies from "../../../utils/serialize-cookies";
|
||||||
|
import { SendOneTimeCodeEmailResponse } from "../../../types";
|
||||||
|
|
||||||
const varDatabaseDbHandler = require("../../backend/varDatabaseDbHandler");
|
type Param = {
|
||||||
const nodemailer = require("nodemailer");
|
email: string;
|
||||||
const http = require("http");
|
database: string;
|
||||||
const getAuthCookieNames = require("../../backend/cookies/get-auth-cookie-names");
|
email_login_field?: string;
|
||||||
const encrypt = require("../../dsql/encrypt");
|
mail_domain?: string;
|
||||||
const serializeCookies = require("../../../utils/serialize-cookies");
|
mail_port?: number;
|
||||||
|
sender?: string;
|
||||||
|
mail_username?: string;
|
||||||
|
mail_password?: string;
|
||||||
|
html: string;
|
||||||
|
useLocal?: boolean;
|
||||||
|
response?: http.ServerResponse & { [s: string]: any };
|
||||||
|
extraCookies?: import("../../../../package-shared/types").CookieObject[];
|
||||||
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* # Send Email Login Code
|
* # Send Email Login Code
|
||||||
*
|
|
||||||
* @param {object} param
|
|
||||||
* @param {string} param.email
|
|
||||||
* @param {string} param.database
|
|
||||||
* @param {string} [param.email_login_field]
|
|
||||||
* @param {string} [param.mail_domain]
|
|
||||||
* @param {number} [param.mail_port]
|
|
||||||
* @param {string} [param.sender]
|
|
||||||
* @param {string} [param.mail_username]
|
|
||||||
* @param {string} [param.mail_password]
|
|
||||||
* @param {string} param.html
|
|
||||||
* @param {boolean} [param.useLocal]
|
|
||||||
* @param {http.ServerResponse & Object<string,any>} [param.response]
|
|
||||||
* @param {import("../../../../package-shared/types").CookieObject[]} [param.extraCookies]
|
|
||||||
*
|
|
||||||
* @returns {Promise<import("../../../types").SendOneTimeCodeEmailResponse>}
|
|
||||||
*/
|
*/
|
||||||
module.exports = async function apiSendEmailCode({
|
export default async function apiSendEmailCode({
|
||||||
email,
|
email,
|
||||||
database,
|
database,
|
||||||
email_login_field,
|
email_login_field,
|
||||||
@ -39,7 +37,7 @@ module.exports = async function apiSendEmailCode({
|
|||||||
useLocal,
|
useLocal,
|
||||||
response,
|
response,
|
||||||
extraCookies,
|
extraCookies,
|
||||||
}) {
|
}: Param): Promise<SendOneTimeCodeEmailResponse> {
|
||||||
if (email?.match(/ /)) {
|
if (email?.match(/ /)) {
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
@ -83,7 +81,11 @@ module.exports = async function apiSendEmailCode({
|
|||||||
|
|
||||||
let transporter = nodemailer.createTransport({
|
let transporter = nodemailer.createTransport({
|
||||||
host: mail_domain || process.env.DSQL_MAIL_HOST,
|
host: mail_domain || process.env.DSQL_MAIL_HOST,
|
||||||
port: mail_port || process.env.DSQL_MAIL_PORT || 465,
|
port: mail_port
|
||||||
|
? mail_port
|
||||||
|
: process.env.DSQL_MAIL_PORT
|
||||||
|
? Number(process.env.DSQL_MAIL_PORT)
|
||||||
|
: 465,
|
||||||
secure: true,
|
secure: true,
|
||||||
auth: {
|
auth: {
|
||||||
user: mail_username || process.env.DSQL_MAIL_EMAIL,
|
user: mail_username || process.env.DSQL_MAIL_EMAIL,
|
||||||
@ -91,7 +93,7 @@ module.exports = async function apiSendEmailCode({
|
|||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
let mailObject = {};
|
let mailObject: SendMailOptions = {};
|
||||||
|
|
||||||
mailObject["from"] = `"Datasquirel SSO" <${
|
mailObject["from"] = `"Datasquirel SSO" <${
|
||||||
sender || "support@datasquirel.com"
|
sender || "support@datasquirel.com"
|
||||||
@ -116,7 +118,8 @@ module.exports = async function apiSendEmailCode({
|
|||||||
});
|
});
|
||||||
|
|
||||||
/** @type {import("../../../types").SendOneTimeCodeEmailResponse} */
|
/** @type {import("../../../types").SendOneTimeCodeEmailResponse} */
|
||||||
const resObject = {
|
const resObject: import("../../../types").SendOneTimeCodeEmailResponse =
|
||||||
|
{
|
||||||
success: true,
|
success: true,
|
||||||
code: tempCode,
|
code: tempCode,
|
||||||
email: email,
|
email: email,
|
||||||
@ -139,7 +142,8 @@ module.exports = async function apiSendEmailCode({
|
|||||||
}
|
}
|
||||||
|
|
||||||
/** @type {import("../../../../package-shared/types").CookieObject} */
|
/** @type {import("../../../../package-shared/types").CookieObject} */
|
||||||
const oneTimeCookieObject = {
|
const oneTimeCookieObject: import("../../../../package-shared/types").CookieObject =
|
||||||
|
{
|
||||||
name: oneTimeCodeCookieName,
|
name: oneTimeCodeCookieName,
|
||||||
value: encryptedPayload,
|
value: encryptedPayload,
|
||||||
sameSite: "Strict",
|
sameSite: "Strict",
|
||||||
@ -149,7 +153,8 @@ module.exports = async function apiSendEmailCode({
|
|||||||
};
|
};
|
||||||
|
|
||||||
/** @type {import("../../../../package-shared/types").CookieObject[]} */
|
/** @type {import("../../../../package-shared/types").CookieObject[]} */
|
||||||
const cookiesObjectArray = extraCookies
|
const cookiesObjectArray: import("../../../../package-shared/types").CookieObject[] =
|
||||||
|
extraCookies
|
||||||
? [...extraCookies, oneTimeCookieObject]
|
? [...extraCookies, oneTimeCookieObject]
|
||||||
: [oneTimeCookieObject];
|
: [oneTimeCookieObject];
|
||||||
|
|
||||||
@ -167,4 +172,4 @@ module.exports = async function apiSendEmailCode({
|
|||||||
msg: "Invalid Email/Password format",
|
msg: "Invalid Email/Password format",
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
};
|
}
|
@ -1,14 +0,0 @@
|
|||||||
declare function _exports({ payload, dbFullName, updatedUserId, useLocal, dbSchema, }: {
|
|
||||||
payload: {
|
|
||||||
[x: string]: any;
|
|
||||||
};
|
|
||||||
dbFullName: string;
|
|
||||||
updatedUserId: string | number;
|
|
||||||
useLocal?: boolean;
|
|
||||||
dbSchema?: import("../../../types").DSQL_DatabaseSchemaType;
|
|
||||||
}): Promise<{
|
|
||||||
success: boolean;
|
|
||||||
payload?: any;
|
|
||||||
msg?: string;
|
|
||||||
}>;
|
|
||||||
export = _exports;
|
|
@ -1,29 +1,30 @@
|
|||||||
// @ts-check
|
// @ts-check
|
||||||
|
|
||||||
const updateDbEntry = require("../../backend/db/updateDbEntry");
|
import updateDbEntry from "../../backend/db/updateDbEntry";
|
||||||
const encrypt = require("../../dsql/encrypt");
|
import encrypt from "../../dsql/encrypt";
|
||||||
const hashPassword = require("../../dsql/hashPassword");
|
import hashPassword from "../../dsql/hashPassword";
|
||||||
const varDatabaseDbHandler = require("../../backend/varDatabaseDbHandler");
|
import varDatabaseDbHandler from "../../backend/varDatabaseDbHandler";
|
||||||
|
|
||||||
|
type Param = {
|
||||||
|
payload: { [s: string]: any };
|
||||||
|
dbFullName: string;
|
||||||
|
updatedUserId: string | number;
|
||||||
|
useLocal?: boolean;
|
||||||
|
dbSchema?: import("../../../types").DSQL_DatabaseSchemaType;
|
||||||
|
};
|
||||||
|
|
||||||
|
type Return = { success: boolean; payload?: any; msg?: string };
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* # Update API User Function
|
* # Update API User Function
|
||||||
*
|
|
||||||
* @param {object} params
|
|
||||||
* @param {Object<string, any>} params.payload
|
|
||||||
* @param {string} params.dbFullName
|
|
||||||
* @param {string | number} params.updatedUserId
|
|
||||||
* @param {boolean} [params.useLocal]
|
|
||||||
* @param {import("../../../types").DSQL_DatabaseSchemaType} [params.dbSchema]
|
|
||||||
*
|
|
||||||
* @returns {Promise<{ success: boolean, payload?: any, msg?: string }>}
|
|
||||||
*/
|
*/
|
||||||
module.exports = async function apiUpdateUser({
|
export default async function apiUpdateUser({
|
||||||
payload,
|
payload,
|
||||||
dbFullName,
|
dbFullName,
|
||||||
updatedUserId,
|
updatedUserId,
|
||||||
useLocal,
|
useLocal,
|
||||||
dbSchema,
|
dbSchema,
|
||||||
}) {
|
}: Param): Promise<Return> {
|
||||||
const existingUserQuery = `SELECT * FROM users WHERE id = ?`;
|
const existingUserQuery = `SELECT * FROM users WHERE id = ?`;
|
||||||
const existingUserValues = [updatedUserId];
|
const existingUserValues = [updatedUserId];
|
||||||
|
|
||||||
@ -56,7 +57,7 @@ module.exports = async function apiUpdateUser({
|
|||||||
})();
|
})();
|
||||||
|
|
||||||
/** @type {any} */
|
/** @type {any} */
|
||||||
const finalData = {};
|
const finalData: any = {};
|
||||||
|
|
||||||
reqBodyKeys.forEach((key) => {
|
reqBodyKeys.forEach((key) => {
|
||||||
const targetFieldSchema = targetTableSchema?.fields?.find(
|
const targetFieldSchema = targetTableSchema?.fields?.find(
|
||||||
@ -95,4 +96,4 @@ module.exports = async function apiUpdateUser({
|
|||||||
success: true,
|
success: true,
|
||||||
payload: updateUser,
|
payload: updateUser,
|
||||||
};
|
};
|
||||||
};
|
}
|
@ -1,12 +0,0 @@
|
|||||||
declare function _exports({ code, clientId, clientSecret, database, additionalFields, email, additionalData, }: {
|
|
||||||
code?: string;
|
|
||||||
clientId?: string;
|
|
||||||
clientSecret?: string;
|
|
||||||
database?: string;
|
|
||||||
additionalFields?: string[];
|
|
||||||
additionalData?: {
|
|
||||||
[x: string]: string | number;
|
|
||||||
};
|
|
||||||
email?: string;
|
|
||||||
}): Promise<import("../../../../types").APILoginFunctionReturn>;
|
|
||||||
export = _exports;
|
|
@ -1,23 +1,22 @@
|
|||||||
// @ts-check
|
import handleSocialDb from "../../social-login/handleSocialDb";
|
||||||
|
import githubLogin from "../../social-login/githubLogin";
|
||||||
|
import camelJoinedtoCamelSpace from "../../../../utils/camelJoinedtoCamelSpace";
|
||||||
|
import { APILoginFunctionReturn } from "../../../../types";
|
||||||
|
|
||||||
const handleSocialDb = require("../../social-login/handleSocialDb");
|
type Param = {
|
||||||
const githubLogin = require("../../social-login/githubLogin");
|
code?: string;
|
||||||
const camelJoinedtoCamelSpace = require("../../../../utils/camelJoinedtoCamelSpace");
|
clientId?: string;
|
||||||
|
clientSecret?: string;
|
||||||
|
database?: string;
|
||||||
|
additionalFields?: string[];
|
||||||
|
additionalData?: { [s: string]: string | number };
|
||||||
|
email?: string;
|
||||||
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* # Login with Github
|
* # API Login with Github
|
||||||
* @param {object} param
|
|
||||||
* @param {string} [param.code]
|
|
||||||
* @param {string} [param.clientId]
|
|
||||||
* @param {string} [param.clientSecret]
|
|
||||||
* @param {string} [param.database]
|
|
||||||
* @param {string[]} [param.additionalFields]
|
|
||||||
* @param {Object<string,string|number>} [param.additionalData]
|
|
||||||
* @param {string} [param.email]
|
|
||||||
*
|
|
||||||
* @returns {Promise<import("../../../../types").APILoginFunctionReturn>}
|
|
||||||
*/
|
*/
|
||||||
module.exports = async function apiGithubLogin({
|
export default async function apiGithubLogin({
|
||||||
code,
|
code,
|
||||||
clientId,
|
clientId,
|
||||||
clientSecret,
|
clientSecret,
|
||||||
@ -25,7 +24,7 @@ module.exports = async function apiGithubLogin({
|
|||||||
additionalFields,
|
additionalFields,
|
||||||
email,
|
email,
|
||||||
additionalData,
|
additionalData,
|
||||||
}) {
|
}: Param): Promise<APILoginFunctionReturn> {
|
||||||
if (!code || !clientId || !clientSecret || !database) {
|
if (!code || !clientId || !clientSecret || !database) {
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
@ -101,4 +100,4 @@ module.exports = async function apiGithubLogin({
|
|||||||
////////////////////////////////////////////////
|
////////////////////////////////////////////////
|
||||||
|
|
||||||
return { ...loggedInGithubUser };
|
return { ...loggedInGithubUser };
|
||||||
};
|
}
|
@ -1,2 +0,0 @@
|
|||||||
declare const _exports: import("../../../../types").APIGoogleLoginFunction;
|
|
||||||
export = _exports;
|
|
@ -1,19 +1,24 @@
|
|||||||
// @ts-check
|
import https from "https";
|
||||||
|
import handleSocialDb from "../../social-login/handleSocialDb";
|
||||||
|
import EJSON from "../../../../utils/ejson";
|
||||||
|
import {
|
||||||
|
APIGoogleLoginFunctionParams,
|
||||||
|
APILoginFunctionReturn,
|
||||||
|
GoogleOauth2User,
|
||||||
|
} from "../../../../types";
|
||||||
|
|
||||||
const https = require("https");
|
/**
|
||||||
const handleSocialDb = require("../../social-login/handleSocialDb");
|
* # API google login
|
||||||
const EJSON = require("../../../../utils/ejson");
|
*/
|
||||||
|
export default async function apiGoogleLogin({
|
||||||
/** @type {import("../../../../types").APIGoogleLoginFunction} */
|
|
||||||
module.exports = async function apiGoogleLogin({
|
|
||||||
token,
|
token,
|
||||||
database,
|
database,
|
||||||
additionalFields,
|
additionalFields,
|
||||||
additionalData,
|
additionalData,
|
||||||
}) {
|
}: APIGoogleLoginFunctionParams): Promise<APILoginFunctionReturn> {
|
||||||
try {
|
try {
|
||||||
/** @type {import("../../../../types").GoogleOauth2User | undefined} */
|
const gUser: GoogleOauth2User | undefined = await new Promise(
|
||||||
const gUser = await new Promise((resolve, reject) => {
|
(resolve, reject) => {
|
||||||
https
|
https
|
||||||
.request(
|
.request(
|
||||||
{
|
{
|
||||||
@ -30,12 +35,13 @@ module.exports = async function apiGoogleLogin({
|
|||||||
data += chunk;
|
data += chunk;
|
||||||
});
|
});
|
||||||
res.on("end", () => {
|
res.on("end", () => {
|
||||||
resolve(/** @type {any} */ (EJSON.parse(data)));
|
resolve(EJSON.parse(data) as any);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
.end();
|
.end();
|
||||||
});
|
}
|
||||||
|
);
|
||||||
|
|
||||||
if (!gUser?.email_verified) throw new Error("No Google User.");
|
if (!gUser?.email_verified) throw new Error("No Google User.");
|
||||||
|
|
||||||
@ -60,7 +66,7 @@ module.exports = async function apiGoogleLogin({
|
|||||||
const { given_name, family_name, email, sub, picture } = gUser;
|
const { given_name, family_name, email, sub, picture } = gUser;
|
||||||
|
|
||||||
/** @type {Object<string, any>} */
|
/** @type {Object<string, any>} */
|
||||||
let payloadObject = {
|
let payloadObject: { [s: string]: any } = {
|
||||||
email: email,
|
email: email,
|
||||||
first_name: given_name,
|
first_name: given_name,
|
||||||
last_name: family_name,
|
last_name: family_name,
|
||||||
@ -89,7 +95,7 @@ module.exports = async function apiGoogleLogin({
|
|||||||
////////////////////////////////////////
|
////////////////////////////////////////
|
||||||
|
|
||||||
return { ...loggedInGoogleUser };
|
return { ...loggedInGoogleUser };
|
||||||
} catch (/** @type {any} */ error) {
|
} catch (/** @type {any} */ error: any) {
|
||||||
console.log(`apo-google-login.js ERROR: ${error.message}`);
|
console.log(`apo-google-login.js ERROR: ${error.message}`);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
@ -98,4 +104,4 @@ module.exports = async function apiGoogleLogin({
|
|||||||
msg: error.message,
|
msg: error.message,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
};
|
}
|
@ -1,11 +0,0 @@
|
|||||||
declare function _exports({ query, user, useLocal }: {
|
|
||||||
query: {
|
|
||||||
invite: number;
|
|
||||||
database_access: string;
|
|
||||||
priviledge: string;
|
|
||||||
email: string;
|
|
||||||
};
|
|
||||||
useLocal?: boolean;
|
|
||||||
user: import("../../types").DATASQUIREL_LoggedInUser;
|
|
||||||
}): Promise<any>;
|
|
||||||
export = _exports;
|
|
@ -1,9 +1,19 @@
|
|||||||
// @ts-check
|
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";
|
||||||
|
import { DATASQUIREL_LoggedInUser } from "../../types";
|
||||||
|
|
||||||
const serverError = require("./serverError");
|
type Param = {
|
||||||
const DB_HANDLER = require("../../utils/backend/global-db/DB_HANDLER");
|
query: {
|
||||||
const addDbEntry = require("./db/addDbEntry");
|
invite: number;
|
||||||
const LOCAL_DB_HANDLER = require("../../utils/backend/global-db/LOCAL_DB_HANDLER");
|
database_access: string;
|
||||||
|
priviledge: string;
|
||||||
|
email: string;
|
||||||
|
};
|
||||||
|
useLocal?: boolean;
|
||||||
|
user: DATASQUIREL_LoggedInUser;
|
||||||
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Add Admin User on Login
|
* Add Admin User on Login
|
||||||
@ -12,21 +22,12 @@ const LOCAL_DB_HANDLER = require("../../utils/backend/global-db/LOCAL_DB_HANDLER
|
|||||||
* @description this function handles admin users that have been invited by another
|
* @description this function handles admin users that have been invited by another
|
||||||
* admin user. This fires when the invited user has been logged in or a new account
|
* admin user. This fires when the invited user has been logged in or a new account
|
||||||
* has been created for the invited user
|
* has been created for the invited user
|
||||||
*
|
|
||||||
* @param {object} params - parameters object
|
|
||||||
*
|
|
||||||
* @param {object} params.query - query object
|
|
||||||
* @param {number} params.query.invite - Invitation user id
|
|
||||||
* @param {string} params.query.database_access - String containing authorized databases
|
|
||||||
* @param {string} params.query.priviledge - String containing databases priviledges
|
|
||||||
* @param {string} params.query.email - Inviting user email address
|
|
||||||
*
|
|
||||||
* @param {boolean} [params.useLocal]
|
|
||||||
* @param {import("../../types").DATASQUIREL_LoggedInUser} params.user - invited user object
|
|
||||||
*
|
|
||||||
* @returns {Promise<any>} new user auth object payload
|
|
||||||
*/
|
*/
|
||||||
module.exports = async function addAdminUserOnLogin({ query, user, useLocal }) {
|
export default async function addAdminUserOnLogin({
|
||||||
|
query,
|
||||||
|
user,
|
||||||
|
useLocal,
|
||||||
|
}: Param): Promise<any> {
|
||||||
try {
|
try {
|
||||||
const finalDbHandler = useLocal ? LOCAL_DB_HANDLER : DB_HANDLER;
|
const finalDbHandler = useLocal ? LOCAL_DB_HANDLER : DB_HANDLER;
|
||||||
const { invite, database_access, priviledge, email } = query;
|
const { invite, database_access, priviledge, email } = query;
|
||||||
@ -132,23 +133,11 @@ module.exports = async function addAdminUserOnLogin({ query, user, useLocal }) {
|
|||||||
[invite, email]
|
[invite, email]
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
} catch (error: any) {
|
||||||
////////////////////////////////////////////////
|
|
||||||
////////////////////////////////////////////////
|
|
||||||
////////////////////////////////////////////////
|
|
||||||
} catch (/** @type {any} */ error) {
|
|
||||||
////////////////////////////////////////////////
|
|
||||||
////////////////////////////////////////////////
|
|
||||||
////////////////////////////////////////////////
|
|
||||||
|
|
||||||
serverError({
|
serverError({
|
||||||
component: "addAdminUserOnLogin",
|
component: "addAdminUserOnLogin",
|
||||||
message: error.message,
|
message: error.message,
|
||||||
user: user,
|
user: user,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
};
|
}
|
||||||
|
|
||||||
////////////////////////////////////////////////
|
|
||||||
////////////////////////////////////////////////
|
|
||||||
////////////////////////////////////////////////
|
|
@ -1,5 +0,0 @@
|
|||||||
declare function _exports({ userId, useLocal }: {
|
|
||||||
userId: number | string;
|
|
||||||
useLocal?: boolean;
|
|
||||||
}): Promise<any>;
|
|
||||||
export = _exports;
|
|
@ -1,24 +1,22 @@
|
|||||||
// @ts-check
|
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";
|
||||||
|
|
||||||
const generator = require("generate-password");
|
type Param = {
|
||||||
const DB_HANDLER = require("../../utils/backend/global-db/DB_HANDLER");
|
userId: number | string;
|
||||||
const NO_DB_HANDLER = require("../../utils/backend/global-db/NO_DB_HANDLER");
|
useLocal?: boolean;
|
||||||
const addDbEntry = require("./db/addDbEntry");
|
};
|
||||||
const encrypt = require("../dsql/encrypt");
|
|
||||||
const LOCAL_DB_HANDLER = require("../../utils/backend/global-db/LOCAL_DB_HANDLER");
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* # Add Mariadb User
|
* # Add Mariadb User
|
||||||
*
|
|
||||||
* @description this function adds a Mariadb user to the database server
|
|
||||||
*
|
|
||||||
* @param {object} params - parameters object *
|
|
||||||
* @param {number | string} params.userId - invited user object
|
|
||||||
* @param {boolean} [params.useLocal]
|
|
||||||
*
|
|
||||||
* @returns {Promise<any>} new user auth object payload
|
|
||||||
*/
|
*/
|
||||||
module.exports = async function addMariadbUser({ userId, useLocal }) {
|
export default async function addMariadbUser({
|
||||||
|
userId,
|
||||||
|
useLocal,
|
||||||
|
}: Param): Promise<any> {
|
||||||
try {
|
try {
|
||||||
const defaultMariadbUserHost = process.env.DSQL_DB_HOST || "127.0.0.1";
|
const defaultMariadbUserHost = process.env.DSQL_DB_HOST || "127.0.0.1";
|
||||||
|
|
||||||
@ -62,13 +60,13 @@ module.exports = async function addMariadbUser({ userId, useLocal }) {
|
|||||||
});
|
});
|
||||||
|
|
||||||
console.log(`User ${userId} SQL credentials successfully added.`);
|
console.log(`User ${userId} SQL credentials successfully added.`);
|
||||||
} catch (/** @type {any} */ error) {
|
} catch (/** @type {any} */ error: any) {
|
||||||
console.log(
|
console.log(
|
||||||
`Error in adding SQL user in 'addMariadbUser' function =>`,
|
`Error in adding SQL user in 'addMariadbUser' function =>`,
|
||||||
error.message
|
error.message
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
};
|
}
|
||||||
|
|
||||||
////////////////////////////////////////////////
|
////////////////////////////////////////////////
|
||||||
////////////////////////////////////////////////
|
////////////////////////////////////////////////
|
@ -1,9 +0,0 @@
|
|||||||
declare function _exports({ userId, database, useLocal, payload, }: {
|
|
||||||
userId: number;
|
|
||||||
database: string;
|
|
||||||
useLocal?: boolean;
|
|
||||||
payload?: {
|
|
||||||
[x: string]: any;
|
|
||||||
};
|
|
||||||
}): Promise<any>;
|
|
||||||
export = _exports;
|
|
@ -1,34 +1,28 @@
|
|||||||
// @ts-check
|
import serverError from "./serverError";
|
||||||
|
import DB_HANDLER from "../../utils/backend/global-db/DB_HANDLER";
|
||||||
|
import { default as grabUserSchemaData } from "./grabUserSchemaData";
|
||||||
|
import { default as setUserSchemaData } from "./setUserSchemaData";
|
||||||
|
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";
|
||||||
|
|
||||||
const fs = require("fs");
|
type Param = {
|
||||||
const path = require("path");
|
userId: number;
|
||||||
const { execSync } = require("child_process");
|
database: string;
|
||||||
const serverError = require("./serverError");
|
useLocal?: boolean;
|
||||||
const DB_HANDLER = require("../../utils/backend/global-db/DB_HANDLER");
|
payload?: { [s: string]: any };
|
||||||
const { default: grabUserSchemaData } = require("./grabUserSchemaData");
|
};
|
||||||
const { default: setUserSchemaData } = require("./setUserSchemaData");
|
|
||||||
const addDbEntry = require("./db/addDbEntry");
|
|
||||||
const createDbFromSchema = require("../../shell/createDbFromSchema");
|
|
||||||
const LOCAL_DB_HANDLER = require("../../utils/backend/global-db/LOCAL_DB_HANDLER");
|
|
||||||
const grabNewUsersTableSchema = require("./grabNewUsersTableSchema");
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* # Add User Table to Database
|
* # Add User Table to Database
|
||||||
*
|
|
||||||
* @param {object} params
|
|
||||||
* @param {number} params.userId - user id
|
|
||||||
* @param {string} params.database
|
|
||||||
* @param {boolean} [params.useLocal]
|
|
||||||
* @param {Object<string, any>} [params.payload] - payload object
|
|
||||||
*
|
|
||||||
* @returns {Promise<any>} new user auth object payload
|
|
||||||
*/
|
*/
|
||||||
module.exports = async function addUsersTableToDb({
|
export default async function addUsersTableToDb({
|
||||||
userId,
|
userId,
|
||||||
database,
|
database,
|
||||||
useLocal,
|
useLocal,
|
||||||
payload,
|
payload,
|
||||||
}) {
|
}: Param): Promise<any> {
|
||||||
try {
|
try {
|
||||||
const dbFullName = database;
|
const dbFullName = database;
|
||||||
|
|
||||||
@ -39,7 +33,7 @@ module.exports = async function addUsersTableToDb({
|
|||||||
if (!userSchemaData) throw new Error("User schema data not found!");
|
if (!userSchemaData) throw new Error("User schema data not found!");
|
||||||
|
|
||||||
let targetDatabase = userSchemaData.find(
|
let targetDatabase = userSchemaData.find(
|
||||||
(db) => db.dbFullName === database
|
(db: any) => db.dbFullName === database
|
||||||
);
|
);
|
||||||
|
|
||||||
if (!targetDatabase) {
|
if (!targetDatabase) {
|
||||||
@ -47,7 +41,7 @@ module.exports = async function addUsersTableToDb({
|
|||||||
}
|
}
|
||||||
|
|
||||||
let existingTableIndex = targetDatabase?.tables.findIndex(
|
let existingTableIndex = targetDatabase?.tables.findIndex(
|
||||||
(table) => table.tableName === "users"
|
(table: any) => table.tableName === "users"
|
||||||
);
|
);
|
||||||
|
|
||||||
if (typeof existingTableIndex == "number" && existingTableIndex > 0) {
|
if (typeof existingTableIndex == "number" && existingTableIndex > 0) {
|
||||||
@ -59,7 +53,7 @@ module.exports = async function addUsersTableToDb({
|
|||||||
setUserSchemaData({ schemaData: userSchemaData, userId });
|
setUserSchemaData({ schemaData: userSchemaData, userId });
|
||||||
|
|
||||||
/** @type {any[] | null} */
|
/** @type {any[] | null} */
|
||||||
const targetDb = useLocal
|
const targetDb: any[] | null = useLocal
|
||||||
? await LOCAL_DB_HANDLER(
|
? await LOCAL_DB_HANDLER(
|
||||||
`SELECT id FROM user_databases WHERE user_id=? AND db_slug=?`,
|
`SELECT id FROM user_databases WHERE user_id=? AND db_slug=?`,
|
||||||
[userId, database]
|
[userId, database]
|
||||||
@ -90,7 +84,7 @@ module.exports = async function addUsersTableToDb({
|
|||||||
});
|
});
|
||||||
|
|
||||||
return `Done!`;
|
return `Done!`;
|
||||||
} catch (/** @type {any} */ error) {
|
} catch (/** @type {any} */ error: any) {
|
||||||
console.log(`addUsersTableToDb.js ERROR: ${error.message}`);
|
console.log(`addUsersTableToDb.js ERROR: ${error.message}`);
|
||||||
|
|
||||||
serverError({
|
serverError({
|
||||||
@ -100,4 +94,4 @@ module.exports = async function addUsersTableToDb({
|
|||||||
});
|
});
|
||||||
return error.message;
|
return error.message;
|
||||||
}
|
}
|
||||||
};
|
}
|
@ -1,10 +1,17 @@
|
|||||||
// @ts-check
|
import fs from "fs";
|
||||||
|
import decrypt from "../dsql/decrypt";
|
||||||
|
import { CheckApiCredentialsFn } from "../../types";
|
||||||
|
|
||||||
const fs = require("fs");
|
/**
|
||||||
const decrypt = require("../dsql/decrypt");
|
* # Grap API Credentials
|
||||||
|
*/
|
||||||
/** @type {import("../../types").CheckApiCredentialsFn} */
|
const grabApiCred: CheckApiCredentialsFn = ({
|
||||||
const grabApiCred = ({ key, database, table, user_id, media }) => {
|
key,
|
||||||
|
database,
|
||||||
|
table,
|
||||||
|
user_id,
|
||||||
|
media,
|
||||||
|
}) => {
|
||||||
if (!key) return null;
|
if (!key) return null;
|
||||||
if (!user_id) return null;
|
if (!user_id) return null;
|
||||||
|
|
||||||
@ -18,7 +25,9 @@ const grabApiCred = ({ key, database, table, user_id, media }) => {
|
|||||||
|
|
||||||
const ApiJSON = decrypt({ encryptedString: key });
|
const ApiJSON = decrypt({ encryptedString: key });
|
||||||
/** @type {import("../../types").ApiKeyObject} */
|
/** @type {import("../../types").ApiKeyObject} */
|
||||||
const ApiObject = JSON.parse(ApiJSON || "");
|
const ApiObject: import("../../types").ApiKeyObject = JSON.parse(
|
||||||
|
ApiJSON || ""
|
||||||
|
);
|
||||||
const isApiKeyValid = fs.existsSync(
|
const isApiKeyValid = fs.existsSync(
|
||||||
`${allowedKeysPath}/${ApiObject.sign}`
|
`${allowedKeysPath}/${ApiObject.sign}`
|
||||||
);
|
);
|
||||||
@ -41,10 +50,10 @@ const grabApiCred = ({ key, database, table, user_id, media }) => {
|
|||||||
.includes(String(table));
|
.includes(String(table));
|
||||||
if (isTableAllowed) return ApiObject;
|
if (isTableAllowed) return ApiObject;
|
||||||
return null;
|
return null;
|
||||||
} catch (/** @type {any} */ error) {
|
} catch (/** @type {any} */ error: any) {
|
||||||
console.log(`api-cred ERROR: ${error.message}`);
|
console.log(`api-cred ERROR: ${error.message}`);
|
||||||
return { error: `api-cred ERROR: ${error.message}` };
|
return { error: `api-cred ERROR: ${error.message}` };
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
module.exports = grabApiCred;
|
export default grabApiCred;
|
@ -1,26 +0,0 @@
|
|||||||
export function grabAuthDirs(): {
|
|
||||||
root: string;
|
|
||||||
auth: string;
|
|
||||||
};
|
|
||||||
export function initAuthFiles(): boolean;
|
|
||||||
/**
|
|
||||||
* # Write Auth Files
|
|
||||||
* @param {string} name
|
|
||||||
* @param {string} data
|
|
||||||
*/
|
|
||||||
export function writeAuthFile(name: string, data: string): boolean;
|
|
||||||
/**
|
|
||||||
* # Get Auth Files
|
|
||||||
* @param {string} name
|
|
||||||
*/
|
|
||||||
export function getAuthFile(name: string): string;
|
|
||||||
/**
|
|
||||||
* # Delete Auth Files
|
|
||||||
* @param {string} name
|
|
||||||
*/
|
|
||||||
export function deleteAuthFile(name: string): void;
|
|
||||||
/**
|
|
||||||
* # Delete Auth Files
|
|
||||||
* @param {string} name
|
|
||||||
*/
|
|
||||||
export function checkAuthFile(name: string): boolean;
|
|
@ -1,9 +1,7 @@
|
|||||||
// @ts-check
|
import fs from "fs";
|
||||||
|
import path from "path";
|
||||||
|
|
||||||
const fs = require("fs");
|
export const grabAuthDirs = () => {
|
||||||
const path = require("path");
|
|
||||||
|
|
||||||
const grabAuthDirs = () => {
|
|
||||||
const DSQL_AUTH_DIR = process.env.DSQL_AUTH_DIR;
|
const DSQL_AUTH_DIR = process.env.DSQL_AUTH_DIR;
|
||||||
const ROOT_DIR = DSQL_AUTH_DIR?.match(/./)
|
const ROOT_DIR = DSQL_AUTH_DIR?.match(/./)
|
||||||
? DSQL_AUTH_DIR
|
? DSQL_AUTH_DIR
|
||||||
@ -13,7 +11,7 @@ const grabAuthDirs = () => {
|
|||||||
return { root: ROOT_DIR, auth: AUTH_DIR };
|
return { root: ROOT_DIR, auth: AUTH_DIR };
|
||||||
};
|
};
|
||||||
|
|
||||||
const initAuthFiles = () => {
|
export const initAuthFiles = () => {
|
||||||
try {
|
try {
|
||||||
const authDirs = grabAuthDirs();
|
const authDirs = grabAuthDirs();
|
||||||
|
|
||||||
@ -22,7 +20,7 @@ const initAuthFiles = () => {
|
|||||||
if (!fs.existsSync(authDirs.auth))
|
if (!fs.existsSync(authDirs.auth))
|
||||||
fs.mkdirSync(authDirs.auth, { recursive: true });
|
fs.mkdirSync(authDirs.auth, { recursive: true });
|
||||||
return true;
|
return true;
|
||||||
} catch (/** @type {any} */ error) {
|
} catch (error: any) {
|
||||||
console.log(`Error initializing Auth Files: ${error.message}`);
|
console.log(`Error initializing Auth Files: ${error.message}`);
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
@ -30,15 +28,13 @@ const initAuthFiles = () => {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* # Write Auth Files
|
* # Write Auth Files
|
||||||
* @param {string} name
|
|
||||||
* @param {string} data
|
|
||||||
*/
|
*/
|
||||||
const writeAuthFile = (name, data) => {
|
export const writeAuthFile = (name: string, data: string) => {
|
||||||
initAuthFiles();
|
initAuthFiles();
|
||||||
try {
|
try {
|
||||||
fs.writeFileSync(path.join(grabAuthDirs().auth, name), data);
|
fs.writeFileSync(path.join(grabAuthDirs().auth, name), data);
|
||||||
return true;
|
return true;
|
||||||
} catch (/** @type {any} */ error) {
|
} catch (/** @type {any} */ error: any) {
|
||||||
console.log(`Error writing Auth File: ${error.message}`);
|
console.log(`Error writing Auth File: ${error.message}`);
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
@ -46,13 +42,12 @@ const writeAuthFile = (name, data) => {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* # Get Auth Files
|
* # Get Auth Files
|
||||||
* @param {string} name
|
|
||||||
*/
|
*/
|
||||||
const getAuthFile = (name) => {
|
export const getAuthFile = (name: string) => {
|
||||||
try {
|
try {
|
||||||
const authFilePath = path.join(grabAuthDirs().auth, name);
|
const authFilePath = path.join(grabAuthDirs().auth, name);
|
||||||
return fs.readFileSync(authFilePath, "utf-8");
|
return fs.readFileSync(authFilePath, "utf-8");
|
||||||
} catch (/** @type {any} */ error) {
|
} catch (/** @type {any} */ error: any) {
|
||||||
console.log(`Error getting Auth File: ${error.message}`);
|
console.log(`Error getting Auth File: ${error.message}`);
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
@ -62,10 +57,10 @@ const getAuthFile = (name) => {
|
|||||||
* # Delete Auth Files
|
* # Delete Auth Files
|
||||||
* @param {string} name
|
* @param {string} name
|
||||||
*/
|
*/
|
||||||
const deleteAuthFile = (name) => {
|
export const deleteAuthFile = (name: string) => {
|
||||||
try {
|
try {
|
||||||
return fs.rmSync(path.join(grabAuthDirs().auth, name));
|
return fs.rmSync(path.join(grabAuthDirs().auth, name));
|
||||||
} catch (/** @type {any} */ error) {
|
} catch (/** @type {any} */ error: any) {
|
||||||
console.log(`Error deleting Auth File: ${error.message}`);
|
console.log(`Error deleting Auth File: ${error.message}`);
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
@ -75,19 +70,12 @@ const deleteAuthFile = (name) => {
|
|||||||
* # Delete Auth Files
|
* # Delete Auth Files
|
||||||
* @param {string} name
|
* @param {string} name
|
||||||
*/
|
*/
|
||||||
const checkAuthFile = (name) => {
|
export const checkAuthFile = (name: string) => {
|
||||||
try {
|
try {
|
||||||
return fs.existsSync(path.join(grabAuthDirs().auth, name));
|
return fs.existsSync(path.join(grabAuthDirs().auth, name));
|
||||||
return true;
|
return true;
|
||||||
} catch (/** @type {any} */ error) {
|
} catch (/** @type {any} */ error: any) {
|
||||||
console.log(`Error checking Auth File: ${error.message}`);
|
console.log(`Error checking Auth File: ${error.message}`);
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
exports.grabAuthDirs = grabAuthDirs;
|
|
||||||
exports.initAuthFiles = initAuthFiles;
|
|
||||||
exports.writeAuthFile = writeAuthFile;
|
|
||||||
exports.getAuthFile = getAuthFile;
|
|
||||||
exports.deleteAuthFile = deleteAuthFile;
|
|
||||||
exports.checkAuthFile = checkAuthFile;
|
|
@ -1,9 +0,0 @@
|
|||||||
declare function _exports(params?: {
|
|
||||||
database?: string;
|
|
||||||
userId?: string | number;
|
|
||||||
}): {
|
|
||||||
keyCookieName: string;
|
|
||||||
csrfCookieName: string;
|
|
||||||
oneTimeCodeName: string;
|
|
||||||
};
|
|
||||||
export = _exports;
|
|
@ -1,15 +1,18 @@
|
|||||||
// @ts-check
|
type Param = {
|
||||||
|
database?: string;
|
||||||
|
userId?: string | number;
|
||||||
|
};
|
||||||
|
|
||||||
|
type Return = {
|
||||||
|
keyCookieName: string;
|
||||||
|
csrfCookieName: string;
|
||||||
|
oneTimeCodeName: string;
|
||||||
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* # Grab Auth Cookie Names
|
* # Grab Auth Cookie Names
|
||||||
*
|
|
||||||
* @param {object} [params]
|
|
||||||
* @param {string} [params.database]
|
|
||||||
* @param {string | number} [params.userId]
|
|
||||||
*
|
|
||||||
* @returns {{ keyCookieName: string, csrfCookieName: string, oneTimeCodeName: string }}
|
|
||||||
*/
|
*/
|
||||||
module.exports = function getAuthCookieNames(params) {
|
export default function getAuthCookieNames(params?: Param): Return {
|
||||||
const cookiesPrefix = process.env.DSQL_COOKIES_PREFIX || "dsql_";
|
const cookiesPrefix = process.env.DSQL_COOKIES_PREFIX || "dsql_";
|
||||||
const cookiesKeyName = process.env.DSQL_COOKIES_KEY_NAME || "key";
|
const cookiesKeyName = process.env.DSQL_COOKIES_KEY_NAME || "key";
|
||||||
const cookiesCSRFName = process.env.DSQL_COOKIES_CSRF_NAME || "csrf";
|
const cookiesCSRFName = process.env.DSQL_COOKIES_CSRF_NAME || "csrf";
|
||||||
@ -40,4 +43,4 @@ module.exports = function getAuthCookieNames(params) {
|
|||||||
csrfCookieName,
|
csrfCookieName,
|
||||||
oneTimeCodeName,
|
oneTimeCodeName,
|
||||||
};
|
};
|
||||||
};
|
}
|
@ -1,39 +0,0 @@
|
|||||||
export = addDbEntry;
|
|
||||||
/**
|
|
||||||
* Add a db Entry Function
|
|
||||||
* ==============================================================================
|
|
||||||
* @description Description
|
|
||||||
* @async
|
|
||||||
*
|
|
||||||
* @param {object} params - An object containing the function parameters.
|
|
||||||
* @param {("Master" | "Dsql User")} [params.dbContext] - What is the database context? "Master"
|
|
||||||
* or "Dsql User". Defaults to "Master"
|
|
||||||
* @param {("Read Only" | "Full Access")} [params.paradigm] - What is the paradigm for "Dsql User"?
|
|
||||||
* "Read only" or "Full Access"? Defaults to "Read Only"
|
|
||||||
* @param {string} [params.dbFullName] - Database full name
|
|
||||||
* @param {string} params.tableName - Table name
|
|
||||||
* @param {any} params.data - Data to add
|
|
||||||
* @param {import("../../../types").DSQL_TableSchemaType} [params.tableSchema] - Table schema
|
|
||||||
* @param {string} [params.duplicateColumnName] - Duplicate column name
|
|
||||||
* @param {string} [params.duplicateColumnValue] - Duplicate column value
|
|
||||||
* @param {boolean} [params.update] - Update this row if it exists
|
|
||||||
* @param {string} [params.encryptionKey] - Update this row if it exists
|
|
||||||
* @param {string} [params.encryptionSalt] - Update this row if it exists
|
|
||||||
* @param {boolean} [params.useLocal]
|
|
||||||
*
|
|
||||||
* @returns {Promise<any>}
|
|
||||||
*/
|
|
||||||
declare function addDbEntry({ dbContext, paradigm, dbFullName, tableName, data, tableSchema, duplicateColumnName, duplicateColumnValue, update, encryptionKey, encryptionSalt, useLocal, }: {
|
|
||||||
dbContext?: ("Master" | "Dsql User");
|
|
||||||
paradigm?: ("Read Only" | "Full Access");
|
|
||||||
dbFullName?: string;
|
|
||||||
tableName: string;
|
|
||||||
data: any;
|
|
||||||
tableSchema?: import("../../../types").DSQL_TableSchemaType;
|
|
||||||
duplicateColumnName?: string;
|
|
||||||
duplicateColumnValue?: string;
|
|
||||||
update?: boolean;
|
|
||||||
encryptionKey?: string;
|
|
||||||
encryptionSalt?: string;
|
|
||||||
useLocal?: boolean;
|
|
||||||
}): Promise<any>;
|
|
@ -1,13 +1,28 @@
|
|||||||
// @ts-check
|
// @ts-check
|
||||||
|
|
||||||
const sanitizeHtml = require("sanitize-html");
|
import sanitizeHtml from "sanitize-html";
|
||||||
const sanitizeHtmlOptions = require("../html/sanitizeHtmlOptions");
|
import sanitizeHtmlOptions from "../html/sanitizeHtmlOptions";
|
||||||
const updateDbEntry = require("./updateDbEntry");
|
import updateDbEntry from "./updateDbEntry";
|
||||||
const _ = require("lodash");
|
import _ from "lodash";
|
||||||
const DB_HANDLER = require("../../../utils/backend/global-db/DB_HANDLER");
|
import DB_HANDLER from "../../../utils/backend/global-db/DB_HANDLER";
|
||||||
const DSQL_USER_DB_HANDLER = require("../../../utils/backend/global-db/DSQL_USER_DB_HANDLER");
|
import DSQL_USER_DB_HANDLER from "../../../utils/backend/global-db/DSQL_USER_DB_HANDLER";
|
||||||
const encrypt = require("../../dsql/encrypt");
|
import encrypt from "../../dsql/encrypt";
|
||||||
const LOCAL_DB_HANDLER = require("../../../utils/backend/global-db/LOCAL_DB_HANDLER");
|
import LOCAL_DB_HANDLER from "../../../utils/backend/global-db/LOCAL_DB_HANDLER";
|
||||||
|
|
||||||
|
type Param = {
|
||||||
|
dbContext?: "Master" | "Dsql User";
|
||||||
|
paradigm?: "Read Only" | "Full Access";
|
||||||
|
dbFullName?: string;
|
||||||
|
tableName: string;
|
||||||
|
data: any;
|
||||||
|
tableSchema?: import("../../../types").DSQL_TableSchemaType;
|
||||||
|
duplicateColumnName?: string;
|
||||||
|
duplicateColumnValue?: string;
|
||||||
|
update?: boolean;
|
||||||
|
encryptionKey?: string;
|
||||||
|
encryptionSalt?: string;
|
||||||
|
useLocal?: boolean;
|
||||||
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Add a db Entry Function
|
* Add a db Entry Function
|
||||||
@ -33,7 +48,7 @@ const LOCAL_DB_HANDLER = require("../../../utils/backend/global-db/LOCAL_DB_HAND
|
|||||||
*
|
*
|
||||||
* @returns {Promise<any>}
|
* @returns {Promise<any>}
|
||||||
*/
|
*/
|
||||||
async function addDbEntry({
|
export default async function addDbEntry({
|
||||||
dbContext,
|
dbContext,
|
||||||
paradigm,
|
paradigm,
|
||||||
dbFullName,
|
dbFullName,
|
||||||
@ -46,7 +61,7 @@ async function addDbEntry({
|
|||||||
encryptionKey,
|
encryptionKey,
|
||||||
encryptionSalt,
|
encryptionSalt,
|
||||||
useLocal,
|
useLocal,
|
||||||
}) {
|
}: Param): Promise<any> {
|
||||||
/**
|
/**
|
||||||
* Initialize variables
|
* Initialize variables
|
||||||
*/
|
*/
|
||||||
@ -59,7 +74,7 @@ async function addDbEntry({
|
|||||||
: true;
|
: true;
|
||||||
|
|
||||||
/** @type { any } */
|
/** @type { any } */
|
||||||
const dbHandler = useLocal
|
const dbHandler: any = useLocal
|
||||||
? LOCAL_DB_HANDLER
|
? LOCAL_DB_HANDLER
|
||||||
: isMaster
|
: isMaster
|
||||||
? DB_HANDLER
|
? DB_HANDLER
|
||||||
@ -187,7 +202,7 @@ async function addDbEntry({
|
|||||||
} else {
|
} else {
|
||||||
insertValuesArray.push(value);
|
insertValuesArray.push(value);
|
||||||
}
|
}
|
||||||
} catch (/** @type {any} */ error) {
|
} catch (/** @type {any} */ error: any) {
|
||||||
console.log("DSQL: Error in parsing data keys =>", error.message);
|
console.log("DSQL: Error in parsing data keys =>", error.message);
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
@ -233,18 +248,8 @@ async function addDbEntry({
|
|||||||
queryValues: queryValuesArray,
|
queryValues: queryValuesArray,
|
||||||
});
|
});
|
||||||
|
|
||||||
////////////////////////////////////////
|
|
||||||
////////////////////////////////////////
|
|
||||||
////////////////////////////////////////
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Return statement
|
* Return statement
|
||||||
*/
|
*/
|
||||||
return newInsert;
|
return newInsert;
|
||||||
}
|
}
|
||||||
|
|
||||||
////////////////////////////////////////
|
|
||||||
////////////////////////////////////////
|
|
||||||
////////////////////////////////////////
|
|
||||||
|
|
||||||
module.exports = addDbEntry;
|
|
@ -1,34 +0,0 @@
|
|||||||
export = deleteDbEntry;
|
|
||||||
/**
|
|
||||||
* Imports: Handle imports
|
|
||||||
*/
|
|
||||||
/**
|
|
||||||
* Delete DB Entry Function
|
|
||||||
* ==============================================================================
|
|
||||||
* @description Description
|
|
||||||
* @async
|
|
||||||
*
|
|
||||||
* @param {object} params - An object containing the function parameters.
|
|
||||||
* @param {string} [params.dbContext] - What is the database context? "Master"
|
|
||||||
* or "Dsql User". Defaults to "Master"
|
|
||||||
* @param {("Read Only" | "Full Access")} [params.paradigm] - What is the paradigm for "Dsql User"?
|
|
||||||
* "Read only" or "Full Access"? Defaults to "Read Only"
|
|
||||||
* @param {string} params.dbFullName - Database full name
|
|
||||||
* @param {string} params.tableName - Table name
|
|
||||||
* @param {import("../../../types").DSQL_TableSchemaType} [params.tableSchema] - Table schema
|
|
||||||
* @param {string} params.identifierColumnName - Update row identifier column name
|
|
||||||
* @param {string|number} params.identifierValue - Update row identifier column value
|
|
||||||
* @param {boolean} [params.useLocal]
|
|
||||||
*
|
|
||||||
* @returns {Promise<object|null>}
|
|
||||||
*/
|
|
||||||
declare function deleteDbEntry({ dbContext, paradigm, dbFullName, tableName, identifierColumnName, identifierValue, useLocal, }: {
|
|
||||||
dbContext?: string;
|
|
||||||
paradigm?: ("Read Only" | "Full Access");
|
|
||||||
dbFullName: string;
|
|
||||||
tableName: string;
|
|
||||||
tableSchema?: import("../../../types").DSQL_TableSchemaType;
|
|
||||||
identifierColumnName: string;
|
|
||||||
identifierValue: string | number;
|
|
||||||
useLocal?: boolean;
|
|
||||||
}): Promise<object | null>;
|
|
@ -1,104 +0,0 @@
|
|||||||
// @ts-check
|
|
||||||
|
|
||||||
const DB_HANDLER = require("../../../utils/backend/global-db/DB_HANDLER");
|
|
||||||
const DSQL_USER_DB_HANDLER = require("../../../utils/backend/global-db/DSQL_USER_DB_HANDLER");
|
|
||||||
const LOCAL_DB_HANDLER = require("../../../utils/backend/global-db/LOCAL_DB_HANDLER");
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Imports: Handle imports
|
|
||||||
*/
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Delete DB Entry Function
|
|
||||||
* ==============================================================================
|
|
||||||
* @description Description
|
|
||||||
* @async
|
|
||||||
*
|
|
||||||
* @param {object} params - An object containing the function parameters.
|
|
||||||
* @param {string} [params.dbContext] - What is the database context? "Master"
|
|
||||||
* or "Dsql User". Defaults to "Master"
|
|
||||||
* @param {("Read Only" | "Full Access")} [params.paradigm] - What is the paradigm for "Dsql User"?
|
|
||||||
* "Read only" or "Full Access"? Defaults to "Read Only"
|
|
||||||
* @param {string} params.dbFullName - Database full name
|
|
||||||
* @param {string} params.tableName - Table name
|
|
||||||
* @param {import("../../../types").DSQL_TableSchemaType} [params.tableSchema] - Table schema
|
|
||||||
* @param {string} params.identifierColumnName - Update row identifier column name
|
|
||||||
* @param {string|number} params.identifierValue - Update row identifier column value
|
|
||||||
* @param {boolean} [params.useLocal]
|
|
||||||
*
|
|
||||||
* @returns {Promise<object|null>}
|
|
||||||
*/
|
|
||||||
async function deleteDbEntry({
|
|
||||||
dbContext,
|
|
||||||
paradigm,
|
|
||||||
dbFullName,
|
|
||||||
tableName,
|
|
||||||
identifierColumnName,
|
|
||||||
identifierValue,
|
|
||||||
useLocal,
|
|
||||||
}) {
|
|
||||||
try {
|
|
||||||
/**
|
|
||||||
* Check if data is valid
|
|
||||||
*/
|
|
||||||
const isMaster = useLocal
|
|
||||||
? true
|
|
||||||
: dbContext?.match(/dsql.user/i)
|
|
||||||
? false
|
|
||||||
: dbFullName && !dbFullName.match(/^datasquirel$/)
|
|
||||||
? false
|
|
||||||
: true;
|
|
||||||
|
|
||||||
/** @type { (a1:any, a2?:any) => any } */
|
|
||||||
const dbHandler = useLocal
|
|
||||||
? LOCAL_DB_HANDLER
|
|
||||||
: isMaster
|
|
||||||
? DB_HANDLER
|
|
||||||
: DSQL_USER_DB_HANDLER;
|
|
||||||
|
|
||||||
////////////////////////////////////////
|
|
||||||
////////////////////////////////////////
|
|
||||||
////////////////////////////////////////
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Execution
|
|
||||||
*
|
|
||||||
* @description
|
|
||||||
*/
|
|
||||||
const query = `DELETE FROM ${tableName} WHERE \`${identifierColumnName}\`=?`;
|
|
||||||
|
|
||||||
const deletedEntry = isMaster
|
|
||||||
? await dbHandler(query, [identifierValue])
|
|
||||||
: await dbHandler({
|
|
||||||
paradigm,
|
|
||||||
queryString: query,
|
|
||||||
database: dbFullName,
|
|
||||||
queryValues: [identifierValue],
|
|
||||||
});
|
|
||||||
|
|
||||||
////////////////////////////////////////
|
|
||||||
////////////////////////////////////////
|
|
||||||
////////////////////////////////////////
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Return statement
|
|
||||||
*/
|
|
||||||
return deletedEntry;
|
|
||||||
|
|
||||||
////////////////////////////////////////
|
|
||||||
////////////////////////////////////////
|
|
||||||
////////////////////////////////////////
|
|
||||||
} catch (error) {
|
|
||||||
////////////////////////////////////////
|
|
||||||
////////////////////////////////////////
|
|
||||||
////////////////////////////////////////
|
|
||||||
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
////////////////////////////////////////
|
|
||||||
////////////////////////////////////////
|
|
||||||
////////////////////////////////////////
|
|
||||||
|
|
||||||
module.exports = deleteDbEntry;
|
|
68
package-shared/functions/backend/db/deleteDbEntry.ts
Normal file
68
package-shared/functions/backend/db/deleteDbEntry.ts
Normal file
@ -0,0 +1,68 @@
|
|||||||
|
import DB_HANDLER from "../../../utils/backend/global-db/DB_HANDLER";
|
||||||
|
import DSQL_USER_DB_HANDLER from "../../../utils/backend/global-db/DSQL_USER_DB_HANDLER";
|
||||||
|
import LOCAL_DB_HANDLER from "../../../utils/backend/global-db/LOCAL_DB_HANDLER";
|
||||||
|
|
||||||
|
type Param = {
|
||||||
|
dbContext?: string;
|
||||||
|
paradigm?: "Read Only" | "Full Access";
|
||||||
|
dbFullName: string;
|
||||||
|
tableName: string;
|
||||||
|
tableSchema?: import("../../../types").DSQL_TableSchemaType;
|
||||||
|
identifierColumnName: string;
|
||||||
|
identifierValue: string | number;
|
||||||
|
useLocal?: boolean;
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* # Delete DB Entry Function
|
||||||
|
* @description
|
||||||
|
*/
|
||||||
|
export default async function deleteDbEntry({
|
||||||
|
dbContext,
|
||||||
|
paradigm,
|
||||||
|
dbFullName,
|
||||||
|
tableName,
|
||||||
|
identifierColumnName,
|
||||||
|
identifierValue,
|
||||||
|
useLocal,
|
||||||
|
}: Param): Promise<object | null> {
|
||||||
|
try {
|
||||||
|
const isMaster = useLocal
|
||||||
|
? true
|
||||||
|
: dbContext?.match(/dsql.user/i)
|
||||||
|
? false
|
||||||
|
: dbFullName && !dbFullName.match(/^datasquirel$/)
|
||||||
|
? false
|
||||||
|
: true;
|
||||||
|
|
||||||
|
/** @type { (a1:any, a2?:any) => any } */
|
||||||
|
const dbHandler: (a1: any, a2?: any) => any = useLocal
|
||||||
|
? LOCAL_DB_HANDLER
|
||||||
|
: isMaster
|
||||||
|
? DB_HANDLER
|
||||||
|
: DSQL_USER_DB_HANDLER;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Execution
|
||||||
|
*
|
||||||
|
* @description
|
||||||
|
*/
|
||||||
|
const query = `DELETE FROM ${tableName} WHERE \`${identifierColumnName}\`=?`;
|
||||||
|
|
||||||
|
const deletedEntry = isMaster
|
||||||
|
? await dbHandler(query, [identifierValue])
|
||||||
|
: await dbHandler({
|
||||||
|
paradigm,
|
||||||
|
queryString: query,
|
||||||
|
database: dbFullName,
|
||||||
|
queryValues: [identifierValue],
|
||||||
|
});
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Return statement
|
||||||
|
*/
|
||||||
|
return deletedEntry;
|
||||||
|
} catch (error) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
@ -1,14 +0,0 @@
|
|||||||
// @ts-check
|
|
||||||
|
|
||||||
/**
|
|
||||||
* # Path Traversal Check
|
|
||||||
*
|
|
||||||
* @param {string|number} text - Text or number or object
|
|
||||||
*
|
|
||||||
* @returns {string}
|
|
||||||
*/
|
|
||||||
function pathTraversalCheck(text) {
|
|
||||||
return text.toString().replace(/\//g, "");
|
|
||||||
}
|
|
||||||
|
|
||||||
module.exports = pathTraversalCheck;
|
|
@ -0,0 +1,7 @@
|
|||||||
|
/**
|
||||||
|
* # Path Traversal Check
|
||||||
|
* @returns {string}
|
||||||
|
*/
|
||||||
|
export default function pathTraversalCheck(text: string | number): string {
|
||||||
|
return text.toString().replace(/\//g, "");
|
||||||
|
}
|
@ -1,24 +0,0 @@
|
|||||||
export = runQuery;
|
|
||||||
/**
|
|
||||||
* Run DSQL users queries
|
|
||||||
* ==============================================================================
|
|
||||||
* @param {object} params - An object containing the function parameters.
|
|
||||||
* @param {string} params.dbFullName - Database full name. Eg. "datasquire_user_2_test"
|
|
||||||
* @param {string | any} params.query - Query string or object
|
|
||||||
* @param {boolean} [params.readOnly] - Is this operation read only?
|
|
||||||
* @param {boolean} [params.local] - Is this operation read only?
|
|
||||||
* @param {import("../../../types").DSQL_DatabaseSchemaType} [params.dbSchema] - Database schema
|
|
||||||
* @param {(string | number)[]} [params.queryValuesArray] - An optional array of query values if "?" is used in the query string
|
|
||||||
* @param {string} [params.tableName] - Table Name
|
|
||||||
*
|
|
||||||
* @return {Promise<any>}
|
|
||||||
*/
|
|
||||||
declare function runQuery({ dbFullName, query, readOnly, dbSchema, queryValuesArray, tableName, local, }: {
|
|
||||||
dbFullName: string;
|
|
||||||
query: string | any;
|
|
||||||
readOnly?: boolean;
|
|
||||||
local?: boolean;
|
|
||||||
dbSchema?: import("../../../types").DSQL_DatabaseSchemaType;
|
|
||||||
queryValuesArray?: (string | number)[];
|
|
||||||
tableName?: string;
|
|
||||||
}): Promise<any>;
|
|
@ -1,32 +1,26 @@
|
|||||||
// @ts-check
|
import fullAccessDbHandler from "../fullAccessDbHandler";
|
||||||
|
import varReadOnlyDatabaseDbHandler from "../varReadOnlyDatabaseDbHandler";
|
||||||
|
import serverError from "../serverError";
|
||||||
|
import addDbEntry from "./addDbEntry";
|
||||||
|
import updateDbEntry from "./updateDbEntry";
|
||||||
|
import deleteDbEntry from "./deleteDbEntry";
|
||||||
|
import trimSql from "../../../utils/trim-sql";
|
||||||
|
import { DSQL_TableSchemaType } from "../../../types";
|
||||||
|
|
||||||
const fs = require("fs");
|
type Param = {
|
||||||
|
dbFullName: string;
|
||||||
const LOCAL_DB_HANDLER = require("../../../utils/backend/global-db/LOCAL_DB_HANDLER");
|
query: string | any;
|
||||||
const fullAccessDbHandler = require("../fullAccessDbHandler");
|
readOnly?: boolean;
|
||||||
const varReadOnlyDatabaseDbHandler = require("../varReadOnlyDatabaseDbHandler");
|
local?: boolean;
|
||||||
const serverError = require("../serverError");
|
dbSchema?: import("../../../types").DSQL_DatabaseSchemaType;
|
||||||
const addDbEntry = require("./addDbEntry");
|
queryValuesArray?: (string | number)[];
|
||||||
const updateDbEntry = require("./updateDbEntry");
|
tableName?: string;
|
||||||
const deleteDbEntry = require("./deleteDbEntry");
|
};
|
||||||
const parseDbResults = require("../parseDbResults");
|
|
||||||
const trimSql = require("../../../utils/trim-sql");
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Run DSQL users queries
|
* # Run DSQL users queries
|
||||||
* ==============================================================================
|
|
||||||
* @param {object} params - An object containing the function parameters.
|
|
||||||
* @param {string} params.dbFullName - Database full name. Eg. "datasquire_user_2_test"
|
|
||||||
* @param {string | any} params.query - Query string or object
|
|
||||||
* @param {boolean} [params.readOnly] - Is this operation read only?
|
|
||||||
* @param {boolean} [params.local] - Is this operation read only?
|
|
||||||
* @param {import("../../../types").DSQL_DatabaseSchemaType} [params.dbSchema] - Database schema
|
|
||||||
* @param {(string | number)[]} [params.queryValuesArray] - An optional array of query values if "?" is used in the query string
|
|
||||||
* @param {string} [params.tableName] - Table Name
|
|
||||||
*
|
|
||||||
* @return {Promise<any>}
|
|
||||||
*/
|
*/
|
||||||
async function runQuery({
|
export default async function runQuery({
|
||||||
dbFullName,
|
dbFullName,
|
||||||
query,
|
query,
|
||||||
readOnly,
|
readOnly,
|
||||||
@ -34,19 +28,16 @@ async function runQuery({
|
|||||||
queryValuesArray,
|
queryValuesArray,
|
||||||
tableName,
|
tableName,
|
||||||
local,
|
local,
|
||||||
}) {
|
}: Param): Promise<any> {
|
||||||
/**
|
/**
|
||||||
* Declare variables
|
* Declare variables
|
||||||
*
|
*
|
||||||
* @description Declare "results" variable
|
* @description Declare "results" variable
|
||||||
*/
|
*/
|
||||||
|
|
||||||
/** @type {any} */
|
let result: any;
|
||||||
let result;
|
let error: any;
|
||||||
/** @type {any} */
|
let tableSchema: DSQL_TableSchemaType | undefined;
|
||||||
let error;
|
|
||||||
/** @type {import("../../../types").DSQL_TableSchemaType | undefined} */
|
|
||||||
let tableSchema;
|
|
||||||
|
|
||||||
if (dbSchema) {
|
if (dbSchema) {
|
||||||
try {
|
try {
|
||||||
@ -178,11 +169,7 @@ async function runQuery({
|
|||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
} catch (/** @type {any} */ error: any) {
|
||||||
////////////////////////////////////////
|
|
||||||
////////////////////////////////////////
|
|
||||||
////////////////////////////////////////
|
|
||||||
} catch (/** @type {any} */ error) {
|
|
||||||
serverError({
|
serverError({
|
||||||
component: "functions/backend/runQuery",
|
component: "functions/backend/runQuery",
|
||||||
message: error.message,
|
message: error.message,
|
||||||
@ -191,15 +178,5 @@ async function runQuery({
|
|||||||
error = error.message;
|
error = error.message;
|
||||||
}
|
}
|
||||||
|
|
||||||
////////////////////////////////////////
|
|
||||||
////////////////////////////////////////
|
|
||||||
////////////////////////////////////////
|
|
||||||
|
|
||||||
return { result, error };
|
return { result, error };
|
||||||
|
|
||||||
////////////////////////////////////////
|
|
||||||
////////////////////////////////////////
|
|
||||||
////////////////////////////////////////
|
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports = runQuery;
|
|
@ -1,20 +1,12 @@
|
|||||||
// @ts-check
|
import _ from "lodash";
|
||||||
|
|
||||||
const _ = require("lodash");
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Sanitize SQL function
|
* Sanitize SQL function
|
||||||
* ==============================================================================
|
* ==============================================================================
|
||||||
* @description this function takes in a text(or number) and returns a sanitized
|
* @description this function takes in a text(or number) and returns a sanitized
|
||||||
* text, usually without spaces
|
* text, usually without spaces
|
||||||
*
|
|
||||||
* @param {any} text - Text or number or object
|
|
||||||
* @param {boolean} [spaces] - Allow spaces
|
|
||||||
* @param {RegExp?} [regex] - Regular expression, removes any match
|
|
||||||
*
|
|
||||||
* @returns {any}
|
|
||||||
*/
|
*/
|
||||||
function sanitizeSql(text, spaces, regex) {
|
function sanitizeSql(text: any, spaces: boolean, regex?: RegExp | null): any {
|
||||||
if (!text) return "";
|
if (!text) return "";
|
||||||
if (typeof text == "number" || typeof text == "boolean") return text;
|
if (typeof text == "number" || typeof text == "boolean") return text;
|
||||||
if (typeof text == "string" && !text?.toString()?.match(/./)) return "";
|
if (typeof text == "string" && !text?.toString()?.match(/./)) return "";
|
||||||
@ -63,9 +55,9 @@ function sanitizeSql(text, spaces, regex) {
|
|||||||
*
|
*
|
||||||
* @returns {object}
|
* @returns {object}
|
||||||
*/
|
*/
|
||||||
function sanitizeObjects(object, spaces) {
|
function sanitizeObjects(object: any, spaces: boolean): object {
|
||||||
/** @type {any} */
|
/** @type {any} */
|
||||||
let objectUpdated = { ...object };
|
let objectUpdated: any = { ...object };
|
||||||
const keys = Object.keys(objectUpdated);
|
const keys = Object.keys(objectUpdated);
|
||||||
|
|
||||||
keys.forEach((key) => {
|
keys.forEach((key) => {
|
||||||
@ -98,7 +90,10 @@ function sanitizeObjects(object, spaces) {
|
|||||||
*
|
*
|
||||||
* @returns {string[]|number[]|object[]}
|
* @returns {string[]|number[]|object[]}
|
||||||
*/
|
*/
|
||||||
function sanitizeArrays(array, spaces) {
|
function sanitizeArrays(
|
||||||
|
array: any[],
|
||||||
|
spaces: boolean
|
||||||
|
): string[] | number[] | object[] {
|
||||||
let arrayUpdated = _.cloneDeep(array);
|
let arrayUpdated = _.cloneDeep(array);
|
||||||
|
|
||||||
arrayUpdated.forEach((item, index) => {
|
arrayUpdated.forEach((item, index) => {
|
||||||
@ -121,4 +116,4 @@ function sanitizeArrays(array, spaces) {
|
|||||||
return arrayUpdated;
|
return arrayUpdated;
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports = sanitizeSql;
|
export default sanitizeSql;
|
@ -1,37 +0,0 @@
|
|||||||
export = updateDbEntry;
|
|
||||||
/**
|
|
||||||
* Update DB Function
|
|
||||||
* ==============================================================================
|
|
||||||
* @description Description
|
|
||||||
* @async
|
|
||||||
*
|
|
||||||
* @param {object} params - An object containing the function parameters.
|
|
||||||
* @param {("Master" | "Dsql User")} [params.dbContext] - What is the database context? "Master"
|
|
||||||
* or "Dsql User". Defaults to "Master"
|
|
||||||
* @param {("Read Only" | "Full Access")} [params.paradigm] - What is the paradigm for "Dsql User"?
|
|
||||||
* "Read only" or "Full Access"? Defaults to "Read Only"
|
|
||||||
* @param {string} [params.dbFullName] - Database full name
|
|
||||||
* @param {string} params.tableName - Table name
|
|
||||||
* @param {string} [params.encryptionKey]
|
|
||||||
* @param {string} [params.encryptionSalt]
|
|
||||||
* @param {any} params.data - Data to add
|
|
||||||
* @param {import("../../../types").DSQL_TableSchemaType} [params.tableSchema] - Table schema
|
|
||||||
* @param {string} params.identifierColumnName - Update row identifier column name
|
|
||||||
* @param {string | number} params.identifierValue - Update row identifier column value
|
|
||||||
* @param {boolean} [params.useLocal]
|
|
||||||
*
|
|
||||||
* @returns {Promise<object|null>}
|
|
||||||
*/
|
|
||||||
declare function updateDbEntry({ dbContext, paradigm, dbFullName, tableName, data, tableSchema, identifierColumnName, identifierValue, encryptionKey, encryptionSalt, useLocal, }: {
|
|
||||||
dbContext?: ("Master" | "Dsql User");
|
|
||||||
paradigm?: ("Read Only" | "Full Access");
|
|
||||||
dbFullName?: string;
|
|
||||||
tableName: string;
|
|
||||||
encryptionKey?: string;
|
|
||||||
encryptionSalt?: string;
|
|
||||||
data: any;
|
|
||||||
tableSchema?: import("../../../types").DSQL_TableSchemaType;
|
|
||||||
identifierColumnName: string;
|
|
||||||
identifierValue: string | number;
|
|
||||||
useLocal?: boolean;
|
|
||||||
}): Promise<object | null>;
|
|
@ -1,39 +1,29 @@
|
|||||||
// @ts-check
|
import sanitizeHtml from "sanitize-html";
|
||||||
|
import sanitizeHtmlOptions from "../html/sanitizeHtmlOptions";
|
||||||
|
import DB_HANDLER from "../../../utils/backend/global-db/DB_HANDLER";
|
||||||
|
import DSQL_USER_DB_HANDLER from "../../../utils/backend/global-db/DSQL_USER_DB_HANDLER";
|
||||||
|
import encrypt from "../../dsql/encrypt";
|
||||||
|
import LOCAL_DB_HANDLER from "../../../utils/backend/global-db/LOCAL_DB_HANDLER";
|
||||||
|
|
||||||
|
type Param = {
|
||||||
|
dbContext?: "Master" | "Dsql User";
|
||||||
|
paradigm?: "Read Only" | "Full Access";
|
||||||
|
dbFullName?: string;
|
||||||
|
tableName: string;
|
||||||
|
encryptionKey?: string;
|
||||||
|
encryptionSalt?: string;
|
||||||
|
data: any;
|
||||||
|
tableSchema?: import("../../../types").DSQL_TableSchemaType;
|
||||||
|
identifierColumnName: string;
|
||||||
|
identifierValue: string | number;
|
||||||
|
useLocal?: boolean;
|
||||||
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Imports: Handle imports
|
* # Update DB Function
|
||||||
|
* @description
|
||||||
*/
|
*/
|
||||||
const sanitizeHtml = require("sanitize-html");
|
export default async function updateDbEntry({
|
||||||
const sanitizeHtmlOptions = require("../html/sanitizeHtmlOptions");
|
|
||||||
const DB_HANDLER = require("../../../utils/backend/global-db/DB_HANDLER");
|
|
||||||
const DSQL_USER_DB_HANDLER = require("../../../utils/backend/global-db/DSQL_USER_DB_HANDLER");
|
|
||||||
const encrypt = require("../../dsql/encrypt");
|
|
||||||
const LOCAL_DB_HANDLER = require("../../../utils/backend/global-db/LOCAL_DB_HANDLER");
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Update DB Function
|
|
||||||
* ==============================================================================
|
|
||||||
* @description Description
|
|
||||||
* @async
|
|
||||||
*
|
|
||||||
* @param {object} params - An object containing the function parameters.
|
|
||||||
* @param {("Master" | "Dsql User")} [params.dbContext] - What is the database context? "Master"
|
|
||||||
* or "Dsql User". Defaults to "Master"
|
|
||||||
* @param {("Read Only" | "Full Access")} [params.paradigm] - What is the paradigm for "Dsql User"?
|
|
||||||
* "Read only" or "Full Access"? Defaults to "Read Only"
|
|
||||||
* @param {string} [params.dbFullName] - Database full name
|
|
||||||
* @param {string} params.tableName - Table name
|
|
||||||
* @param {string} [params.encryptionKey]
|
|
||||||
* @param {string} [params.encryptionSalt]
|
|
||||||
* @param {any} params.data - Data to add
|
|
||||||
* @param {import("../../../types").DSQL_TableSchemaType} [params.tableSchema] - Table schema
|
|
||||||
* @param {string} params.identifierColumnName - Update row identifier column name
|
|
||||||
* @param {string | number} params.identifierValue - Update row identifier column value
|
|
||||||
* @param {boolean} [params.useLocal]
|
|
||||||
*
|
|
||||||
* @returns {Promise<object|null>}
|
|
||||||
*/
|
|
||||||
async function updateDbEntry({
|
|
||||||
dbContext,
|
dbContext,
|
||||||
paradigm,
|
paradigm,
|
||||||
dbFullName,
|
dbFullName,
|
||||||
@ -45,7 +35,7 @@ async function updateDbEntry({
|
|||||||
encryptionKey,
|
encryptionKey,
|
||||||
encryptionSalt,
|
encryptionSalt,
|
||||||
useLocal,
|
useLocal,
|
||||||
}) {
|
}: Param): Promise<object | null> {
|
||||||
/**
|
/**
|
||||||
* Check if data is valid
|
* Check if data is valid
|
||||||
*/
|
*/
|
||||||
@ -60,7 +50,7 @@ async function updateDbEntry({
|
|||||||
: true;
|
: true;
|
||||||
|
|
||||||
/** @type {(a1:any, a2?:any)=> any } */
|
/** @type {(a1:any, a2?:any)=> any } */
|
||||||
const dbHandler = useLocal
|
const dbHandler: (a1: any, a2?: any) => any = useLocal
|
||||||
? LOCAL_DB_HANDLER
|
? LOCAL_DB_HANDLER
|
||||||
: isMaster
|
: isMaster
|
||||||
? DB_HANDLER
|
? DB_HANDLER
|
||||||
@ -153,7 +143,7 @@ async function updateDbEntry({
|
|||||||
|
|
||||||
////////////////////////////////////////
|
////////////////////////////////////////
|
||||||
////////////////////////////////////////
|
////////////////////////////////////////
|
||||||
} catch (/** @type {any} */ error) {
|
} catch (/** @type {any} */ error: any) {
|
||||||
////////////////////////////////////////
|
////////////////////////////////////////
|
||||||
////////////////////////////////////////
|
////////////////////////////////////////
|
||||||
|
|
||||||
@ -189,18 +179,8 @@ async function updateDbEntry({
|
|||||||
queryValues: updateValues,
|
queryValues: updateValues,
|
||||||
});
|
});
|
||||||
|
|
||||||
////////////////////////////////////////
|
|
||||||
////////////////////////////////////////
|
|
||||||
////////////////////////////////////////
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Return statement
|
* Return statement
|
||||||
*/
|
*/
|
||||||
return updatedEntry;
|
return updatedEntry;
|
||||||
}
|
}
|
||||||
|
|
||||||
////////////////////////////////////////
|
|
||||||
////////////////////////////////////////
|
|
||||||
////////////////////////////////////////
|
|
||||||
|
|
||||||
module.exports = updateDbEntry;
|
|
@ -1,10 +1,8 @@
|
|||||||
// @ts-check
|
import fs from "fs";
|
||||||
|
import serverError from "./serverError";
|
||||||
|
|
||||||
const fs = require("fs");
|
import mysql from "serverless-mysql";
|
||||||
const serverError = require("./serverError");
|
import grabDbSSL from "../../utils/backend/grabDbSSL";
|
||||||
|
|
||||||
const mysql = require("serverless-mysql");
|
|
||||||
const grabDbSSL = require("../../utils/backend/grabDbSSL");
|
|
||||||
|
|
||||||
const connection = mysql({
|
const connection = mysql({
|
||||||
config: {
|
config: {
|
||||||
@ -18,14 +16,9 @@ const connection = mysql({
|
|||||||
});
|
});
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Main DB Handler Function
|
* # Main DB Handler Function
|
||||||
* ==============================================================================
|
|
||||||
* @async
|
|
||||||
*
|
|
||||||
* @param {any} args
|
|
||||||
* @returns {Promise<object|null>}
|
|
||||||
*/
|
*/
|
||||||
module.exports = async function dbHandler(...args) {
|
export default async function dbHandler(...args: any[]) {
|
||||||
process.env.NODE_ENV?.match(/dev/) &&
|
process.env.NODE_ENV?.match(/dev/) &&
|
||||||
fs.appendFileSync(
|
fs.appendFileSync(
|
||||||
"./.tmp/sqlQuery.sql",
|
"./.tmp/sqlQuery.sql",
|
||||||
@ -47,18 +40,20 @@ module.exports = async function dbHandler(...args) {
|
|||||||
*/
|
*/
|
||||||
try {
|
try {
|
||||||
results = await new Promise((resolve, reject) => {
|
results = await new Promise((resolve, reject) => {
|
||||||
// @ts-ignore
|
connection.query(
|
||||||
connection.query(...args, (error, result, fields) => {
|
...args,
|
||||||
|
(error: any, result: any, fields: any) => {
|
||||||
if (error) {
|
if (error) {
|
||||||
resolve({ error: error.message });
|
resolve({ error: error.message });
|
||||||
} else {
|
} else {
|
||||||
resolve(result);
|
resolve(result);
|
||||||
}
|
}
|
||||||
});
|
}
|
||||||
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
await connection.end();
|
await connection.end();
|
||||||
} catch (/** @type {any} */ error) {
|
} catch (error: any) {
|
||||||
fs.appendFileSync(
|
fs.appendFileSync(
|
||||||
"./.tmp/dbErrorLogs.txt",
|
"./.tmp/dbErrorLogs.txt",
|
||||||
JSON.stringify(error, null, 4) + "\n" + Date() + "\n\n\n",
|
JSON.stringify(error, null, 4) + "\n" + Date() + "\n\n\n",
|
||||||
@ -83,4 +78,4 @@ module.exports = async function dbHandler(...args) {
|
|||||||
} else {
|
} else {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
};
|
}
|
@ -1,7 +0,0 @@
|
|||||||
export = defaultFieldsRegexp;
|
|
||||||
/**
|
|
||||||
* Regular expression to match default fields
|
|
||||||
*
|
|
||||||
* @description Regular expression to match default fields
|
|
||||||
*/
|
|
||||||
declare const defaultFieldsRegexp: RegExp;
|
|
@ -1,5 +1,3 @@
|
|||||||
// @ts-check
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Regular expression to match default fields
|
* Regular expression to match default fields
|
||||||
*
|
*
|
||||||
@ -8,4 +6,4 @@
|
|||||||
const defaultFieldsRegexp =
|
const defaultFieldsRegexp =
|
||||||
/^id$|^uuid$|^date_created$|^date_created_code$|^date_created_timestamp$|^date_updated$|^date_updated_code$|^date_updated_timestamp$/;
|
/^id$|^uuid$|^date_created$|^date_created_code$|^date_created_timestamp$|^date_updated$|^date_updated_code$|^date_updated_timestamp$/;
|
||||||
|
|
||||||
module.exports = defaultFieldsRegexp;
|
export default defaultFieldsRegexp;
|
@ -1,8 +0,0 @@
|
|||||||
declare function _exports({ queryString, database, tableSchema, queryValuesArray, local, }: {
|
|
||||||
queryString: string;
|
|
||||||
database: string;
|
|
||||||
local?: boolean;
|
|
||||||
tableSchema?: import("../../types").DSQL_TableSchemaType | null;
|
|
||||||
queryValuesArray?: string[];
|
|
||||||
}): Promise<any>;
|
|
||||||
export = _exports;
|
|
@ -1,27 +1,28 @@
|
|||||||
// @ts-check
|
// @ts-check
|
||||||
|
|
||||||
const DSQL_USER_DB_HANDLER = require("../../utils/backend/global-db/DSQL_USER_DB_HANDLER");
|
import DSQL_USER_DB_HANDLER from "../../utils/backend/global-db/DSQL_USER_DB_HANDLER";
|
||||||
const LOCAL_DB_HANDLER = require("../../utils/backend/global-db/LOCAL_DB_HANDLER");
|
import LOCAL_DB_HANDLER from "../../utils/backend/global-db/LOCAL_DB_HANDLER";
|
||||||
const parseDbResults = require("./parseDbResults");
|
import parseDbResults from "./parseDbResults";
|
||||||
const serverError = require("./serverError");
|
import serverError from "./serverError";
|
||||||
|
|
||||||
|
type Param = {
|
||||||
|
queryString: string;
|
||||||
|
database: string;
|
||||||
|
local?: boolean;
|
||||||
|
tableSchema?: import("../../types").DSQL_TableSchemaType | null;
|
||||||
|
queryValuesArray?: string[];
|
||||||
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
*
|
* # Full Access Db Handler
|
||||||
* @param {object} param0
|
|
||||||
* @param {string} param0.queryString
|
|
||||||
* @param {string} param0.database
|
|
||||||
* @param {boolean} [param0.local]
|
|
||||||
* @param {import("../../types").DSQL_TableSchemaType | null} [param0.tableSchema]
|
|
||||||
* @param {string[]} [param0.queryValuesArray]
|
|
||||||
* @returns
|
|
||||||
*/
|
*/
|
||||||
module.exports = async function fullAccessDbHandler({
|
export default async function fullAccessDbHandler({
|
||||||
queryString,
|
queryString,
|
||||||
database,
|
database,
|
||||||
tableSchema,
|
tableSchema,
|
||||||
queryValuesArray,
|
queryValuesArray,
|
||||||
local,
|
local,
|
||||||
}) {
|
}: Param) {
|
||||||
/**
|
/**
|
||||||
* Declare variables
|
* Declare variables
|
||||||
*
|
*
|
||||||
@ -47,7 +48,7 @@ module.exports = async function fullAccessDbHandler({
|
|||||||
});
|
});
|
||||||
|
|
||||||
////////////////////////////////////////
|
////////////////////////////////////////
|
||||||
} catch (/** @type {any} */ error) {
|
} catch (/** @type {any} */ error: any) {
|
||||||
////////////////////////////////////////
|
////////////////////////////////////////
|
||||||
|
|
||||||
serverError({
|
serverError({
|
||||||
@ -78,4 +79,4 @@ module.exports = async function fullAccessDbHandler({
|
|||||||
} else {
|
} else {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
};
|
}
|
@ -1,6 +0,0 @@
|
|||||||
declare function _exports(params?: {
|
|
||||||
payload?: {
|
|
||||||
[x: string]: any;
|
|
||||||
};
|
|
||||||
}): import("../../types").DSQL_TableSchemaType | null;
|
|
||||||
export = _exports;
|
|
@ -1,22 +1,16 @@
|
|||||||
// @ts-check
|
import { DSQL_FieldSchemaType, DSQL_TableSchemaType } from "../../types";
|
||||||
|
import grabSchemaFieldsFromData from "./grabSchemaFieldsFromData";
|
||||||
const grabSchemaFieldsFromData = require("./grabSchemaFieldsFromData");
|
import serverError from "./serverError";
|
||||||
const serverError = require("./serverError");
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* # Add User Table to Database
|
* # Add User Table to Database
|
||||||
*
|
|
||||||
* @param {object} [params]
|
|
||||||
* @param {Object<string,any>} [params.payload] - fields to add to the table
|
|
||||||
*
|
|
||||||
* @returns {import("../../types").DSQL_TableSchemaType | null} new user auth object payload
|
|
||||||
*/
|
*/
|
||||||
module.exports = function grabNewUsersTableSchema(params) {
|
export default function grabNewUsersTableSchema(params: {
|
||||||
|
payload?: { [s: string]: any };
|
||||||
|
}): DSQL_TableSchemaType | null {
|
||||||
try {
|
try {
|
||||||
/** @type {import("../../types").DSQL_TableSchemaType} */
|
const userPreset: DSQL_TableSchemaType = require("../../data/presets/users.json");
|
||||||
const userPreset = require("../../data/presets/users.json");
|
const defaultFields: DSQL_FieldSchemaType[] = require("../../data/defaultFields.json");
|
||||||
/** @type {import("../../types").DSQL_FieldSchemaType[]} */
|
|
||||||
const defaultFields = require("../../data/defaultFields.json");
|
|
||||||
|
|
||||||
const supplementalFields = params?.payload
|
const supplementalFields = params?.payload
|
||||||
? grabSchemaFieldsFromData({
|
? grabSchemaFieldsFromData({
|
||||||
@ -41,7 +35,7 @@ module.exports = function grabNewUsersTableSchema(params) {
|
|||||||
userPreset.fields = [...finalFields];
|
userPreset.fields = [...finalFields];
|
||||||
|
|
||||||
return userPreset;
|
return userPreset;
|
||||||
} catch (/** @type {any} */ error) {
|
} catch (/** @type {any} */ error: any) {
|
||||||
console.log(`grabNewUsersTableSchema.js ERROR: ${error.message}`);
|
console.log(`grabNewUsersTableSchema.js ERROR: ${error.message}`);
|
||||||
|
|
||||||
serverError({
|
serverError({
|
||||||
@ -51,4 +45,4 @@ module.exports = function grabNewUsersTableSchema(params) {
|
|||||||
|
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
};
|
}
|
@ -1,11 +0,0 @@
|
|||||||
declare function _exports({ data, fields, excludeData, excludeFields, }: {
|
|
||||||
data?: {
|
|
||||||
[x: string]: any;
|
|
||||||
};
|
|
||||||
fields?: string[];
|
|
||||||
excludeData?: {
|
|
||||||
[x: string]: any;
|
|
||||||
};
|
|
||||||
excludeFields?: import("../../types").DSQL_FieldSchemaType[];
|
|
||||||
}): import("../../types").DSQL_FieldSchemaType[];
|
|
||||||
export = _exports;
|
|
@ -1,33 +1,31 @@
|
|||||||
// @ts-check
|
import { DSQL_FieldSchemaType } from "../../types";
|
||||||
|
import serverError from "./serverError";
|
||||||
|
|
||||||
const serverError = require("./serverError");
|
type Param = {
|
||||||
|
data?: { [s: string]: any };
|
||||||
|
fields?: string[];
|
||||||
|
excludeData?: { [s: string]: any };
|
||||||
|
excludeFields?: DSQL_FieldSchemaType[];
|
||||||
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* # Add User Table to Database
|
* # Add User Table to Database
|
||||||
*
|
|
||||||
* @param {object} params
|
|
||||||
* @param {Object<string,any>} [params.data]
|
|
||||||
* @param {string[]} [params.fields]
|
|
||||||
* @param {Object<string,any>} [params.excludeData]
|
|
||||||
* @param {import("../../types").DSQL_FieldSchemaType[]} [params.excludeFields]
|
|
||||||
*
|
|
||||||
* @returns {import("../../types").DSQL_FieldSchemaType[]} new user auth object payload
|
|
||||||
*/
|
*/
|
||||||
module.exports = function grabSchemaFieldsFromData({
|
export default function grabSchemaFieldsFromData({
|
||||||
data,
|
data,
|
||||||
fields,
|
fields,
|
||||||
excludeData,
|
excludeData,
|
||||||
excludeFields,
|
excludeFields,
|
||||||
}) {
|
}: Param): DSQL_FieldSchemaType[] {
|
||||||
try {
|
try {
|
||||||
const possibleFields = require("../../data/possibleFields.json");
|
const possibleFields = require("../../data/possibleFields.json");
|
||||||
const dataTypes = require("../../data/dataTypes.json");
|
const dataTypes = require("../../data/dataTypes.json");
|
||||||
|
|
||||||
/** @type {import("../../types").DSQL_FieldSchemaType[]} */
|
/** @type {DSQL_FieldSchemaType[]} */
|
||||||
const finalFields = [];
|
const finalFields: DSQL_FieldSchemaType[] = [];
|
||||||
|
|
||||||
/** @type {string[]} */
|
/** @type {string[]} */
|
||||||
let filteredFields = [];
|
let filteredFields: string[] = [];
|
||||||
|
|
||||||
if (data && Object.keys(data)?.[0]) {
|
if (data && Object.keys(data)?.[0]) {
|
||||||
filteredFields = Object.keys(data);
|
filteredFields = Object.keys(data);
|
||||||
@ -52,11 +50,10 @@ module.exports = function grabSchemaFieldsFromData({
|
|||||||
const value = data ? data[fld] : null;
|
const value = data ? data[fld] : null;
|
||||||
|
|
||||||
if (typeof value == "string") {
|
if (typeof value == "string") {
|
||||||
const newField =
|
const newField: DSQL_FieldSchemaType = {
|
||||||
/** @type {import("../../types").DSQL_FieldSchemaType} */ ({
|
|
||||||
fieldName: fld,
|
fieldName: fld,
|
||||||
dataType: value.length > 255 ? "TEXT" : "VARCHAR(255)",
|
dataType: value.length > 255 ? "TEXT" : "VARCHAR(255)",
|
||||||
});
|
};
|
||||||
|
|
||||||
if (Boolean(value.match(/<[^>]+>/g))) {
|
if (Boolean(value.match(/<[^>]+>/g))) {
|
||||||
newField.richText = true;
|
newField.richText = true;
|
||||||
@ -64,24 +61,20 @@ module.exports = function grabSchemaFieldsFromData({
|
|||||||
|
|
||||||
finalFields.push(newField);
|
finalFields.push(newField);
|
||||||
} else if (typeof value == "number") {
|
} else if (typeof value == "number") {
|
||||||
finalFields.push(
|
finalFields.push({
|
||||||
/** @type {import("../../types").DSQL_FieldSchemaType} */ ({
|
|
||||||
fieldName: fld,
|
fieldName: fld,
|
||||||
dataType: "INT",
|
dataType: "INT",
|
||||||
})
|
});
|
||||||
);
|
|
||||||
} else {
|
} else {
|
||||||
finalFields.push(
|
finalFields.push({
|
||||||
/** @type {import("../../types").DSQL_FieldSchemaType} */ ({
|
|
||||||
fieldName: fld,
|
fieldName: fld,
|
||||||
dataType: "VARCHAR(255)",
|
dataType: "VARCHAR(255)",
|
||||||
})
|
});
|
||||||
);
|
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
return finalFields;
|
return finalFields;
|
||||||
} catch (/** @type {any} */ error) {
|
} catch (/** @type {any} */ error: any) {
|
||||||
console.log(`grabSchemaFieldsFromData.js ERROR: ${error.message}`);
|
console.log(`grabSchemaFieldsFromData.js ERROR: ${error.message}`);
|
||||||
|
|
||||||
serverError({
|
serverError({
|
||||||
@ -91,4 +84,4 @@ module.exports = function grabSchemaFieldsFromData({
|
|||||||
|
|
||||||
return [];
|
return [];
|
||||||
}
|
}
|
||||||
};
|
}
|
@ -1,4 +0,0 @@
|
|||||||
declare function _exports({ userId }: {
|
|
||||||
userId: string | number;
|
|
||||||
}): import("../../types").DSQL_DatabaseSchemaType[] | null;
|
|
||||||
export = _exports;
|
|
@ -1,46 +0,0 @@
|
|||||||
// @ts-check
|
|
||||||
|
|
||||||
const serverError = require("./serverError");
|
|
||||||
const fs = require("fs");
|
|
||||||
const path = require("path");
|
|
||||||
|
|
||||||
/** ****************************************************************************** */
|
|
||||||
/** ****************************************************************************** */
|
|
||||||
/** ****************************************************************************** */
|
|
||||||
/** ****************************************************************************** */
|
|
||||||
/** ****************************************************************************** */
|
|
||||||
/** ****************************************************************************** */
|
|
||||||
|
|
||||||
/**
|
|
||||||
* ==============================================================================
|
|
||||||
* @param {Object} params
|
|
||||||
* @param {string | number} params.userId
|
|
||||||
* @returns {import("../../types").DSQL_DatabaseSchemaType[] | null}
|
|
||||||
*/
|
|
||||||
module.exports = function grabUserSchemaData({ userId }) {
|
|
||||||
try {
|
|
||||||
const userSchemaFilePath = path.resolve(
|
|
||||||
process.cwd(),
|
|
||||||
`${process.env.DSQL_USER_DB_SCHEMA_PATH}/user-${userId}/main.json`
|
|
||||||
);
|
|
||||||
const userSchemaData = JSON.parse(
|
|
||||||
fs.readFileSync(userSchemaFilePath, "utf-8")
|
|
||||||
);
|
|
||||||
|
|
||||||
return userSchemaData;
|
|
||||||
} catch (/** @type {any} */ error) {
|
|
||||||
serverError({
|
|
||||||
component: "grabUserSchemaData",
|
|
||||||
message: error.message,
|
|
||||||
});
|
|
||||||
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
/** ****************************************************************************** */
|
|
||||||
/** ****************************************************************************** */
|
|
||||||
/** ****************************************************************************** */
|
|
||||||
/** ****************************************************************************** */
|
|
||||||
/** ****************************************************************************** */
|
|
||||||
/** ****************************************************************************** */
|
|
31
package-shared/functions/backend/grabUserSchemaData.ts
Executable file
31
package-shared/functions/backend/grabUserSchemaData.ts
Executable file
@ -0,0 +1,31 @@
|
|||||||
|
import serverError from "./serverError";
|
||||||
|
import fs from "fs";
|
||||||
|
import path from "path";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* # Grab User Schema Data
|
||||||
|
*/
|
||||||
|
export default function grabUserSchemaData({
|
||||||
|
userId,
|
||||||
|
}: {
|
||||||
|
userId: string | number;
|
||||||
|
}): import("../../types").DSQL_DatabaseSchemaType[] | null {
|
||||||
|
try {
|
||||||
|
const userSchemaFilePath = path.resolve(
|
||||||
|
process.cwd(),
|
||||||
|
`${process.env.DSQL_USER_DB_SCHEMA_PATH}/user-${userId}/main.json`
|
||||||
|
);
|
||||||
|
const userSchemaData = JSON.parse(
|
||||||
|
fs.readFileSync(userSchemaFilePath, "utf-8")
|
||||||
|
);
|
||||||
|
|
||||||
|
return userSchemaData;
|
||||||
|
} catch (error: any) {
|
||||||
|
serverError({
|
||||||
|
component: "grabUserSchemaData",
|
||||||
|
message: error.message,
|
||||||
|
});
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user