Compare commits
3 Commits
549d0abc02
...
a3561da53d
Author | SHA1 | Date | |
---|---|---|---|
![]() |
a3561da53d | ||
![]() |
9192dae0b5 | ||
![]() |
eb0992f28d |
1
.gitignore
vendored
1
.gitignore
vendored
@ -90,7 +90,6 @@ out
|
|||||||
|
|
||||||
# Nuxt.js build / generate output
|
# Nuxt.js build / generate output
|
||||||
.nuxt
|
.nuxt
|
||||||
dist
|
|
||||||
|
|
||||||
# Gatsby files
|
# Gatsby files
|
||||||
.cache/
|
.cache/
|
||||||
|
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;
|
||||||
|
}
|
31
console-colors.ts
Normal file
31
console-colors.ts
Normal file
@ -0,0 +1,31 @@
|
|||||||
|
const colors = {
|
||||||
|
Reset: "\x1b[0m",
|
||||||
|
Bright: "\x1b[1m",
|
||||||
|
Dim: "\x1b[2m",
|
||||||
|
Underscore: "\x1b[4m",
|
||||||
|
Blink: "\x1b[5m",
|
||||||
|
Reverse: "\x1b[7m",
|
||||||
|
Hidden: "\x1b[8m",
|
||||||
|
|
||||||
|
FgBlack: "\x1b[30m",
|
||||||
|
FgRed: "\x1b[31m",
|
||||||
|
FgGreen: "\x1b[32m",
|
||||||
|
FgYellow: "\x1b[33m",
|
||||||
|
FgBlue: "\x1b[34m",
|
||||||
|
FgMagenta: "\x1b[35m",
|
||||||
|
FgCyan: "\x1b[36m",
|
||||||
|
FgWhite: "\x1b[37m",
|
||||||
|
FgGray: "\x1b[90m",
|
||||||
|
|
||||||
|
BgBlack: "\x1b[40m",
|
||||||
|
BgRed: "\x1b[41m",
|
||||||
|
BgGreen: "\x1b[42m",
|
||||||
|
BgYellow: "\x1b[43m",
|
||||||
|
BgBlue: "\x1b[44m",
|
||||||
|
BgMagenta: "\x1b[45m",
|
||||||
|
BgCyan: "\x1b[46m",
|
||||||
|
BgWhite: "\x1b[47m",
|
||||||
|
BgGray: "\x1b[100m",
|
||||||
|
};
|
||||||
|
|
||||||
|
export default colors;
|
13
dist/client/auth/github/getAccessToken.d.ts
vendored
Normal file
13
dist/client/auth/github/getAccessToken.d.ts
vendored
Normal file
@ -0,0 +1,13 @@
|
|||||||
|
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;
|
||||||
|
export {};
|
15
dist/client/auth/github/getAccessToken.js
vendored
Normal file
15
dist/client/auth/github/getAccessToken.js
vendored
Normal file
@ -0,0 +1,15 @@
|
|||||||
|
"use strict";
|
||||||
|
Object.defineProperty(exports, "__esModule", { value: true });
|
||||||
|
exports.default = getAccessToken;
|
||||||
|
/**
|
||||||
|
* Login with Github Function
|
||||||
|
* ===============================================================================
|
||||||
|
* @description This function uses github api to login a user with datasquirel
|
||||||
|
*/
|
||||||
|
function getAccessToken({ clientId, redirectUrl, setLoading, scopes, }) {
|
||||||
|
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);
|
||||||
|
}
|
18
dist/client/auth/google/getAccessToken.d.ts
vendored
Normal file
18
dist/client/auth/google/getAccessToken.d.ts
vendored
Normal file
@ -0,0 +1,18 @@
|
|||||||
|
interface GoogleGetAccessTokenFunctionParams {
|
||||||
|
clientId: string;
|
||||||
|
triggerPrompt?: boolean;
|
||||||
|
setLoading?: React.Dispatch<React.SetStateAction<boolean>>;
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* Login with Google Function
|
||||||
|
* ===============================================================================
|
||||||
|
* @description This function uses google identity api to login a user with datasquirel
|
||||||
|
*/
|
||||||
|
export default function getAccessToken(params: GoogleGetAccessTokenFunctionParams): Promise<string>;
|
||||||
|
/**
|
||||||
|
* # Google Login Function
|
||||||
|
*/
|
||||||
|
export declare function googleLogin({ google, clientId, setLoading, triggerPrompt, }: GoogleGetAccessTokenFunctionParams & {
|
||||||
|
google: any;
|
||||||
|
}): Promise<unknown>;
|
||||||
|
export {};
|
71
dist/client/auth/google/getAccessToken.js
vendored
Normal file
71
dist/client/auth/google/getAccessToken.js
vendored
Normal file
@ -0,0 +1,71 @@
|
|||||||
|
"use strict";
|
||||||
|
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||||
|
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||||
|
return new (P || (P = Promise))(function (resolve, reject) {
|
||||||
|
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||||
|
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||||
|
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||||
|
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||||
|
});
|
||||||
|
};
|
||||||
|
Object.defineProperty(exports, "__esModule", { value: true });
|
||||||
|
exports.default = getAccessToken;
|
||||||
|
exports.googleLogin = googleLogin;
|
||||||
|
let interval;
|
||||||
|
/**
|
||||||
|
* Login with Google Function
|
||||||
|
* ===============================================================================
|
||||||
|
* @description This function uses google identity api to login a user with datasquirel
|
||||||
|
*/
|
||||||
|
function getAccessToken(params) {
|
||||||
|
return __awaiter(this, void 0, void 0, function* () {
|
||||||
|
var _a, _b;
|
||||||
|
(_a = params.setLoading) === null || _a === void 0 ? void 0 : _a.call(params, true);
|
||||||
|
const response = (yield new Promise((resolve, reject) => {
|
||||||
|
interval = setInterval(() => {
|
||||||
|
// @ts-ignore
|
||||||
|
let google = window.google;
|
||||||
|
if (google) {
|
||||||
|
window.clearInterval(interval);
|
||||||
|
resolve(googleLogin(Object.assign(Object.assign({}, params), { google })));
|
||||||
|
}
|
||||||
|
}, 500);
|
||||||
|
}));
|
||||||
|
(_b = params.setLoading) === null || _b === void 0 ? void 0 : _b.call(params, false);
|
||||||
|
return response;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* # Google Login Function
|
||||||
|
*/
|
||||||
|
function googleLogin({ google, clientId, setLoading, triggerPrompt, }) {
|
||||||
|
setTimeout(() => {
|
||||||
|
setLoading === null || setLoading === void 0 ? void 0 : setLoading(false);
|
||||||
|
}, 3000);
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
/**
|
||||||
|
* # Callback Function
|
||||||
|
* @param {import("../../../package-shared/types").GoogleAccessTokenObject} response
|
||||||
|
*/
|
||||||
|
function handleCredentialResponse(response) {
|
||||||
|
resolve(response.access_token);
|
||||||
|
}
|
||||||
|
const googleAuth = google.accounts.oauth2.initTokenClient({
|
||||||
|
client_id: clientId,
|
||||||
|
scope: "email profile",
|
||||||
|
callback: handleCredentialResponse,
|
||||||
|
});
|
||||||
|
googleAuth.requestAccessToken();
|
||||||
|
if (triggerPrompt) {
|
||||||
|
google.accounts.id.prompt(triggerGooglePromptCallback);
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* Google prompt notification callback
|
||||||
|
* ========================================================
|
||||||
|
* @param {import("../../../package-shared/types").GoogleIdentityPromptNotification} notification
|
||||||
|
*/
|
||||||
|
function triggerGooglePromptCallback(notification) {
|
||||||
|
console.log(notification);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
8
dist/client/auth/logout.d.ts
vendored
Normal file
8
dist/client/auth/logout.d.ts
vendored
Normal file
@ -0,0 +1,8 @@
|
|||||||
|
/**
|
||||||
|
* Login with Google Function
|
||||||
|
* ===============================================================================
|
||||||
|
* @description This function uses google identity api to login a user with datasquirel
|
||||||
|
*/
|
||||||
|
export default function logout(params: {
|
||||||
|
[s: string]: any;
|
||||||
|
} | null): Promise<boolean>;
|
102
dist/client/auth/logout.js
vendored
Normal file
102
dist/client/auth/logout.js
vendored
Normal file
@ -0,0 +1,102 @@
|
|||||||
|
"use strict";
|
||||||
|
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||||
|
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||||
|
return new (P || (P = Promise))(function (resolve, reject) {
|
||||||
|
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||||
|
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||||
|
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||||
|
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||||
|
});
|
||||||
|
};
|
||||||
|
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||||
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||||
|
};
|
||||||
|
Object.defineProperty(exports, "__esModule", { value: true });
|
||||||
|
exports.default = logout;
|
||||||
|
const parseClientCookies_1 = __importDefault(require("../utils/parseClientCookies"));
|
||||||
|
/**
|
||||||
|
* Login with Google Function
|
||||||
|
* ===============================================================================
|
||||||
|
* @description This function uses google identity api to login a user with datasquirel
|
||||||
|
*/
|
||||||
|
function logout(params) {
|
||||||
|
return __awaiter(this, void 0, void 0, function* () {
|
||||||
|
try {
|
||||||
|
const localUser = localStorage.getItem("user");
|
||||||
|
let targetUser;
|
||||||
|
try {
|
||||||
|
targetUser = JSON.parse(localUser || "");
|
||||||
|
}
|
||||||
|
catch (error) {
|
||||||
|
console.log(error);
|
||||||
|
}
|
||||||
|
if (!targetUser) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
////////////////////////////////////////
|
||||||
|
////////////////////////////////////////
|
||||||
|
////////////////////////////////////////
|
||||||
|
const cookies = (0, parseClientCookies_1.default)();
|
||||||
|
const socialId = (cookies === null || cookies === void 0 ? void 0 : cookies.datasquirel_social_id) &&
|
||||||
|
typeof cookies.datasquirel_social_id == "string" &&
|
||||||
|
!cookies.datasquirel_social_id.match(/^null$/i)
|
||||||
|
? cookies.datasquirel_social_id
|
||||||
|
: null;
|
||||||
|
////////////////////////////////////////
|
||||||
|
////////////////////////////////////////
|
||||||
|
////////////////////////////////////////
|
||||||
|
localStorage.setItem("user", "{}");
|
||||||
|
localStorage.removeItem("csrf");
|
||||||
|
document.cookie = `datasquirel_social_id=null;samesite=strict;path=/`;
|
||||||
|
////////////////////////////////////////
|
||||||
|
////////////////////////////////////////
|
||||||
|
////////////////////////////////////////
|
||||||
|
const response = yield new Promise((resolve, reject) => {
|
||||||
|
if (socialId && !(socialId === null || socialId === void 0 ? void 0 : socialId.match(/^null$/i))) {
|
||||||
|
const googleClientId = params === null || params === void 0 ? void 0 : params.googleClientId;
|
||||||
|
if (googleClientId) {
|
||||||
|
const googleScript = document.createElement("script");
|
||||||
|
googleScript.src = "https://accounts.google.com/gsi/client";
|
||||||
|
googleScript.className = "social-script-tag";
|
||||||
|
document.body.appendChild(googleScript);
|
||||||
|
////////////////////////////////////////
|
||||||
|
////////////////////////////////////////
|
||||||
|
////////////////////////////////////////
|
||||||
|
googleScript.onload = function (e) {
|
||||||
|
// @ts-ignore
|
||||||
|
const google = window.google;
|
||||||
|
if (google) {
|
||||||
|
////////////////////////////////////////
|
||||||
|
////////////////////////////////////////
|
||||||
|
////////////////////////////////////////
|
||||||
|
google.accounts.id.initialize({
|
||||||
|
client_id: googleClientId,
|
||||||
|
});
|
||||||
|
google.accounts.id.revoke(socialId, (done) => {
|
||||||
|
console.log(done.error);
|
||||||
|
resolve(true);
|
||||||
|
});
|
||||||
|
////////////////////////////////////////
|
||||||
|
////////////////////////////////////////
|
||||||
|
////////////////////////////////////////
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
resolve(true);
|
||||||
|
}
|
||||||
|
////////////////////////////////////////
|
||||||
|
////////////////////////////////////////
|
||||||
|
////////////////////////////////////////
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
resolve(true);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
return response;
|
||||||
|
}
|
||||||
|
catch (error) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
21
dist/client/fetch/index.d.ts
vendored
Normal file
21
dist/client/fetch/index.d.ts
vendored
Normal file
@ -0,0 +1,21 @@
|
|||||||
|
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 function fetchApi(url: string, options?: FetchApiOptions, csrf?: boolean,
|
||||||
|
/** Key to use to grab local Storage csrf value. */
|
||||||
|
localStorageCSRFKey?: string): Promise<any>;
|
||||||
|
export {};
|
89
dist/client/fetch/index.js
vendored
Normal file
89
dist/client/fetch/index.js
vendored
Normal file
@ -0,0 +1,89 @@
|
|||||||
|
"use strict";
|
||||||
|
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||||
|
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||||
|
return new (P || (P = Promise))(function (resolve, reject) {
|
||||||
|
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||||
|
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||||
|
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||||
|
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||||
|
});
|
||||||
|
};
|
||||||
|
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||||
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||||
|
};
|
||||||
|
Object.defineProperty(exports, "__esModule", { value: true });
|
||||||
|
exports.default = fetchApi;
|
||||||
|
const lodash_1 = __importDefault(require("lodash"));
|
||||||
|
/**
|
||||||
|
* # Fetch API
|
||||||
|
*/
|
||||||
|
function fetchApi(url, options, csrf,
|
||||||
|
/** Key to use to grab local Storage csrf value. */
|
||||||
|
localStorageCSRFKey) {
|
||||||
|
return __awaiter(this, void 0, void 0, function* () {
|
||||||
|
let data;
|
||||||
|
const csrfValue = localStorage.getItem(localStorageCSRFKey || "csrf");
|
||||||
|
let finalHeaders = {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
};
|
||||||
|
if (csrf && csrfValue) {
|
||||||
|
finalHeaders[`'${csrfValue.replace(/\"/g, "")}'`] = "true";
|
||||||
|
}
|
||||||
|
if (typeof options === "string") {
|
||||||
|
try {
|
||||||
|
let fetchData;
|
||||||
|
switch (options) {
|
||||||
|
case "post":
|
||||||
|
fetchData = yield fetch(url, {
|
||||||
|
method: options,
|
||||||
|
headers: finalHeaders,
|
||||||
|
});
|
||||||
|
data = fetchData.json();
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
fetchData = yield fetch(url);
|
||||||
|
data = fetchData.json();
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (error) {
|
||||||
|
console.log("FetchAPI error #1:", error.message);
|
||||||
|
data = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else if (typeof options === "object") {
|
||||||
|
try {
|
||||||
|
let fetchData;
|
||||||
|
if (options.body && typeof options.body === "object") {
|
||||||
|
let oldOptionsBody = lodash_1.default.cloneDeep(options.body);
|
||||||
|
options.body = JSON.stringify(oldOptionsBody);
|
||||||
|
}
|
||||||
|
if (options.headers) {
|
||||||
|
options.headers = lodash_1.default.merge(options.headers, finalHeaders);
|
||||||
|
const finalOptions = Object.assign({}, options);
|
||||||
|
fetchData = yield fetch(url, finalOptions);
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
const finalOptions = Object.assign(Object.assign({}, options), { headers: finalHeaders });
|
||||||
|
fetchData = yield fetch(url, finalOptions);
|
||||||
|
}
|
||||||
|
data = fetchData.json();
|
||||||
|
}
|
||||||
|
catch (error) {
|
||||||
|
console.log("FetchAPI error #2:", error.message);
|
||||||
|
data = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
try {
|
||||||
|
let fetchData = yield fetch(url);
|
||||||
|
data = yield fetchData.json();
|
||||||
|
}
|
||||||
|
catch (error) {
|
||||||
|
console.log("FetchAPI error #3:", error.message);
|
||||||
|
data = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return data;
|
||||||
|
});
|
||||||
|
}
|
49
dist/client/index.d.ts
vendored
Normal file
49
dist/client/index.d.ts
vendored
Normal file
@ -0,0 +1,49 @@
|
|||||||
|
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 serializeQuery from "../package-shared/utils/serialize-query";
|
||||||
|
import serializeCookies from "../package-shared/utils/serialize-cookies";
|
||||||
|
import numberfy from "../package-shared/utils/numberfy";
|
||||||
|
import slugify from "../package-shared/utils/slugify";
|
||||||
|
/**
|
||||||
|
* Main Export
|
||||||
|
*/
|
||||||
|
declare const datasquirelClient: {
|
||||||
|
media: {
|
||||||
|
imageInputToBase64: typeof imageInputToBase64;
|
||||||
|
imageInputFileToBase64: typeof imageInputFileToBase64;
|
||||||
|
inputFileToBase64: typeof inputFileToBase64;
|
||||||
|
};
|
||||||
|
auth: {
|
||||||
|
google: {
|
||||||
|
getAccessToken: typeof getAccessToken;
|
||||||
|
};
|
||||||
|
github: {
|
||||||
|
getAccessToken: typeof getGithubAccessToken;
|
||||||
|
};
|
||||||
|
logout: typeof logout;
|
||||||
|
};
|
||||||
|
fetch: {
|
||||||
|
fetchApi: typeof fetchApi;
|
||||||
|
clientFetch: typeof fetchApi;
|
||||||
|
};
|
||||||
|
utils: {
|
||||||
|
serializeQuery: typeof serializeQuery;
|
||||||
|
serializeCookies: typeof serializeCookies;
|
||||||
|
EJSON: {
|
||||||
|
parse: (string: string | null | number, reviver?: (this: any, key: string, value: any) => any) => {
|
||||||
|
[s: string]: any;
|
||||||
|
} | {
|
||||||
|
[s: string]: any;
|
||||||
|
}[] | undefined;
|
||||||
|
stringify: (value: any, replacer?: (this: any, key: string, value: any) => any, space?: string | number) => string | undefined;
|
||||||
|
};
|
||||||
|
numberfy: typeof numberfy;
|
||||||
|
slugify: typeof slugify;
|
||||||
|
};
|
||||||
|
};
|
||||||
|
export default datasquirelClient;
|
60
dist/client/index.js
vendored
Normal file
60
dist/client/index.js
vendored
Normal file
@ -0,0 +1,60 @@
|
|||||||
|
"use strict";
|
||||||
|
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||||
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||||
|
};
|
||||||
|
Object.defineProperty(exports, "__esModule", { value: true });
|
||||||
|
const imageInputFileToBase64_1 = __importDefault(require("./media/imageInputFileToBase64"));
|
||||||
|
const imageInputToBase64_1 = __importDefault(require("./media/imageInputToBase64"));
|
||||||
|
const inputFileToBase64_1 = __importDefault(require("./media/inputFileToBase64"));
|
||||||
|
const getAccessToken_1 = __importDefault(require("./auth/google/getAccessToken"));
|
||||||
|
const getAccessToken_2 = __importDefault(require("./auth/github/getAccessToken"));
|
||||||
|
const logout_1 = __importDefault(require("./auth/logout"));
|
||||||
|
const fetch_1 = __importDefault(require("./fetch"));
|
||||||
|
const fetch_2 = __importDefault(require("./fetch"));
|
||||||
|
const serialize_query_1 = __importDefault(require("../package-shared/utils/serialize-query"));
|
||||||
|
const serialize_cookies_1 = __importDefault(require("../package-shared/utils/serialize-cookies"));
|
||||||
|
const ejson_1 = __importDefault(require("../package-shared/utils/ejson"));
|
||||||
|
const numberfy_1 = __importDefault(require("../package-shared/utils/numberfy"));
|
||||||
|
const slugify_1 = __importDefault(require("../package-shared/utils/slugify"));
|
||||||
|
////////////////////////////////////////
|
||||||
|
////////////////////////////////////////
|
||||||
|
////////////////////////////////////////
|
||||||
|
/**
|
||||||
|
* Media Functions Object
|
||||||
|
*/
|
||||||
|
const media = {
|
||||||
|
imageInputToBase64: imageInputToBase64_1.default,
|
||||||
|
imageInputFileToBase64: imageInputFileToBase64_1.default,
|
||||||
|
inputFileToBase64: inputFileToBase64_1.default,
|
||||||
|
};
|
||||||
|
/**
|
||||||
|
* User Auth Object
|
||||||
|
*/
|
||||||
|
const auth = {
|
||||||
|
google: {
|
||||||
|
getAccessToken: getAccessToken_1.default,
|
||||||
|
},
|
||||||
|
github: {
|
||||||
|
getAccessToken: getAccessToken_2.default,
|
||||||
|
},
|
||||||
|
logout: logout_1.default,
|
||||||
|
};
|
||||||
|
const utils = {
|
||||||
|
serializeQuery: serialize_query_1.default,
|
||||||
|
serializeCookies: serialize_cookies_1.default,
|
||||||
|
EJSON: ejson_1.default,
|
||||||
|
numberfy: numberfy_1.default,
|
||||||
|
slugify: slugify_1.default,
|
||||||
|
};
|
||||||
|
/**
|
||||||
|
* Fetch
|
||||||
|
*/
|
||||||
|
const fetch = {
|
||||||
|
fetchApi: fetch_1.default,
|
||||||
|
clientFetch: fetch_2.default,
|
||||||
|
};
|
||||||
|
/**
|
||||||
|
* Main Export
|
||||||
|
*/
|
||||||
|
const datasquirelClient = { media, auth, fetch, utils };
|
||||||
|
exports.default = datasquirelClient;
|
14
dist/client/media/client.d.ts
vendored
Normal file
14
dist/client/media/client.d.ts
vendored
Normal file
@ -0,0 +1,14 @@
|
|||||||
|
import imageInputFileToBase64 from "./imageInputFileToBase64";
|
||||||
|
import imageInputToBase64 from "./imageInputToBase64";
|
||||||
|
/**
|
||||||
|
* ==========================
|
||||||
|
* Main Export
|
||||||
|
* ==========================
|
||||||
|
*/
|
||||||
|
declare const datasquirelClient: {
|
||||||
|
media: {
|
||||||
|
imageInputToBase64: typeof imageInputToBase64;
|
||||||
|
imageInputFileToBase64: typeof imageInputFileToBase64;
|
||||||
|
};
|
||||||
|
};
|
||||||
|
export default datasquirelClient;
|
34
dist/client/media/client.js
vendored
Normal file
34
dist/client/media/client.js
vendored
Normal file
@ -0,0 +1,34 @@
|
|||||||
|
"use strict";
|
||||||
|
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||||
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||||
|
};
|
||||||
|
Object.defineProperty(exports, "__esModule", { value: true });
|
||||||
|
const imageInputFileToBase64_1 = __importDefault(require("./imageInputFileToBase64"));
|
||||||
|
const imageInputToBase64_1 = __importDefault(require("./imageInputToBase64"));
|
||||||
|
/**
|
||||||
|
* ==========================
|
||||||
|
* Media Functions Object
|
||||||
|
* ==========================
|
||||||
|
*/
|
||||||
|
const media = {
|
||||||
|
imageInputToBase64: imageInputToBase64_1.default,
|
||||||
|
imageInputFileToBase64: imageInputFileToBase64_1.default,
|
||||||
|
};
|
||||||
|
/**
|
||||||
|
* ==========================
|
||||||
|
* Media Functions Object
|
||||||
|
* ==========================
|
||||||
|
*/
|
||||||
|
const auth = {
|
||||||
|
imageInputToBase64: imageInputToBase64_1.default,
|
||||||
|
imageInputFileToBase64: imageInputFileToBase64_1.default,
|
||||||
|
};
|
||||||
|
/**
|
||||||
|
* ==========================
|
||||||
|
* Main Export
|
||||||
|
* ==========================
|
||||||
|
*/
|
||||||
|
const datasquirelClient = {
|
||||||
|
media: media,
|
||||||
|
};
|
||||||
|
exports.default = datasquirelClient;
|
11
dist/client/media/imageInputFileToBase64.d.ts
vendored
Normal file
11
dist/client/media/imageInputFileToBase64.d.ts
vendored
Normal file
@ -0,0 +1,11 @@
|
|||||||
|
import { ImageInputFileToBase64FunctionReturn } from "../../package-shared/types";
|
||||||
|
type Param = {
|
||||||
|
imageInputFile: File;
|
||||||
|
maxWidth?: number;
|
||||||
|
imagePreviewNode?: HTMLImageElement;
|
||||||
|
};
|
||||||
|
/**
|
||||||
|
* # Image input File top Base64
|
||||||
|
*/
|
||||||
|
export default function imageInputFileToBase64({ imageInputFile, maxWidth, imagePreviewNode, }: Param): Promise<ImageInputFileToBase64FunctionReturn>;
|
||||||
|
export {};
|
92
dist/client/media/imageInputFileToBase64.js
vendored
Normal file
92
dist/client/media/imageInputFileToBase64.js
vendored
Normal file
@ -0,0 +1,92 @@
|
|||||||
|
"use strict";
|
||||||
|
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||||
|
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||||
|
return new (P || (P = Promise))(function (resolve, reject) {
|
||||||
|
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||||
|
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||||
|
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||||
|
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||||
|
});
|
||||||
|
};
|
||||||
|
Object.defineProperty(exports, "__esModule", { value: true });
|
||||||
|
exports.default = imageInputFileToBase64;
|
||||||
|
/**
|
||||||
|
* # Image input File top Base64
|
||||||
|
*/
|
||||||
|
function imageInputFileToBase64(_a) {
|
||||||
|
return __awaiter(this, arguments, void 0, function* ({ imageInputFile, maxWidth, imagePreviewNode, }) {
|
||||||
|
/**
|
||||||
|
* Make https request
|
||||||
|
*
|
||||||
|
* @description make a request to datasquirel.com
|
||||||
|
*/
|
||||||
|
try {
|
||||||
|
let imageName = imageInputFile.name.replace(/\..*/, "");
|
||||||
|
let imageDataBase64;
|
||||||
|
let imageSize;
|
||||||
|
let canvas = document.createElement("canvas");
|
||||||
|
const MIME_TYPE = imageInputFile.type;
|
||||||
|
const QUALITY = 0.95;
|
||||||
|
const MAX_WIDTH = maxWidth ? maxWidth : null;
|
||||||
|
const file = imageInputFile;
|
||||||
|
const blobURL = URL.createObjectURL(file);
|
||||||
|
const img = new Image();
|
||||||
|
/** ********************* Add source to new image */
|
||||||
|
img.src = blobURL;
|
||||||
|
imageDataBase64 = yield new Promise((res, rej) => {
|
||||||
|
/** ********************* Handle Errors in loading image */
|
||||||
|
img.onerror = function () {
|
||||||
|
URL.revokeObjectURL(this.src);
|
||||||
|
console.log("Cannot load image");
|
||||||
|
};
|
||||||
|
/** ********************* Handle new image when loaded */
|
||||||
|
img.onload = function (e) {
|
||||||
|
const imgEl = e.target;
|
||||||
|
URL.revokeObjectURL(imgEl.src);
|
||||||
|
if (MAX_WIDTH) {
|
||||||
|
const scaleSize = MAX_WIDTH / img.naturalWidth;
|
||||||
|
canvas.width =
|
||||||
|
img.naturalWidth < MAX_WIDTH
|
||||||
|
? img.naturalWidth
|
||||||
|
: MAX_WIDTH;
|
||||||
|
canvas.height =
|
||||||
|
img.naturalWidth < MAX_WIDTH
|
||||||
|
? img.naturalHeight
|
||||||
|
: img.naturalHeight * scaleSize;
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
canvas.width = img.naturalWidth;
|
||||||
|
canvas.height = img.naturalHeight;
|
||||||
|
}
|
||||||
|
const ctx = canvas.getContext("2d");
|
||||||
|
ctx === null || ctx === void 0 ? void 0 : ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
|
||||||
|
const srcEncoded = canvas.toDataURL(MIME_TYPE, QUALITY);
|
||||||
|
if (imagePreviewNode) {
|
||||||
|
imagePreviewNode.src = srcEncoded;
|
||||||
|
}
|
||||||
|
res(srcEncoded);
|
||||||
|
};
|
||||||
|
});
|
||||||
|
imageSize = yield new Promise((res, rej) => {
|
||||||
|
canvas.toBlob((blob) => {
|
||||||
|
res(blob === null || blob === void 0 ? void 0 : blob.size);
|
||||||
|
}, MIME_TYPE, QUALITY);
|
||||||
|
});
|
||||||
|
return {
|
||||||
|
imageBase64: imageDataBase64 === null || imageDataBase64 === void 0 ? void 0 : imageDataBase64.replace(/.*?base64,/, ""),
|
||||||
|
imageBase64Full: imageDataBase64,
|
||||||
|
imageName: imageName,
|
||||||
|
imageSize: imageSize,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
catch (error) {
|
||||||
|
console.log("Image Processing Error! =>", error.message);
|
||||||
|
return {
|
||||||
|
imageBase64: undefined,
|
||||||
|
imageBase64Full: undefined,
|
||||||
|
imageName: undefined,
|
||||||
|
imageSize: undefined,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
15
dist/client/media/imageInputToBase64.d.ts
vendored
Normal file
15
dist/client/media/imageInputToBase64.d.ts
vendored
Normal file
@ -0,0 +1,15 @@
|
|||||||
|
type FunctionReturn = {
|
||||||
|
imageBase64?: string;
|
||||||
|
imageBase64Full?: string;
|
||||||
|
imageName?: string;
|
||||||
|
};
|
||||||
|
type Param = {
|
||||||
|
imageInput: HTMLInputElement;
|
||||||
|
maxWidth?: number;
|
||||||
|
mimeType?: string;
|
||||||
|
};
|
||||||
|
/**
|
||||||
|
* # Image Input Element to Base 64
|
||||||
|
*/
|
||||||
|
export default function imageInputToBase64({ imageInput, maxWidth, mimeType, }: Param): Promise<FunctionReturn>;
|
||||||
|
export {};
|
90
dist/client/media/imageInputToBase64.js
vendored
Normal file
90
dist/client/media/imageInputToBase64.js
vendored
Normal file
@ -0,0 +1,90 @@
|
|||||||
|
"use strict";
|
||||||
|
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||||
|
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||||
|
return new (P || (P = Promise))(function (resolve, reject) {
|
||||||
|
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||||
|
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||||
|
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||||
|
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||||
|
});
|
||||||
|
};
|
||||||
|
Object.defineProperty(exports, "__esModule", { value: true });
|
||||||
|
exports.default = imageInputToBase64;
|
||||||
|
/**
|
||||||
|
* # Image Input Element to Base 64
|
||||||
|
*/
|
||||||
|
function imageInputToBase64(_a) {
|
||||||
|
return __awaiter(this, arguments, void 0, function* ({ imageInput, maxWidth, mimeType, }) {
|
||||||
|
var _b, _c;
|
||||||
|
/**
|
||||||
|
* Make https request
|
||||||
|
*
|
||||||
|
* @description make a request to datasquirel.com
|
||||||
|
*/
|
||||||
|
try {
|
||||||
|
let imagePreviewNode = document.querySelector(`[data-imagepreview='image']`);
|
||||||
|
let imageName = (_b = imageInput.files) === null || _b === void 0 ? void 0 : _b[0].name.replace(/\..*/, "");
|
||||||
|
let imageDataBase64;
|
||||||
|
const MIME_TYPE = mimeType ? mimeType : "image/jpeg";
|
||||||
|
const QUALITY = 0.95;
|
||||||
|
const MAX_WIDTH = maxWidth ? maxWidth : null;
|
||||||
|
const file = (_c = imageInput.files) === null || _c === void 0 ? void 0 : _c[0];
|
||||||
|
const blobURL = file ? URL.createObjectURL(file) : undefined;
|
||||||
|
const img = new Image();
|
||||||
|
if (blobURL) {
|
||||||
|
img.src = blobURL;
|
||||||
|
imageDataBase64 = yield new Promise((res, rej) => {
|
||||||
|
/** ********************* Handle Errors in loading image */
|
||||||
|
img.onerror = function () {
|
||||||
|
URL.revokeObjectURL(this.src);
|
||||||
|
window.alert("Cannot load image!");
|
||||||
|
};
|
||||||
|
img.onload = function (e) {
|
||||||
|
const imgEl = e.target;
|
||||||
|
URL.revokeObjectURL(imgEl.src);
|
||||||
|
const canvas = document.createElement("canvas");
|
||||||
|
if (MAX_WIDTH) {
|
||||||
|
const scaleSize = MAX_WIDTH / img.naturalWidth;
|
||||||
|
canvas.width =
|
||||||
|
img.naturalWidth < MAX_WIDTH
|
||||||
|
? img.naturalWidth
|
||||||
|
: MAX_WIDTH;
|
||||||
|
canvas.height =
|
||||||
|
img.naturalWidth < MAX_WIDTH
|
||||||
|
? img.naturalHeight
|
||||||
|
: img.naturalHeight * scaleSize;
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
canvas.width = img.naturalWidth;
|
||||||
|
canvas.height = img.naturalHeight;
|
||||||
|
}
|
||||||
|
const ctx = canvas.getContext("2d");
|
||||||
|
ctx === null || ctx === void 0 ? void 0 : ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
|
||||||
|
const srcEncoded = canvas.toDataURL(MIME_TYPE, QUALITY);
|
||||||
|
if (imagePreviewNode) {
|
||||||
|
document
|
||||||
|
.querySelectorAll(`[data-imagepreview='image']`)
|
||||||
|
.forEach((_img) => {
|
||||||
|
const _imgEl = _img;
|
||||||
|
_imgEl.src = srcEncoded;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
res(srcEncoded);
|
||||||
|
};
|
||||||
|
});
|
||||||
|
return {
|
||||||
|
imageBase64: imageDataBase64 === null || imageDataBase64 === void 0 ? void 0 : imageDataBase64.replace(/.*?base64,/, ""),
|
||||||
|
imageBase64Full: imageDataBase64,
|
||||||
|
imageName: imageName,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch ( /** @type {*} */error) {
|
||||||
|
console.log("Image Processing Error! =>", error.message);
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
21
dist/client/media/inputFileToBase64.d.ts
vendored
Normal file
21
dist/client/media/inputFileToBase64.d.ts
vendored
Normal file
@ -0,0 +1,21 @@
|
|||||||
|
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 function inputFileToBase64({ inputFile, allowedRegex, }: Param): Promise<FunctionReturn>;
|
||||||
|
export {};
|
59
dist/client/media/inputFileToBase64.js
vendored
Normal file
59
dist/client/media/inputFileToBase64.js
vendored
Normal file
@ -0,0 +1,59 @@
|
|||||||
|
"use strict";
|
||||||
|
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||||
|
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||||
|
return new (P || (P = Promise))(function (resolve, reject) {
|
||||||
|
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||||
|
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||||
|
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||||
|
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||||
|
});
|
||||||
|
};
|
||||||
|
Object.defineProperty(exports, "__esModule", { value: true });
|
||||||
|
exports.default = inputFileToBase64;
|
||||||
|
/**
|
||||||
|
* 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.
|
||||||
|
*/
|
||||||
|
function inputFileToBase64(_a) {
|
||||||
|
return __awaiter(this, arguments, void 0, function* ({ inputFile, allowedRegex, }) {
|
||||||
|
var _b;
|
||||||
|
const allowedTypesRegex = allowedRegex ? allowedRegex : /image\/*|\/pdf/;
|
||||||
|
if (!((_b = inputFile === null || inputFile === void 0 ? void 0 : inputFile.type) === null || _b === void 0 ? void 0 : _b.match(allowedTypesRegex))) {
|
||||||
|
window.alert(`We currently don't support ${inputFile.type} file types. Support is coming soon. For now we support only images and PDFs.`);
|
||||||
|
return {
|
||||||
|
fileName: inputFile.name,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
let fileName = inputFile.name.replace(/\..*/, "");
|
||||||
|
const fileData = yield new Promise((resolve, reject) => {
|
||||||
|
var reader = new FileReader();
|
||||||
|
reader.readAsDataURL(inputFile);
|
||||||
|
reader.onload = function () {
|
||||||
|
var _a;
|
||||||
|
resolve((_a = reader.result) === null || _a === void 0 ? void 0 : _a.toString());
|
||||||
|
};
|
||||||
|
reader.onerror = function (/** @type {*} */ error) {
|
||||||
|
console.log("Error: ", error.message);
|
||||||
|
};
|
||||||
|
});
|
||||||
|
return {
|
||||||
|
fileBase64: fileData === null || fileData === void 0 ? void 0 : fileData.replace(/.*?base64,/, ""),
|
||||||
|
fileBase64Full: fileData,
|
||||||
|
fileName: fileName,
|
||||||
|
fileSize: inputFile.size,
|
||||||
|
fileType: inputFile.type,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
catch (error) {
|
||||||
|
console.log("File Processing Error! =>", error.message);
|
||||||
|
return {
|
||||||
|
fileName: inputFile.name,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
8
dist/client/utils/parseClientCookies.d.ts
vendored
Normal file
8
dist/client/utils/parseClientCookies.d.ts
vendored
Normal file
@ -0,0 +1,8 @@
|
|||||||
|
/**
|
||||||
|
* 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;
|
31
dist/client/utils/parseClientCookies.js
vendored
Normal file
31
dist/client/utils/parseClientCookies.js
vendored
Normal file
@ -0,0 +1,31 @@
|
|||||||
|
"use strict";
|
||||||
|
Object.defineProperty(exports, "__esModule", { value: true });
|
||||||
|
exports.default = default_1;
|
||||||
|
/**
|
||||||
|
* Parse request cookies
|
||||||
|
* ============================================================================== *
|
||||||
|
* @description This function takes in a request object and returns the cookies as a JS object
|
||||||
|
*/
|
||||||
|
function default_1() {
|
||||||
|
/**
|
||||||
|
* Check inputs
|
||||||
|
*
|
||||||
|
* @description Check inputs
|
||||||
|
*/
|
||||||
|
const cookieString = document.cookie;
|
||||||
|
if (!cookieString || typeof cookieString !== "string") {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
return cookieObject;
|
||||||
|
}
|
28
dist/console-colors.d.ts
vendored
Normal file
28
dist/console-colors.d.ts
vendored
Normal file
@ -0,0 +1,28 @@
|
|||||||
|
declare const colors: {
|
||||||
|
Reset: string;
|
||||||
|
Bright: string;
|
||||||
|
Dim: string;
|
||||||
|
Underscore: string;
|
||||||
|
Blink: string;
|
||||||
|
Reverse: string;
|
||||||
|
Hidden: string;
|
||||||
|
FgBlack: string;
|
||||||
|
FgRed: string;
|
||||||
|
FgGreen: string;
|
||||||
|
FgYellow: string;
|
||||||
|
FgBlue: string;
|
||||||
|
FgMagenta: string;
|
||||||
|
FgCyan: string;
|
||||||
|
FgWhite: string;
|
||||||
|
FgGray: string;
|
||||||
|
BgBlack: string;
|
||||||
|
BgRed: string;
|
||||||
|
BgGreen: string;
|
||||||
|
BgYellow: string;
|
||||||
|
BgBlue: string;
|
||||||
|
BgMagenta: string;
|
||||||
|
BgCyan: string;
|
||||||
|
BgWhite: string;
|
||||||
|
BgGray: string;
|
||||||
|
};
|
||||||
|
export default colors;
|
7
console-colors.js → dist/console-colors.js
vendored
7
console-colors.js → dist/console-colors.js
vendored
@ -1,3 +1,5 @@
|
|||||||
|
"use strict";
|
||||||
|
Object.defineProperty(exports, "__esModule", { value: true });
|
||||||
const colors = {
|
const colors = {
|
||||||
Reset: "\x1b[0m",
|
Reset: "\x1b[0m",
|
||||||
Bright: "\x1b[1m",
|
Bright: "\x1b[1m",
|
||||||
@ -6,7 +8,6 @@ const colors = {
|
|||||||
Blink: "\x1b[5m",
|
Blink: "\x1b[5m",
|
||||||
Reverse: "\x1b[7m",
|
Reverse: "\x1b[7m",
|
||||||
Hidden: "\x1b[8m",
|
Hidden: "\x1b[8m",
|
||||||
|
|
||||||
FgBlack: "\x1b[30m",
|
FgBlack: "\x1b[30m",
|
||||||
FgRed: "\x1b[31m",
|
FgRed: "\x1b[31m",
|
||||||
FgGreen: "\x1b[32m",
|
FgGreen: "\x1b[32m",
|
||||||
@ -16,7 +17,6 @@ const colors = {
|
|||||||
FgCyan: "\x1b[36m",
|
FgCyan: "\x1b[36m",
|
||||||
FgWhite: "\x1b[37m",
|
FgWhite: "\x1b[37m",
|
||||||
FgGray: "\x1b[90m",
|
FgGray: "\x1b[90m",
|
||||||
|
|
||||||
BgBlack: "\x1b[40m",
|
BgBlack: "\x1b[40m",
|
||||||
BgRed: "\x1b[41m",
|
BgRed: "\x1b[41m",
|
||||||
BgGreen: "\x1b[42m",
|
BgGreen: "\x1b[42m",
|
||||||
@ -27,5 +27,4 @@ const colors = {
|
|||||||
BgWhite: "\x1b[47m",
|
BgWhite: "\x1b[47m",
|
||||||
BgGray: "\x1b[100m",
|
BgGray: "\x1b[100m",
|
||||||
};
|
};
|
||||||
|
exports.default = colors;
|
||||||
module.exports = colors;
|
|
2
dist/engine/dsql.d.ts
vendored
Normal file
2
dist/engine/dsql.d.ts
vendored
Normal file
@ -0,0 +1,2 @@
|
|||||||
|
#! /usr/bin/env node
|
||||||
|
export default function run(): Promise<void>;
|
115
dist/engine/dsql.js
vendored
Normal file
115
dist/engine/dsql.js
vendored
Normal file
@ -0,0 +1,115 @@
|
|||||||
|
#! /usr/bin/env node
|
||||||
|
"use strict";
|
||||||
|
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||||
|
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||||
|
return new (P || (P = Promise))(function (resolve, reject) {
|
||||||
|
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||||
|
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||||
|
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||||
|
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||||
|
});
|
||||||
|
};
|
||||||
|
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||||
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||||
|
};
|
||||||
|
Object.defineProperty(exports, "__esModule", { value: true });
|
||||||
|
exports.default = run;
|
||||||
|
const fs_1 = __importDefault(require("fs"));
|
||||||
|
const path_1 = __importDefault(require("path"));
|
||||||
|
require("dotenv").config({
|
||||||
|
path: path_1.default.resolve(process.cwd(), ".env"),
|
||||||
|
});
|
||||||
|
const index_1 = __importDefault(require("../index"));
|
||||||
|
const console_colors_1 = __importDefault(require("../console-colors"));
|
||||||
|
const createDbFromSchema_1 = __importDefault(require("../package-shared/shell/createDbFromSchema"));
|
||||||
|
if (!fs_1.default.existsSync(path_1.default.resolve(process.cwd(), ".env"))) {
|
||||||
|
console.log(".env file not found");
|
||||||
|
process.exit();
|
||||||
|
}
|
||||||
|
const { DSQL_HOST, DSQL_USER, DSQL_PASS, DSQL_DB_NAME, DSQL_KEY, DSQL_REF_DB_NAME, DSQL_FULL_SYNC, } = process.env;
|
||||||
|
if (!(DSQL_HOST === null || DSQL_HOST === void 0 ? void 0 : DSQL_HOST.match(/./))) {
|
||||||
|
console.log("DSQL_HOST is required in your `.env` file");
|
||||||
|
process.exit();
|
||||||
|
}
|
||||||
|
if (!(DSQL_USER === null || DSQL_USER === void 0 ? void 0 : DSQL_USER.match(/./))) {
|
||||||
|
console.log("DSQL_USER is required in your `.env` file");
|
||||||
|
process.exit();
|
||||||
|
}
|
||||||
|
if (!(DSQL_PASS === null || DSQL_PASS === void 0 ? void 0 : DSQL_PASS.match(/./))) {
|
||||||
|
console.log("DSQL_PASS is required in your `.env` file");
|
||||||
|
process.exit();
|
||||||
|
}
|
||||||
|
const dbSchemaLocalFilePath = path_1.default.resolve(process.cwd(), "dsql.schema.json");
|
||||||
|
function run() {
|
||||||
|
return __awaiter(this, void 0, void 0, function* () {
|
||||||
|
let schemaData;
|
||||||
|
if (DSQL_KEY && (DSQL_REF_DB_NAME === null || DSQL_REF_DB_NAME === void 0 ? void 0 : DSQL_REF_DB_NAME.match(/./))) {
|
||||||
|
const dbSchemaDataResponse = yield index_1.default.getSchema({
|
||||||
|
key: DSQL_KEY,
|
||||||
|
database: DSQL_REF_DB_NAME || undefined,
|
||||||
|
});
|
||||||
|
if (!dbSchemaDataResponse.payload ||
|
||||||
|
Array.isArray(dbSchemaDataResponse.payload)) {
|
||||||
|
console.log("DSQL_KEY+DSQL_REF_DB_NAME => Error in fetching DB schema");
|
||||||
|
console.log(dbSchemaDataResponse);
|
||||||
|
process.exit();
|
||||||
|
}
|
||||||
|
let fetchedDbSchemaObject = dbSchemaDataResponse.payload;
|
||||||
|
if (DSQL_DB_NAME)
|
||||||
|
fetchedDbSchemaObject.dbFullName = DSQL_DB_NAME;
|
||||||
|
schemaData = [fetchedDbSchemaObject];
|
||||||
|
}
|
||||||
|
else if (DSQL_KEY) {
|
||||||
|
const dbSchemaDataResponse = yield index_1.default.getSchema({
|
||||||
|
key: DSQL_KEY,
|
||||||
|
database: DSQL_REF_DB_NAME || undefined,
|
||||||
|
});
|
||||||
|
if (!dbSchemaDataResponse.payload ||
|
||||||
|
!Array.isArray(dbSchemaDataResponse.payload)) {
|
||||||
|
console.log("DSQL_KEY => Error in fetching DB schema");
|
||||||
|
console.log(dbSchemaDataResponse);
|
||||||
|
process.exit();
|
||||||
|
}
|
||||||
|
let fetchedDbSchemaObject = dbSchemaDataResponse.payload;
|
||||||
|
// fetchedDbSchemaObject.forEach((db, index) => {
|
||||||
|
// db.dbFullName = db.dbFullName?.replace(/^datasquirel_user_\d+_/, "");
|
||||||
|
// });
|
||||||
|
schemaData = fetchedDbSchemaObject;
|
||||||
|
}
|
||||||
|
else if (fs_1.default.existsSync(dbSchemaLocalFilePath)) {
|
||||||
|
schemaData = [
|
||||||
|
JSON.parse(fs_1.default.readFileSync(dbSchemaLocalFilePath, "utf8")),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
console.log("No source for DB Schema. Please provide a local `dsql.schema.json` file, or provide `DSQL_KEY` and `DSQL_REF_DB_NAME` environment variables.");
|
||||||
|
process.exit();
|
||||||
|
}
|
||||||
|
if (!schemaData) {
|
||||||
|
console.log("No schema found");
|
||||||
|
process.exit();
|
||||||
|
}
|
||||||
|
if (DSQL_FULL_SYNC === null || DSQL_FULL_SYNC === void 0 ? void 0 : DSQL_FULL_SYNC.match(/true/i)) {
|
||||||
|
fs_1.default.writeFileSync(dbSchemaLocalFilePath, JSON.stringify(schemaData[0], null, 4), "utf8");
|
||||||
|
}
|
||||||
|
console.log(` - ${console_colors_1.default.FgBlue}Info:${console_colors_1.default.Reset} Now generating and mapping databases ...`);
|
||||||
|
yield (0, createDbFromSchema_1.default)({
|
||||||
|
dbSchemaData: schemaData,
|
||||||
|
});
|
||||||
|
console.log(` - ${console_colors_1.default.FgGreen}Success:${console_colors_1.default.Reset} Databases created Successfully!`);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
let interval;
|
||||||
|
if (fs_1.default.existsSync(dbSchemaLocalFilePath) && !(DSQL_KEY === null || DSQL_KEY === void 0 ? void 0 : DSQL_KEY.match(/....../))) {
|
||||||
|
fs_1.default.watchFile(dbSchemaLocalFilePath, { interval: 1000 }, (curr, prev) => {
|
||||||
|
console.log(` - ${console_colors_1.default.FgBlue}Info:${console_colors_1.default.Reset} Syncing Databases Locally ...`);
|
||||||
|
run();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
else if (DSQL_KEY === null || DSQL_KEY === void 0 ? void 0 : DSQL_KEY.match(/....../)) {
|
||||||
|
interval = setInterval(() => {
|
||||||
|
console.log(` - ${console_colors_1.default.FgMagenta}Info:${console_colors_1.default.Reset} Syncing Databases from the cloud ...`);
|
||||||
|
run();
|
||||||
|
}, 20000);
|
||||||
|
}
|
||||||
|
run();
|
2
dist/engine/dump.d.ts
vendored
Normal file
2
dist/engine/dump.d.ts
vendored
Normal file
@ -0,0 +1,2 @@
|
|||||||
|
#! /usr/bin/env node
|
||||||
|
export {};
|
50
dist/engine/dump.js
vendored
Normal file
50
dist/engine/dump.js
vendored
Normal file
@ -0,0 +1,50 @@
|
|||||||
|
#! /usr/bin/env node
|
||||||
|
"use strict";
|
||||||
|
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||||
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||||
|
};
|
||||||
|
var _a, _b;
|
||||||
|
Object.defineProperty(exports, "__esModule", { value: true });
|
||||||
|
const path_1 = __importDefault(require("path"));
|
||||||
|
const child_process_1 = require("child_process");
|
||||||
|
require("dotenv").config({
|
||||||
|
path: path_1.default.resolve(process.cwd(), ".env"),
|
||||||
|
});
|
||||||
|
const mysqlPath = ((_a = process.platform) === null || _a === void 0 ? void 0 : _a.match(/win/i))
|
||||||
|
? "'" + "C:\\Program Files\\MySQL\\MySQL Server 8.0\\bin\\mysql.exe" + "'"
|
||||||
|
: "mysql";
|
||||||
|
const mysqlDumpPath = ((_b = process.platform) === null || _b === void 0 ? void 0 : _b.match(/win/i))
|
||||||
|
? "'" +
|
||||||
|
"C:\\Program Files\\MySQL\\MySQL Server 8.0\\bin\\mysqldump.exe" +
|
||||||
|
"'"
|
||||||
|
: "mysqldump";
|
||||||
|
const { DSQL_USER, DSQL_PASS, DSQL_DB_NAME } = process.env;
|
||||||
|
const dbName = DSQL_DB_NAME || "";
|
||||||
|
const dumpFilePathArg = process.argv.indexOf("--file");
|
||||||
|
if (dumpFilePathArg < 0) {
|
||||||
|
console.log("Please provide a dump file path using `--file` argument");
|
||||||
|
process.exit();
|
||||||
|
}
|
||||||
|
const dumpFilePath = process.argv[dumpFilePathArg + 1];
|
||||||
|
if (!(dbName === null || dbName === void 0 ? void 0 : dbName.match(/./))) {
|
||||||
|
console.log("DSQL_DB_NAME is required in your `.env` file");
|
||||||
|
process.exit();
|
||||||
|
}
|
||||||
|
if (!(DSQL_USER === null || DSQL_USER === void 0 ? void 0 : DSQL_USER.match(/./)) || !(DSQL_PASS === null || DSQL_PASS === void 0 ? void 0 : DSQL_PASS.match(/./))) {
|
||||||
|
console.log("DSQL_USER and DSQL_PASS are required in your `.env` file");
|
||||||
|
process.exit();
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
let execSyncOptions = {
|
||||||
|
cwd: process.cwd(),
|
||||||
|
};
|
||||||
|
// if (process.platform.match(/win/i)) execSyncOptions.shell = "bash.exe";
|
||||||
|
const dump = (0, child_process_1.execSync)(`${mysqlPath} -u ${DSQL_USER} -p${DSQL_PASS} ${dbName} < ${dumpFilePath}`, execSyncOptions);
|
||||||
|
console.log("Dumped successfully", dump.toString());
|
||||||
|
////////////////////////////////////////
|
||||||
|
////////////////////////////////////////
|
||||||
|
////////////////////////////////////////
|
||||||
|
}
|
||||||
|
catch (error) {
|
||||||
|
console.log("Dump Error: ", error.message);
|
||||||
|
}
|
108
dist/index.d.ts
vendored
Normal file
108
dist/index.d.ts
vendored
Normal file
@ -0,0 +1,108 @@
|
|||||||
|
/**
|
||||||
|
* 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 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";
|
||||||
|
/**
|
||||||
|
* Main Export
|
||||||
|
*/
|
||||||
|
declare const datasquirel: {
|
||||||
|
get: typeof get;
|
||||||
|
post: typeof post;
|
||||||
|
media: {
|
||||||
|
uploadImage: typeof uploadImage;
|
||||||
|
uploadFile: typeof uploadFile;
|
||||||
|
deleteFile: typeof deleteFile;
|
||||||
|
};
|
||||||
|
user: {
|
||||||
|
createUser: typeof createUser;
|
||||||
|
deleteUser: any;
|
||||||
|
loginUser: typeof loginUser;
|
||||||
|
sendEmailCode: typeof sendEmailCode;
|
||||||
|
logoutUser: typeof logoutUser;
|
||||||
|
userAuth: typeof userAuth;
|
||||||
|
reAuthUser: typeof reAuthUser;
|
||||||
|
updateUser: typeof updateUser;
|
||||||
|
getUser: typeof getUser;
|
||||||
|
getToken: typeof getToken;
|
||||||
|
validateToken: typeof validateToken;
|
||||||
|
validateTempEmailCode: any;
|
||||||
|
social: {
|
||||||
|
loginWithGoogle: typeof loginWithGoogle;
|
||||||
|
loginWithGithub: typeof loginWithGithub;
|
||||||
|
};
|
||||||
|
};
|
||||||
|
getSchema: typeof getSchema;
|
||||||
|
client: {
|
||||||
|
media: {
|
||||||
|
imageInputToBase64: typeof import("./client/media/imageInputToBase64").default;
|
||||||
|
imageInputFileToBase64: typeof import("./client/media/imageInputFileToBase64").default;
|
||||||
|
inputFileToBase64: typeof import("./client/media/inputFileToBase64").default;
|
||||||
|
};
|
||||||
|
auth: {
|
||||||
|
google: {
|
||||||
|
getAccessToken: typeof import("./client/auth/google/getAccessToken").default;
|
||||||
|
};
|
||||||
|
github: {
|
||||||
|
getAccessToken: typeof import("./client/auth/github/getAccessToken").default;
|
||||||
|
};
|
||||||
|
logout: typeof import("./client/auth/logout").default;
|
||||||
|
};
|
||||||
|
fetch: {
|
||||||
|
fetchApi: typeof import("./client/fetch").default;
|
||||||
|
clientFetch: typeof import("./client/fetch").default;
|
||||||
|
};
|
||||||
|
utils: {
|
||||||
|
serializeQuery: typeof import("./package-shared/utils/serialize-query").default;
|
||||||
|
serializeCookies: typeof import("./package-shared/utils/serialize-cookies").default;
|
||||||
|
EJSON: {
|
||||||
|
parse: (string: string | null | number, reviver?: (this: any, key: string, value: any) => any) => {
|
||||||
|
[s: string]: any;
|
||||||
|
} | {
|
||||||
|
[s: string]: any;
|
||||||
|
}[] | undefined;
|
||||||
|
stringify: (value: any, replacer?: (this: any, key: string, value: any) => any, space?: string | number) => string | undefined;
|
||||||
|
};
|
||||||
|
numberfy: typeof import("./package-shared/utils/numberfy").default;
|
||||||
|
slugify: typeof import("./package-shared/utils/slugify").default;
|
||||||
|
};
|
||||||
|
};
|
||||||
|
sql: {
|
||||||
|
sqlGenerator: typeof sqlGenerator;
|
||||||
|
sqlInsertGenerator: typeof sqlInsertGenerator;
|
||||||
|
sqlDeleteGenerator: typeof sqlDeleteGenerator;
|
||||||
|
trim: typeof trimSql;
|
||||||
|
};
|
||||||
|
utils: {
|
||||||
|
crypto: {
|
||||||
|
encrypt: any;
|
||||||
|
decrypt: any;
|
||||||
|
hash: any;
|
||||||
|
};
|
||||||
|
parseCookies: typeof parseCookies;
|
||||||
|
httpRequest: typeof httpRequest;
|
||||||
|
};
|
||||||
|
};
|
||||||
|
export default datasquirel;
|
97
dist/index.js
vendored
Normal file
97
dist/index.js
vendored
Normal file
@ -0,0 +1,97 @@
|
|||||||
|
"use strict";
|
||||||
|
// @ts-check
|
||||||
|
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||||
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||||
|
};
|
||||||
|
Object.defineProperty(exports, "__esModule", { value: true });
|
||||||
|
/**
|
||||||
|
* Imports
|
||||||
|
*/
|
||||||
|
const get_1 = __importDefault(require("./utils/get"));
|
||||||
|
const post_1 = __importDefault(require("./utils/post"));
|
||||||
|
const get_schema_1 = __importDefault(require("./utils/get-schema"));
|
||||||
|
const upload_image_1 = __importDefault(require("./utils/upload-image"));
|
||||||
|
const upload_file_1 = __importDefault(require("./utils/upload-file"));
|
||||||
|
const delete_file_1 = __importDefault(require("./utils/delete-file"));
|
||||||
|
const add_user_1 = __importDefault(require("./users/add-user"));
|
||||||
|
const update_user_1 = __importDefault(require("./users/update-user"));
|
||||||
|
const login_user_1 = __importDefault(require("./users/login-user"));
|
||||||
|
const send_email_code_1 = __importDefault(require("./users/send-email-code"));
|
||||||
|
const logout_user_1 = __importDefault(require("./users/logout-user"));
|
||||||
|
const user_auth_1 = __importDefault(require("./users/user-auth"));
|
||||||
|
const reauth_user_1 = __importDefault(require("./users/reauth-user"));
|
||||||
|
const get_user_1 = __importDefault(require("./users/get-user"));
|
||||||
|
const google_auth_1 = __importDefault(require("./users/social/google-auth"));
|
||||||
|
const github_auth_1 = __importDefault(require("./users/social/github-auth"));
|
||||||
|
const get_token_1 = __importDefault(require("./users/get-token"));
|
||||||
|
const validate_token_1 = __importDefault(require("./users/validate-token"));
|
||||||
|
const client_1 = __importDefault(require("./client"));
|
||||||
|
const sql_generator_1 = __importDefault(require("./package-shared/functions/dsql/sql/sql-generator"));
|
||||||
|
const sql_insert_generator_1 = __importDefault(require("./package-shared/functions/dsql/sql/sql-insert-generator"));
|
||||||
|
const sql_delete_generator_1 = __importDefault(require("./package-shared/functions/dsql/sql/sql-delete-generator"));
|
||||||
|
const trim_sql_1 = __importDefault(require("./package-shared/utils/trim-sql"));
|
||||||
|
const parseCookies_1 = __importDefault(require("./package-shared/utils/backend/parseCookies"));
|
||||||
|
const httpRequest_1 = __importDefault(require("./package-shared/functions/backend/httpRequest"));
|
||||||
|
////////////////////////////////////////
|
||||||
|
////////////////////////////////////////
|
||||||
|
////////////////////////////////////////
|
||||||
|
/**
|
||||||
|
* User Functions Object
|
||||||
|
*/
|
||||||
|
const user = {
|
||||||
|
createUser: add_user_1.default,
|
||||||
|
deleteUser: require("./users/delete-user"),
|
||||||
|
loginUser: login_user_1.default,
|
||||||
|
sendEmailCode: send_email_code_1.default,
|
||||||
|
logoutUser: logout_user_1.default,
|
||||||
|
userAuth: user_auth_1.default,
|
||||||
|
reAuthUser: reauth_user_1.default,
|
||||||
|
updateUser: update_user_1.default,
|
||||||
|
getUser: get_user_1.default,
|
||||||
|
getToken: get_token_1.default,
|
||||||
|
validateToken: validate_token_1.default,
|
||||||
|
validateTempEmailCode: require("./users/validate-temp-email-code"),
|
||||||
|
social: {
|
||||||
|
loginWithGoogle: google_auth_1.default,
|
||||||
|
loginWithGithub: github_auth_1.default,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
/**
|
||||||
|
* Media Functions Object
|
||||||
|
*/
|
||||||
|
const media = {
|
||||||
|
uploadImage: upload_image_1.default,
|
||||||
|
uploadFile: upload_file_1.default,
|
||||||
|
deleteFile: delete_file_1.default,
|
||||||
|
};
|
||||||
|
/**
|
||||||
|
* SQL Utils
|
||||||
|
*/
|
||||||
|
const sql = {
|
||||||
|
sqlGenerator: sql_generator_1.default,
|
||||||
|
sqlInsertGenerator: sql_insert_generator_1.default,
|
||||||
|
sqlDeleteGenerator: sql_delete_generator_1.default,
|
||||||
|
trim: trim_sql_1.default,
|
||||||
|
};
|
||||||
|
/**
|
||||||
|
* Main Export
|
||||||
|
*/
|
||||||
|
const datasquirel = {
|
||||||
|
get: get_1.default,
|
||||||
|
post: post_1.default,
|
||||||
|
media,
|
||||||
|
user,
|
||||||
|
getSchema: get_schema_1.default,
|
||||||
|
client: client_1.default,
|
||||||
|
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: parseCookies_1.default,
|
||||||
|
httpRequest: httpRequest_1.default,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
exports.default = datasquirel;
|
13
dist/package-shared/functions/api/query/get.d.ts
vendored
Normal file
13
dist/package-shared/functions/api/query/get.d.ts
vendored
Normal file
@ -0,0 +1,13 @@
|
|||||||
|
type Param = {
|
||||||
|
query: string;
|
||||||
|
queryValues?: (string | number)[];
|
||||||
|
dbFullName: string;
|
||||||
|
tableName?: string;
|
||||||
|
dbSchema?: import("../../../types").DSQL_DatabaseSchemaType;
|
||||||
|
useLocal?: boolean;
|
||||||
|
};
|
||||||
|
/**
|
||||||
|
* # Get Function FOr API
|
||||||
|
*/
|
||||||
|
export default function apiGet({ query, dbFullName, queryValues, tableName, dbSchema, useLocal, }: Param): Promise<import("../../../types").GetReturn>;
|
||||||
|
export {};
|
82
dist/package-shared/functions/api/query/get.js
vendored
Normal file
82
dist/package-shared/functions/api/query/get.js
vendored
Normal file
@ -0,0 +1,82 @@
|
|||||||
|
"use strict";
|
||||||
|
// @ts-check
|
||||||
|
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||||
|
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||||
|
return new (P || (P = Promise))(function (resolve, reject) {
|
||||||
|
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||||
|
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||||
|
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||||
|
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||||
|
});
|
||||||
|
};
|
||||||
|
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||||
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||||
|
};
|
||||||
|
Object.defineProperty(exports, "__esModule", { value: true });
|
||||||
|
exports.default = apiGet;
|
||||||
|
const lodash_1 = __importDefault(require("lodash"));
|
||||||
|
const serverError_1 = __importDefault(require("../../backend/serverError"));
|
||||||
|
const runQuery_1 = __importDefault(require("../../backend/db/runQuery"));
|
||||||
|
/**
|
||||||
|
* # Get Function FOr API
|
||||||
|
*/
|
||||||
|
function apiGet(_a) {
|
||||||
|
return __awaiter(this, arguments, void 0, function* ({ query, dbFullName, queryValues, tableName, dbSchema, useLocal, }) {
|
||||||
|
if (typeof query == "string" &&
|
||||||
|
query.match(/^alter|^delete|information_schema|databases|^create/i)) {
|
||||||
|
return { success: false, msg: "Wrong Input." };
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* Create new user folder and file
|
||||||
|
*
|
||||||
|
* @description Create new user folder and file
|
||||||
|
*/
|
||||||
|
let results;
|
||||||
|
try {
|
||||||
|
let { result, error } = yield (0, runQuery_1.default)({
|
||||||
|
dbFullName: dbFullName,
|
||||||
|
query: query,
|
||||||
|
queryValuesArray: queryValues,
|
||||||
|
readOnly: true,
|
||||||
|
dbSchema,
|
||||||
|
tableName,
|
||||||
|
local: useLocal,
|
||||||
|
});
|
||||||
|
/** @type {import("../../../types").DSQL_TableSchemaType | undefined} */
|
||||||
|
let tableSchema;
|
||||||
|
if (dbSchema) {
|
||||||
|
const targetTable = dbSchema.tables.find((table) => table.tableName === tableName);
|
||||||
|
if (targetTable) {
|
||||||
|
const clonedTargetTable = lodash_1.default.cloneDeep(targetTable);
|
||||||
|
delete clonedTargetTable.childTable;
|
||||||
|
delete clonedTargetTable.childTableDbFullName;
|
||||||
|
delete clonedTargetTable.childTableName;
|
||||||
|
delete clonedTargetTable.childrenTables;
|
||||||
|
delete clonedTargetTable.updateData;
|
||||||
|
delete clonedTargetTable.tableNameOld;
|
||||||
|
delete clonedTargetTable.indexes;
|
||||||
|
tableSchema = clonedTargetTable;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (error)
|
||||||
|
throw error;
|
||||||
|
if (result.error)
|
||||||
|
throw new Error(result.error);
|
||||||
|
results = result;
|
||||||
|
/** @type {import("../../../types").GetReturn} */
|
||||||
|
const resObject = {
|
||||||
|
success: true,
|
||||||
|
payload: results,
|
||||||
|
schema: tableName && tableSchema ? tableSchema : undefined,
|
||||||
|
};
|
||||||
|
return resObject;
|
||||||
|
}
|
||||||
|
catch ( /** @type {any} */error) {
|
||||||
|
(0, serverError_1.default)({
|
||||||
|
component: "/api/query/get/lines-85-94",
|
||||||
|
message: error.message,
|
||||||
|
});
|
||||||
|
return { success: false, payload: null, error: error.message };
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
14
dist/package-shared/functions/api/query/post.d.ts
vendored
Normal file
14
dist/package-shared/functions/api/query/post.d.ts
vendored
Normal file
@ -0,0 +1,14 @@
|
|||||||
|
import { DSQL_DatabaseSchemaType, PostReturn } from "../../../types";
|
||||||
|
type Param = {
|
||||||
|
query: any;
|
||||||
|
queryValues?: (string | number)[];
|
||||||
|
dbFullName: string;
|
||||||
|
tableName?: string;
|
||||||
|
dbSchema?: DSQL_DatabaseSchemaType;
|
||||||
|
useLocal?: boolean;
|
||||||
|
};
|
||||||
|
/**
|
||||||
|
* # Post Function For API
|
||||||
|
*/
|
||||||
|
export default function apiPost({ query, dbFullName, queryValues, tableName, dbSchema, useLocal, }: Param): Promise<PostReturn>;
|
||||||
|
export {};
|
86
dist/package-shared/functions/api/query/post.js
vendored
Normal file
86
dist/package-shared/functions/api/query/post.js
vendored
Normal file
@ -0,0 +1,86 @@
|
|||||||
|
"use strict";
|
||||||
|
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||||
|
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||||
|
return new (P || (P = Promise))(function (resolve, reject) {
|
||||||
|
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||||
|
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||||
|
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||||
|
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||||
|
});
|
||||||
|
};
|
||||||
|
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||||
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||||
|
};
|
||||||
|
Object.defineProperty(exports, "__esModule", { value: true });
|
||||||
|
exports.default = apiPost;
|
||||||
|
const lodash_1 = __importDefault(require("lodash"));
|
||||||
|
const serverError_1 = __importDefault(require("../../backend/serverError"));
|
||||||
|
const runQuery_1 = __importDefault(require("../../backend/db/runQuery"));
|
||||||
|
/**
|
||||||
|
* # Post Function For API
|
||||||
|
*/
|
||||||
|
function apiPost(_a) {
|
||||||
|
return __awaiter(this, arguments, void 0, function* ({ query, dbFullName, queryValues, tableName, dbSchema, useLocal, }) {
|
||||||
|
var _b;
|
||||||
|
if (typeof query === "string" && (query === null || query === void 0 ? void 0 : query.match(/^create |^alter |^drop /i))) {
|
||||||
|
return { success: false, msg: "Wrong Input" };
|
||||||
|
}
|
||||||
|
if (typeof query === "object" &&
|
||||||
|
((_b = query === null || query === void 0 ? void 0 : query.action) === null || _b === void 0 ? void 0 : _b.match(/^create |^alter |^drop /i))) {
|
||||||
|
return { success: false, msg: "Wrong Input" };
|
||||||
|
}
|
||||||
|
/** @type {any} */
|
||||||
|
let results;
|
||||||
|
/**
|
||||||
|
* Create new user folder and file
|
||||||
|
*
|
||||||
|
* @description Create new user folder and file
|
||||||
|
*/
|
||||||
|
try {
|
||||||
|
let { result, error } = yield (0, runQuery_1.default)({
|
||||||
|
dbFullName: dbFullName,
|
||||||
|
query: query,
|
||||||
|
dbSchema: dbSchema,
|
||||||
|
queryValuesArray: queryValues,
|
||||||
|
tableName,
|
||||||
|
local: useLocal,
|
||||||
|
});
|
||||||
|
results = result;
|
||||||
|
if (error)
|
||||||
|
throw error;
|
||||||
|
/** @type {import("../../../types").DSQL_TableSchemaType | undefined} */
|
||||||
|
let tableSchema;
|
||||||
|
if (dbSchema) {
|
||||||
|
const targetTable = dbSchema.tables.find((table) => table.tableName === tableName);
|
||||||
|
if (targetTable) {
|
||||||
|
const clonedTargetTable = lodash_1.default.cloneDeep(targetTable);
|
||||||
|
delete clonedTargetTable.childTable;
|
||||||
|
delete clonedTargetTable.childTableDbFullName;
|
||||||
|
delete clonedTargetTable.childTableName;
|
||||||
|
delete clonedTargetTable.childrenTables;
|
||||||
|
delete clonedTargetTable.updateData;
|
||||||
|
delete clonedTargetTable.tableNameOld;
|
||||||
|
delete clonedTargetTable.indexes;
|
||||||
|
tableSchema = clonedTargetTable;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
payload: results,
|
||||||
|
error: error,
|
||||||
|
schema: tableName && tableSchema ? tableSchema : undefined,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
catch (error) {
|
||||||
|
(0, serverError_1.default)({
|
||||||
|
component: "/api/query/post/lines-132-142",
|
||||||
|
message: error.message,
|
||||||
|
});
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
payload: results,
|
||||||
|
error: error.message,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
8
dist/package-shared/functions/api/social-login/facebookLogin.d.ts
vendored
Normal file
8
dist/package-shared/functions/api/social-login/facebookLogin.d.ts
vendored
Normal file
@ -0,0 +1,8 @@
|
|||||||
|
import { UserType } from "../../../types";
|
||||||
|
/**
|
||||||
|
* # Facebook Login
|
||||||
|
*/
|
||||||
|
export default function facebookLogin({ usertype, body, }: {
|
||||||
|
body: any;
|
||||||
|
usertype: UserType;
|
||||||
|
}): Promise<any>;
|
78
dist/package-shared/functions/api/social-login/facebookLogin.js
vendored
Normal file
78
dist/package-shared/functions/api/social-login/facebookLogin.js
vendored
Normal file
@ -0,0 +1,78 @@
|
|||||||
|
"use strict";
|
||||||
|
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||||
|
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||||
|
return new (P || (P = Promise))(function (resolve, reject) {
|
||||||
|
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||||
|
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||||
|
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||||
|
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||||
|
});
|
||||||
|
};
|
||||||
|
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||||
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||||
|
};
|
||||||
|
Object.defineProperty(exports, "__esModule", { value: true });
|
||||||
|
exports.default = facebookLogin;
|
||||||
|
const DB_HANDLER_1 = __importDefault(require("../../../utils/backend/global-db/DB_HANDLER"));
|
||||||
|
const serverError_1 = __importDefault(require("../../backend/serverError"));
|
||||||
|
const hashPassword_1 = __importDefault(require("../../dsql/hashPassword"));
|
||||||
|
/**
|
||||||
|
* # Facebook Login
|
||||||
|
*/
|
||||||
|
function facebookLogin(_a) {
|
||||||
|
return __awaiter(this, arguments, void 0, function* ({ usertype, body, }) {
|
||||||
|
try {
|
||||||
|
const foundUser = yield (0, DB_HANDLER_1.default)(`SELECT * FROM users WHERE email='${body.facebookUserEmail}' AND social_login='1'`);
|
||||||
|
if (foundUser && foundUser[0]) {
|
||||||
|
return foundUser[0];
|
||||||
|
}
|
||||||
|
let socialHashedPassword = (0, hashPassword_1.default)({
|
||||||
|
password: body.facebookUserId,
|
||||||
|
});
|
||||||
|
let newUser = yield (0, DB_HANDLER_1.default)(`INSERT INTO ${usertype} (
|
||||||
|
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 = yield (0, DB_HANDLER_1.default)(`SELECT * FROM ${usertype} WHERE id='${newUser.insertId}'`);
|
||||||
|
}
|
||||||
|
catch ( /** @type {any} */error) {
|
||||||
|
(0, serverError_1.default)({
|
||||||
|
component: "functions/backend/facebookLogin",
|
||||||
|
message: error.message,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
isFacebookAuthValid: false,
|
||||||
|
newFoundUser: null,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
}
|
43
dist/package-shared/functions/api/social-login/githubLogin.d.ts
vendored
Normal file
43
dist/package-shared/functions/api/social-login/githubLogin.d.ts
vendored
Normal file
@ -0,0 +1,43 @@
|
|||||||
|
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 function githubLogin({ code, clientId, clientSecret, }: Param): Promise<GithubUserPayload | null | undefined>;
|
||||||
|
export {};
|
62
dist/package-shared/functions/api/social-login/githubLogin.js
vendored
Normal file
62
dist/package-shared/functions/api/social-login/githubLogin.js
vendored
Normal file
@ -0,0 +1,62 @@
|
|||||||
|
"use strict";
|
||||||
|
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||||
|
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||||
|
return new (P || (P = Promise))(function (resolve, reject) {
|
||||||
|
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||||
|
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||||
|
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||||
|
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||||
|
});
|
||||||
|
};
|
||||||
|
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||||
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||||
|
};
|
||||||
|
Object.defineProperty(exports, "__esModule", { value: true });
|
||||||
|
exports.default = githubLogin;
|
||||||
|
const DB_HANDLER_1 = __importDefault(require("../../../utils/backend/global-db/DB_HANDLER"));
|
||||||
|
const httpsRequest_1 = __importDefault(require("../../backend/httpsRequest"));
|
||||||
|
/**
|
||||||
|
* # Login/signup a github user
|
||||||
|
*/
|
||||||
|
function githubLogin(_a) {
|
||||||
|
return __awaiter(this, arguments, void 0, function* ({ code, clientId, clientSecret, }) {
|
||||||
|
let gitHubUser;
|
||||||
|
try {
|
||||||
|
const response = yield (0, httpsRequest_1.default)({
|
||||||
|
method: "POST",
|
||||||
|
hostname: "github.com",
|
||||||
|
path: `/login/oauth/access_token?client_id=${clientId}&client_secret=${clientSecret}&code=${code}`,
|
||||||
|
headers: {
|
||||||
|
Accept: "application/json",
|
||||||
|
"User-Agent": "*",
|
||||||
|
},
|
||||||
|
scheme: "https",
|
||||||
|
});
|
||||||
|
const accessTokenObject = JSON.parse(response);
|
||||||
|
if (!(accessTokenObject === null || accessTokenObject === void 0 ? void 0 : accessTokenObject.access_token)) {
|
||||||
|
return gitHubUser;
|
||||||
|
}
|
||||||
|
const userDataResponse = yield (0, httpsRequest_1.default)({
|
||||||
|
method: "GET",
|
||||||
|
hostname: "api.github.com",
|
||||||
|
path: "/user",
|
||||||
|
headers: {
|
||||||
|
Authorization: `Bearer ${accessTokenObject.access_token}`,
|
||||||
|
"User-Agent": "*",
|
||||||
|
},
|
||||||
|
scheme: "https",
|
||||||
|
});
|
||||||
|
gitHubUser = JSON.parse(userDataResponse);
|
||||||
|
if (!(gitHubUser === null || gitHubUser === void 0 ? void 0 : gitHubUser.email) && gitHubUser) {
|
||||||
|
const existingGithubUser = yield (0, DB_HANDLER_1.default)(`SELECT email FROM users WHERE social_login='1' AND social_platform='github' AND social_id='${gitHubUser.id}'`);
|
||||||
|
if (existingGithubUser && existingGithubUser[0]) {
|
||||||
|
gitHubUser.email = existingGithubUser[0].email;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch ( /** @type {any} */error) {
|
||||||
|
console.log("ERROR in githubLogin.js backend function =>", error.message);
|
||||||
|
}
|
||||||
|
return gitHubUser;
|
||||||
|
});
|
||||||
|
}
|
22
dist/package-shared/functions/api/social-login/googleLogin.d.ts
vendored
Normal file
22
dist/package-shared/functions/api/social-login/googleLogin.d.ts
vendored
Normal file
@ -0,0 +1,22 @@
|
|||||||
|
type Param = {
|
||||||
|
usertype: string;
|
||||||
|
foundUser: any;
|
||||||
|
isSocialValidated: boolean;
|
||||||
|
isUserValid: boolean;
|
||||||
|
reqBody: any;
|
||||||
|
serverRes: any;
|
||||||
|
loginFailureReason: any;
|
||||||
|
};
|
||||||
|
/**
|
||||||
|
* # Google Login
|
||||||
|
*/
|
||||||
|
export default function googleLogin({ usertype, foundUser, isSocialValidated, isUserValid, reqBody, serverRes, loginFailureReason, }: Param): Promise<{
|
||||||
|
isGoogleAuthValid: boolean;
|
||||||
|
newFoundUser: null;
|
||||||
|
loginFailureReason: any;
|
||||||
|
} | {
|
||||||
|
isGoogleAuthValid: boolean;
|
||||||
|
newFoundUser: any;
|
||||||
|
loginFailureReason?: undefined;
|
||||||
|
} | undefined>;
|
||||||
|
export {};
|
123
dist/package-shared/functions/api/social-login/googleLogin.js
vendored
Normal file
123
dist/package-shared/functions/api/social-login/googleLogin.js
vendored
Normal file
@ -0,0 +1,123 @@
|
|||||||
|
"use strict";
|
||||||
|
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||||
|
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||||
|
return new (P || (P = Promise))(function (resolve, reject) {
|
||||||
|
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||||
|
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||||
|
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||||
|
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||||
|
});
|
||||||
|
};
|
||||||
|
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||||
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||||
|
};
|
||||||
|
Object.defineProperty(exports, "__esModule", { value: true });
|
||||||
|
exports.default = googleLogin;
|
||||||
|
const google_auth_library_1 = require("google-auth-library");
|
||||||
|
const serverError_1 = __importDefault(require("../../backend/serverError"));
|
||||||
|
const DB_HANDLER_1 = __importDefault(require("../../../utils/backend/global-db/DB_HANDLER"));
|
||||||
|
const hashPassword_1 = __importDefault(require("../../dsql/hashPassword"));
|
||||||
|
/**
|
||||||
|
* # Google Login
|
||||||
|
*/
|
||||||
|
function googleLogin(_a) {
|
||||||
|
return __awaiter(this, arguments, void 0, function* ({ usertype, foundUser, isSocialValidated, isUserValid, reqBody, serverRes, loginFailureReason, }) {
|
||||||
|
var _b;
|
||||||
|
const client = new google_auth_library_1.OAuth2Client(process.env.NEXT_PUBLIC_DSQL_GOOGLE_CLIENT_ID);
|
||||||
|
let isGoogleAuthValid = false;
|
||||||
|
let newFoundUser = null;
|
||||||
|
////////////////////////////////////////////////
|
||||||
|
////////////////////////////////////////////////
|
||||||
|
////////////////////////////////////////////////
|
||||||
|
try {
|
||||||
|
const ticket = yield client.verifyIdToken({
|
||||||
|
idToken: reqBody.token,
|
||||||
|
audience: process.env.NEXT_PUBLIC_DSQL_GOOGLE_CLIENT_ID, // Specify the CLIENT_ID of the app that accesses the backend
|
||||||
|
// Or, if multiple clients access the backend:
|
||||||
|
//[CLIENT_ID_1, CLIENT_ID_2, CLIENT_ID_3]
|
||||||
|
});
|
||||||
|
const payload = ticket.getPayload();
|
||||||
|
const userid = payload === null || payload === void 0 ? void 0 : payload["sub"];
|
||||||
|
if (!payload)
|
||||||
|
throw new Error("Google login failed. Credentials invalid");
|
||||||
|
isUserValid = Boolean(payload.email_verified);
|
||||||
|
if (!isUserValid || !payload || !payload.email_verified)
|
||||||
|
return;
|
||||||
|
serverRes.isUserValid = payload.email_verified;
|
||||||
|
isSocialValidated = payload.email_verified;
|
||||||
|
isGoogleAuthValid = payload.email_verified;
|
||||||
|
////// If request specified a G Suite domain:
|
||||||
|
////// const domain = payload['hd'];
|
||||||
|
let socialHashedPassword = (0, hashPassword_1.default)({
|
||||||
|
password: payload.at_hash || "",
|
||||||
|
});
|
||||||
|
////////////////////////////////////////////////
|
||||||
|
////////////////////////////////////////////////
|
||||||
|
////////////////////////////////////////////////
|
||||||
|
let existinEmail = yield (0, DB_HANDLER_1.default)(`SELECT * FROM ${usertype} WHERE email='${payload.email}' AND social_login!='1' AND social_platform!='google'`);
|
||||||
|
if (existinEmail && existinEmail[0]) {
|
||||||
|
loginFailureReason = "Email Exists Already";
|
||||||
|
isGoogleAuthValid = false;
|
||||||
|
return {
|
||||||
|
isGoogleAuthValid: isGoogleAuthValid,
|
||||||
|
newFoundUser: newFoundUser,
|
||||||
|
loginFailureReason: loginFailureReason,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
////////////////////////////////////////
|
||||||
|
foundUser = yield (0, DB_HANDLER_1.default)(`SELECT * FROM ${usertype} WHERE email='${payload.email}' AND social_login='1' AND social_platform='google'`);
|
||||||
|
if (foundUser && foundUser[0]) {
|
||||||
|
newFoundUser = foundUser;
|
||||||
|
return {
|
||||||
|
isGoogleAuthValid: isGoogleAuthValid,
|
||||||
|
newFoundUser: newFoundUser,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
////////////////////////////////////////////////
|
||||||
|
////////////////////////////////////////////////
|
||||||
|
////////////////////////////////////////////////
|
||||||
|
let newUser = yield (0, DB_HANDLER_1.default)(`INSERT INTO ${usertype} (
|
||||||
|
first_name,
|
||||||
|
last_name,
|
||||||
|
social_platform,
|
||||||
|
social_name,
|
||||||
|
social_id,
|
||||||
|
email,
|
||||||
|
image,
|
||||||
|
image_thumbnail,
|
||||||
|
password,
|
||||||
|
verification_status,
|
||||||
|
social_login,
|
||||||
|
terms_agreement,
|
||||||
|
date_created,
|
||||||
|
date_code
|
||||||
|
) VALUES (
|
||||||
|
'${payload.given_name}',
|
||||||
|
'${payload.family_name}',
|
||||||
|
'google',
|
||||||
|
'google_${(_b = payload.email) === null || _b === void 0 ? void 0 : _b.replace(/@.*/, "")}',
|
||||||
|
'${payload.sub}',
|
||||||
|
'${payload.email}',
|
||||||
|
'${payload.picture}',
|
||||||
|
'${payload.picture}',
|
||||||
|
'${socialHashedPassword}',
|
||||||
|
'1',
|
||||||
|
'1',
|
||||||
|
'1',
|
||||||
|
'${Date()}',
|
||||||
|
'${Date.now()}'
|
||||||
|
)`);
|
||||||
|
newFoundUser = yield (0, DB_HANDLER_1.default)(`SELECT * FROM ${usertype} WHERE id='${newUser.insertId}'`);
|
||||||
|
}
|
||||||
|
catch (error) {
|
||||||
|
(0, serverError_1.default)({
|
||||||
|
component: "googleLogin",
|
||||||
|
message: error.message,
|
||||||
|
});
|
||||||
|
loginFailureReason = error;
|
||||||
|
isUserValid = false;
|
||||||
|
isSocialValidated = false;
|
||||||
|
}
|
||||||
|
return { isGoogleAuthValid: isGoogleAuthValid, newFoundUser: newFoundUser };
|
||||||
|
});
|
||||||
|
}
|
5
dist/package-shared/functions/api/social-login/handleSocialDb.d.ts
vendored
Normal file
5
dist/package-shared/functions/api/social-login/handleSocialDb.d.ts
vendored
Normal file
@ -0,0 +1,5 @@
|
|||||||
|
import { APILoginFunctionReturn, HandleSocialDbFunctionParams } from "../../../types";
|
||||||
|
/**
|
||||||
|
* # Handle Social DB
|
||||||
|
*/
|
||||||
|
export default function handleSocialDb({ database, social_id, email, social_platform, payload, invitation, supEmail, additionalFields, useLocal, }: HandleSocialDbFunctionParams): Promise<APILoginFunctionReturn>;
|
202
dist/package-shared/functions/api/social-login/handleSocialDb.js
vendored
Normal file
202
dist/package-shared/functions/api/social-login/handleSocialDb.js
vendored
Normal file
@ -0,0 +1,202 @@
|
|||||||
|
"use strict";
|
||||||
|
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||||
|
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||||
|
return new (P || (P = Promise))(function (resolve, reject) {
|
||||||
|
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||||
|
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||||
|
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||||
|
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||||
|
});
|
||||||
|
};
|
||||||
|
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||||
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||||
|
};
|
||||||
|
Object.defineProperty(exports, "__esModule", { value: true });
|
||||||
|
exports.default = handleSocialDb;
|
||||||
|
const fs_1 = __importDefault(require("fs"));
|
||||||
|
const handleNodemailer_1 = __importDefault(require("../../backend/handleNodemailer"));
|
||||||
|
const path_1 = __importDefault(require("path"));
|
||||||
|
const addMariadbUser_1 = __importDefault(require("../../backend/addMariadbUser"));
|
||||||
|
const varDatabaseDbHandler_1 = __importDefault(require("../../backend/varDatabaseDbHandler"));
|
||||||
|
const encrypt_1 = __importDefault(require("../../dsql/encrypt"));
|
||||||
|
const addDbEntry_1 = __importDefault(require("../../backend/db/addDbEntry"));
|
||||||
|
const loginSocialUser_1 = __importDefault(require("./loginSocialUser"));
|
||||||
|
/**
|
||||||
|
* # Handle Social DB
|
||||||
|
*/
|
||||||
|
function handleSocialDb(_a) {
|
||||||
|
return __awaiter(this, arguments, void 0, function* ({ database, social_id, email, social_platform, payload, invitation, supEmail, additionalFields, useLocal, }) {
|
||||||
|
try {
|
||||||
|
const existingSocialIdUserQuery = `SELECT * FROM users WHERE social_id = ? AND social_login='1' AND social_platform = ? `;
|
||||||
|
const existingSocialIdUserValues = [
|
||||||
|
social_id.toString(),
|
||||||
|
social_platform,
|
||||||
|
];
|
||||||
|
let existingSocialIdUser = yield (0, varDatabaseDbHandler_1.default)({
|
||||||
|
database: database ? database : "datasquirel",
|
||||||
|
queryString: existingSocialIdUserQuery,
|
||||||
|
queryValuesArray: existingSocialIdUserValues,
|
||||||
|
useLocal,
|
||||||
|
});
|
||||||
|
if (existingSocialIdUser && existingSocialIdUser[0]) {
|
||||||
|
return yield (0, loginSocialUser_1.default)({
|
||||||
|
user: existingSocialIdUser[0],
|
||||||
|
social_platform,
|
||||||
|
invitation,
|
||||||
|
database,
|
||||||
|
additionalFields,
|
||||||
|
useLocal,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
const finalEmail = email ? email : supEmail ? supEmail : null;
|
||||||
|
if (!finalEmail) {
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
payload: null,
|
||||||
|
msg: "No Email Present",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
const existingEmailOnlyQuery = `SELECT * FROM users WHERE email='${finalEmail}'`;
|
||||||
|
let existingEmailOnly = yield (0, varDatabaseDbHandler_1.default)({
|
||||||
|
database: database ? database : "datasquirel",
|
||||||
|
queryString: existingEmailOnlyQuery,
|
||||||
|
useLocal,
|
||||||
|
});
|
||||||
|
if (existingEmailOnly && existingEmailOnly[0]) {
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
payload: null,
|
||||||
|
msg: "This Email is already taken",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
const foundUserQuery = `SELECT * FROM users WHERE email=? AND social_login='1' AND social_platform=? AND social_id=?`;
|
||||||
|
const foundUserQueryValues = [finalEmail, social_platform, social_id];
|
||||||
|
const foundUser = yield (0, varDatabaseDbHandler_1.default)({
|
||||||
|
database: database ? database : "datasquirel",
|
||||||
|
queryString: foundUserQuery,
|
||||||
|
queryValuesArray: foundUserQueryValues,
|
||||||
|
useLocal,
|
||||||
|
});
|
||||||
|
if (foundUser && foundUser[0]) {
|
||||||
|
return yield (0, loginSocialUser_1.default)({
|
||||||
|
user: payload,
|
||||||
|
social_platform,
|
||||||
|
invitation,
|
||||||
|
database,
|
||||||
|
additionalFields,
|
||||||
|
useLocal,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
const socialHashedPassword = (0, encrypt_1.default)({
|
||||||
|
data: social_id.toString(),
|
||||||
|
});
|
||||||
|
const data = {
|
||||||
|
social_login: "1",
|
||||||
|
verification_status: supEmail ? "0" : "1",
|
||||||
|
password: socialHashedPassword,
|
||||||
|
};
|
||||||
|
Object.keys(payload).forEach((key) => {
|
||||||
|
data[key] = payload[key];
|
||||||
|
});
|
||||||
|
/** @type {any} */
|
||||||
|
const newUser = yield (0, addDbEntry_1.default)({
|
||||||
|
dbContext: database ? "Dsql User" : undefined,
|
||||||
|
paradigm: database ? "Full Access" : undefined,
|
||||||
|
dbFullName: database ? database : "datasquirel",
|
||||||
|
tableName: "users",
|
||||||
|
duplicateColumnName: "email",
|
||||||
|
duplicateColumnValue: finalEmail,
|
||||||
|
data: Object.assign(Object.assign({}, data), { email: finalEmail }),
|
||||||
|
useLocal,
|
||||||
|
});
|
||||||
|
if (newUser === null || newUser === void 0 ? void 0 : newUser.insertId) {
|
||||||
|
if (!database) {
|
||||||
|
/**
|
||||||
|
* Add a Mariadb User for this User
|
||||||
|
*/
|
||||||
|
yield (0, addMariadbUser_1.default)({ userId: newUser.insertId, useLocal });
|
||||||
|
}
|
||||||
|
const newUserQueriedQuery = `SELECT * FROM users WHERE id='${newUser.insertId}'`;
|
||||||
|
const newUserQueried = yield (0, varDatabaseDbHandler_1.default)({
|
||||||
|
database: database ? database : "datasquirel",
|
||||||
|
queryString: newUserQueriedQuery,
|
||||||
|
useLocal,
|
||||||
|
});
|
||||||
|
if (!newUserQueried || !newUserQueried[0])
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
payload: null,
|
||||||
|
msg: "User Insertion Failed!",
|
||||||
|
};
|
||||||
|
if (supEmail && (database === null || database === void 0 ? void 0 : database.match(/^datasquirel$/))) {
|
||||||
|
/**
|
||||||
|
* Send email Verification
|
||||||
|
*
|
||||||
|
* @description Send verification email to newly created agent
|
||||||
|
*/
|
||||||
|
let generatedToken = (0, encrypt_1.default)({
|
||||||
|
data: JSON.stringify({
|
||||||
|
id: newUser.insertId,
|
||||||
|
email: supEmail,
|
||||||
|
dateCode: Date.now(),
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
(0, handleNodemailer_1.default)({
|
||||||
|
to: supEmail,
|
||||||
|
subject: "Verify Email Address",
|
||||||
|
text: "Please click the link to verify your email address",
|
||||||
|
html: fs_1.default
|
||||||
|
.readFileSync("./email/send-email-verification-link.html", "utf8")
|
||||||
|
.replace(/{{host}}/, process.env.DSQL_HOST || "")
|
||||||
|
.replace(/{{token}}/, generatedToken || ""),
|
||||||
|
}).then(() => { });
|
||||||
|
}
|
||||||
|
const STATIC_ROOT = process.env.DSQL_STATIC_SERVER_DIR;
|
||||||
|
if (!STATIC_ROOT) {
|
||||||
|
console.log("Static File ENV not Found!");
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
payload: null,
|
||||||
|
msg: "Static File ENV not Found!",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* Create new user folder and file
|
||||||
|
*
|
||||||
|
* @description Create new user folder and file
|
||||||
|
*/
|
||||||
|
if (!database || (database === null || database === void 0 ? void 0 : database.match(/^datasquirel$/))) {
|
||||||
|
let newUserSchemaFolderPath = `${process.env.DSQL_USER_DB_SCHEMA_PATH}/user-${newUser.insertId}`;
|
||||||
|
let newUserMediaFolderPath = path_1.default.join(STATIC_ROOT, `images/user-images/user-${newUser.insertId}`);
|
||||||
|
fs_1.default.mkdirSync(newUserSchemaFolderPath);
|
||||||
|
fs_1.default.mkdirSync(newUserMediaFolderPath);
|
||||||
|
fs_1.default.writeFileSync(`${newUserSchemaFolderPath}/main.json`, JSON.stringify([]), "utf8");
|
||||||
|
}
|
||||||
|
return yield (0, loginSocialUser_1.default)({
|
||||||
|
user: newUserQueried[0],
|
||||||
|
social_platform,
|
||||||
|
invitation,
|
||||||
|
database,
|
||||||
|
additionalFields,
|
||||||
|
useLocal,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
console.log("Social User Failed to insert in 'handleSocialDb.js' backend function =>", newUser);
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
payload: null,
|
||||||
|
msg: "Social User Failed to insert in 'handleSocialDb.js' backend function",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (error) {
|
||||||
|
console.log("ERROR in 'handleSocialDb.js' backend function =>", error.message);
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
payload: null,
|
||||||
|
msg: error.message,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
22
dist/package-shared/functions/api/social-login/loginSocialUser.d.ts
vendored
Normal file
22
dist/package-shared/functions/api/social-login/loginSocialUser.d.ts
vendored
Normal file
@ -0,0 +1,22 @@
|
|||||||
|
import { APILoginFunctionReturn } from "../../../types";
|
||||||
|
type Param = {
|
||||||
|
user: {
|
||||||
|
first_name: string;
|
||||||
|
last_name: string;
|
||||||
|
email: string;
|
||||||
|
social_id: string | number;
|
||||||
|
};
|
||||||
|
social_platform: string;
|
||||||
|
invitation?: any;
|
||||||
|
database?: string;
|
||||||
|
additionalFields?: string[];
|
||||||
|
useLocal?: boolean;
|
||||||
|
};
|
||||||
|
/**
|
||||||
|
* Function to login social user
|
||||||
|
* ==============================================================================
|
||||||
|
* @description This function logs in the user after 'handleSocialDb' function finishes
|
||||||
|
* the user creation or confirmation process
|
||||||
|
*/
|
||||||
|
export default function loginSocialUser({ user, social_platform, invitation, database, additionalFields, useLocal, }: Param): Promise<APILoginFunctionReturn>;
|
||||||
|
export {};
|
80
dist/package-shared/functions/api/social-login/loginSocialUser.js
vendored
Normal file
80
dist/package-shared/functions/api/social-login/loginSocialUser.js
vendored
Normal file
@ -0,0 +1,80 @@
|
|||||||
|
"use strict";
|
||||||
|
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||||
|
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||||
|
return new (P || (P = Promise))(function (resolve, reject) {
|
||||||
|
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||||
|
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||||
|
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||||
|
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||||
|
});
|
||||||
|
};
|
||||||
|
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||||
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||||
|
};
|
||||||
|
Object.defineProperty(exports, "__esModule", { value: true });
|
||||||
|
exports.default = loginSocialUser;
|
||||||
|
const addAdminUserOnLogin_1 = __importDefault(require("../../backend/addAdminUserOnLogin"));
|
||||||
|
const varDatabaseDbHandler_1 = __importDefault(require("../../backend/varDatabaseDbHandler"));
|
||||||
|
/**
|
||||||
|
* Function to login social user
|
||||||
|
* ==============================================================================
|
||||||
|
* @description This function logs in the user after 'handleSocialDb' function finishes
|
||||||
|
* the user creation or confirmation process
|
||||||
|
*/
|
||||||
|
function loginSocialUser(_a) {
|
||||||
|
return __awaiter(this, arguments, void 0, function* ({ user, social_platform, invitation, database, additionalFields, useLocal, }) {
|
||||||
|
const foundUserQuery = `SELECT * FROM users WHERE email=? AND social_id=? AND social_platform=?`;
|
||||||
|
const foundUserValues = [user.email, user.social_id, social_platform];
|
||||||
|
const foundUser = yield (0, varDatabaseDbHandler_1.default)({
|
||||||
|
database: database ? database : "datasquirel",
|
||||||
|
queryString: foundUserQuery,
|
||||||
|
queryValuesArray: foundUserValues,
|
||||||
|
useLocal,
|
||||||
|
});
|
||||||
|
if (!(foundUser === null || foundUser === void 0 ? void 0 : foundUser[0]))
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
payload: null,
|
||||||
|
};
|
||||||
|
let csrfKey = Math.random().toString(36).substring(2) +
|
||||||
|
"-" +
|
||||||
|
Math.random().toString(36).substring(2);
|
||||||
|
/** @type {import("../../../types").DATASQUIREL_LoggedInUser} */
|
||||||
|
let userPayload = {
|
||||||
|
id: foundUser[0].id,
|
||||||
|
first_name: foundUser[0].first_name,
|
||||||
|
last_name: foundUser[0].last_name,
|
||||||
|
username: foundUser[0].username,
|
||||||
|
user_type: foundUser[0].user_type,
|
||||||
|
email: foundUser[0].email,
|
||||||
|
social_id: foundUser[0].social_id,
|
||||||
|
image: foundUser[0].image,
|
||||||
|
image_thumbnail: foundUser[0].image_thumbnail,
|
||||||
|
verification_status: foundUser[0].verification_status,
|
||||||
|
social_login: foundUser[0].social_login,
|
||||||
|
social_platform: foundUser[0].social_platform,
|
||||||
|
csrf_k: csrfKey,
|
||||||
|
logged_in_status: true,
|
||||||
|
date: Date.now(),
|
||||||
|
};
|
||||||
|
if (additionalFields === null || additionalFields === void 0 ? void 0 : additionalFields[0]) {
|
||||||
|
additionalFields.forEach((key) => {
|
||||||
|
userPayload[key] = foundUser[0][key];
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if (invitation && (!database || (database === null || database === void 0 ? void 0 : database.match(/^datasquirel$/)))) {
|
||||||
|
(0, addAdminUserOnLogin_1.default)({
|
||||||
|
query: invitation,
|
||||||
|
user: userPayload,
|
||||||
|
useLocal,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
/** @type {import("../../../types").APILoginFunctionReturn} */
|
||||||
|
let result = {
|
||||||
|
success: true,
|
||||||
|
payload: userPayload,
|
||||||
|
csrf: csrfKey,
|
||||||
|
};
|
||||||
|
return result;
|
||||||
|
});
|
||||||
|
}
|
25
dist/package-shared/functions/api/users/api-create-user.d.ts
vendored
Normal file
25
dist/package-shared/functions/api/users/api-create-user.d.ts
vendored
Normal file
@ -0,0 +1,25 @@
|
|||||||
|
import { APICreateUserFunctionParams } from "../../../types";
|
||||||
|
/**
|
||||||
|
* # API Create User
|
||||||
|
*/
|
||||||
|
export default function apiCreateUser({ encryptionKey, payload, database, userId, useLocal, }: APICreateUserFunctionParams): Promise<{
|
||||||
|
success: boolean;
|
||||||
|
msg: string;
|
||||||
|
payload: null;
|
||||||
|
sqlResult?: undefined;
|
||||||
|
} | {
|
||||||
|
success: boolean;
|
||||||
|
msg: string;
|
||||||
|
payload?: undefined;
|
||||||
|
sqlResult?: undefined;
|
||||||
|
} | {
|
||||||
|
success: boolean;
|
||||||
|
payload: any;
|
||||||
|
msg?: undefined;
|
||||||
|
sqlResult?: undefined;
|
||||||
|
} | {
|
||||||
|
success: boolean;
|
||||||
|
msg: string;
|
||||||
|
sqlResult: any;
|
||||||
|
payload: null;
|
||||||
|
}>;
|
142
dist/package-shared/functions/api/users/api-create-user.js
vendored
Normal file
142
dist/package-shared/functions/api/users/api-create-user.js
vendored
Normal file
@ -0,0 +1,142 @@
|
|||||||
|
"use strict";
|
||||||
|
// @ts-check
|
||||||
|
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||||
|
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||||
|
return new (P || (P = Promise))(function (resolve, reject) {
|
||||||
|
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||||
|
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||||
|
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||||
|
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||||
|
});
|
||||||
|
};
|
||||||
|
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||||
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||||
|
};
|
||||||
|
Object.defineProperty(exports, "__esModule", { value: true });
|
||||||
|
exports.default = apiCreateUser;
|
||||||
|
const addUsersTableToDb_1 = __importDefault(require("../../backend/addUsersTableToDb"));
|
||||||
|
const addDbEntry_1 = __importDefault(require("../../backend/db/addDbEntry"));
|
||||||
|
const updateUsersTableSchema_1 = __importDefault(require("../../backend/updateUsersTableSchema"));
|
||||||
|
const varDatabaseDbHandler_1 = __importDefault(require("../../backend/varDatabaseDbHandler"));
|
||||||
|
const hashPassword_1 = __importDefault(require("../../dsql/hashPassword"));
|
||||||
|
/**
|
||||||
|
* # API Create User
|
||||||
|
*/
|
||||||
|
function apiCreateUser(_a) {
|
||||||
|
return __awaiter(this, arguments, void 0, function* ({ encryptionKey, payload, database, userId, useLocal, }) {
|
||||||
|
const dbFullName = database;
|
||||||
|
const API_USER_ID = userId || process.env.DSQL_API_USER_ID;
|
||||||
|
const finalEncryptionKey = encryptionKey || process.env.DSQL_ENCRYPTION_PASSWORD;
|
||||||
|
if (!finalEncryptionKey) {
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
msg: "No encryption key provided",
|
||||||
|
payload: null,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
if (!(finalEncryptionKey === null || finalEncryptionKey === void 0 ? void 0 : finalEncryptionKey.match(/.{8,}/))) {
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
msg: "Encryption key must be at least 8 characters long",
|
||||||
|
payload: null,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
const hashedPassword = (0, hashPassword_1.default)({
|
||||||
|
encryptionKey: finalEncryptionKey,
|
||||||
|
password: String(payload.password),
|
||||||
|
});
|
||||||
|
payload.password = hashedPassword;
|
||||||
|
const fieldsQuery = `SHOW COLUMNS FROM users`;
|
||||||
|
let fields = yield (0, varDatabaseDbHandler_1.default)({
|
||||||
|
queryString: fieldsQuery,
|
||||||
|
database: dbFullName,
|
||||||
|
useLocal,
|
||||||
|
});
|
||||||
|
if (!(fields === null || fields === void 0 ? void 0 : fields[0])) {
|
||||||
|
const newTable = yield (0, addUsersTableToDb_1.default)({
|
||||||
|
userId: Number(API_USER_ID),
|
||||||
|
database: dbFullName,
|
||||||
|
useLocal,
|
||||||
|
payload: payload,
|
||||||
|
});
|
||||||
|
fields = yield (0, varDatabaseDbHandler_1.default)({
|
||||||
|
queryString: fieldsQuery,
|
||||||
|
database: dbFullName,
|
||||||
|
useLocal,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if (!(fields === null || fields === void 0 ? void 0 : fields[0])) {
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
msg: "Could not create users table",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
const fieldsTitles = fields.map((fieldObject) => fieldObject.Field);
|
||||||
|
let invalidField = null;
|
||||||
|
for (let i = 0; i < Object.keys(payload).length; i++) {
|
||||||
|
const key = Object.keys(payload)[i];
|
||||||
|
if (!fieldsTitles.includes(key)) {
|
||||||
|
yield (0, updateUsersTableSchema_1.default)({
|
||||||
|
userId: Number(API_USER_ID),
|
||||||
|
database: dbFullName,
|
||||||
|
newPayload: {
|
||||||
|
[key]: payload[key],
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (invalidField) {
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
msg: `${invalidField} is not a valid field!`,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
const existingUserQuery = `SELECT * FROM users WHERE email = ?${payload.username ? " OR username = ?" : ""}`;
|
||||||
|
const existingUserValues = payload.username
|
||||||
|
? [payload.email, payload.username]
|
||||||
|
: [payload.email];
|
||||||
|
const existingUser = yield (0, varDatabaseDbHandler_1.default)({
|
||||||
|
queryString: existingUserQuery,
|
||||||
|
queryValuesArray: existingUserValues,
|
||||||
|
database: dbFullName,
|
||||||
|
useLocal,
|
||||||
|
});
|
||||||
|
if (existingUser === null || existingUser === void 0 ? void 0 : existingUser[0]) {
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
msg: "User Already Exists",
|
||||||
|
payload: null,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
const addUser = yield (0, addDbEntry_1.default)({
|
||||||
|
dbContext: "Dsql User",
|
||||||
|
paradigm: "Full Access",
|
||||||
|
dbFullName: dbFullName,
|
||||||
|
tableName: "users",
|
||||||
|
data: Object.assign(Object.assign({}, payload), { image: process.env.DSQL_DEFAULT_USER_IMAGE ||
|
||||||
|
"/images/user-preset.png", image_thumbnail: process.env.DSQL_DEFAULT_USER_IMAGE ||
|
||||||
|
"/images/user-preset-thumbnail.png" }),
|
||||||
|
useLocal,
|
||||||
|
});
|
||||||
|
if (addUser === null || addUser === void 0 ? void 0 : addUser.insertId) {
|
||||||
|
const newlyAddedUserQuery = `SELECT id,first_name,last_name,email,username,phone,image,image_thumbnail,city,state,country,zip_code,address,verification_status,more_user_data FROM users WHERE id='${addUser.insertId}'`;
|
||||||
|
const newlyAddedUser = yield (0, varDatabaseDbHandler_1.default)({
|
||||||
|
queryString: newlyAddedUserQuery,
|
||||||
|
database: dbFullName,
|
||||||
|
useLocal,
|
||||||
|
});
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
payload: newlyAddedUser[0],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
msg: "Could not create user",
|
||||||
|
sqlResult: addUser,
|
||||||
|
payload: null,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
15
dist/package-shared/functions/api/users/api-delete-user.d.ts
vendored
Normal file
15
dist/package-shared/functions/api/users/api-delete-user.d.ts
vendored
Normal file
@ -0,0 +1,15 @@
|
|||||||
|
type Param = {
|
||||||
|
dbFullName: string;
|
||||||
|
deletedUserId: string | number;
|
||||||
|
useLocal?: boolean;
|
||||||
|
};
|
||||||
|
type Return = {
|
||||||
|
success: boolean;
|
||||||
|
result?: any;
|
||||||
|
msg?: string;
|
||||||
|
};
|
||||||
|
/**
|
||||||
|
* # Update API User Function
|
||||||
|
*/
|
||||||
|
export default function apiDeleteUser({ dbFullName, deletedUserId, useLocal, }: Param): Promise<Return>;
|
||||||
|
export {};
|
51
dist/package-shared/functions/api/users/api-delete-user.js
vendored
Normal file
51
dist/package-shared/functions/api/users/api-delete-user.js
vendored
Normal file
@ -0,0 +1,51 @@
|
|||||||
|
"use strict";
|
||||||
|
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||||
|
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||||
|
return new (P || (P = Promise))(function (resolve, reject) {
|
||||||
|
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||||
|
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||||
|
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||||
|
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||||
|
});
|
||||||
|
};
|
||||||
|
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||||
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||||
|
};
|
||||||
|
Object.defineProperty(exports, "__esModule", { value: true });
|
||||||
|
exports.default = apiDeleteUser;
|
||||||
|
const deleteDbEntry_1 = __importDefault(require("../../backend/db/deleteDbEntry"));
|
||||||
|
const varDatabaseDbHandler_1 = __importDefault(require("../../backend/varDatabaseDbHandler"));
|
||||||
|
/**
|
||||||
|
* # Update API User Function
|
||||||
|
*/
|
||||||
|
function apiDeleteUser(_a) {
|
||||||
|
return __awaiter(this, arguments, void 0, function* ({ dbFullName, deletedUserId, useLocal, }) {
|
||||||
|
const existingUserQuery = `SELECT * FROM users WHERE id = ?`;
|
||||||
|
const existingUserValues = [deletedUserId];
|
||||||
|
const existingUser = yield (0, varDatabaseDbHandler_1.default)({
|
||||||
|
queryString: existingUserQuery,
|
||||||
|
queryValuesArray: existingUserValues,
|
||||||
|
database: dbFullName,
|
||||||
|
useLocal,
|
||||||
|
});
|
||||||
|
if (!(existingUser === null || existingUser === void 0 ? void 0 : existingUser[0])) {
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
msg: "User not found",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
const deleteUser = yield (0, deleteDbEntry_1.default)({
|
||||||
|
dbContext: "Dsql User",
|
||||||
|
paradigm: "Full Access",
|
||||||
|
dbFullName,
|
||||||
|
tableName: "users",
|
||||||
|
identifierColumnName: "id",
|
||||||
|
identifierValue: deletedUserId,
|
||||||
|
useLocal,
|
||||||
|
});
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
result: deleteUser,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
}
|
5
dist/package-shared/functions/api/users/api-get-user.d.ts
vendored
Normal file
5
dist/package-shared/functions/api/users/api-get-user.d.ts
vendored
Normal file
@ -0,0 +1,5 @@
|
|||||||
|
import { APIGetUserFunctionParams, GetUserFunctionReturn } from "../../../types";
|
||||||
|
/**
|
||||||
|
* # API Get User
|
||||||
|
*/
|
||||||
|
export default function apiGetUser({ fields, dbFullName, userId, useLocal, }: APIGetUserFunctionParams): Promise<GetUserFunctionReturn>;
|
41
dist/package-shared/functions/api/users/api-get-user.js
vendored
Normal file
41
dist/package-shared/functions/api/users/api-get-user.js
vendored
Normal file
@ -0,0 +1,41 @@
|
|||||||
|
"use strict";
|
||||||
|
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||||
|
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||||
|
return new (P || (P = Promise))(function (resolve, reject) {
|
||||||
|
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||||
|
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||||
|
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||||
|
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||||
|
});
|
||||||
|
};
|
||||||
|
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||||
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||||
|
};
|
||||||
|
Object.defineProperty(exports, "__esModule", { value: true });
|
||||||
|
exports.default = apiGetUser;
|
||||||
|
const varDatabaseDbHandler_1 = __importDefault(require("../../backend/varDatabaseDbHandler"));
|
||||||
|
/**
|
||||||
|
* # API Get User
|
||||||
|
*/
|
||||||
|
function apiGetUser(_a) {
|
||||||
|
return __awaiter(this, arguments, void 0, function* ({ fields, dbFullName, userId, useLocal, }) {
|
||||||
|
const query = `SELECT ${fields.join(",")} FROM users WHERE id=?`;
|
||||||
|
const API_USER_ID = userId || process.env.DSQL_API_USER_ID;
|
||||||
|
let foundUser = yield (0, varDatabaseDbHandler_1.default)({
|
||||||
|
queryString: query,
|
||||||
|
queryValuesArray: [API_USER_ID],
|
||||||
|
database: dbFullName.replace(/[^a-z0-9_]/g, ""),
|
||||||
|
useLocal,
|
||||||
|
});
|
||||||
|
if (!foundUser || !foundUser[0]) {
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
payload: null,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
payload: foundUser[0],
|
||||||
|
};
|
||||||
|
});
|
||||||
|
}
|
5
dist/package-shared/functions/api/users/api-login.d.ts
vendored
Normal file
5
dist/package-shared/functions/api/users/api-login.d.ts
vendored
Normal file
@ -0,0 +1,5 @@
|
|||||||
|
import { APILoginFunctionParams, APILoginFunctionReturn } from "../../../types";
|
||||||
|
/**
|
||||||
|
* # API Login
|
||||||
|
*/
|
||||||
|
export default function apiLoginUser({ encryptionKey, email, username, password, database, additionalFields, email_login, email_login_code, email_login_field, token, skipPassword, social, useLocal, }: APILoginFunctionParams): Promise<APILoginFunctionReturn>;
|
137
dist/package-shared/functions/api/users/api-login.js
vendored
Normal file
137
dist/package-shared/functions/api/users/api-login.js
vendored
Normal file
@ -0,0 +1,137 @@
|
|||||||
|
"use strict";
|
||||||
|
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||||
|
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||||
|
return new (P || (P = Promise))(function (resolve, reject) {
|
||||||
|
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||||
|
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||||
|
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||||
|
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||||
|
});
|
||||||
|
};
|
||||||
|
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||||
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||||
|
};
|
||||||
|
Object.defineProperty(exports, "__esModule", { value: true });
|
||||||
|
exports.default = apiLoginUser;
|
||||||
|
const varDatabaseDbHandler_1 = __importDefault(require("../../backend/varDatabaseDbHandler"));
|
||||||
|
const hashPassword_1 = __importDefault(require("../../dsql/hashPassword"));
|
||||||
|
/**
|
||||||
|
* # API Login
|
||||||
|
*/
|
||||||
|
function apiLoginUser(_a) {
|
||||||
|
return __awaiter(this, arguments, void 0, function* ({ encryptionKey, email, username, password, database, additionalFields, email_login, email_login_code, email_login_field, token, skipPassword, social, useLocal, }) {
|
||||||
|
const dbFullName = database;
|
||||||
|
/**
|
||||||
|
* Check input validity
|
||||||
|
*
|
||||||
|
* @description Check input validity
|
||||||
|
*/
|
||||||
|
if ((email === null || email === void 0 ? void 0 : email.match(/ /)) ||
|
||||||
|
(username && (username === null || username === void 0 ? void 0 : username.match(/ /))) ||
|
||||||
|
(password && (password === null || password === void 0 ? void 0 : password.match(/ /)))) {
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
msg: "Invalid Email/Password format",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* Password hash
|
||||||
|
*
|
||||||
|
* @description Password hash
|
||||||
|
*/
|
||||||
|
let hashedPassword = password
|
||||||
|
? (0, hashPassword_1.default)({
|
||||||
|
encryptionKey: encryptionKey,
|
||||||
|
password: password,
|
||||||
|
})
|
||||||
|
: null;
|
||||||
|
let foundUser = yield (0, varDatabaseDbHandler_1.default)({
|
||||||
|
queryString: `SELECT * FROM users WHERE email = ? OR username = ?`,
|
||||||
|
queryValuesArray: [email, username],
|
||||||
|
database: dbFullName.replace(/[^a-z0-9_]/g, ""),
|
||||||
|
useLocal,
|
||||||
|
});
|
||||||
|
if ((!foundUser || !foundUser[0]) && !social)
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
payload: null,
|
||||||
|
msg: "No user found",
|
||||||
|
};
|
||||||
|
let isPasswordCorrect = false;
|
||||||
|
if ((foundUser === null || foundUser === void 0 ? void 0 : foundUser[0]) && !email_login && skipPassword) {
|
||||||
|
isPasswordCorrect = true;
|
||||||
|
}
|
||||||
|
else if ((foundUser === null || foundUser === void 0 ? void 0 : foundUser[0]) && !email_login) {
|
||||||
|
isPasswordCorrect = hashedPassword === foundUser[0].password;
|
||||||
|
}
|
||||||
|
else if (foundUser &&
|
||||||
|
foundUser[0] &&
|
||||||
|
email_login &&
|
||||||
|
email_login_code &&
|
||||||
|
email_login_field) {
|
||||||
|
/** @type {string} */
|
||||||
|
const tempCode = foundUser[0][email_login_field];
|
||||||
|
if (!tempCode)
|
||||||
|
throw new Error("No code Found!");
|
||||||
|
const tempCodeArray = tempCode.split("-");
|
||||||
|
const [code, codeDate] = tempCodeArray;
|
||||||
|
const millisecond15mins = 1000 * 60 * 15;
|
||||||
|
if (Date.now() - Number(codeDate) > millisecond15mins) {
|
||||||
|
throw new Error("Code Expired");
|
||||||
|
}
|
||||||
|
isPasswordCorrect = code === email_login_code;
|
||||||
|
}
|
||||||
|
let socialUserValid = false;
|
||||||
|
if (!isPasswordCorrect && !socialUserValid) {
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
msg: "Wrong password, no social login validity",
|
||||||
|
payload: null,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
if (isPasswordCorrect && email_login) {
|
||||||
|
const resetTempCode = yield (0, varDatabaseDbHandler_1.default)({
|
||||||
|
queryString: `UPDATE users SET ${email_login_field} = '' WHERE email = ? OR username = ?`,
|
||||||
|
queryValuesArray: [email, username],
|
||||||
|
database: dbFullName.replace(/[^a-z0-9_]/g, ""),
|
||||||
|
useLocal,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
let csrfKey = Math.random().toString(36).substring(2) +
|
||||||
|
"-" +
|
||||||
|
Math.random().toString(36).substring(2);
|
||||||
|
let userPayload = {
|
||||||
|
id: foundUser[0].id,
|
||||||
|
first_name: foundUser[0].first_name,
|
||||||
|
last_name: foundUser[0].last_name,
|
||||||
|
username: foundUser[0].username,
|
||||||
|
email: foundUser[0].email,
|
||||||
|
phone: foundUser[0].phone,
|
||||||
|
social_id: foundUser[0].social_id,
|
||||||
|
image: foundUser[0].image,
|
||||||
|
image_thumbnail: foundUser[0].image_thumbnail,
|
||||||
|
verification_status: foundUser[0].verification_status,
|
||||||
|
social_login: foundUser[0].social_login,
|
||||||
|
social_platform: foundUser[0].social_platform,
|
||||||
|
csrf_k: csrfKey,
|
||||||
|
more_data: foundUser[0].more_user_data,
|
||||||
|
logged_in_status: true,
|
||||||
|
date: Date.now(),
|
||||||
|
};
|
||||||
|
const resposeObject = {
|
||||||
|
success: true,
|
||||||
|
msg: "Login Successful",
|
||||||
|
payload: userPayload,
|
||||||
|
userId: foundUser[0].id,
|
||||||
|
csrf: csrfKey,
|
||||||
|
};
|
||||||
|
if (additionalFields &&
|
||||||
|
Array.isArray(additionalFields) &&
|
||||||
|
additionalFields.length > 0) {
|
||||||
|
additionalFields.forEach((key) => {
|
||||||
|
userPayload[key] = foundUser[0][key];
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return resposeObject;
|
||||||
|
});
|
||||||
|
}
|
14
dist/package-shared/functions/api/users/api-reauth-user.d.ts
vendored
Normal file
14
dist/package-shared/functions/api/users/api-reauth-user.d.ts
vendored
Normal file
@ -0,0 +1,14 @@
|
|||||||
|
import { APILoginFunctionReturn } from "../../../types";
|
||||||
|
type Param = {
|
||||||
|
existingUser: {
|
||||||
|
[s: string]: any;
|
||||||
|
};
|
||||||
|
database?: string;
|
||||||
|
additionalFields?: string[];
|
||||||
|
useLocal?: boolean;
|
||||||
|
};
|
||||||
|
/**
|
||||||
|
* # Re-authenticate API user
|
||||||
|
*/
|
||||||
|
export default function apiReauthUser({ existingUser, database, additionalFields, useLocal, }: Param): Promise<APILoginFunctionReturn>;
|
||||||
|
export {};
|
72
dist/package-shared/functions/api/users/api-reauth-user.js
vendored
Normal file
72
dist/package-shared/functions/api/users/api-reauth-user.js
vendored
Normal file
@ -0,0 +1,72 @@
|
|||||||
|
"use strict";
|
||||||
|
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||||
|
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||||
|
return new (P || (P = Promise))(function (resolve, reject) {
|
||||||
|
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||||
|
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||||
|
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||||
|
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||||
|
});
|
||||||
|
};
|
||||||
|
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||||
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||||
|
};
|
||||||
|
Object.defineProperty(exports, "__esModule", { value: true });
|
||||||
|
exports.default = apiReauthUser;
|
||||||
|
const varDatabaseDbHandler_1 = __importDefault(require("../../backend/varDatabaseDbHandler"));
|
||||||
|
/**
|
||||||
|
* # Re-authenticate API user
|
||||||
|
*/
|
||||||
|
function apiReauthUser(_a) {
|
||||||
|
return __awaiter(this, arguments, void 0, function* ({ existingUser, database, additionalFields, useLocal, }) {
|
||||||
|
let foundUser = (existingUser === null || existingUser === void 0 ? void 0 : existingUser.id) && existingUser.id.toString().match(/./)
|
||||||
|
? yield (0, varDatabaseDbHandler_1.default)({
|
||||||
|
queryString: `SELECT * FROM users WHERE id=?`,
|
||||||
|
queryValuesArray: [existingUser.id.toString()],
|
||||||
|
database,
|
||||||
|
useLocal,
|
||||||
|
})
|
||||||
|
: null;
|
||||||
|
if (!foundUser || !foundUser[0])
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
payload: null,
|
||||||
|
msg: "No user found",
|
||||||
|
};
|
||||||
|
let csrfKey = Math.random().toString(36).substring(2) +
|
||||||
|
"-" +
|
||||||
|
Math.random().toString(36).substring(2);
|
||||||
|
/** @type {import("../../../types").DATASQUIREL_LoggedInUser} */
|
||||||
|
let userPayload = {
|
||||||
|
id: foundUser[0].id,
|
||||||
|
first_name: foundUser[0].first_name,
|
||||||
|
last_name: foundUser[0].last_name,
|
||||||
|
username: foundUser[0].username,
|
||||||
|
email: foundUser[0].email,
|
||||||
|
phone: foundUser[0].phone,
|
||||||
|
social_id: foundUser[0].social_id,
|
||||||
|
image: foundUser[0].image,
|
||||||
|
image_thumbnail: foundUser[0].image_thumbnail,
|
||||||
|
verification_status: foundUser[0].verification_status,
|
||||||
|
social_login: foundUser[0].social_login,
|
||||||
|
social_platform: foundUser[0].social_platform,
|
||||||
|
csrf_k: csrfKey,
|
||||||
|
more_data: foundUser[0].more_user_data,
|
||||||
|
logged_in_status: true,
|
||||||
|
date: Date.now(),
|
||||||
|
};
|
||||||
|
if (additionalFields &&
|
||||||
|
Array.isArray(additionalFields) &&
|
||||||
|
additionalFields.length > 0) {
|
||||||
|
additionalFields.forEach((key) => {
|
||||||
|
userPayload[key] = foundUser[0][key];
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
msg: "Login Successful",
|
||||||
|
payload: userPayload,
|
||||||
|
csrf: csrfKey,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
}
|
23
dist/package-shared/functions/api/users/api-send-email-code.d.ts
vendored
Normal file
23
dist/package-shared/functions/api/users/api-send-email-code.d.ts
vendored
Normal file
@ -0,0 +1,23 @@
|
|||||||
|
import http from "http";
|
||||||
|
import { SendOneTimeCodeEmailResponse } from "../../../types";
|
||||||
|
type Param = {
|
||||||
|
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 & {
|
||||||
|
[s: string]: any;
|
||||||
|
};
|
||||||
|
extraCookies?: import("../../../../package-shared/types").CookieObject[];
|
||||||
|
};
|
||||||
|
/**
|
||||||
|
* # Send Email Login Code
|
||||||
|
*/
|
||||||
|
export default function apiSendEmailCode({ email, database, email_login_field, mail_domain, mail_port, sender, mail_username, mail_password, html, useLocal, response, extraCookies, }: Param): Promise<SendOneTimeCodeEmailResponse>;
|
||||||
|
export {};
|
134
dist/package-shared/functions/api/users/api-send-email-code.js
vendored
Normal file
134
dist/package-shared/functions/api/users/api-send-email-code.js
vendored
Normal file
@ -0,0 +1,134 @@
|
|||||||
|
"use strict";
|
||||||
|
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||||
|
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||||
|
return new (P || (P = Promise))(function (resolve, reject) {
|
||||||
|
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||||
|
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||||
|
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||||
|
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||||
|
});
|
||||||
|
};
|
||||||
|
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||||
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||||
|
};
|
||||||
|
Object.defineProperty(exports, "__esModule", { value: true });
|
||||||
|
exports.default = apiSendEmailCode;
|
||||||
|
const varDatabaseDbHandler_1 = __importDefault(require("../../backend/varDatabaseDbHandler"));
|
||||||
|
const nodemailer_1 = __importDefault(require("nodemailer"));
|
||||||
|
const get_auth_cookie_names_1 = __importDefault(require("../../backend/cookies/get-auth-cookie-names"));
|
||||||
|
const encrypt_1 = __importDefault(require("../../dsql/encrypt"));
|
||||||
|
const serialize_cookies_1 = __importDefault(require("../../../utils/serialize-cookies"));
|
||||||
|
/**
|
||||||
|
* # Send Email Login Code
|
||||||
|
*/
|
||||||
|
function apiSendEmailCode(_a) {
|
||||||
|
return __awaiter(this, arguments, void 0, function* ({ email, database, email_login_field, mail_domain, mail_port, sender, mail_username, mail_password, html, useLocal, response, extraCookies, }) {
|
||||||
|
if (email === null || email === void 0 ? void 0 : email.match(/ /)) {
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
msg: "Invalid Email/Password format",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
const createdAt = Date.now();
|
||||||
|
const foundUserQuery = `SELECT * FROM users WHERE email = ?`;
|
||||||
|
const foundUserValues = [email];
|
||||||
|
let foundUser = yield (0, varDatabaseDbHandler_1.default)({
|
||||||
|
queryString: foundUserQuery,
|
||||||
|
queryValuesArray: foundUserValues,
|
||||||
|
database,
|
||||||
|
useLocal,
|
||||||
|
});
|
||||||
|
////////////////////////////////////////
|
||||||
|
////////////////////////////////////////
|
||||||
|
////////////////////////////////////////
|
||||||
|
if (!foundUser || !foundUser[0]) {
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
msg: "No user found",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
function generateCode() {
|
||||||
|
const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
|
||||||
|
let code = "";
|
||||||
|
for (let i = 0; i < 8; i++) {
|
||||||
|
code += chars[Math.floor(Math.random() * chars.length)];
|
||||||
|
}
|
||||||
|
return code;
|
||||||
|
}
|
||||||
|
if ((foundUser === null || foundUser === void 0 ? void 0 : foundUser[0]) && email_login_field) {
|
||||||
|
const tempCode = generateCode();
|
||||||
|
let transporter = nodemailer_1.default.createTransport({
|
||||||
|
host: mail_domain || process.env.DSQL_MAIL_HOST,
|
||||||
|
port: mail_port
|
||||||
|
? mail_port
|
||||||
|
: process.env.DSQL_MAIL_PORT
|
||||||
|
? Number(process.env.DSQL_MAIL_PORT)
|
||||||
|
: 465,
|
||||||
|
secure: true,
|
||||||
|
auth: {
|
||||||
|
user: mail_username || process.env.DSQL_MAIL_EMAIL,
|
||||||
|
pass: mail_password || process.env.DSQL_MAIL_PASSWORD,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
let mailObject = {};
|
||||||
|
mailObject["from"] = `"Datasquirel SSO" <${sender || "support@datasquirel.com"}>`;
|
||||||
|
mailObject["sender"] = sender || "support@datasquirel.com";
|
||||||
|
mailObject["to"] = email;
|
||||||
|
mailObject["subject"] = "One Time Login Code";
|
||||||
|
mailObject["html"] = html.replace(/{{code}}/, tempCode);
|
||||||
|
const info = yield transporter.sendMail(mailObject);
|
||||||
|
if (!(info === null || info === void 0 ? void 0 : info.accepted))
|
||||||
|
throw new Error("Mail not Sent!");
|
||||||
|
const setTempCodeQuery = `UPDATE users SET ${email_login_field} = ? WHERE email = ?`;
|
||||||
|
const setTempCodeValues = [tempCode + `-${createdAt}`, email];
|
||||||
|
let setTempCode = yield (0, varDatabaseDbHandler_1.default)({
|
||||||
|
queryString: setTempCodeQuery,
|
||||||
|
queryValuesArray: setTempCodeValues,
|
||||||
|
database: database,
|
||||||
|
useLocal,
|
||||||
|
});
|
||||||
|
/** @type {import("../../../types").SendOneTimeCodeEmailResponse} */
|
||||||
|
const resObject = {
|
||||||
|
success: true,
|
||||||
|
code: tempCode,
|
||||||
|
email: email,
|
||||||
|
createdAt,
|
||||||
|
msg: "Success",
|
||||||
|
};
|
||||||
|
if (response) {
|
||||||
|
const cookieKeyNames = (0, get_auth_cookie_names_1.default)();
|
||||||
|
const oneTimeCodeCookieName = cookieKeyNames.oneTimeCodeName;
|
||||||
|
const encryptedPayload = (0, encrypt_1.default)({
|
||||||
|
data: JSON.stringify(resObject),
|
||||||
|
});
|
||||||
|
if (!encryptedPayload) {
|
||||||
|
throw new Error("apiSendEmailCode Error: Failed to encrypt payload");
|
||||||
|
}
|
||||||
|
/** @type {import("../../../../package-shared/types").CookieObject} */
|
||||||
|
const oneTimeCookieObject = {
|
||||||
|
name: oneTimeCodeCookieName,
|
||||||
|
value: encryptedPayload,
|
||||||
|
sameSite: "Strict",
|
||||||
|
path: "/",
|
||||||
|
httpOnly: true,
|
||||||
|
secure: true,
|
||||||
|
};
|
||||||
|
/** @type {import("../../../../package-shared/types").CookieObject[]} */
|
||||||
|
const cookiesObjectArray = extraCookies
|
||||||
|
? [...extraCookies, oneTimeCookieObject]
|
||||||
|
: [oneTimeCookieObject];
|
||||||
|
const serializedCookies = (0, serialize_cookies_1.default)({
|
||||||
|
cookies: cookiesObjectArray,
|
||||||
|
});
|
||||||
|
response.setHeader("Set-Cookie", serializedCookies);
|
||||||
|
}
|
||||||
|
return resObject;
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
msg: "Invalid Email/Password format",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
19
dist/package-shared/functions/api/users/api-update-user.d.ts
vendored
Normal file
19
dist/package-shared/functions/api/users/api-update-user.d.ts
vendored
Normal file
@ -0,0 +1,19 @@
|
|||||||
|
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
|
||||||
|
*/
|
||||||
|
export default function apiUpdateUser({ payload, dbFullName, updatedUserId, useLocal, dbSchema, }: Param): Promise<Return>;
|
||||||
|
export {};
|
85
dist/package-shared/functions/api/users/api-update-user.js
vendored
Normal file
85
dist/package-shared/functions/api/users/api-update-user.js
vendored
Normal file
@ -0,0 +1,85 @@
|
|||||||
|
"use strict";
|
||||||
|
// @ts-check
|
||||||
|
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||||
|
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||||
|
return new (P || (P = Promise))(function (resolve, reject) {
|
||||||
|
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||||
|
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||||
|
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||||
|
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||||
|
});
|
||||||
|
};
|
||||||
|
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||||
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||||
|
};
|
||||||
|
Object.defineProperty(exports, "__esModule", { value: true });
|
||||||
|
exports.default = apiUpdateUser;
|
||||||
|
const updateDbEntry_1 = __importDefault(require("../../backend/db/updateDbEntry"));
|
||||||
|
const encrypt_1 = __importDefault(require("../../dsql/encrypt"));
|
||||||
|
const hashPassword_1 = __importDefault(require("../../dsql/hashPassword"));
|
||||||
|
const varDatabaseDbHandler_1 = __importDefault(require("../../backend/varDatabaseDbHandler"));
|
||||||
|
/**
|
||||||
|
* # Update API User Function
|
||||||
|
*/
|
||||||
|
function apiUpdateUser(_a) {
|
||||||
|
return __awaiter(this, arguments, void 0, function* ({ payload, dbFullName, updatedUserId, useLocal, dbSchema, }) {
|
||||||
|
const existingUserQuery = `SELECT * FROM users WHERE id = ?`;
|
||||||
|
const existingUserValues = [updatedUserId];
|
||||||
|
const existingUser = yield (0, varDatabaseDbHandler_1.default)({
|
||||||
|
queryString: existingUserQuery,
|
||||||
|
queryValuesArray: existingUserValues,
|
||||||
|
database: dbFullName,
|
||||||
|
useLocal,
|
||||||
|
});
|
||||||
|
if (!(existingUser === null || existingUser === void 0 ? void 0 : existingUser[0])) {
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
msg: "User not found",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
const data = (() => {
|
||||||
|
const reqBodyKeys = Object.keys(payload);
|
||||||
|
const targetTableSchema = (() => {
|
||||||
|
var _a;
|
||||||
|
try {
|
||||||
|
const targetDatabaseSchema = (_a = dbSchema === null || dbSchema === void 0 ? void 0 : dbSchema.tables) === null || _a === void 0 ? void 0 : _a.find((tbl) => tbl.tableName == "users");
|
||||||
|
return targetDatabaseSchema;
|
||||||
|
}
|
||||||
|
catch (error) {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
})();
|
||||||
|
/** @type {any} */
|
||||||
|
const finalData = {};
|
||||||
|
reqBodyKeys.forEach((key) => {
|
||||||
|
var _a;
|
||||||
|
const targetFieldSchema = (_a = targetTableSchema === null || targetTableSchema === void 0 ? void 0 : targetTableSchema.fields) === null || _a === void 0 ? void 0 : _a.find((field) => field.fieldName == key);
|
||||||
|
if (key === null || key === void 0 ? void 0 : key.match(/^date_|^id$|^uuid$/))
|
||||||
|
return;
|
||||||
|
let value = payload[key];
|
||||||
|
if (targetFieldSchema === null || targetFieldSchema === void 0 ? void 0 : targetFieldSchema.encrypted) {
|
||||||
|
value = (0, encrypt_1.default)({ data: value });
|
||||||
|
}
|
||||||
|
finalData[key] = value;
|
||||||
|
});
|
||||||
|
if (finalData.password && typeof finalData.password == "string") {
|
||||||
|
finalData.password = (0, hashPassword_1.default)({ password: finalData.password });
|
||||||
|
}
|
||||||
|
return finalData;
|
||||||
|
})();
|
||||||
|
const updateUser = yield (0, updateDbEntry_1.default)({
|
||||||
|
dbContext: "Dsql User",
|
||||||
|
paradigm: "Full Access",
|
||||||
|
dbFullName,
|
||||||
|
tableName: "users",
|
||||||
|
identifierColumnName: "id",
|
||||||
|
identifierValue: updatedUserId,
|
||||||
|
data: data,
|
||||||
|
useLocal,
|
||||||
|
});
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
payload: updateUser,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
}
|
17
dist/package-shared/functions/api/users/social/api-github-login.d.ts
vendored
Normal file
17
dist/package-shared/functions/api/users/social/api-github-login.d.ts
vendored
Normal file
@ -0,0 +1,17 @@
|
|||||||
|
import { APILoginFunctionReturn } from "../../../../types";
|
||||||
|
type Param = {
|
||||||
|
code?: string;
|
||||||
|
clientId?: string;
|
||||||
|
clientSecret?: string;
|
||||||
|
database?: string;
|
||||||
|
additionalFields?: string[];
|
||||||
|
additionalData?: {
|
||||||
|
[s: string]: string | number;
|
||||||
|
};
|
||||||
|
email?: string;
|
||||||
|
};
|
||||||
|
/**
|
||||||
|
* # API Login with Github
|
||||||
|
*/
|
||||||
|
export default function apiGithubLogin({ code, clientId, clientSecret, database, additionalFields, email, additionalData, }: Param): Promise<APILoginFunctionReturn>;
|
||||||
|
export {};
|
89
dist/package-shared/functions/api/users/social/api-github-login.js
vendored
Normal file
89
dist/package-shared/functions/api/users/social/api-github-login.js
vendored
Normal file
@ -0,0 +1,89 @@
|
|||||||
|
"use strict";
|
||||||
|
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||||
|
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||||
|
return new (P || (P = Promise))(function (resolve, reject) {
|
||||||
|
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||||
|
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||||
|
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||||
|
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||||
|
});
|
||||||
|
};
|
||||||
|
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||||
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||||
|
};
|
||||||
|
Object.defineProperty(exports, "__esModule", { value: true });
|
||||||
|
exports.default = apiGithubLogin;
|
||||||
|
const handleSocialDb_1 = __importDefault(require("../../social-login/handleSocialDb"));
|
||||||
|
const githubLogin_1 = __importDefault(require("../../social-login/githubLogin"));
|
||||||
|
const camelJoinedtoCamelSpace_1 = __importDefault(require("../../../../utils/camelJoinedtoCamelSpace"));
|
||||||
|
/**
|
||||||
|
* # API Login with Github
|
||||||
|
*/
|
||||||
|
function apiGithubLogin(_a) {
|
||||||
|
return __awaiter(this, arguments, void 0, function* ({ code, clientId, clientSecret, database, additionalFields, email, additionalData, }) {
|
||||||
|
if (!code || !clientId || !clientSecret || !database) {
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
msg: "Missing query params",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
if (typeof code !== "string" ||
|
||||||
|
typeof clientId !== "string" ||
|
||||||
|
typeof clientSecret !== "string" ||
|
||||||
|
typeof database !== "string") {
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
msg: "Wrong Parameters",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* Create new user folder and file
|
||||||
|
*
|
||||||
|
* @description Create new user folder and file
|
||||||
|
*/
|
||||||
|
const gitHubUser = yield (0, githubLogin_1.default)({
|
||||||
|
code: code,
|
||||||
|
clientId: clientId,
|
||||||
|
clientSecret: clientSecret,
|
||||||
|
});
|
||||||
|
if (!gitHubUser) {
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
msg: "No github user returned",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
const socialId = gitHubUser.name || gitHubUser.id || gitHubUser.login;
|
||||||
|
const targetName = gitHubUser.name || gitHubUser.login;
|
||||||
|
const nameArray = (targetName === null || targetName === void 0 ? void 0 : targetName.match(/ /))
|
||||||
|
? targetName === null || targetName === void 0 ? void 0 : targetName.split(" ")
|
||||||
|
: (targetName === null || targetName === void 0 ? void 0 : targetName.match(/\-/))
|
||||||
|
? targetName === null || targetName === void 0 ? void 0 : targetName.split("-")
|
||||||
|
: [targetName];
|
||||||
|
let payload = {
|
||||||
|
email: gitHubUser.email,
|
||||||
|
first_name: (0, camelJoinedtoCamelSpace_1.default)(nameArray[0]),
|
||||||
|
last_name: (0, camelJoinedtoCamelSpace_1.default)(nameArray[1]),
|
||||||
|
social_id: socialId,
|
||||||
|
social_platform: "github",
|
||||||
|
image: gitHubUser.avatar_url,
|
||||||
|
image_thumbnail: gitHubUser.avatar_url,
|
||||||
|
username: "github-user-" + socialId,
|
||||||
|
};
|
||||||
|
if (additionalData) {
|
||||||
|
payload = Object.assign(Object.assign({}, payload), additionalData);
|
||||||
|
}
|
||||||
|
const loggedInGithubUser = yield (0, handleSocialDb_1.default)({
|
||||||
|
database,
|
||||||
|
email: gitHubUser.email,
|
||||||
|
payload,
|
||||||
|
social_platform: "github",
|
||||||
|
social_id: socialId,
|
||||||
|
supEmail: email,
|
||||||
|
additionalFields,
|
||||||
|
});
|
||||||
|
////////////////////////////////////////////////
|
||||||
|
////////////////////////////////////////////////
|
||||||
|
////////////////////////////////////////////////
|
||||||
|
return Object.assign({}, loggedInGithubUser);
|
||||||
|
});
|
||||||
|
}
|
5
dist/package-shared/functions/api/users/social/api-google-login.d.ts
vendored
Normal file
5
dist/package-shared/functions/api/users/social/api-google-login.d.ts
vendored
Normal file
@ -0,0 +1,5 @@
|
|||||||
|
import { APIGoogleLoginFunctionParams, APILoginFunctionReturn } from "../../../../types";
|
||||||
|
/**
|
||||||
|
* # API google login
|
||||||
|
*/
|
||||||
|
export default function apiGoogleLogin({ token, database, additionalFields, additionalData, }: APIGoogleLoginFunctionParams): Promise<APILoginFunctionReturn>;
|
99
dist/package-shared/functions/api/users/social/api-google-login.js
vendored
Normal file
99
dist/package-shared/functions/api/users/social/api-google-login.js
vendored
Normal file
@ -0,0 +1,99 @@
|
|||||||
|
"use strict";
|
||||||
|
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||||
|
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||||
|
return new (P || (P = Promise))(function (resolve, reject) {
|
||||||
|
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||||
|
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||||
|
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||||
|
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||||
|
});
|
||||||
|
};
|
||||||
|
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||||
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||||
|
};
|
||||||
|
Object.defineProperty(exports, "__esModule", { value: true });
|
||||||
|
exports.default = apiGoogleLogin;
|
||||||
|
const https_1 = __importDefault(require("https"));
|
||||||
|
const handleSocialDb_1 = __importDefault(require("../../social-login/handleSocialDb"));
|
||||||
|
const ejson_1 = __importDefault(require("../../../../utils/ejson"));
|
||||||
|
/**
|
||||||
|
* # API google login
|
||||||
|
*/
|
||||||
|
function apiGoogleLogin(_a) {
|
||||||
|
return __awaiter(this, arguments, void 0, function* ({ token, database, additionalFields, additionalData, }) {
|
||||||
|
try {
|
||||||
|
const gUser = yield new Promise((resolve, reject) => {
|
||||||
|
https_1.default
|
||||||
|
.request({
|
||||||
|
method: "GET",
|
||||||
|
hostname: "www.googleapis.com",
|
||||||
|
path: "/oauth2/v3/userinfo",
|
||||||
|
headers: {
|
||||||
|
Authorization: `Bearer ${token}`,
|
||||||
|
},
|
||||||
|
}, (res) => {
|
||||||
|
let data = "";
|
||||||
|
res.on("data", (chunk) => {
|
||||||
|
data += chunk;
|
||||||
|
});
|
||||||
|
res.on("end", () => {
|
||||||
|
resolve(ejson_1.default.parse(data));
|
||||||
|
});
|
||||||
|
})
|
||||||
|
.end();
|
||||||
|
});
|
||||||
|
if (!(gUser === null || gUser === void 0 ? void 0 : gUser.email_verified))
|
||||||
|
throw new Error("No Google User.");
|
||||||
|
////////////////////////////////////////
|
||||||
|
////////////////////////////////////////
|
||||||
|
////////////////////////////////////////
|
||||||
|
if (!database || typeof database != "string" || (database === null || database === void 0 ? void 0 : database.match(/ /))) {
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
payload: undefined,
|
||||||
|
msg: "Please provide a database slug(database name in lowercase with no spaces)",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* Create new user folder and file
|
||||||
|
*
|
||||||
|
* @description Create new user folder and file
|
||||||
|
*/
|
||||||
|
const { given_name, family_name, email, sub, picture } = gUser;
|
||||||
|
/** @type {Object<string, any>} */
|
||||||
|
let payloadObject = {
|
||||||
|
email: email,
|
||||||
|
first_name: given_name,
|
||||||
|
last_name: family_name,
|
||||||
|
social_id: sub,
|
||||||
|
social_platform: "google",
|
||||||
|
image: picture,
|
||||||
|
image_thumbnail: picture,
|
||||||
|
username: `google-user-${sub}`,
|
||||||
|
};
|
||||||
|
if (additionalData) {
|
||||||
|
payloadObject = Object.assign(Object.assign({}, payloadObject), additionalData);
|
||||||
|
}
|
||||||
|
const loggedInGoogleUser = yield (0, handleSocialDb_1.default)({
|
||||||
|
database,
|
||||||
|
email: email || "",
|
||||||
|
payload: payloadObject,
|
||||||
|
social_platform: "google",
|
||||||
|
social_id: sub,
|
||||||
|
additionalFields,
|
||||||
|
});
|
||||||
|
////////////////////////////////////////
|
||||||
|
////////////////////////////////////////
|
||||||
|
////////////////////////////////////////
|
||||||
|
return Object.assign({}, loggedInGoogleUser);
|
||||||
|
}
|
||||||
|
catch ( /** @type {any} */error) {
|
||||||
|
console.log(`apo-google-login.js ERROR: ${error.message}`);
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
payload: undefined,
|
||||||
|
msg: error.message,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
21
dist/package-shared/functions/backend/addAdminUserOnLogin.d.ts
vendored
Normal file
21
dist/package-shared/functions/backend/addAdminUserOnLogin.d.ts
vendored
Normal file
@ -0,0 +1,21 @@
|
|||||||
|
import { DATASQUIREL_LoggedInUser } from "../../types";
|
||||||
|
type Param = {
|
||||||
|
query: {
|
||||||
|
invite: number;
|
||||||
|
database_access: string;
|
||||||
|
priviledge: string;
|
||||||
|
email: string;
|
||||||
|
};
|
||||||
|
useLocal?: boolean;
|
||||||
|
user: DATASQUIREL_LoggedInUser;
|
||||||
|
};
|
||||||
|
/**
|
||||||
|
* Add Admin User on Login
|
||||||
|
* ==============================================================================
|
||||||
|
*
|
||||||
|
* @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
|
||||||
|
* has been created for the invited user
|
||||||
|
*/
|
||||||
|
export default function addAdminUserOnLogin({ query, user, useLocal, }: Param): Promise<any>;
|
||||||
|
export {};
|
110
dist/package-shared/functions/backend/addAdminUserOnLogin.js
vendored
Normal file
110
dist/package-shared/functions/backend/addAdminUserOnLogin.js
vendored
Normal file
@ -0,0 +1,110 @@
|
|||||||
|
"use strict";
|
||||||
|
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||||
|
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||||
|
return new (P || (P = Promise))(function (resolve, reject) {
|
||||||
|
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||||
|
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||||
|
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||||
|
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||||
|
});
|
||||||
|
};
|
||||||
|
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||||
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||||
|
};
|
||||||
|
Object.defineProperty(exports, "__esModule", { value: true });
|
||||||
|
exports.default = addAdminUserOnLogin;
|
||||||
|
const serverError_1 = __importDefault(require("./serverError"));
|
||||||
|
const DB_HANDLER_1 = __importDefault(require("../../utils/backend/global-db/DB_HANDLER"));
|
||||||
|
const addDbEntry_1 = __importDefault(require("./db/addDbEntry"));
|
||||||
|
const LOCAL_DB_HANDLER_1 = __importDefault(require("../../utils/backend/global-db/LOCAL_DB_HANDLER"));
|
||||||
|
/**
|
||||||
|
* Add Admin User on Login
|
||||||
|
* ==============================================================================
|
||||||
|
*
|
||||||
|
* @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
|
||||||
|
* has been created for the invited user
|
||||||
|
*/
|
||||||
|
function addAdminUserOnLogin(_a) {
|
||||||
|
return __awaiter(this, arguments, void 0, function* ({ query, user, useLocal, }) {
|
||||||
|
try {
|
||||||
|
const finalDbHandler = useLocal ? LOCAL_DB_HANDLER_1.default : DB_HANDLER_1.default;
|
||||||
|
const { invite, database_access, priviledge, email } = query;
|
||||||
|
const lastInviteTimeQuery = `SELECT date_created_code FROM invitations WHERE inviting_user_id=? AND invited_user_email=?`;
|
||||||
|
const lastInviteTimeValues = [invite, email];
|
||||||
|
const lastInviteTimeArray = yield finalDbHandler(lastInviteTimeQuery, lastInviteTimeValues);
|
||||||
|
if (!lastInviteTimeArray || !lastInviteTimeArray[0]) {
|
||||||
|
throw new Error("No Invitation Found");
|
||||||
|
}
|
||||||
|
////////////////////////////////////////////////
|
||||||
|
////////////////////////////////////////////////
|
||||||
|
////////////////////////////////////////////////
|
||||||
|
const invitingUserDbQuery = `SELECT first_name,last_name,email FROM users WHERE id=?`;
|
||||||
|
const invitingUserDbValues = [invite];
|
||||||
|
const invitingUserDb = yield finalDbHandler(invitingUserDbQuery, invitingUserDbValues);
|
||||||
|
if (invitingUserDb === null || invitingUserDb === void 0 ? void 0 : invitingUserDb[0]) {
|
||||||
|
const existingUserUser = yield finalDbHandler(`SELECT email FROM user_users WHERE user_id=? AND invited_user_id=? AND user_type='admin' AND email=?`, [invite, user.id, email]);
|
||||||
|
if (existingUserUser === null || existingUserUser === void 0 ? void 0 : existingUserUser[0]) {
|
||||||
|
console.log("User already added");
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
(0, addDbEntry_1.default)({
|
||||||
|
dbFullName: "datasquirel",
|
||||||
|
tableName: "user_users",
|
||||||
|
data: {
|
||||||
|
user_id: invite,
|
||||||
|
invited_user_id: user.id,
|
||||||
|
database_access: database_access,
|
||||||
|
first_name: user.first_name,
|
||||||
|
last_name: user.last_name,
|
||||||
|
phone: user.phone,
|
||||||
|
email: user.email,
|
||||||
|
username: user.username,
|
||||||
|
user_type: "admin",
|
||||||
|
user_priviledge: priviledge,
|
||||||
|
image: user.image,
|
||||||
|
image_thumbnail: user.image_thumbnail,
|
||||||
|
},
|
||||||
|
useLocal,
|
||||||
|
});
|
||||||
|
////////////////////////////////////////////////
|
||||||
|
////////////////////////////////////////////////
|
||||||
|
////////////////////////////////////////////////
|
||||||
|
const dbTableData = yield finalDbHandler(`SELECT db_tables_data FROM invitations WHERE inviting_user_id=? AND invited_user_email=?`, [invite, email]);
|
||||||
|
const clearEntries = yield finalDbHandler(`DELETE FROM delegated_user_tables WHERE root_user_id=? AND delegated_user_id=?`, [invite, user.id]);
|
||||||
|
////////////////////////////////////////////////
|
||||||
|
////////////////////////////////////////////////
|
||||||
|
////////////////////////////////////////////////
|
||||||
|
if (dbTableData && dbTableData[0]) {
|
||||||
|
const dbTableEntries = dbTableData[0].db_tables_data.split("|");
|
||||||
|
for (let i = 0; i < dbTableEntries.length; i++) {
|
||||||
|
const dbTableEntry = dbTableEntries[i];
|
||||||
|
const dbTableEntryArray = dbTableEntry.split("-");
|
||||||
|
const [db_slug, table_slug] = dbTableEntryArray;
|
||||||
|
const newEntry = yield (0, addDbEntry_1.default)({
|
||||||
|
dbFullName: "datasquirel",
|
||||||
|
tableName: "delegated_user_tables",
|
||||||
|
data: {
|
||||||
|
delegated_user_id: user.id,
|
||||||
|
root_user_id: invite,
|
||||||
|
database: db_slug,
|
||||||
|
table: table_slug,
|
||||||
|
priviledge: priviledge,
|
||||||
|
},
|
||||||
|
useLocal,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const inviteAccepted = yield finalDbHandler(`UPDATE invitations SET invitation_status='Accepted' WHERE inviting_user_id=? AND invited_user_email=?`, [invite, email]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (error) {
|
||||||
|
(0, serverError_1.default)({
|
||||||
|
component: "addAdminUserOnLogin",
|
||||||
|
message: error.message,
|
||||||
|
user: user,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
9
dist/package-shared/functions/backend/addMariadbUser.d.ts
vendored
Normal file
9
dist/package-shared/functions/backend/addMariadbUser.d.ts
vendored
Normal file
@ -0,0 +1,9 @@
|
|||||||
|
type Param = {
|
||||||
|
userId: number | string;
|
||||||
|
useLocal?: boolean;
|
||||||
|
};
|
||||||
|
/**
|
||||||
|
* # Add Mariadb User
|
||||||
|
*/
|
||||||
|
export default function addMariadbUser({ userId, useLocal, }: Param): Promise<any>;
|
||||||
|
export {};
|
72
dist/package-shared/functions/backend/addMariadbUser.js
vendored
Normal file
72
dist/package-shared/functions/backend/addMariadbUser.js
vendored
Normal file
@ -0,0 +1,72 @@
|
|||||||
|
"use strict";
|
||||||
|
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||||
|
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||||
|
return new (P || (P = Promise))(function (resolve, reject) {
|
||||||
|
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||||
|
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||||
|
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||||
|
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||||
|
});
|
||||||
|
};
|
||||||
|
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||||
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||||
|
};
|
||||||
|
Object.defineProperty(exports, "__esModule", { value: true });
|
||||||
|
exports.default = addMariadbUser;
|
||||||
|
const generate_password_1 = __importDefault(require("generate-password"));
|
||||||
|
const DB_HANDLER_1 = __importDefault(require("../../utils/backend/global-db/DB_HANDLER"));
|
||||||
|
const NO_DB_HANDLER_1 = __importDefault(require("../../utils/backend/global-db/NO_DB_HANDLER"));
|
||||||
|
const addDbEntry_1 = __importDefault(require("./db/addDbEntry"));
|
||||||
|
const encrypt_1 = __importDefault(require("../dsql/encrypt"));
|
||||||
|
const LOCAL_DB_HANDLER_1 = __importDefault(require("../../utils/backend/global-db/LOCAL_DB_HANDLER"));
|
||||||
|
/**
|
||||||
|
* # Add Mariadb User
|
||||||
|
*/
|
||||||
|
function addMariadbUser(_a) {
|
||||||
|
return __awaiter(this, arguments, void 0, function* ({ userId, useLocal, }) {
|
||||||
|
try {
|
||||||
|
const defaultMariadbUserHost = process.env.DSQL_DB_HOST || "127.0.0.1";
|
||||||
|
const username = `dsql_user_${userId}`;
|
||||||
|
const password = generate_password_1.default.generate({
|
||||||
|
length: 16,
|
||||||
|
numbers: true,
|
||||||
|
symbols: true,
|
||||||
|
uppercase: true,
|
||||||
|
exclude: "*#.'`\"",
|
||||||
|
});
|
||||||
|
const encryptedPassword = (0, encrypt_1.default)({ data: password });
|
||||||
|
const createMariadbUsersQuery = `CREATE USER IF NOT EXISTS '${username}'@'127.0.0.1' IDENTIFIED BY '${password}'`;
|
||||||
|
if (useLocal) {
|
||||||
|
yield (0, LOCAL_DB_HANDLER_1.default)(createMariadbUsersQuery);
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
yield (0, NO_DB_HANDLER_1.default)(createMariadbUsersQuery);
|
||||||
|
}
|
||||||
|
const updateUserQuery = `UPDATE users SET mariadb_user = ?, mariadb_host = '127.0.0.1', mariadb_pass = ? WHERE id = ?`;
|
||||||
|
const updateUserValues = [username, encryptedPassword, userId];
|
||||||
|
const updateUser = useLocal
|
||||||
|
? yield (0, LOCAL_DB_HANDLER_1.default)(updateUserQuery, updateUserValues)
|
||||||
|
: yield (0, DB_HANDLER_1.default)(updateUserQuery, updateUserValues);
|
||||||
|
const addMariadbUser = yield (0, addDbEntry_1.default)({
|
||||||
|
tableName: "mariadb_users",
|
||||||
|
data: {
|
||||||
|
user_id: userId,
|
||||||
|
username,
|
||||||
|
host: defaultMariadbUserHost,
|
||||||
|
password: encryptedPassword,
|
||||||
|
primary: "1",
|
||||||
|
grants: '[{"database":"*","table":"*","privileges":["ALL"]}]',
|
||||||
|
},
|
||||||
|
dbContext: "Master",
|
||||||
|
useLocal,
|
||||||
|
});
|
||||||
|
console.log(`User ${userId} SQL credentials successfully added.`);
|
||||||
|
}
|
||||||
|
catch ( /** @type {any} */error) {
|
||||||
|
console.log(`Error in adding SQL user in 'addMariadbUser' function =>`, error.message);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
////////////////////////////////////////////////
|
||||||
|
////////////////////////////////////////////////
|
||||||
|
////////////////////////////////////////////////
|
13
dist/package-shared/functions/backend/addUsersTableToDb.d.ts
vendored
Normal file
13
dist/package-shared/functions/backend/addUsersTableToDb.d.ts
vendored
Normal file
@ -0,0 +1,13 @@
|
|||||||
|
type Param = {
|
||||||
|
userId: number;
|
||||||
|
database: string;
|
||||||
|
useLocal?: boolean;
|
||||||
|
payload?: {
|
||||||
|
[s: string]: any;
|
||||||
|
};
|
||||||
|
};
|
||||||
|
/**
|
||||||
|
* # Add User Table to Database
|
||||||
|
*/
|
||||||
|
export default function addUsersTableToDb({ userId, database, useLocal, payload, }: Param): Promise<any>;
|
||||||
|
export {};
|
83
dist/package-shared/functions/backend/addUsersTableToDb.js
vendored
Normal file
83
dist/package-shared/functions/backend/addUsersTableToDb.js
vendored
Normal file
@ -0,0 +1,83 @@
|
|||||||
|
"use strict";
|
||||||
|
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||||
|
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||||
|
return new (P || (P = Promise))(function (resolve, reject) {
|
||||||
|
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||||
|
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||||
|
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||||
|
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||||
|
});
|
||||||
|
};
|
||||||
|
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||||
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||||
|
};
|
||||||
|
Object.defineProperty(exports, "__esModule", { value: true });
|
||||||
|
exports.default = addUsersTableToDb;
|
||||||
|
const serverError_1 = __importDefault(require("./serverError"));
|
||||||
|
const DB_HANDLER_1 = __importDefault(require("../../utils/backend/global-db/DB_HANDLER"));
|
||||||
|
const grabUserSchemaData_1 = __importDefault(require("./grabUserSchemaData"));
|
||||||
|
const setUserSchemaData_1 = __importDefault(require("./setUserSchemaData"));
|
||||||
|
const addDbEntry_1 = __importDefault(require("./db/addDbEntry"));
|
||||||
|
const createDbFromSchema_1 = __importDefault(require("../../shell/createDbFromSchema"));
|
||||||
|
const LOCAL_DB_HANDLER_1 = __importDefault(require("../../utils/backend/global-db/LOCAL_DB_HANDLER"));
|
||||||
|
const grabNewUsersTableSchema_1 = __importDefault(require("./grabNewUsersTableSchema"));
|
||||||
|
/**
|
||||||
|
* # Add User Table to Database
|
||||||
|
*/
|
||||||
|
function addUsersTableToDb(_a) {
|
||||||
|
return __awaiter(this, arguments, void 0, function* ({ userId, database, useLocal, payload, }) {
|
||||||
|
try {
|
||||||
|
const dbFullName = database;
|
||||||
|
const userPreset = (0, grabNewUsersTableSchema_1.default)({ payload });
|
||||||
|
if (!userPreset)
|
||||||
|
throw new Error("Couldn't Get User Preset!");
|
||||||
|
const userSchemaData = (0, grabUserSchemaData_1.default)({ userId });
|
||||||
|
if (!userSchemaData)
|
||||||
|
throw new Error("User schema data not found!");
|
||||||
|
let targetDatabase = userSchemaData.find((db) => db.dbFullName === database);
|
||||||
|
if (!targetDatabase) {
|
||||||
|
throw new Error("Couldn't Find Target Database!");
|
||||||
|
}
|
||||||
|
let existingTableIndex = targetDatabase === null || targetDatabase === void 0 ? void 0 : targetDatabase.tables.findIndex((table) => table.tableName === "users");
|
||||||
|
if (typeof existingTableIndex == "number" && existingTableIndex > 0) {
|
||||||
|
targetDatabase.tables[existingTableIndex] = userPreset;
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
targetDatabase.tables.push(userPreset);
|
||||||
|
}
|
||||||
|
(0, setUserSchemaData_1.default)({ schemaData: userSchemaData, userId });
|
||||||
|
/** @type {any[] | null} */
|
||||||
|
const targetDb = useLocal
|
||||||
|
? yield (0, LOCAL_DB_HANDLER_1.default)(`SELECT id FROM user_databases WHERE user_id=? AND db_slug=?`, [userId, database])
|
||||||
|
: yield (0, DB_HANDLER_1.default)(`SELECT id FROM user_databases WHERE user_id=? AND db_slug=?`, [userId, database]);
|
||||||
|
if (targetDb === null || targetDb === void 0 ? void 0 : targetDb[0]) {
|
||||||
|
const newTableEntry = yield (0, addDbEntry_1.default)({
|
||||||
|
dbFullName: "datasquirel",
|
||||||
|
tableName: "user_database_tables",
|
||||||
|
data: {
|
||||||
|
user_id: userId,
|
||||||
|
db_id: targetDb[0].id,
|
||||||
|
db_slug: targetDatabase.dbSlug,
|
||||||
|
table_name: "Users",
|
||||||
|
table_slug: "users",
|
||||||
|
},
|
||||||
|
useLocal,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
const dbShellUpdate = yield (0, createDbFromSchema_1.default)({
|
||||||
|
userId,
|
||||||
|
targetDatabase: dbFullName,
|
||||||
|
});
|
||||||
|
return `Done!`;
|
||||||
|
}
|
||||||
|
catch ( /** @type {any} */error) {
|
||||||
|
console.log(`addUsersTableToDb.js ERROR: ${error.message}`);
|
||||||
|
(0, serverError_1.default)({
|
||||||
|
component: "addUsersTableToDb",
|
||||||
|
message: error.message,
|
||||||
|
user: { id: userId },
|
||||||
|
});
|
||||||
|
return error.message;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
6
dist/package-shared/functions/backend/api-cred.d.ts
vendored
Normal file
6
dist/package-shared/functions/backend/api-cred.d.ts
vendored
Normal file
@ -0,0 +1,6 @@
|
|||||||
|
import { CheckApiCredentialsFn } from "../../types";
|
||||||
|
/**
|
||||||
|
* # Grap API Credentials
|
||||||
|
*/
|
||||||
|
declare const grabApiCred: CheckApiCredentialsFn;
|
||||||
|
export default grabApiCred;
|
50
dist/package-shared/functions/backend/api-cred.js
vendored
Normal file
50
dist/package-shared/functions/backend/api-cred.js
vendored
Normal file
@ -0,0 +1,50 @@
|
|||||||
|
"use strict";
|
||||||
|
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||||
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||||
|
};
|
||||||
|
Object.defineProperty(exports, "__esModule", { value: true });
|
||||||
|
const fs_1 = __importDefault(require("fs"));
|
||||||
|
const decrypt_1 = __importDefault(require("../dsql/decrypt"));
|
||||||
|
/**
|
||||||
|
* # Grap API Credentials
|
||||||
|
*/
|
||||||
|
const grabApiCred = ({ key, database, table, user_id, media, }) => {
|
||||||
|
var _a, _b;
|
||||||
|
if (!key)
|
||||||
|
return null;
|
||||||
|
if (!user_id)
|
||||||
|
return null;
|
||||||
|
try {
|
||||||
|
const allowedKeysPath = process.env.DSQL_API_KEYS_PATH;
|
||||||
|
if (!allowedKeysPath)
|
||||||
|
throw new Error("process.env.DSQL_API_KEYS_PATH variable not found");
|
||||||
|
const ApiJSON = (0, decrypt_1.default)({ encryptedString: key });
|
||||||
|
/** @type {import("../../types").ApiKeyObject} */
|
||||||
|
const ApiObject = JSON.parse(ApiJSON || "");
|
||||||
|
const isApiKeyValid = fs_1.default.existsSync(`${allowedKeysPath}/${ApiObject.sign}`);
|
||||||
|
if (String(ApiObject.user_id) !== String(user_id))
|
||||||
|
return null;
|
||||||
|
if (!isApiKeyValid)
|
||||||
|
return null;
|
||||||
|
if (!ApiObject.target_database)
|
||||||
|
return ApiObject;
|
||||||
|
if (media)
|
||||||
|
return ApiObject;
|
||||||
|
if (!database && ApiObject.target_database)
|
||||||
|
return null;
|
||||||
|
const isDatabaseAllowed = (_a = ApiObject.target_database) === null || _a === void 0 ? void 0 : _a.split(",").includes(String(database));
|
||||||
|
if (isDatabaseAllowed && !ApiObject.target_table)
|
||||||
|
return ApiObject;
|
||||||
|
if (isDatabaseAllowed && !table && ApiObject.target_table)
|
||||||
|
return null;
|
||||||
|
const isTableAllowed = (_b = ApiObject.target_table) === null || _b === void 0 ? void 0 : _b.split(",").includes(String(table));
|
||||||
|
if (isTableAllowed)
|
||||||
|
return ApiObject;
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
catch ( /** @type {any} */error) {
|
||||||
|
console.log(`api-cred ERROR: ${error.message}`);
|
||||||
|
return { error: `api-cred ERROR: ${error.message}` };
|
||||||
|
}
|
||||||
|
};
|
||||||
|
exports.default = grabApiCred;
|
23
dist/package-shared/functions/backend/auth/write-auth-files.d.ts
vendored
Normal file
23
dist/package-shared/functions/backend/auth/write-auth-files.d.ts
vendored
Normal file
@ -0,0 +1,23 @@
|
|||||||
|
export declare const grabAuthDirs: () => {
|
||||||
|
root: string;
|
||||||
|
auth: string;
|
||||||
|
};
|
||||||
|
export declare const initAuthFiles: () => boolean;
|
||||||
|
/**
|
||||||
|
* # Write Auth Files
|
||||||
|
*/
|
||||||
|
export declare const writeAuthFile: (name: string, data: string) => boolean;
|
||||||
|
/**
|
||||||
|
* # Get Auth Files
|
||||||
|
*/
|
||||||
|
export declare const getAuthFile: (name: string) => string | null;
|
||||||
|
/**
|
||||||
|
* # Delete Auth Files
|
||||||
|
* @param {string} name
|
||||||
|
*/
|
||||||
|
export declare const deleteAuthFile: (name: string) => void | null;
|
||||||
|
/**
|
||||||
|
* # Delete Auth Files
|
||||||
|
* @param {string} name
|
||||||
|
*/
|
||||||
|
export declare const checkAuthFile: (name: string) => boolean;
|
90
dist/package-shared/functions/backend/auth/write-auth-files.js
vendored
Normal file
90
dist/package-shared/functions/backend/auth/write-auth-files.js
vendored
Normal file
@ -0,0 +1,90 @@
|
|||||||
|
"use strict";
|
||||||
|
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||||
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||||
|
};
|
||||||
|
Object.defineProperty(exports, "__esModule", { value: true });
|
||||||
|
exports.checkAuthFile = exports.deleteAuthFile = exports.getAuthFile = exports.writeAuthFile = exports.initAuthFiles = exports.grabAuthDirs = void 0;
|
||||||
|
const fs_1 = __importDefault(require("fs"));
|
||||||
|
const path_1 = __importDefault(require("path"));
|
||||||
|
const grabAuthDirs = () => {
|
||||||
|
const DSQL_AUTH_DIR = process.env.DSQL_AUTH_DIR;
|
||||||
|
const ROOT_DIR = (DSQL_AUTH_DIR === null || DSQL_AUTH_DIR === void 0 ? void 0 : DSQL_AUTH_DIR.match(/./))
|
||||||
|
? DSQL_AUTH_DIR
|
||||||
|
: path_1.default.resolve(process.cwd(), "./.tmp");
|
||||||
|
const AUTH_DIR = path_1.default.join(ROOT_DIR, "logins");
|
||||||
|
return { root: ROOT_DIR, auth: AUTH_DIR };
|
||||||
|
};
|
||||||
|
exports.grabAuthDirs = grabAuthDirs;
|
||||||
|
const initAuthFiles = () => {
|
||||||
|
try {
|
||||||
|
const authDirs = (0, exports.grabAuthDirs)();
|
||||||
|
if (!fs_1.default.existsSync(authDirs.root))
|
||||||
|
fs_1.default.mkdirSync(authDirs.root, { recursive: true });
|
||||||
|
if (!fs_1.default.existsSync(authDirs.auth))
|
||||||
|
fs_1.default.mkdirSync(authDirs.auth, { recursive: true });
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
catch (error) {
|
||||||
|
console.log(`Error initializing Auth Files: ${error.message}`);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
exports.initAuthFiles = initAuthFiles;
|
||||||
|
/**
|
||||||
|
* # Write Auth Files
|
||||||
|
*/
|
||||||
|
const writeAuthFile = (name, data) => {
|
||||||
|
(0, exports.initAuthFiles)();
|
||||||
|
try {
|
||||||
|
fs_1.default.writeFileSync(path_1.default.join((0, exports.grabAuthDirs)().auth, name), data);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
catch ( /** @type {any} */error) {
|
||||||
|
console.log(`Error writing Auth File: ${error.message}`);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
exports.writeAuthFile = writeAuthFile;
|
||||||
|
/**
|
||||||
|
* # Get Auth Files
|
||||||
|
*/
|
||||||
|
const getAuthFile = (name) => {
|
||||||
|
try {
|
||||||
|
const authFilePath = path_1.default.join((0, exports.grabAuthDirs)().auth, name);
|
||||||
|
return fs_1.default.readFileSync(authFilePath, "utf-8");
|
||||||
|
}
|
||||||
|
catch ( /** @type {any} */error) {
|
||||||
|
console.log(`Error getting Auth File: ${error.message}`);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
exports.getAuthFile = getAuthFile;
|
||||||
|
/**
|
||||||
|
* # Delete Auth Files
|
||||||
|
* @param {string} name
|
||||||
|
*/
|
||||||
|
const deleteAuthFile = (name) => {
|
||||||
|
try {
|
||||||
|
return fs_1.default.rmSync(path_1.default.join((0, exports.grabAuthDirs)().auth, name));
|
||||||
|
}
|
||||||
|
catch ( /** @type {any} */error) {
|
||||||
|
console.log(`Error deleting Auth File: ${error.message}`);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
exports.deleteAuthFile = deleteAuthFile;
|
||||||
|
/**
|
||||||
|
* # Delete Auth Files
|
||||||
|
* @param {string} name
|
||||||
|
*/
|
||||||
|
const checkAuthFile = (name) => {
|
||||||
|
try {
|
||||||
|
return fs_1.default.existsSync(path_1.default.join((0, exports.grabAuthDirs)().auth, name));
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
catch ( /** @type {any} */error) {
|
||||||
|
console.log(`Error checking Auth File: ${error.message}`);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
exports.checkAuthFile = checkAuthFile;
|
14
dist/package-shared/functions/backend/cookies/get-auth-cookie-names.d.ts
vendored
Normal file
14
dist/package-shared/functions/backend/cookies/get-auth-cookie-names.d.ts
vendored
Normal file
@ -0,0 +1,14 @@
|
|||||||
|
type Param = {
|
||||||
|
database?: string;
|
||||||
|
userId?: string | number;
|
||||||
|
};
|
||||||
|
type Return = {
|
||||||
|
keyCookieName: string;
|
||||||
|
csrfCookieName: string;
|
||||||
|
oneTimeCodeName: string;
|
||||||
|
};
|
||||||
|
/**
|
||||||
|
* # Grab Auth Cookie Names
|
||||||
|
*/
|
||||||
|
export default function getAuthCookieNames(params?: Param): Return;
|
||||||
|
export {};
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user