Compare commits
287
Commits
549d0abc02
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3d0ee2e688 | ||
|
|
0e44676226 | ||
|
|
a68e42beab | ||
|
|
3d4ee58d01 | ||
|
|
ac489ce443 | ||
|
|
0da68e30b8 | ||
|
|
0a1993494d | ||
|
|
194e4dcad0 | ||
|
|
70908a2019 | ||
|
|
cf2cbe452b | ||
|
|
16cc7bede5 | ||
|
|
5847bd34ab | ||
|
|
af2749a922 | ||
|
|
fd83f6ab1b | ||
|
|
2741214db8 | ||
|
|
35ad577ead | ||
|
|
e1ca42137a | ||
|
|
a90706de5d | ||
|
|
80df059135 | ||
|
|
09fff9881e | ||
|
|
b25316485b | ||
|
|
7345010391 | ||
|
|
42caaecb18 | ||
|
|
b6fa30a3f2 | ||
|
|
7169e467cc | ||
|
|
cda056311b | ||
|
|
acccc26c38 | ||
|
|
664cb3a3d8 | ||
|
|
b50e100732 | ||
|
|
0a03405598 | ||
|
|
18a9409aec | ||
|
|
1c20286c8c | ||
|
|
a915be704b | ||
|
|
a10524da95 | ||
|
|
ea40a1a8c2 | ||
|
|
9402c859f7 | ||
|
|
58984214fc | ||
|
|
8bcb35a8f0 | ||
|
|
18e29fa413 | ||
|
|
def2f2f057 | ||
|
|
290dfe303c | ||
|
|
f0d44092e5 | ||
|
|
a8128c23ab | ||
|
|
b07153673e | ||
|
|
bd507eb9ea | ||
|
|
d109388af5 | ||
|
|
d985503688 | ||
|
|
8277ff3e41 | ||
|
|
b8e5d45762 | ||
|
|
515db80a79 | ||
|
|
05733b4ade | ||
|
|
f7a2d6e03a | ||
|
|
276a0db83b | ||
|
|
637ca6ea54 | ||
|
|
19eb7bf222 | ||
|
|
863906f3e6 | ||
|
|
b10bcb4d46 | ||
|
|
83eb4b976f | ||
|
|
d9f0f74481 | ||
|
|
49276d4cb3 | ||
|
|
0dc8f3c787 | ||
|
|
27887ded41 | ||
|
|
f1e0aa9fc4 | ||
|
|
5caa604b8f | ||
|
|
f95cf21ffd | ||
|
|
0e5b5fea6e | ||
|
|
d7cef41552 | ||
|
|
b02399c64d | ||
|
|
98aaa94b80 | ||
|
|
cfcd08680f | ||
|
|
0d9f313dc0 | ||
|
|
14ea760373 | ||
|
|
c88fb13375 | ||
|
|
f91aff421c | ||
|
|
57f06a631f | ||
|
|
9ab5543c5c | ||
|
|
4a6da06580 | ||
|
|
c6d1ac7793 | ||
|
|
77fca5e47c | ||
|
|
3346486b6b | ||
|
|
672e011cd8 | ||
|
|
7959014721 | ||
|
|
0858b18344 | ||
|
|
8eebe3215a | ||
|
|
5fcfc4dc2c | ||
|
|
22434ee656 | ||
|
|
d2fe98b4b8 | ||
|
|
57e67f5c51 | ||
|
|
957709f79d | ||
|
|
66f207416d | ||
|
|
90c36f2345 | ||
|
|
e6b4b09277 | ||
|
|
b81948d2c1 | ||
|
|
557bbb30bd | ||
|
|
0fcd92ab3e | ||
|
|
d646b4e93a | ||
|
|
c5954f6ba2 | ||
|
|
5c3324105e | ||
|
|
c34d256891 | ||
|
|
97f480c208 | ||
|
|
1086b35b9d | ||
|
|
2336b71703 | ||
|
|
82bea3efd0 | ||
|
|
e8269a8b5e | ||
|
|
56198e8ac5 | ||
|
|
700a704abd | ||
|
|
a1e56bb1b0 | ||
|
|
689f885d9d | ||
|
|
eb98148533 | ||
|
|
43a741f9ac | ||
|
|
ab13c68c8e | ||
|
|
71a8431de5 | ||
|
|
9ca64cf25e | ||
|
|
1f375fe94f | ||
|
|
8ac8b8eb51 | ||
|
|
a429436939 | ||
|
|
3437be2c08 | ||
|
|
3cf76f5155 | ||
|
|
5a4d4448a5 | ||
|
|
05d6d13ef0 | ||
|
|
20a390e4a8 | ||
|
|
a53b6e6974 | ||
|
|
9ce8bf2c90 | ||
|
|
c7e02a3061 | ||
|
|
caa26217a0 | ||
|
|
5cb8a067c0 | ||
|
|
166bde51c7 | ||
|
|
f9725a1d6f | ||
|
|
5ab079f687 | ||
|
|
a131764e1e | ||
|
|
c593404263 | ||
|
|
da87fe6491 | ||
|
|
e8787a2ef8 | ||
|
|
03abe33d22 | ||
|
|
382da38bb0 | ||
|
|
c37d105dee | ||
|
|
ccb5605b58 | ||
|
|
6acf0f2cd6 | ||
|
|
b38ddc9f21 | ||
|
|
3597b11342 | ||
|
|
fcc668d3a1 | ||
|
|
ad904622eb | ||
|
|
d80d876ac1 | ||
|
|
23d1b28354 | ||
|
|
56a58c225e | ||
|
|
a2d8fba8d7 | ||
|
|
728183b827 | ||
|
|
4f4eb44a98 | ||
|
|
321683e7c8 | ||
|
|
3730e4722e | ||
|
|
7e8bb37c09 | ||
|
|
6e334c2525 | ||
|
|
881128fcea | ||
|
|
761348de08 | ||
|
|
1364074c2c | ||
|
|
4a083fe73b | ||
|
|
8639c9f34d | ||
|
|
cd96c11817 | ||
|
|
9b7c98cff6 | ||
|
|
b28b05956b | ||
|
|
a68d1c1d3f | ||
|
|
b3353b8b70 | ||
|
|
2618d472dc | ||
|
|
0fc2c7fb3e | ||
|
|
4adb5af430 | ||
|
|
04a56b5bc3 | ||
|
|
a90989cea7 | ||
|
|
674af34355 | ||
|
|
07c2186b98 | ||
|
|
fe2b34d0ee | ||
|
|
181501296a | ||
|
|
cd4a2f7902 | ||
|
|
cc29a3c107 | ||
|
|
8d855ce94d | ||
|
|
9ea903a401 | ||
|
|
e4c6c995ef | ||
|
|
c71c1c29ca | ||
|
|
e7b7cf0314 | ||
|
|
daad62141e | ||
|
|
22f4372cbf | ||
|
|
18cbf9b2f4 | ||
|
|
2ad17ae682 | ||
|
|
d78e44c98d | ||
|
|
cd6bfdfc67 | ||
|
|
6593047efd | ||
|
|
8d38f99bf1 | ||
|
|
fb0bc4b753 | ||
|
|
7c04884a00 | ||
|
|
656eb27b8c | ||
|
|
ee23d71b66 | ||
|
|
ba1a4aeeb8 | ||
|
|
d41d28104f | ||
|
|
a9c0dd4b63 | ||
|
|
870de51f5d | ||
|
|
c24afca519 | ||
|
|
6e32bbb4e0 | ||
|
|
bcaaaae347 | ||
|
|
cd224b24df | ||
|
|
fe97939faf | ||
|
|
2091c823c8 | ||
|
|
e3c98388c6 | ||
|
|
fecb9a1df6 | ||
|
|
fbe4f7e5e6 | ||
|
|
e829ebd2ed | ||
|
|
870bc7fd17 | ||
|
|
34f843bc84 | ||
|
|
ec4d0428bb | ||
|
|
c192d9cd13 | ||
|
|
d4cb764a18 | ||
|
|
e9bb9fb07f | ||
|
|
c08db13f3d | ||
|
|
2e0b6d0a70 | ||
|
|
8b3553fcd5 | ||
|
|
b578843c6d | ||
|
|
12296a3e75 | ||
|
|
dbc68e54c6 | ||
|
|
5819017a97 | ||
|
|
e089f84ef4 | ||
|
|
ca65327527 | ||
|
|
e6702c7f82 | ||
|
|
95318307fe | ||
|
|
a2961d6b89 | ||
|
|
5e3476ad15 | ||
|
|
3358412028 | ||
|
|
6d4ccb63a3 | ||
|
|
b8fbbd3afb | ||
|
|
64ee344ba1 | ||
|
|
06de31dcb2 | ||
|
|
1acdad97a2 | ||
|
|
e41224bab7 | ||
|
|
97fc8f42c2 | ||
|
|
38abc55870 | ||
|
|
94d15ecb30 | ||
|
|
7188fe6e2c | ||
|
|
ff5550ec85 | ||
|
|
b6a3e002fb | ||
|
|
8ecef72efc | ||
|
|
4fe8921bc6 | ||
|
|
483ea16d4d | ||
|
|
ebf3618667 | ||
|
|
e82bcd0824 | ||
|
|
1db9c3a2e7 | ||
|
|
9f773de1a1 | ||
|
|
4aa69791c1 | ||
|
|
d89ded9d43 | ||
|
|
8d809412bb | ||
|
|
7d0f3e12f3 | ||
|
|
16191975f9 | ||
|
|
c210e6ca46 | ||
|
|
3695a75919 | ||
|
|
fdd3913f4f | ||
|
|
3dd1d08a5b | ||
|
|
dfe6fb3177 | ||
|
|
c947567311 | ||
|
|
a44526aeed | ||
|
|
982149f759 | ||
|
|
b18ec506b3 | ||
|
|
a2feec6f5b | ||
|
|
342056060b | ||
|
|
967cbae93f | ||
|
|
e13a14ab5c | ||
|
|
785b15aad5 | ||
|
|
8394963f0b | ||
|
|
60cccc9d9f | ||
|
|
82152082f3 | ||
|
|
9cd2707157 | ||
|
|
fc9839fd0c | ||
|
|
49716e8c5c | ||
|
|
62bb1fd6d4 | ||
|
|
f181b79ef7 | ||
|
|
09bfbd4214 | ||
|
|
20754d5cae | ||
|
|
0731e8cb6c | ||
|
|
03d4fdc270 | ||
|
|
d55fe64d47 | ||
|
|
edd555c088 | ||
|
|
0cd3eb418c | ||
|
|
2118a55ab6 | ||
|
|
7551749784 | ||
|
|
285d3b8369 | ||
|
|
87c7b4a83b | ||
|
|
d586de0639 | ||
|
|
8f00f333aa | ||
|
|
186cc76ffb | ||
|
|
a3561da53d | ||
|
|
9192dae0b5 | ||
|
|
eb0992f28d |
@@ -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
@@ -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);
|
|
||||||
|
|
||||||
//////////////////////////////////////////////////////////////////////////////////
|
|
||||||
//////////////////////////////////////////////////////////////////////////////////
|
|
||||||
//////////////////////////////////////////////////////////////////////////////////
|
|
||||||
//////////////////////////////////////////////////////////////////////////////////
|
|
||||||
//////////////////////////////////////////////////////////////////////////////////
|
|
||||||
//////////////////////////////////////////////////////////////////////////////////
|
|
||||||
};
|
|
||||||
@@ -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
@@ -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);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
Vendored
-2
@@ -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;
|
|
||||||
|
|
||||||
//////////////////////////////////////////////////////////////////////////////////
|
|
||||||
//////////////////////////////////////////////////////////////////////////////////
|
|
||||||
//////////////////////////////////////////////////////////////////////////////////
|
|
||||||
//////////////////////////////////////////////////////////////////////////////////
|
|
||||||
//////////////////////////////////////////////////////////////////////////////////
|
|
||||||
//////////////////////////////////////////////////////////////////////////////////
|
|
||||||
};
|
|
||||||
@@ -0,0 +1,104 @@
|
|||||||
|
import getCsrfHeaderName from "../../package-shared/actions/get-csrf-header-name";
|
||||||
|
import parseClientCookies from "../utils/parseClientCookies";
|
||||||
|
/**
|
||||||
|
* Login with Google Function
|
||||||
|
* ===============================================================================
|
||||||
|
* @description This function uses google identity api to login a user with datasquirel
|
||||||
|
*/
|
||||||
|
export default async function logout(params?: {
|
||||||
|
googleClientId?: any;
|
||||||
|
}): 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(getCsrfHeaderName());
|
||||||
|
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
import getCsrfHeaderName from "../../package-shared/actions/get-csrf-header-name";
|
||||||
|
import { APILoginFunctionReturn } from "../../package-shared/types";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Client Setup After Login
|
||||||
|
* ===============================================================================
|
||||||
|
* @description This function sets local storage variables like `csrf` after a user
|
||||||
|
* is logged in. Use this in conjunction with the `datasquirel.user.loginUser`
|
||||||
|
* function
|
||||||
|
*/
|
||||||
|
export default function postLogin(res: APILoginFunctionReturn): boolean {
|
||||||
|
try {
|
||||||
|
if (!res.payload) return false;
|
||||||
|
if (!res.payload.csrf_k) return false;
|
||||||
|
localStorage.setItem(getCsrfHeaderName(), res.payload.csrf_k);
|
||||||
|
localStorage.setItem("user", JSON.stringify(res.payload));
|
||||||
|
return true;
|
||||||
|
} catch (error) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,60 @@
|
|||||||
|
import {
|
||||||
|
APIResponseObject,
|
||||||
|
ClientCrudFetchParams,
|
||||||
|
PostInsertReturn,
|
||||||
|
} from "../../package-shared/types";
|
||||||
|
import serializeQuery from "../../package-shared/utils/serialize-query";
|
||||||
|
import fetchApi from "../fetch";
|
||||||
|
|
||||||
|
export default async function clientCrudFetch<
|
||||||
|
T extends { [k: string]: any } = { [k: string]: any },
|
||||||
|
P = string,
|
||||||
|
R extends { [k: string]: any } = { [k: string]: any }
|
||||||
|
>({
|
||||||
|
table,
|
||||||
|
basePath,
|
||||||
|
body,
|
||||||
|
query,
|
||||||
|
targetId,
|
||||||
|
method = "GET",
|
||||||
|
apiOrigin,
|
||||||
|
headers,
|
||||||
|
...options
|
||||||
|
}: ClientCrudFetchParams<T, P>) {
|
||||||
|
try {
|
||||||
|
let pathname = basePath || ``;
|
||||||
|
|
||||||
|
pathname += `/${String(table)}`;
|
||||||
|
|
||||||
|
if (targetId) {
|
||||||
|
pathname += `/${String(targetId)}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (query) {
|
||||||
|
pathname = `${pathname}${serializeQuery(query)}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
pathname = pathname.replace(/\/{2,}/g, "/");
|
||||||
|
|
||||||
|
pathname = apiOrigin
|
||||||
|
? `${apiOrigin}/${pathname}`.replace(/([^:]\/)\/+/g, "$1")
|
||||||
|
: pathname;
|
||||||
|
|
||||||
|
const res = await fetchApi<
|
||||||
|
any,
|
||||||
|
APIResponseObject<PostInsertReturn | R[]>
|
||||||
|
>(pathname, {
|
||||||
|
method,
|
||||||
|
body,
|
||||||
|
headers,
|
||||||
|
...options,
|
||||||
|
});
|
||||||
|
|
||||||
|
return res;
|
||||||
|
} catch (error: any) {
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
msg: `API ERROR => ${error.message}`,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
Vendored
-5
@@ -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;
|
|
||||||
@@ -0,0 +1,87 @@
|
|||||||
|
import _ from "lodash";
|
||||||
|
import {
|
||||||
|
DSQLClientFetchHeader,
|
||||||
|
DSQLFetchApiOptions,
|
||||||
|
} from "../../package-shared/types";
|
||||||
|
import serializeQuery from "../../package-shared/utils/serialize-query";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* # Fetch API
|
||||||
|
*/
|
||||||
|
export default async function fetchApi<
|
||||||
|
T extends { [k: string]: any } = { [k: string]: any },
|
||||||
|
R extends any = any,
|
||||||
|
>(url: string, options?: DSQLFetchApiOptions<T>): Promise<R> {
|
||||||
|
let data;
|
||||||
|
|
||||||
|
let finalHeaders = {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
} as DSQLClientFetchHeader;
|
||||||
|
|
||||||
|
if (options?.csrfKey && options.csrfValue) {
|
||||||
|
finalHeaders[options.csrfKey] = options.csrfValue;
|
||||||
|
}
|
||||||
|
|
||||||
|
let finalURL = url;
|
||||||
|
|
||||||
|
if (options?.query) {
|
||||||
|
finalURL += serializeQuery(options.query);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (typeof options === "string") {
|
||||||
|
try {
|
||||||
|
let fetchData;
|
||||||
|
|
||||||
|
switch (options) {
|
||||||
|
case "post":
|
||||||
|
fetchData = await fetch(finalURL, {
|
||||||
|
method: options,
|
||||||
|
headers: finalHeaders,
|
||||||
|
} as RequestInit);
|
||||||
|
data = fetchData.json();
|
||||||
|
break;
|
||||||
|
|
||||||
|
default:
|
||||||
|
fetchData = await fetch(finalURL);
|
||||||
|
data = fetchData.json();
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
} catch (error: any) {
|
||||||
|
console.log("FetchAPI error #1:", error.message);
|
||||||
|
data = null;
|
||||||
|
}
|
||||||
|
} else if (typeof options === "object") {
|
||||||
|
let fetchData;
|
||||||
|
let fetchOptions: RequestInit = {};
|
||||||
|
|
||||||
|
try {
|
||||||
|
fetchOptions.method = options.method;
|
||||||
|
|
||||||
|
if (options.method.match(/post|put|delete|patch/i)) {
|
||||||
|
if (options.body && typeof options.body == "object") {
|
||||||
|
fetchOptions.body = JSON.stringify(options.body);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fetchOptions.headers = _.merge(finalHeaders, options.headers || {});
|
||||||
|
|
||||||
|
fetchOptions = _.merge(fetchOptions, options.fetchOptions);
|
||||||
|
|
||||||
|
fetchData = await fetch(finalURL, fetchOptions);
|
||||||
|
data = fetchData.json();
|
||||||
|
} catch (error: any) {
|
||||||
|
console.log("FetchAPI error #2:", error.message);
|
||||||
|
data = null;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
try {
|
||||||
|
let fetchData = await fetch(finalURL);
|
||||||
|
data = await fetchData.json();
|
||||||
|
} catch (error: any) {
|
||||||
|
console.log("FetchAPI error #3:", error.message);
|
||||||
|
data = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return data;
|
||||||
|
}
|
||||||
Vendored
-38
@@ -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;
|
|
||||||
@@ -0,0 +1,68 @@
|
|||||||
|
import imageInputFileToBase64 from "./media/imageInputFileToBase64";
|
||||||
|
import imageInputToBase64 from "./media/imageInputToBase64";
|
||||||
|
import inputFileToBase64 from "./media/inputFileToBase64";
|
||||||
|
import getAccessToken from "./auth/google/getAccessToken";
|
||||||
|
import getGithubAccessToken from "./auth/github/getAccessToken";
|
||||||
|
import logout from "./auth/logout";
|
||||||
|
import fetchApi from "./fetch";
|
||||||
|
import clientFetch from "./fetch";
|
||||||
|
import serializeQuery from "../package-shared/utils/serialize-query";
|
||||||
|
import serializeCookies from "../package-shared/utils/serialize-cookies";
|
||||||
|
import EJSON from "../package-shared/utils/ejson";
|
||||||
|
import numberfy from "../package-shared/utils/numberfy";
|
||||||
|
import slugify from "../package-shared/utils/slugify";
|
||||||
|
import postLogin from "./auth/post-login";
|
||||||
|
import deserializeQuery from "../package-shared/utils/deserialize-query";
|
||||||
|
import debugLog from "../package-shared/utils/logging/debug-log";
|
||||||
|
import clientCrudFetch from "./crud-fetch";
|
||||||
|
|
||||||
|
const media = {
|
||||||
|
imageInputToBase64,
|
||||||
|
imageInputFileToBase64,
|
||||||
|
inputFileToBase64,
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* User Auth Object
|
||||||
|
*/
|
||||||
|
const auth = {
|
||||||
|
google: {
|
||||||
|
getAccessToken: getAccessToken,
|
||||||
|
},
|
||||||
|
github: {
|
||||||
|
getAccessToken: getGithubAccessToken,
|
||||||
|
},
|
||||||
|
logout,
|
||||||
|
postLogin,
|
||||||
|
};
|
||||||
|
|
||||||
|
const utils = {
|
||||||
|
deserializeQuery,
|
||||||
|
serializeQuery,
|
||||||
|
serializeCookies,
|
||||||
|
EJSON,
|
||||||
|
numberfy,
|
||||||
|
slugify,
|
||||||
|
debugLog,
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Fetch
|
||||||
|
*/
|
||||||
|
const fetch = {
|
||||||
|
fetchApi,
|
||||||
|
clientFetch,
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Main Export
|
||||||
|
*/
|
||||||
|
const datasquirelClient = {
|
||||||
|
media,
|
||||||
|
auth,
|
||||||
|
fetch,
|
||||||
|
utils,
|
||||||
|
clientCrudFetch,
|
||||||
|
};
|
||||||
|
|
||||||
|
export default datasquirelClient;
|
||||||
-8
@@ -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,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
};
|
}
|
||||||
|
|
||||||
/** ********************************************** */
|
|
||||||
/** ********************************************** */
|
|
||||||
/** ********************************************** */
|
|
||||||
Vendored
-14
@@ -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,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
/** ********************************************** */
|
|
||||||
/** ********************************************** */
|
|
||||||
/** ********************************************** */
|
|
||||||
@@ -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 {};
|
||||||
|
}
|
||||||
|
}
|
||||||
Vendored
-19
@@ -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,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
////////////////////////////////////////
|
|
||||||
////////////////////////////////////////
|
|
||||||
////////////////////////////////////////
|
|
||||||
@@ -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,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
Vendored
-2
@@ -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;
|
|
||||||
};
|
|
||||||
|
|
||||||
////////////////////////////////////////
|
|
||||||
////////////////////////////////////////
|
|
||||||
////////////////////////////////////////
|
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
/**
|
||||||
|
* Parse request cookies
|
||||||
|
* ============================================================================== *
|
||||||
|
* @description This function takes in a request object and returns the cookies as a JS object
|
||||||
|
*/
|
||||||
|
export default function (): { [s: string]: any } | null {
|
||||||
|
/**
|
||||||
|
* Check inputs
|
||||||
|
*
|
||||||
|
* @description Check inputs
|
||||||
|
*/
|
||||||
|
|
||||||
|
const cookieString: string | null = document.cookie;
|
||||||
|
|
||||||
|
if (!cookieString || typeof cookieString !== "string") {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const cookieSplitArray: string[] = cookieString.split(";");
|
||||||
|
|
||||||
|
let cookieObject: { [s: string]: any } = {};
|
||||||
|
|
||||||
|
cookieSplitArray.forEach((keyValueString) => {
|
||||||
|
const [key, value] = keyValueString.split("=");
|
||||||
|
if (key && typeof key == "string") {
|
||||||
|
cookieObject[key.replace(/^ +| +$/, "")] =
|
||||||
|
value && typeof value == "string"
|
||||||
|
? value.replace(/^ +| +$/, "")
|
||||||
|
: null;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
return cookieObject;
|
||||||
|
}
|
||||||
@@ -28,4 +28,4 @@ const colors = {
|
|||||||
BgGray: "\x1b[100m",
|
BgGray: "\x1b[100m",
|
||||||
};
|
};
|
||||||
|
|
||||||
module.exports = colors;
|
export default colors;
|
||||||
+13
@@ -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
@@ -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
@@ -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
@@ -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);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
Vendored
+8
@@ -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?: {
|
||||||
|
googleClientId?: any;
|
||||||
|
}): Promise<boolean>;
|
||||||
Vendored
+103
@@ -0,0 +1,103 @@
|
|||||||
|
"use strict";
|
||||||
|
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||||
|
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||||
|
return new (P || (P = Promise))(function (resolve, reject) {
|
||||||
|
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||||
|
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||||
|
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||||
|
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||||
|
});
|
||||||
|
};
|
||||||
|
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||||
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||||
|
};
|
||||||
|
Object.defineProperty(exports, "__esModule", { value: true });
|
||||||
|
exports.default = logout;
|
||||||
|
const get_csrf_header_name_1 = __importDefault(require("../../package-shared/actions/get-csrf-header-name"));
|
||||||
|
const parseClientCookies_1 = __importDefault(require("../utils/parseClientCookies"));
|
||||||
|
/**
|
||||||
|
* Login with Google Function
|
||||||
|
* ===============================================================================
|
||||||
|
* @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((0, get_csrf_header_name_1.default)());
|
||||||
|
document.cookie = `datasquirel_social_id=null;samesite=strict;path=/`;
|
||||||
|
////////////////////////////////////////
|
||||||
|
////////////////////////////////////////
|
||||||
|
////////////////////////////////////////
|
||||||
|
const response = yield new Promise((resolve, reject) => {
|
||||||
|
if (socialId && !(socialId === null || socialId === void 0 ? void 0 : socialId.match(/^null$/i))) {
|
||||||
|
const googleClientId = params === null || params === void 0 ? void 0 : params.googleClientId;
|
||||||
|
if (googleClientId) {
|
||||||
|
const googleScript = document.createElement("script");
|
||||||
|
googleScript.src = "https://accounts.google.com/gsi/client";
|
||||||
|
googleScript.className = "social-script-tag";
|
||||||
|
document.body.appendChild(googleScript);
|
||||||
|
////////////////////////////////////////
|
||||||
|
////////////////////////////////////////
|
||||||
|
////////////////////////////////////////
|
||||||
|
googleScript.onload = function (e) {
|
||||||
|
// @ts-ignore
|
||||||
|
const google = window.google;
|
||||||
|
if (google) {
|
||||||
|
////////////////////////////////////////
|
||||||
|
////////////////////////////////////////
|
||||||
|
////////////////////////////////////////
|
||||||
|
google.accounts.id.initialize({
|
||||||
|
client_id: googleClientId,
|
||||||
|
});
|
||||||
|
google.accounts.id.revoke(socialId, (done) => {
|
||||||
|
console.log(done.error);
|
||||||
|
resolve(true);
|
||||||
|
});
|
||||||
|
////////////////////////////////////////
|
||||||
|
////////////////////////////////////////
|
||||||
|
////////////////////////////////////////
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
resolve(true);
|
||||||
|
}
|
||||||
|
////////////////////////////////////////
|
||||||
|
////////////////////////////////////////
|
||||||
|
////////////////////////////////////////
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
resolve(true);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
return response;
|
||||||
|
}
|
||||||
|
catch (error) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
Vendored
+9
@@ -0,0 +1,9 @@
|
|||||||
|
import { APILoginFunctionReturn } from "../../package-shared/types";
|
||||||
|
/**
|
||||||
|
* Client Setup After Login
|
||||||
|
* ===============================================================================
|
||||||
|
* @description This function sets local storage variables like `csrf` after a user
|
||||||
|
* is logged in. Use this in conjunction with the `datasquirel.user.loginUser`
|
||||||
|
* function
|
||||||
|
*/
|
||||||
|
export default function postLogin(res: APILoginFunctionReturn): boolean;
|
||||||
Vendored
+28
@@ -0,0 +1,28 @@
|
|||||||
|
"use strict";
|
||||||
|
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||||
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||||
|
};
|
||||||
|
Object.defineProperty(exports, "__esModule", { value: true });
|
||||||
|
exports.default = postLogin;
|
||||||
|
const get_csrf_header_name_1 = __importDefault(require("../../package-shared/actions/get-csrf-header-name"));
|
||||||
|
/**
|
||||||
|
* Client Setup After Login
|
||||||
|
* ===============================================================================
|
||||||
|
* @description This function sets local storage variables like `csrf` after a user
|
||||||
|
* is logged in. Use this in conjunction with the `datasquirel.user.loginUser`
|
||||||
|
* function
|
||||||
|
*/
|
||||||
|
function postLogin(res) {
|
||||||
|
try {
|
||||||
|
if (!res.payload)
|
||||||
|
return false;
|
||||||
|
if (!res.payload.csrf_k)
|
||||||
|
return false;
|
||||||
|
localStorage.setItem((0, get_csrf_header_name_1.default)(), res.payload.csrf_k);
|
||||||
|
localStorage.setItem("user", JSON.stringify(res.payload));
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
catch (error) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
Vendored
+10
@@ -0,0 +1,10 @@
|
|||||||
|
import { APIResponseObject, ClientCrudFetchParams, PostInsertReturn } from "../../package-shared/types";
|
||||||
|
export default function clientCrudFetch<T extends {
|
||||||
|
[k: string]: any;
|
||||||
|
} = {
|
||||||
|
[k: string]: any;
|
||||||
|
}, P = string, R extends {
|
||||||
|
[k: string]: any;
|
||||||
|
} = {
|
||||||
|
[k: string]: any;
|
||||||
|
}>({ table, basePath, body, query, targetId, method, apiOrigin, headers, ...options }: ClientCrudFetchParams<T, P>): Promise<APIResponseObject<PostInsertReturn | R[]>>;
|
||||||
Vendored
+57
@@ -0,0 +1,57 @@
|
|||||||
|
"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 __rest = (this && this.__rest) || function (s, e) {
|
||||||
|
var t = {};
|
||||||
|
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
|
||||||
|
t[p] = s[p];
|
||||||
|
if (s != null && typeof Object.getOwnPropertySymbols === "function")
|
||||||
|
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
|
||||||
|
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
|
||||||
|
t[p[i]] = s[p[i]];
|
||||||
|
}
|
||||||
|
return t;
|
||||||
|
};
|
||||||
|
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||||
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||||
|
};
|
||||||
|
Object.defineProperty(exports, "__esModule", { value: true });
|
||||||
|
exports.default = clientCrudFetch;
|
||||||
|
const serialize_query_1 = __importDefault(require("../../package-shared/utils/serialize-query"));
|
||||||
|
const fetch_1 = __importDefault(require("../fetch"));
|
||||||
|
function clientCrudFetch(_a) {
|
||||||
|
return __awaiter(this, void 0, void 0, function* () {
|
||||||
|
var { table, basePath, body, query, targetId, method = "GET", apiOrigin, headers } = _a, options = __rest(_a, ["table", "basePath", "body", "query", "targetId", "method", "apiOrigin", "headers"]);
|
||||||
|
try {
|
||||||
|
let pathname = basePath || ``;
|
||||||
|
pathname += `/${String(table)}`;
|
||||||
|
if (targetId) {
|
||||||
|
pathname += `/${String(targetId)}`;
|
||||||
|
}
|
||||||
|
if (query) {
|
||||||
|
pathname = `${pathname}${(0, serialize_query_1.default)(query)}`;
|
||||||
|
}
|
||||||
|
pathname = pathname.replace(/\/{2,}/g, "/");
|
||||||
|
pathname = apiOrigin
|
||||||
|
? `${apiOrigin}/${pathname}`.replace(/([^:]\/)\/+/g, "$1")
|
||||||
|
: pathname;
|
||||||
|
const res = yield (0, fetch_1.default)(pathname, Object.assign({ method,
|
||||||
|
body,
|
||||||
|
headers }, options));
|
||||||
|
return res;
|
||||||
|
}
|
||||||
|
catch (error) {
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
msg: `API ERROR => ${error.message}`,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
Vendored
+9
@@ -0,0 +1,9 @@
|
|||||||
|
import { DSQLFetchApiOptions } from "../../package-shared/types";
|
||||||
|
/**
|
||||||
|
* # Fetch API
|
||||||
|
*/
|
||||||
|
export default function fetchApi<T extends {
|
||||||
|
[k: string]: any;
|
||||||
|
} = {
|
||||||
|
[k: string]: any;
|
||||||
|
}, R extends any = any>(url: string, options?: DSQLFetchApiOptions<T>): Promise<R>;
|
||||||
Vendored
+88
@@ -0,0 +1,88 @@
|
|||||||
|
"use strict";
|
||||||
|
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||||
|
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||||
|
return new (P || (P = Promise))(function (resolve, reject) {
|
||||||
|
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||||
|
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||||
|
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||||
|
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||||
|
});
|
||||||
|
};
|
||||||
|
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||||
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||||
|
};
|
||||||
|
Object.defineProperty(exports, "__esModule", { value: true });
|
||||||
|
exports.default = fetchApi;
|
||||||
|
const lodash_1 = __importDefault(require("lodash"));
|
||||||
|
const serialize_query_1 = __importDefault(require("../../package-shared/utils/serialize-query"));
|
||||||
|
/**
|
||||||
|
* # Fetch API
|
||||||
|
*/
|
||||||
|
function fetchApi(url, options) {
|
||||||
|
return __awaiter(this, void 0, void 0, function* () {
|
||||||
|
let data;
|
||||||
|
let finalHeaders = {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
};
|
||||||
|
if ((options === null || options === void 0 ? void 0 : options.csrfKey) && options.csrfValue) {
|
||||||
|
finalHeaders[options.csrfKey] = options.csrfValue;
|
||||||
|
}
|
||||||
|
let finalURL = url;
|
||||||
|
if (options === null || options === void 0 ? void 0 : options.query) {
|
||||||
|
finalURL += (0, serialize_query_1.default)(options.query);
|
||||||
|
}
|
||||||
|
if (typeof options === "string") {
|
||||||
|
try {
|
||||||
|
let fetchData;
|
||||||
|
switch (options) {
|
||||||
|
case "post":
|
||||||
|
fetchData = yield fetch(finalURL, {
|
||||||
|
method: options,
|
||||||
|
headers: finalHeaders,
|
||||||
|
});
|
||||||
|
data = fetchData.json();
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
fetchData = yield fetch(finalURL);
|
||||||
|
data = fetchData.json();
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (error) {
|
||||||
|
console.log("FetchAPI error #1:", error.message);
|
||||||
|
data = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else if (typeof options === "object") {
|
||||||
|
let fetchData;
|
||||||
|
let fetchOptions = {};
|
||||||
|
try {
|
||||||
|
fetchOptions.method = options.method;
|
||||||
|
if (options.method.match(/post|put|delete|patch/i)) {
|
||||||
|
if (options.body && typeof options.body == "object") {
|
||||||
|
fetchOptions.body = JSON.stringify(options.body);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fetchOptions.headers = lodash_1.default.merge(finalHeaders, options.headers || {});
|
||||||
|
fetchOptions = lodash_1.default.merge(fetchOptions, options.fetchOptions);
|
||||||
|
fetchData = yield fetch(finalURL, fetchOptions);
|
||||||
|
data = fetchData.json();
|
||||||
|
}
|
||||||
|
catch (error) {
|
||||||
|
console.log("FetchAPI error #2:", error.message);
|
||||||
|
data = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
try {
|
||||||
|
let fetchData = yield fetch(finalURL);
|
||||||
|
data = yield fetchData.json();
|
||||||
|
}
|
||||||
|
catch (error) {
|
||||||
|
console.log("FetchAPI error #3:", error.message);
|
||||||
|
data = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return data;
|
||||||
|
});
|
||||||
|
}
|
||||||
Vendored
+57
@@ -0,0 +1,57 @@
|
|||||||
|
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";
|
||||||
|
import postLogin from "./auth/post-login";
|
||||||
|
import deserializeQuery from "../package-shared/utils/deserialize-query";
|
||||||
|
import debugLog from "../package-shared/utils/logging/debug-log";
|
||||||
|
import clientCrudFetch from "./crud-fetch";
|
||||||
|
/**
|
||||||
|
* 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;
|
||||||
|
postLogin: typeof postLogin;
|
||||||
|
};
|
||||||
|
fetch: {
|
||||||
|
fetchApi: typeof fetchApi;
|
||||||
|
clientFetch: typeof fetchApi;
|
||||||
|
};
|
||||||
|
utils: {
|
||||||
|
deserializeQuery: typeof deserializeQuery;
|
||||||
|
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) | null, space?: string | number) => string | undefined;
|
||||||
|
};
|
||||||
|
numberfy: typeof numberfy;
|
||||||
|
slugify: typeof slugify;
|
||||||
|
debugLog: typeof debugLog;
|
||||||
|
};
|
||||||
|
clientCrudFetch: typeof clientCrudFetch;
|
||||||
|
};
|
||||||
|
export default datasquirelClient;
|
||||||
Vendored
+67
@@ -0,0 +1,67 @@
|
|||||||
|
"use strict";
|
||||||
|
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||||
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||||
|
};
|
||||||
|
Object.defineProperty(exports, "__esModule", { value: true });
|
||||||
|
const imageInputFileToBase64_1 = __importDefault(require("./media/imageInputFileToBase64"));
|
||||||
|
const imageInputToBase64_1 = __importDefault(require("./media/imageInputToBase64"));
|
||||||
|
const inputFileToBase64_1 = __importDefault(require("./media/inputFileToBase64"));
|
||||||
|
const getAccessToken_1 = __importDefault(require("./auth/google/getAccessToken"));
|
||||||
|
const getAccessToken_2 = __importDefault(require("./auth/github/getAccessToken"));
|
||||||
|
const logout_1 = __importDefault(require("./auth/logout"));
|
||||||
|
const fetch_1 = __importDefault(require("./fetch"));
|
||||||
|
const fetch_2 = __importDefault(require("./fetch"));
|
||||||
|
const serialize_query_1 = __importDefault(require("../package-shared/utils/serialize-query"));
|
||||||
|
const serialize_cookies_1 = __importDefault(require("../package-shared/utils/serialize-cookies"));
|
||||||
|
const ejson_1 = __importDefault(require("../package-shared/utils/ejson"));
|
||||||
|
const numberfy_1 = __importDefault(require("../package-shared/utils/numberfy"));
|
||||||
|
const slugify_1 = __importDefault(require("../package-shared/utils/slugify"));
|
||||||
|
const post_login_1 = __importDefault(require("./auth/post-login"));
|
||||||
|
const deserialize_query_1 = __importDefault(require("../package-shared/utils/deserialize-query"));
|
||||||
|
const debug_log_1 = __importDefault(require("../package-shared/utils/logging/debug-log"));
|
||||||
|
const crud_fetch_1 = __importDefault(require("./crud-fetch"));
|
||||||
|
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,
|
||||||
|
postLogin: post_login_1.default,
|
||||||
|
};
|
||||||
|
const utils = {
|
||||||
|
deserializeQuery: deserialize_query_1.default,
|
||||||
|
serializeQuery: serialize_query_1.default,
|
||||||
|
serializeCookies: serialize_cookies_1.default,
|
||||||
|
EJSON: ejson_1.default,
|
||||||
|
numberfy: numberfy_1.default,
|
||||||
|
slugify: slugify_1.default,
|
||||||
|
debugLog: debug_log_1.default,
|
||||||
|
};
|
||||||
|
/**
|
||||||
|
* Fetch
|
||||||
|
*/
|
||||||
|
const fetch = {
|
||||||
|
fetchApi: fetch_1.default,
|
||||||
|
clientFetch: fetch_2.default,
|
||||||
|
};
|
||||||
|
/**
|
||||||
|
* Main Export
|
||||||
|
*/
|
||||||
|
const datasquirelClient = {
|
||||||
|
media,
|
||||||
|
auth,
|
||||||
|
fetch,
|
||||||
|
utils,
|
||||||
|
clientCrudFetch: crud_fetch_1.default,
|
||||||
|
};
|
||||||
|
exports.default = datasquirelClient;
|
||||||
Vendored
+14
@@ -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;
|
||||||
Vendored
+34
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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;
|
||||||
|
}
|
||||||
Vendored
+28
@@ -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;
|
||||||
Vendored
+30
@@ -0,0 +1,30 @@
|
|||||||
|
"use strict";
|
||||||
|
Object.defineProperty(exports, "__esModule", { value: true });
|
||||||
|
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",
|
||||||
|
};
|
||||||
|
exports.default = colors;
|
||||||
Vendored
+2
@@ -0,0 +1,2 @@
|
|||||||
|
#! /usr/bin/env node
|
||||||
|
export default function run(): Promise<void>;
|
||||||
Vendored
+115
@@ -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();
|
||||||
Vendored
+2
@@ -0,0 +1,2 @@
|
|||||||
|
#! /usr/bin/env node
|
||||||
|
export {};
|
||||||
Vendored
+52
@@ -0,0 +1,52 @@
|
|||||||
|
#! /usr/bin/env node
|
||||||
|
"use strict";
|
||||||
|
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||||
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||||
|
};
|
||||||
|
var _a, _b, _c;
|
||||||
|
Object.defineProperty(exports, "__esModule", { value: true });
|
||||||
|
const path_1 = __importDefault(require("path"));
|
||||||
|
const child_process_1 = require("child_process");
|
||||||
|
const grab_db_names_1 = __importDefault(require("../package-shared/utils/grab-db-names"));
|
||||||
|
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 } = process.env;
|
||||||
|
const { dbFullName } = (0, grab_db_names_1.default)();
|
||||||
|
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 (!(dbFullName === null || dbFullName === void 0 ? void 0 : dbFullName.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} ${dbFullName} < ${dumpFilePath}`, execSyncOptions);
|
||||||
|
console.log("Dumped successfully", dump.toString());
|
||||||
|
////////////////////////////////////////
|
||||||
|
////////////////////////////////////////
|
||||||
|
////////////////////////////////////////
|
||||||
|
}
|
||||||
|
catch (error) {
|
||||||
|
(_c = global.ERROR_CALLBACK) === null || _c === void 0 ? void 0 : _c.call(global, `MariaDB Dump Error`, error);
|
||||||
|
console.log("Dump Error: ", error.message);
|
||||||
|
}
|
||||||
Vendored
+2
@@ -0,0 +1,2 @@
|
|||||||
|
#! /usr/bin/env node
|
||||||
|
export {};
|
||||||
Vendored
+139
@@ -0,0 +1,139 @@
|
|||||||
|
#! /usr/bin/env node
|
||||||
|
"use strict";
|
||||||
|
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
||||||
|
if (k2 === undefined) k2 = k;
|
||||||
|
var desc = Object.getOwnPropertyDescriptor(m, k);
|
||||||
|
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
||||||
|
desc = { enumerable: true, get: function() { return m[k]; } };
|
||||||
|
}
|
||||||
|
Object.defineProperty(o, k2, desc);
|
||||||
|
}) : (function(o, m, k, k2) {
|
||||||
|
if (k2 === undefined) k2 = k;
|
||||||
|
o[k2] = m[k];
|
||||||
|
}));
|
||||||
|
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
||||||
|
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
||||||
|
}) : function(o, v) {
|
||||||
|
o["default"] = v;
|
||||||
|
});
|
||||||
|
var __importStar = (this && this.__importStar) || (function () {
|
||||||
|
var ownKeys = function(o) {
|
||||||
|
ownKeys = Object.getOwnPropertyNames || function (o) {
|
||||||
|
var ar = [];
|
||||||
|
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
||||||
|
return ar;
|
||||||
|
};
|
||||||
|
return ownKeys(o);
|
||||||
|
};
|
||||||
|
return function (mod) {
|
||||||
|
if (mod && mod.__esModule) return mod;
|
||||||
|
var result = {};
|
||||||
|
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
||||||
|
__setModuleDefault(result, mod);
|
||||||
|
return result;
|
||||||
|
};
|
||||||
|
})();
|
||||||
|
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||||
|
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||||
|
return new (P || (P = Promise))(function (resolve, reject) {
|
||||||
|
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||||
|
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||||
|
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||||
|
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||||
|
});
|
||||||
|
};
|
||||||
|
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||||
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||||
|
};
|
||||||
|
Object.defineProperty(exports, "__esModule", { value: true });
|
||||||
|
const fs_1 = __importStar(require("fs"));
|
||||||
|
const __1 = __importDefault(require(".."));
|
||||||
|
const db_schema_to_type_1 = __importDefault(require("../package-shared/functions/dsql/db-schema-to-type"));
|
||||||
|
const path_1 = __importDefault(require("path"));
|
||||||
|
const debug_log_1 = __importDefault(require("../package-shared/utils/logging/debug-log"));
|
||||||
|
const app_names_1 = require("../package-shared/dict/app-names");
|
||||||
|
const configFileName = app_names_1.AppNames["SchemaToTypeDefConfigFileName"];
|
||||||
|
const configFilePath = path_1.default.join(process.cwd(), configFileName);
|
||||||
|
if (!fs_1.default.existsSync(configFilePath)) {
|
||||||
|
(0, debug_log_1.default)({
|
||||||
|
log: `Config File doesn't exist. Please add a '${app_names_1.AppNames["SchemaToTypeDefConfigFileName"]}' in the working directory with relevant configurations.`,
|
||||||
|
addTime: true,
|
||||||
|
type: "error",
|
||||||
|
});
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
const config = JSON.parse((0, fs_1.readFileSync)(path_1.default.join(process.cwd(), configFileName), "utf-8"));
|
||||||
|
if (!config.database) {
|
||||||
|
(0, debug_log_1.default)({
|
||||||
|
log: `Config File needs a 'database' value.`,
|
||||||
|
addTime: true,
|
||||||
|
type: "error",
|
||||||
|
});
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
if (!config.outDir && !config.outFile) {
|
||||||
|
(0, debug_log_1.default)({
|
||||||
|
log: `Config File needs a 'outDir' or 'outFile' value.`,
|
||||||
|
addTime: true,
|
||||||
|
type: "error",
|
||||||
|
});
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
if (!config.apiConnectionConfig) {
|
||||||
|
(0, debug_log_1.default)({
|
||||||
|
log: `Config File needs a 'apiConnectionConfig' value. This value needs an 'apiKey' value.`,
|
||||||
|
addTime: true,
|
||||||
|
type: "error",
|
||||||
|
});
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
if (!config.apiConnectionConfig.apiKey) {
|
||||||
|
(0, debug_log_1.default)({
|
||||||
|
log: `Config value 'apiConnectionConfig' needs an 'apiKey' value.`,
|
||||||
|
addTime: true,
|
||||||
|
type: "error",
|
||||||
|
});
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
(() => __awaiter(void 0, void 0, void 0, function* () {
|
||||||
|
try {
|
||||||
|
if (config.debug) {
|
||||||
|
(0, debug_log_1.default)({
|
||||||
|
log: config,
|
||||||
|
label: "Config",
|
||||||
|
addTime: true,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
const schemaRes = yield __1.default.api.schema.get({
|
||||||
|
dbName: config.database || "",
|
||||||
|
apiConnectionConfig: config.apiConnectionConfig,
|
||||||
|
});
|
||||||
|
const dbSchema = schemaRes.singleRes;
|
||||||
|
if (config.debug) {
|
||||||
|
(0, debug_log_1.default)({
|
||||||
|
log: schemaRes,
|
||||||
|
label: "schema",
|
||||||
|
addTime: true,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if (!dbSchema)
|
||||||
|
throw new Error("No schema found");
|
||||||
|
const definitions = (0, db_schema_to_type_1.default)({ dbSchema });
|
||||||
|
const finalOutfile = path_1.default.resolve(process.cwd(), config.outDir ? config.outDir + "/dsql.ts" : config.outFile || "");
|
||||||
|
const ourfileDir = path_1.default.dirname(finalOutfile);
|
||||||
|
if (!fs_1.default.existsSync(ourfileDir)) {
|
||||||
|
fs_1.default.mkdirSync(ourfileDir, { recursive: true });
|
||||||
|
}
|
||||||
|
fs_1.default.writeFileSync(finalOutfile, (definitions === null || definitions === void 0 ? void 0 : definitions.join("\n\n")) || "", "utf-8");
|
||||||
|
}
|
||||||
|
catch (error) {
|
||||||
|
(0, debug_log_1.default)({
|
||||||
|
log: error.message,
|
||||||
|
label: "Error",
|
||||||
|
title: "Schema to Typedef",
|
||||||
|
addTime: true,
|
||||||
|
type: "error",
|
||||||
|
});
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
}))();
|
||||||
Vendored
+172
@@ -0,0 +1,172 @@
|
|||||||
|
declare global {
|
||||||
|
var ERROR_CALLBACK: ErrorCallback | undefined;
|
||||||
|
}
|
||||||
|
import get from "./package-shared/actions/get";
|
||||||
|
import post from "./package-shared/actions/post";
|
||||||
|
import getSchema from "./package-shared/actions/get-schema";
|
||||||
|
import sqlGenerator from "./package-shared/functions/dsql/sql/sql-generator";
|
||||||
|
import sqlInsertGenerator from "./package-shared/functions/dsql/sql/sql-insert-generator";
|
||||||
|
import sqlDeleteGenerator from "./package-shared/functions/dsql/sql/sql-delete-generator";
|
||||||
|
import trimSql from "./package-shared/utils/trim-sql";
|
||||||
|
import parseCookies from "./package-shared/utils/backend/parseCookies";
|
||||||
|
import connDbHandler from "./package-shared/utils/db/conn-db-handler";
|
||||||
|
import encrypt from "./package-shared/functions/dsql/encrypt";
|
||||||
|
import decrypt from "./package-shared/functions/dsql/decrypt";
|
||||||
|
import hashPassword from "./package-shared/functions/dsql/hashPassword";
|
||||||
|
import dsqlCrud from "./package-shared/utils/data-fetching/crud";
|
||||||
|
import dsqlMethodCrud from "./package-shared/utils/data-fetching/method-crud";
|
||||||
|
import debugLog from "./package-shared/utils/logging/debug-log";
|
||||||
|
import { ErrorCallback } from "./package-shared/types";
|
||||||
|
import parseEnv from "./package-shared/utils/parse-env";
|
||||||
|
import dbHandler from "./package-shared/functions/backend/dbHandler";
|
||||||
|
import httpsRequest from "./package-shared/functions/backend/httpsRequest";
|
||||||
|
import handleNodemailer from "./package-shared/functions/backend/handleNodemailer";
|
||||||
|
import grabDSQLConnection from "./package-shared/utils/grab-dsql-connection";
|
||||||
|
import grabDSQLConnectionConfig from "./package-shared/utils/grab-dsql-connection-config";
|
||||||
|
import purgeDefaultFields from "./package-shared/utils/purge-default-fields";
|
||||||
|
import apiCrudHandler from "./package-shared/api-paths";
|
||||||
|
/**
|
||||||
|
* Main Export
|
||||||
|
*/
|
||||||
|
declare const datasquirel: {
|
||||||
|
/**
|
||||||
|
* API Actions
|
||||||
|
*/
|
||||||
|
api: {
|
||||||
|
crud: {
|
||||||
|
get: typeof import("./package-shared/api/crud/get").default;
|
||||||
|
insert: typeof import("./package-shared/api/crud/post").default;
|
||||||
|
update: typeof import("./package-shared/api/crud/put").default;
|
||||||
|
delete: typeof import("./package-shared/api/crud/delete").default;
|
||||||
|
options: () => Promise<void>;
|
||||||
|
};
|
||||||
|
media: {
|
||||||
|
get: typeof import("./package-shared/api/media/get").default;
|
||||||
|
add: typeof import("./package-shared/api/media/post").default;
|
||||||
|
delete: typeof import("./package-shared/api/media/delete").default;
|
||||||
|
};
|
||||||
|
user: {
|
||||||
|
auth: {
|
||||||
|
login: typeof import("./package-shared/actions/users/login-user").default;
|
||||||
|
get: typeof import("./package-shared/actions/users/get-user").default;
|
||||||
|
signup: typeof import("./package-shared/actions/users/add-user").default;
|
||||||
|
sendEmailCode: typeof import("./package-shared/actions/users/send-email-code").default;
|
||||||
|
update: typeof import("./package-shared/actions/users/update-user").default;
|
||||||
|
resetPassword: typeof import("./package-shared/actions/users/reset-password").default;
|
||||||
|
googleLogin: typeof import("./package-shared/actions/users/social/google-auth").default;
|
||||||
|
logout: typeof import("./package-shared/actions/users/logout-user").default;
|
||||||
|
auth: typeof import("./package-shared/actions/users/user-auth").default;
|
||||||
|
validateTempEmailCode: typeof import("./package-shared/actions/users/validate-temp-email-code").default;
|
||||||
|
};
|
||||||
|
};
|
||||||
|
schema: {
|
||||||
|
get: typeof import("./package-shared/api/schema/get").default;
|
||||||
|
};
|
||||||
|
};
|
||||||
|
/**
|
||||||
|
* Get Action
|
||||||
|
*/
|
||||||
|
get: typeof get;
|
||||||
|
/**
|
||||||
|
* Post Action
|
||||||
|
*/
|
||||||
|
post: typeof post;
|
||||||
|
user: {
|
||||||
|
auth: {
|
||||||
|
login: (_: import("./package-shared/types").LoginUserParam) => Promise<import("./package-shared/types").APIResponseObject>;
|
||||||
|
get: (_: import("./package-shared/types").GetUserParams) => Promise<import("./package-shared/types").APIResponseObject>;
|
||||||
|
signup: (_: import("./package-shared/types").AddUserParams) => Promise<import("./package-shared/types").APIResponseObject>;
|
||||||
|
sendEmailCode: (_: import("./package-shared/types").SendEmailCodeParams) => Promise<import("./package-shared/types").APIResponseObject>;
|
||||||
|
update: (_: import("./package-shared/types").UpdateUserParams) => Promise<import("./package-shared/types").APIResponseObject>;
|
||||||
|
resetPassword: (_: import("./package-shared/types").ResetPasswordParams) => Promise<import("./package-shared/types").APIResponseObject>;
|
||||||
|
googleLogin: (_: import("./package-shared/types").GoogleAuthParams) => Promise<import("./package-shared/types").APIResponseObject>;
|
||||||
|
logout: typeof import("./package-shared/actions/users/logout-user").default;
|
||||||
|
auth: typeof import("./package-shared/actions/users/user-auth").default;
|
||||||
|
validateTempEmailCode: typeof import("./package-shared/actions/users/validate-temp-email-code").default;
|
||||||
|
githubLoginFn: typeof import("./package-shared/functions/api/social-login/githubLogin").default;
|
||||||
|
};
|
||||||
|
};
|
||||||
|
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;
|
||||||
|
postLogin: typeof import("./client/auth/post-login").default;
|
||||||
|
};
|
||||||
|
fetch: {
|
||||||
|
fetchApi: typeof import("./client/fetch").default;
|
||||||
|
clientFetch: typeof import("./client/fetch").default;
|
||||||
|
};
|
||||||
|
utils: {
|
||||||
|
deserializeQuery: typeof import("./package-shared/utils/deserialize-query").default;
|
||||||
|
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) | null, space?: string | number) => string | undefined;
|
||||||
|
};
|
||||||
|
numberfy: typeof import("./package-shared/utils/numberfy").default;
|
||||||
|
slugify: typeof import("./package-shared/utils/slugify").default;
|
||||||
|
debugLog: typeof debugLog;
|
||||||
|
};
|
||||||
|
clientCrudFetch: typeof import("./client/crud-fetch").default;
|
||||||
|
};
|
||||||
|
sql: {
|
||||||
|
sqlGenerator: typeof sqlGenerator;
|
||||||
|
sqlInsertGenerator: typeof sqlInsertGenerator;
|
||||||
|
sqlDeleteGenerator: typeof sqlDeleteGenerator;
|
||||||
|
trim: typeof trimSql;
|
||||||
|
};
|
||||||
|
utils: {
|
||||||
|
crypto: {
|
||||||
|
encrypt: typeof encrypt;
|
||||||
|
decrypt: typeof decrypt;
|
||||||
|
hashPassword: typeof hashPassword;
|
||||||
|
};
|
||||||
|
parseCookies: typeof parseCookies;
|
||||||
|
connDbHandler: typeof connDbHandler;
|
||||||
|
debugLog: typeof debugLog;
|
||||||
|
parseEnv: typeof parseEnv;
|
||||||
|
httpsRequest: typeof httpsRequest;
|
||||||
|
httpRequest: typeof httpsRequest;
|
||||||
|
grabDSQLConnection: typeof grabDSQLConnection;
|
||||||
|
grabDSQLConnectionConfig: typeof grabDSQLConnectionConfig;
|
||||||
|
purgeDefaultFields: typeof purgeDefaultFields;
|
||||||
|
};
|
||||||
|
/**
|
||||||
|
* Run Crud actions `get`, `insert`, `update`, `delete`
|
||||||
|
* @description *Requires global variables `DSQL_USE_LOCAL` and `DSQL_DB_CONN`
|
||||||
|
*/
|
||||||
|
crud: typeof dsqlCrud;
|
||||||
|
/**
|
||||||
|
* Run Crud based on request Methods `GET`, `POST`, `PUT`, `PATCH`
|
||||||
|
* @description *Requires global variables `DSQL_USE_LOCAL` and `DSQL_DB_CONN`
|
||||||
|
*/
|
||||||
|
methodCrud: typeof dsqlMethodCrud;
|
||||||
|
/**
|
||||||
|
* General Database Handler
|
||||||
|
*/
|
||||||
|
dbHandler: typeof dbHandler;
|
||||||
|
/**
|
||||||
|
* Handle Mail
|
||||||
|
*/
|
||||||
|
mail: {
|
||||||
|
mailer: typeof handleNodemailer;
|
||||||
|
};
|
||||||
|
apiCrudHandler: typeof apiCrudHandler;
|
||||||
|
};
|
||||||
|
export default datasquirel;
|
||||||
Vendored
+111
@@ -0,0 +1,111 @@
|
|||||||
|
"use strict";
|
||||||
|
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||||
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||||
|
};
|
||||||
|
Object.defineProperty(exports, "__esModule", { value: true });
|
||||||
|
const get_1 = __importDefault(require("./package-shared/actions/get"));
|
||||||
|
const post_1 = __importDefault(require("./package-shared/actions/post"));
|
||||||
|
const get_schema_1 = __importDefault(require("./package-shared/actions/get-schema"));
|
||||||
|
const client_1 = __importDefault(require("./client"));
|
||||||
|
const sql_generator_1 = __importDefault(require("./package-shared/functions/dsql/sql/sql-generator"));
|
||||||
|
const sql_insert_generator_1 = __importDefault(require("./package-shared/functions/dsql/sql/sql-insert-generator"));
|
||||||
|
const sql_delete_generator_1 = __importDefault(require("./package-shared/functions/dsql/sql/sql-delete-generator"));
|
||||||
|
const trim_sql_1 = __importDefault(require("./package-shared/utils/trim-sql"));
|
||||||
|
const parseCookies_1 = __importDefault(require("./package-shared/utils/backend/parseCookies"));
|
||||||
|
const conn_db_handler_1 = __importDefault(require("./package-shared/utils/db/conn-db-handler"));
|
||||||
|
const encrypt_1 = __importDefault(require("./package-shared/functions/dsql/encrypt"));
|
||||||
|
const decrypt_1 = __importDefault(require("./package-shared/functions/dsql/decrypt"));
|
||||||
|
const hashPassword_1 = __importDefault(require("./package-shared/functions/dsql/hashPassword"));
|
||||||
|
const crud_1 = __importDefault(require("./package-shared/utils/data-fetching/crud"));
|
||||||
|
const method_crud_1 = __importDefault(require("./package-shared/utils/data-fetching/method-crud"));
|
||||||
|
const debug_log_1 = __importDefault(require("./package-shared/utils/logging/debug-log"));
|
||||||
|
const parse_env_1 = __importDefault(require("./package-shared/utils/parse-env"));
|
||||||
|
const crud_2 = __importDefault(require("./package-shared/api/crud"));
|
||||||
|
const user_1 = __importDefault(require("./package-shared/api/user"));
|
||||||
|
const local_user_1 = __importDefault(require("./package-shared/api/user/local-user"));
|
||||||
|
const media_1 = __importDefault(require("./package-shared/api/media"));
|
||||||
|
const dbHandler_1 = __importDefault(require("./package-shared/functions/backend/dbHandler"));
|
||||||
|
const httpsRequest_1 = __importDefault(require("./package-shared/functions/backend/httpsRequest"));
|
||||||
|
const handleNodemailer_1 = __importDefault(require("./package-shared/functions/backend/handleNodemailer"));
|
||||||
|
const grab_dsql_connection_1 = __importDefault(require("./package-shared/utils/grab-dsql-connection"));
|
||||||
|
const grab_dsql_connection_config_1 = __importDefault(require("./package-shared/utils/grab-dsql-connection-config"));
|
||||||
|
const schema_1 = __importDefault(require("./package-shared/api/schema"));
|
||||||
|
const purge_default_fields_1 = __importDefault(require("./package-shared/utils/purge-default-fields"));
|
||||||
|
const api_paths_1 = __importDefault(require("./package-shared/api-paths"));
|
||||||
|
/**
|
||||||
|
* API Functions Object
|
||||||
|
*/
|
||||||
|
const api = {
|
||||||
|
crud: crud_2.default,
|
||||||
|
media: media_1.default,
|
||||||
|
user: user_1.default,
|
||||||
|
schema: schema_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 = {
|
||||||
|
/**
|
||||||
|
* API Actions
|
||||||
|
*/
|
||||||
|
api,
|
||||||
|
/**
|
||||||
|
* Get Action
|
||||||
|
*/
|
||||||
|
get: get_1.default,
|
||||||
|
/**
|
||||||
|
* Post Action
|
||||||
|
*/
|
||||||
|
post: post_1.default,
|
||||||
|
user: local_user_1.default,
|
||||||
|
getSchema: get_schema_1.default,
|
||||||
|
client: client_1.default,
|
||||||
|
sql,
|
||||||
|
utils: {
|
||||||
|
crypto: {
|
||||||
|
encrypt: encrypt_1.default,
|
||||||
|
decrypt: decrypt_1.default,
|
||||||
|
hashPassword: hashPassword_1.default,
|
||||||
|
},
|
||||||
|
parseCookies: parseCookies_1.default,
|
||||||
|
connDbHandler: conn_db_handler_1.default,
|
||||||
|
debugLog: debug_log_1.default,
|
||||||
|
parseEnv: parse_env_1.default,
|
||||||
|
httpsRequest: httpsRequest_1.default,
|
||||||
|
httpRequest: httpsRequest_1.default,
|
||||||
|
grabDSQLConnection: grab_dsql_connection_1.default,
|
||||||
|
grabDSQLConnectionConfig: grab_dsql_connection_config_1.default,
|
||||||
|
purgeDefaultFields: purge_default_fields_1.default,
|
||||||
|
},
|
||||||
|
/**
|
||||||
|
* Run Crud actions `get`, `insert`, `update`, `delete`
|
||||||
|
* @description *Requires global variables `DSQL_USE_LOCAL` and `DSQL_DB_CONN`
|
||||||
|
*/
|
||||||
|
crud: crud_1.default,
|
||||||
|
/**
|
||||||
|
* Run Crud based on request Methods `GET`, `POST`, `PUT`, `PATCH`
|
||||||
|
* @description *Requires global variables `DSQL_USE_LOCAL` and `DSQL_DB_CONN`
|
||||||
|
*/
|
||||||
|
methodCrud: method_crud_1.default,
|
||||||
|
/**
|
||||||
|
* General Database Handler
|
||||||
|
*/
|
||||||
|
dbHandler: dbHandler_1.default,
|
||||||
|
/**
|
||||||
|
* Handle Mail
|
||||||
|
*/
|
||||||
|
mail: {
|
||||||
|
mailer: handleNodemailer_1.default,
|
||||||
|
},
|
||||||
|
apiCrudHandler: api_paths_1.default,
|
||||||
|
};
|
||||||
|
exports.default = datasquirel;
|
||||||
+18
@@ -0,0 +1,18 @@
|
|||||||
|
interface Return {
|
||||||
|
success: boolean;
|
||||||
|
payload: {
|
||||||
|
urlPath: string;
|
||||||
|
urlThumbnailPath: string;
|
||||||
|
} | null;
|
||||||
|
msg?: string;
|
||||||
|
}
|
||||||
|
type Param = {
|
||||||
|
key: string;
|
||||||
|
url: string;
|
||||||
|
user_id?: string | number;
|
||||||
|
};
|
||||||
|
/**
|
||||||
|
* # Delete File via API
|
||||||
|
*/
|
||||||
|
export default function deleteFile({ key, url, user_id, }: Param): Promise<Return>;
|
||||||
|
export {};
|
||||||
+76
@@ -0,0 +1,76 @@
|
|||||||
|
"use strict";
|
||||||
|
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||||
|
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||||
|
return new (P || (P = Promise))(function (resolve, reject) {
|
||||||
|
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||||
|
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||||
|
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||||
|
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||||
|
});
|
||||||
|
};
|
||||||
|
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||||
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||||
|
};
|
||||||
|
Object.defineProperty(exports, "__esModule", { value: true });
|
||||||
|
exports.default = deleteFile;
|
||||||
|
const grab_host_names_1 = __importDefault(require("../utils/grab-host-names"));
|
||||||
|
/**
|
||||||
|
* # Delete File via API
|
||||||
|
*/
|
||||||
|
function deleteFile(_a) {
|
||||||
|
return __awaiter(this, arguments, void 0, function* ({ key, url, user_id, }) {
|
||||||
|
const grabedHostNames = (0, grab_host_names_1.default)();
|
||||||
|
const { host, port, scheme } = grabedHostNames;
|
||||||
|
try {
|
||||||
|
/**
|
||||||
|
* Make https request
|
||||||
|
*
|
||||||
|
* @description make a request to datasquirel.com
|
||||||
|
*/
|
||||||
|
const httpResponse = yield new Promise((resolve, reject) => {
|
||||||
|
const reqPayload = JSON.stringify({ url: url });
|
||||||
|
const httpsRequest = scheme.request({
|
||||||
|
method: "POST",
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
"Content-Length": Buffer.from(reqPayload).length,
|
||||||
|
Authorization: key ||
|
||||||
|
process.env.DSQL_FULL_ACCESS_API_KEY ||
|
||||||
|
process.env.DSQL_API_KEY,
|
||||||
|
},
|
||||||
|
port,
|
||||||
|
hostname: host,
|
||||||
|
path: `/api/query/${user_id || grabedHostNames.user_id}/delete-file`,
|
||||||
|
},
|
||||||
|
/**
|
||||||
|
* Callback Function
|
||||||
|
*
|
||||||
|
* @description https request callback
|
||||||
|
*/
|
||||||
|
(response) => {
|
||||||
|
var str = "";
|
||||||
|
response.on("data", function (chunk) {
|
||||||
|
str += chunk;
|
||||||
|
});
|
||||||
|
response.on("end", function () {
|
||||||
|
resolve(JSON.parse(str));
|
||||||
|
});
|
||||||
|
response.on("error", (err) => {
|
||||||
|
reject(err);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
httpsRequest.write(reqPayload);
|
||||||
|
httpsRequest.end();
|
||||||
|
});
|
||||||
|
return httpResponse;
|
||||||
|
}
|
||||||
|
catch ( /** @type {*} */error) {
|
||||||
|
console.log("Error deleting file: ", error.message);
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
payload: null,
|
||||||
|
msg: error.message,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
export default function getCsrfHeaderName(): string;
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
"use strict";
|
||||||
|
Object.defineProperty(exports, "__esModule", { value: true });
|
||||||
|
exports.default = getCsrfHeaderName;
|
||||||
|
function getCsrfHeaderName() {
|
||||||
|
return "x-dsql-csrf-key";
|
||||||
|
}
|
||||||
+10
@@ -0,0 +1,10 @@
|
|||||||
|
import { DSQL_DatabaseSchemaType, DSQL_FieldSchemaType, DSQL_TableSchemaType, GetSchemaAPIParam } from "../types";
|
||||||
|
type GetSchemaReturn = {
|
||||||
|
success: boolean;
|
||||||
|
payload?: DSQL_DatabaseSchemaType | DSQL_TableSchemaType | DSQL_FieldSchemaType | null;
|
||||||
|
};
|
||||||
|
/**
|
||||||
|
* # Get Schema for Database, table, or field *
|
||||||
|
*/
|
||||||
|
export default function getSchema({ key, database, field, table, user_id, env, }: GetSchemaAPIParam): Promise<GetSchemaReturn>;
|
||||||
|
export {};
|
||||||
+69
@@ -0,0 +1,69 @@
|
|||||||
|
"use strict";
|
||||||
|
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||||
|
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||||
|
return new (P || (P = Promise))(function (resolve, reject) {
|
||||||
|
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||||
|
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||||
|
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||||
|
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||||
|
});
|
||||||
|
};
|
||||||
|
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||||
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||||
|
};
|
||||||
|
Object.defineProperty(exports, "__esModule", { value: true });
|
||||||
|
exports.default = getSchema;
|
||||||
|
const grab_host_names_1 = __importDefault(require("../utils/grab-host-names"));
|
||||||
|
/**
|
||||||
|
* # Get Schema for Database, table, or field *
|
||||||
|
*/
|
||||||
|
function getSchema(_a) {
|
||||||
|
return __awaiter(this, arguments, void 0, function* ({ key, database, field, table, user_id, env, }) {
|
||||||
|
const grabedHostNames = (0, grab_host_names_1.default)({ env });
|
||||||
|
const { host, port, scheme } = grabedHostNames;
|
||||||
|
/**
|
||||||
|
* Make https request
|
||||||
|
*
|
||||||
|
* @description make a request to datasquirel.com
|
||||||
|
*/
|
||||||
|
const httpResponse = yield new Promise((resolve, reject) => {
|
||||||
|
const queryObject = { database, field, table };
|
||||||
|
let query = Object.keys(queryObject)
|
||||||
|
.filter((k) => queryObject[k])
|
||||||
|
.map((k) => `${k}=${queryObject[k]}`)
|
||||||
|
.join("&");
|
||||||
|
scheme
|
||||||
|
.request({
|
||||||
|
method: "GET",
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
Authorization: key ||
|
||||||
|
process.env.DSQL_FULL_ACCESS_API_KEY ||
|
||||||
|
process.env.DSQL_API_KEY,
|
||||||
|
},
|
||||||
|
port,
|
||||||
|
hostname: host,
|
||||||
|
path: `/api/query/${user_id || grabedHostNames.user_id}/get-schema` + ((query === null || query === void 0 ? void 0 : query.match(/./)) ? `?${query}` : ""),
|
||||||
|
},
|
||||||
|
/**
|
||||||
|
* Callback Function
|
||||||
|
*
|
||||||
|
* @description https request callback
|
||||||
|
*/
|
||||||
|
(response) => {
|
||||||
|
var str = "";
|
||||||
|
response.on("data", function (chunk) {
|
||||||
|
str += chunk;
|
||||||
|
});
|
||||||
|
response.on("end", function () {
|
||||||
|
resolve(JSON.parse(str));
|
||||||
|
});
|
||||||
|
response.on("error", (err) => {
|
||||||
|
resolve(null);
|
||||||
|
});
|
||||||
|
})
|
||||||
|
.end();
|
||||||
|
});
|
||||||
|
return httpResponse;
|
||||||
|
});
|
||||||
|
}
|
||||||
Vendored
+24
@@ -0,0 +1,24 @@
|
|||||||
|
import { APIResponseObject, DsqlCrudQueryObject } from "../types";
|
||||||
|
type Param<T extends {
|
||||||
|
[k: string]: any;
|
||||||
|
} = {
|
||||||
|
[k: string]: any;
|
||||||
|
}> = {
|
||||||
|
key?: string;
|
||||||
|
database: string;
|
||||||
|
query: DsqlCrudQueryObject<T>;
|
||||||
|
table?: string;
|
||||||
|
debug?: boolean;
|
||||||
|
useLocal?: boolean;
|
||||||
|
apiVersion?: string;
|
||||||
|
};
|
||||||
|
export type ApiGetParams = Param;
|
||||||
|
/**
|
||||||
|
* # Make a get request to Datasquirel API
|
||||||
|
*/
|
||||||
|
export default function get<T extends {
|
||||||
|
[k: string]: any;
|
||||||
|
} = {
|
||||||
|
[k: string]: any;
|
||||||
|
}>({ key, database, query, table, debug, useLocal, apiVersion, }: Param<T>): Promise<APIResponseObject>;
|
||||||
|
export {};
|
||||||
Vendored
+101
@@ -0,0 +1,101 @@
|
|||||||
|
"use strict";
|
||||||
|
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||||
|
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||||
|
return new (P || (P = Promise))(function (resolve, reject) {
|
||||||
|
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||||
|
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||||
|
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||||
|
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||||
|
});
|
||||||
|
};
|
||||||
|
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||||
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||||
|
};
|
||||||
|
Object.defineProperty(exports, "__esModule", { value: true });
|
||||||
|
exports.default = get;
|
||||||
|
const grab_host_names_1 = __importDefault(require("../utils/grab-host-names"));
|
||||||
|
const serialize_query_1 = __importDefault(require("../utils/serialize-query"));
|
||||||
|
const debug_log_1 = __importDefault(require("../utils/logging/debug-log"));
|
||||||
|
const crud_1 = __importDefault(require("../utils/data-fetching/crud"));
|
||||||
|
const grab_api_key_1 = __importDefault(require("../utils/grab-api-key"));
|
||||||
|
/**
|
||||||
|
* # Make a get request to Datasquirel API
|
||||||
|
*/
|
||||||
|
function get(_a) {
|
||||||
|
return __awaiter(this, arguments, void 0, function* ({ key, database, query, table, debug, useLocal, apiVersion = "v1", }) {
|
||||||
|
const grabedHostNames = (0, grab_host_names_1.default)();
|
||||||
|
const { host, port, scheme } = grabedHostNames;
|
||||||
|
function debugFn(log, label) {
|
||||||
|
(0, debug_log_1.default)({ log, addTime: true, title: "apiGet", label });
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* Check for local DB settings
|
||||||
|
*
|
||||||
|
* @description Look for local db settings in `.env` file and by pass the http request if available
|
||||||
|
*/
|
||||||
|
if (useLocal) {
|
||||||
|
const result = yield (0, crud_1.default)({
|
||||||
|
action: "get",
|
||||||
|
table: table || "",
|
||||||
|
dbFullName: database,
|
||||||
|
query,
|
||||||
|
});
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* Make https request
|
||||||
|
*
|
||||||
|
* @description make a request to datasquirel.com
|
||||||
|
*/
|
||||||
|
const httpResponse = yield new Promise((resolve, reject) => {
|
||||||
|
const queryString = (0, serialize_query_1.default)(query);
|
||||||
|
if (debug) {
|
||||||
|
debugFn(queryString, "queryString");
|
||||||
|
}
|
||||||
|
let path = `/api/${apiVersion}/crud/${database}/${table}`;
|
||||||
|
if (debug) {
|
||||||
|
debugFn(path, "path");
|
||||||
|
}
|
||||||
|
const requestObject = {
|
||||||
|
method: "GET",
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
Authorization: (0, grab_api_key_1.default)(key),
|
||||||
|
},
|
||||||
|
port,
|
||||||
|
hostname: host,
|
||||||
|
path,
|
||||||
|
};
|
||||||
|
scheme
|
||||||
|
.request(requestObject,
|
||||||
|
/**
|
||||||
|
* Callback Function
|
||||||
|
*
|
||||||
|
* @description https request callback
|
||||||
|
*/
|
||||||
|
(response) => {
|
||||||
|
var str = "";
|
||||||
|
response.on("data", function (chunk) {
|
||||||
|
str += chunk;
|
||||||
|
});
|
||||||
|
response.on("end", function () {
|
||||||
|
try {
|
||||||
|
resolve(JSON.parse(str));
|
||||||
|
}
|
||||||
|
catch (error) {
|
||||||
|
reject({
|
||||||
|
error: error.message,
|
||||||
|
result: str,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
response.on("error", (err) => {
|
||||||
|
console.log("DSQL get Error,", err.message);
|
||||||
|
resolve(null);
|
||||||
|
});
|
||||||
|
})
|
||||||
|
.end();
|
||||||
|
});
|
||||||
|
return httpResponse;
|
||||||
|
});
|
||||||
|
}
|
||||||
+16
@@ -0,0 +1,16 @@
|
|||||||
|
import { PostDataPayload, PostReturn } from "../types";
|
||||||
|
type Param = {
|
||||||
|
key?: string;
|
||||||
|
database?: string;
|
||||||
|
query: string | PostDataPayload;
|
||||||
|
queryValues?: any[];
|
||||||
|
tableName?: string;
|
||||||
|
user_id?: boolean;
|
||||||
|
useLocal?: boolean;
|
||||||
|
debug?: boolean;
|
||||||
|
};
|
||||||
|
/**
|
||||||
|
* # Make a post request to Datasquirel API
|
||||||
|
*/
|
||||||
|
export default function post({ key, query, queryValues, database, tableName, user_id, useLocal, debug, }: Param): Promise<PostReturn>;
|
||||||
|
export {};
|
||||||
Vendored
+132
@@ -0,0 +1,132 @@
|
|||||||
|
"use strict";
|
||||||
|
// @ts-check
|
||||||
|
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||||
|
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||||
|
return new (P || (P = Promise))(function (resolve, reject) {
|
||||||
|
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||||
|
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||||
|
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||||
|
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||||
|
});
|
||||||
|
};
|
||||||
|
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||||
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||||
|
};
|
||||||
|
Object.defineProperty(exports, "__esModule", { value: true });
|
||||||
|
exports.default = post;
|
||||||
|
const grab_host_names_1 = __importDefault(require("../utils/grab-host-names"));
|
||||||
|
const post_1 = __importDefault(require("../functions/api/query/post"));
|
||||||
|
const debug_log_1 = __importDefault(require("../utils/logging/debug-log"));
|
||||||
|
/**
|
||||||
|
* # Make a post request to Datasquirel API
|
||||||
|
*/
|
||||||
|
function post(_a) {
|
||||||
|
return __awaiter(this, arguments, void 0, function* ({ key, query, queryValues, database, tableName, user_id, useLocal, debug, }) {
|
||||||
|
const grabedHostNames = (0, grab_host_names_1.default)();
|
||||||
|
const { host, port, scheme } = grabedHostNames;
|
||||||
|
if (debug) {
|
||||||
|
(0, debug_log_1.default)({
|
||||||
|
log: grabedHostNames,
|
||||||
|
addTime: true,
|
||||||
|
label: "grabedHostNames",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* Check for local DB settings
|
||||||
|
*
|
||||||
|
* @description Look for local db settings in `.env` file and by pass the http request if available
|
||||||
|
*/
|
||||||
|
if (useLocal) {
|
||||||
|
if (debug) {
|
||||||
|
(0, debug_log_1.default)({
|
||||||
|
log: "Using Local DB ...",
|
||||||
|
addTime: true,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return yield (0, post_1.default)({
|
||||||
|
dbFullName: database || "",
|
||||||
|
query,
|
||||||
|
queryValues,
|
||||||
|
tableName,
|
||||||
|
debug,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* Make https request
|
||||||
|
*
|
||||||
|
* @description make a request to datasquirel.com
|
||||||
|
*/
|
||||||
|
const httpResponse = yield new Promise((resolve, reject) => {
|
||||||
|
const reqPayloadString = JSON.stringify({
|
||||||
|
query,
|
||||||
|
queryValues,
|
||||||
|
database: process.env.DSQL_API_DB_NAME || database,
|
||||||
|
tableName: tableName ? tableName : null,
|
||||||
|
}).replace(/\n|\r|\n\r/gm, "");
|
||||||
|
try {
|
||||||
|
JSON.parse(reqPayloadString);
|
||||||
|
}
|
||||||
|
catch (error) {
|
||||||
|
console.log("Error Parsing HTTP response for post action: ", error.message);
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
payload: null,
|
||||||
|
error: "Query object is invalid. Please Check query data values",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
const reqPayload = reqPayloadString;
|
||||||
|
const requPath = `/api/query/${user_id || grabedHostNames.user_id}/post`;
|
||||||
|
const httpsRequest = scheme.request({
|
||||||
|
method: "POST",
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
"Content-Length": Buffer.from(reqPayload).length,
|
||||||
|
Authorization: key ||
|
||||||
|
process.env.DSQL_FULL_ACCESS_API_KEY ||
|
||||||
|
process.env.DSQL_API_KEY,
|
||||||
|
},
|
||||||
|
port,
|
||||||
|
hostname: host,
|
||||||
|
path: requPath,
|
||||||
|
},
|
||||||
|
/**
|
||||||
|
* Callback Function
|
||||||
|
*
|
||||||
|
* @description https request callback
|
||||||
|
*/
|
||||||
|
(response) => {
|
||||||
|
var str = "";
|
||||||
|
response.on("data", function (chunk) {
|
||||||
|
str += chunk;
|
||||||
|
});
|
||||||
|
response.on("end", function () {
|
||||||
|
try {
|
||||||
|
resolve(JSON.parse(str));
|
||||||
|
}
|
||||||
|
catch (error) {
|
||||||
|
console.log("Route ERROR:", error.message);
|
||||||
|
resolve({
|
||||||
|
success: false,
|
||||||
|
payload: null,
|
||||||
|
error: error.message,
|
||||||
|
errPayload: str,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
response.on("error", (err) => {
|
||||||
|
resolve({
|
||||||
|
success: false,
|
||||||
|
payload: null,
|
||||||
|
error: err.message,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
httpsRequest.write(reqPayload);
|
||||||
|
httpsRequest.on("error", (error) => {
|
||||||
|
console.log("HTTPS request ERROR =>", error);
|
||||||
|
});
|
||||||
|
httpsRequest.end();
|
||||||
|
});
|
||||||
|
return httpResponse;
|
||||||
|
});
|
||||||
|
}
|
||||||
+24
@@ -0,0 +1,24 @@
|
|||||||
|
interface Return {
|
||||||
|
success: boolean;
|
||||||
|
payload: {
|
||||||
|
urlPath: string;
|
||||||
|
} | null;
|
||||||
|
msg?: string;
|
||||||
|
}
|
||||||
|
type Param = {
|
||||||
|
key: string;
|
||||||
|
payload: {
|
||||||
|
fileData: string;
|
||||||
|
fileName: string;
|
||||||
|
mimeType?: string;
|
||||||
|
folder?: string;
|
||||||
|
isPrivate?: boolean;
|
||||||
|
};
|
||||||
|
user_id?: string | number;
|
||||||
|
useDefault?: boolean;
|
||||||
|
};
|
||||||
|
/**
|
||||||
|
* # Upload File via API
|
||||||
|
*/
|
||||||
|
export default function uploadImage({ key, payload, user_id, useDefault, }: Param): Promise<Return>;
|
||||||
|
export {};
|
||||||
+76
@@ -0,0 +1,76 @@
|
|||||||
|
"use strict";
|
||||||
|
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||||
|
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||||
|
return new (P || (P = Promise))(function (resolve, reject) {
|
||||||
|
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||||
|
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||||
|
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||||
|
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||||
|
});
|
||||||
|
};
|
||||||
|
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||||
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||||
|
};
|
||||||
|
Object.defineProperty(exports, "__esModule", { value: true });
|
||||||
|
exports.default = uploadImage;
|
||||||
|
const grab_host_names_1 = __importDefault(require("../utils/grab-host-names"));
|
||||||
|
/**
|
||||||
|
* # Upload File via API
|
||||||
|
*/
|
||||||
|
function uploadImage(_a) {
|
||||||
|
return __awaiter(this, arguments, void 0, function* ({ key, payload, user_id, useDefault, }) {
|
||||||
|
const grabedHostNames = (0, grab_host_names_1.default)({ useDefault });
|
||||||
|
const { host, port, scheme } = grabedHostNames;
|
||||||
|
try {
|
||||||
|
/**
|
||||||
|
* Make https request
|
||||||
|
*
|
||||||
|
* @description make a request to datasquirel.com
|
||||||
|
*/
|
||||||
|
const httpResponse = yield new Promise((resolve, reject) => {
|
||||||
|
const reqPayload = JSON.stringify(payload);
|
||||||
|
const httpsRequest = scheme.request({
|
||||||
|
method: "POST",
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
"Content-Length": Buffer.from(reqPayload).length,
|
||||||
|
Authorization: key ||
|
||||||
|
process.env.DSQL_FULL_ACCESS_API_KEY ||
|
||||||
|
process.env.DSQL_API_KEY,
|
||||||
|
},
|
||||||
|
port,
|
||||||
|
hostname: host,
|
||||||
|
path: `/api/query/${user_id || grabedHostNames.user_id}/add-file`,
|
||||||
|
},
|
||||||
|
/**
|
||||||
|
* Callback Function
|
||||||
|
*
|
||||||
|
* @description https request callback
|
||||||
|
*/
|
||||||
|
(response) => {
|
||||||
|
var str = "";
|
||||||
|
response.on("data", function (chunk) {
|
||||||
|
str += chunk;
|
||||||
|
});
|
||||||
|
response.on("end", function () {
|
||||||
|
resolve(JSON.parse(str));
|
||||||
|
});
|
||||||
|
response.on("error", (err) => {
|
||||||
|
reject(err);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
httpsRequest.write(reqPayload);
|
||||||
|
httpsRequest.end();
|
||||||
|
});
|
||||||
|
return httpResponse;
|
||||||
|
}
|
||||||
|
catch (error) {
|
||||||
|
console.log("Error in uploading file: ", error.message);
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
payload: null,
|
||||||
|
msg: error.message,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
+27
@@ -0,0 +1,27 @@
|
|||||||
|
export interface DSQLUploadImageFunctionReturn {
|
||||||
|
success: boolean;
|
||||||
|
payload: DSQLUploadImagePayload | null;
|
||||||
|
msg?: string;
|
||||||
|
}
|
||||||
|
export interface DSQLUploadImagePayload {
|
||||||
|
urlPath: string;
|
||||||
|
urlThumbnailPath: string;
|
||||||
|
}
|
||||||
|
type Param = {
|
||||||
|
key?: string;
|
||||||
|
payload: {
|
||||||
|
imageData: string;
|
||||||
|
imageName: string;
|
||||||
|
mimeType?: string;
|
||||||
|
thumbnailSize?: number;
|
||||||
|
folder?: string;
|
||||||
|
isPrivate?: boolean;
|
||||||
|
};
|
||||||
|
user_id?: string | number;
|
||||||
|
useDefault?: boolean;
|
||||||
|
};
|
||||||
|
/**
|
||||||
|
* # Upload Image via API
|
||||||
|
*/
|
||||||
|
export default function uploadImage({ key, payload, user_id, useDefault, }: Param): Promise<DSQLUploadImageFunctionReturn>;
|
||||||
|
export {};
|
||||||
+76
@@ -0,0 +1,76 @@
|
|||||||
|
"use strict";
|
||||||
|
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||||
|
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||||
|
return new (P || (P = Promise))(function (resolve, reject) {
|
||||||
|
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||||
|
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||||
|
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||||
|
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||||
|
});
|
||||||
|
};
|
||||||
|
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||||
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||||
|
};
|
||||||
|
Object.defineProperty(exports, "__esModule", { value: true });
|
||||||
|
exports.default = uploadImage;
|
||||||
|
const grab_host_names_1 = __importDefault(require("../utils/grab-host-names"));
|
||||||
|
/**
|
||||||
|
* # Upload Image via API
|
||||||
|
*/
|
||||||
|
function uploadImage(_a) {
|
||||||
|
return __awaiter(this, arguments, void 0, function* ({ key, payload, user_id, useDefault, }) {
|
||||||
|
const grabedHostNames = (0, grab_host_names_1.default)({ useDefault });
|
||||||
|
const { host, port, scheme } = grabedHostNames;
|
||||||
|
try {
|
||||||
|
/**
|
||||||
|
* Make https request
|
||||||
|
*
|
||||||
|
* @description make a request to datasquirel.com
|
||||||
|
*/
|
||||||
|
const httpResponse = yield new Promise((resolve, reject) => {
|
||||||
|
const reqPayload = JSON.stringify(payload);
|
||||||
|
const httpsRequest = scheme.request({
|
||||||
|
method: "POST",
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
"Content-Length": Buffer.from(reqPayload).length,
|
||||||
|
Authorization: key ||
|
||||||
|
process.env.DSQL_FULL_ACCESS_API_KEY ||
|
||||||
|
process.env.DSQL_API_KEY,
|
||||||
|
},
|
||||||
|
port,
|
||||||
|
hostname: host,
|
||||||
|
path: `/api/query/${user_id || grabedHostNames.user_id}/add-image`,
|
||||||
|
},
|
||||||
|
/**
|
||||||
|
* Callback Function
|
||||||
|
*
|
||||||
|
* @description https request callback
|
||||||
|
*/
|
||||||
|
(response) => {
|
||||||
|
var str = "";
|
||||||
|
response.on("data", function (chunk) {
|
||||||
|
str += chunk;
|
||||||
|
});
|
||||||
|
response.on("end", function () {
|
||||||
|
resolve(JSON.parse(str));
|
||||||
|
});
|
||||||
|
response.on("error", (err) => {
|
||||||
|
reject(err);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
httpsRequest.write(reqPayload);
|
||||||
|
httpsRequest.end();
|
||||||
|
});
|
||||||
|
return httpResponse;
|
||||||
|
}
|
||||||
|
catch (error) {
|
||||||
|
console.log("Error in uploading image: ", error.message);
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
payload: null,
|
||||||
|
msg: error.message,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
import { AddUserParams, APIResponseObject } from "../../types";
|
||||||
|
/**
|
||||||
|
* # Add User to Database
|
||||||
|
*/
|
||||||
|
export default function addUser({ apiKey, payload, database, encryptionKey, useLocal, verify, apiVersion, dsqlUserID, }: AddUserParams): Promise<APIResponseObject>;
|
||||||
+55
@@ -0,0 +1,55 @@
|
|||||||
|
"use strict";
|
||||||
|
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||||
|
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||||
|
return new (P || (P = Promise))(function (resolve, reject) {
|
||||||
|
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||||
|
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||||
|
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||||
|
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||||
|
});
|
||||||
|
};
|
||||||
|
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||||
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||||
|
};
|
||||||
|
Object.defineProperty(exports, "__esModule", { value: true });
|
||||||
|
exports.default = addUser;
|
||||||
|
const grab_host_names_1 = __importDefault(require("../../utils/grab-host-names"));
|
||||||
|
const api_create_user_1 = __importDefault(require("../../functions/api/users/api-create-user"));
|
||||||
|
const grab_api_path_1 = __importDefault(require("../../utils/backend/users/grab-api-path"));
|
||||||
|
const query_dsql_api_1 = __importDefault(require("../../functions/api/query-dsql-api"));
|
||||||
|
/**
|
||||||
|
* # Add User to Database
|
||||||
|
*/
|
||||||
|
function addUser(_a) {
|
||||||
|
return __awaiter(this, arguments, void 0, function* ({ apiKey, payload, database, encryptionKey, useLocal, verify, apiVersion = "v1", dsqlUserID, }) {
|
||||||
|
const grabedHostNames = (0, grab_host_names_1.default)();
|
||||||
|
const { host, port, scheme } = grabedHostNames;
|
||||||
|
const apiAddUserParams = {
|
||||||
|
database,
|
||||||
|
encryptionKey,
|
||||||
|
payload,
|
||||||
|
verify,
|
||||||
|
dsqlUserID,
|
||||||
|
};
|
||||||
|
if (useLocal) {
|
||||||
|
return yield (0, api_create_user_1.default)(apiAddUserParams);
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* Make https request
|
||||||
|
*
|
||||||
|
* @description make a request to datasquirel.com
|
||||||
|
*/
|
||||||
|
const httpResponse = yield (0, query_dsql_api_1.default)({
|
||||||
|
path: (0, grab_api_path_1.default)({
|
||||||
|
paradigm: "auth",
|
||||||
|
action: "signup",
|
||||||
|
database,
|
||||||
|
apiVersion,
|
||||||
|
}),
|
||||||
|
apiKey,
|
||||||
|
body: apiAddUserParams,
|
||||||
|
method: "POST",
|
||||||
|
});
|
||||||
|
return httpResponse;
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
import { UpdateUserFunctionReturn } from "../../types";
|
||||||
|
type Param = {
|
||||||
|
apiKey?: string;
|
||||||
|
database: string;
|
||||||
|
deletedUserId: string | number;
|
||||||
|
useLocal?: boolean;
|
||||||
|
apiVersion?: string;
|
||||||
|
};
|
||||||
|
/**
|
||||||
|
* # Update User
|
||||||
|
*/
|
||||||
|
export default function deleteUser({ apiKey, database, deletedUserId, useLocal, apiVersion, }: Param): Promise<UpdateUserFunctionReturn>;
|
||||||
|
export {};
|
||||||
@@ -0,0 +1,84 @@
|
|||||||
|
"use strict";
|
||||||
|
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||||
|
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||||
|
return new (P || (P = Promise))(function (resolve, reject) {
|
||||||
|
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||||
|
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||||
|
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||||
|
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||||
|
});
|
||||||
|
};
|
||||||
|
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||||
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||||
|
};
|
||||||
|
Object.defineProperty(exports, "__esModule", { value: true });
|
||||||
|
exports.default = deleteUser;
|
||||||
|
const grab_host_names_1 = __importDefault(require("../../utils/grab-host-names"));
|
||||||
|
const api_delete_user_1 = __importDefault(require("../../functions/api/users/api-delete-user"));
|
||||||
|
const grab_api_path_1 = __importDefault(require("../../utils/backend/users/grab-api-path"));
|
||||||
|
/**
|
||||||
|
* # Update User
|
||||||
|
*/
|
||||||
|
function deleteUser(_a) {
|
||||||
|
return __awaiter(this, arguments, void 0, function* ({ apiKey, database, deletedUserId, useLocal, apiVersion = "v1", }) {
|
||||||
|
const grabedHostNames = (0, grab_host_names_1.default)();
|
||||||
|
const { host, port, scheme } = grabedHostNames;
|
||||||
|
if (useLocal) {
|
||||||
|
return yield (0, api_delete_user_1.default)({
|
||||||
|
dbFullName: database,
|
||||||
|
deletedUserId,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* Make https request
|
||||||
|
*
|
||||||
|
* @description make a request to datasquirel.com
|
||||||
|
*/
|
||||||
|
const httpResponse = (yield new Promise((resolve, reject) => {
|
||||||
|
const reqPayload = JSON.stringify({
|
||||||
|
database,
|
||||||
|
deletedUserId,
|
||||||
|
});
|
||||||
|
const finalAPIKey = apiKey ||
|
||||||
|
process.env.DSQL_API_KEY ||
|
||||||
|
process.env.DSQL_FULL_ACCESS_API_KEY;
|
||||||
|
const httpsRequest = scheme.request({
|
||||||
|
method: "POST",
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
"Content-Length": Buffer.from(reqPayload).length,
|
||||||
|
Authorization: finalAPIKey,
|
||||||
|
},
|
||||||
|
port,
|
||||||
|
hostname: host,
|
||||||
|
path: (0, grab_api_path_1.default)({
|
||||||
|
paradigm: "auth",
|
||||||
|
action: "delete",
|
||||||
|
database,
|
||||||
|
apiVersion,
|
||||||
|
userID: deletedUserId,
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
/**
|
||||||
|
* Callback Function
|
||||||
|
*
|
||||||
|
* @description https request callback
|
||||||
|
*/
|
||||||
|
(response) => {
|
||||||
|
var str = "";
|
||||||
|
response.on("data", function (chunk) {
|
||||||
|
str += chunk;
|
||||||
|
});
|
||||||
|
response.on("end", function () {
|
||||||
|
resolve(JSON.parse(str));
|
||||||
|
});
|
||||||
|
response.on("error", (err) => {
|
||||||
|
reject(err);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
httpsRequest.write(reqPayload);
|
||||||
|
httpsRequest.end();
|
||||||
|
}));
|
||||||
|
return httpResponse;
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
import http from "http";
|
||||||
|
type Param = {
|
||||||
|
request?: http.IncomingMessage;
|
||||||
|
cookieString?: string;
|
||||||
|
encryptionKey: string;
|
||||||
|
encryptionSalt: string;
|
||||||
|
database: string;
|
||||||
|
};
|
||||||
|
type Return = {
|
||||||
|
key: string | undefined;
|
||||||
|
csrf: string | undefined;
|
||||||
|
};
|
||||||
|
/**
|
||||||
|
* Get just the access token for user
|
||||||
|
* ==============================================================================
|
||||||
|
* @description This Function takes in a request object and returns a user token
|
||||||
|
* string and csrf token string
|
||||||
|
*/
|
||||||
|
export default function getToken({ request, encryptionKey, encryptionSalt, cookieString, }: Param): Return;
|
||||||
|
export {};
|
||||||
+75
@@ -0,0 +1,75 @@
|
|||||||
|
"use strict";
|
||||||
|
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||||
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||||
|
};
|
||||||
|
Object.defineProperty(exports, "__esModule", { value: true });
|
||||||
|
exports.default = getToken;
|
||||||
|
const decrypt_1 = __importDefault(require("../../functions/dsql/decrypt"));
|
||||||
|
const get_auth_cookie_names_1 = __importDefault(require("../../functions/backend/cookies/get-auth-cookie-names"));
|
||||||
|
const parseCookies_1 = __importDefault(require("../../utils/backend/parseCookies"));
|
||||||
|
/**
|
||||||
|
* Get just the access token for user
|
||||||
|
* ==============================================================================
|
||||||
|
* @description This Function takes in a request object and returns a user token
|
||||||
|
* string and csrf token string
|
||||||
|
*/
|
||||||
|
function getToken({ request, encryptionKey, encryptionSalt, cookieString, }) {
|
||||||
|
try {
|
||||||
|
/**
|
||||||
|
* Grab the payload
|
||||||
|
*
|
||||||
|
* @description Grab the payload
|
||||||
|
*/
|
||||||
|
const cookies = (0, parseCookies_1.default)({ request, cookieString });
|
||||||
|
const keynames = (0, get_auth_cookie_names_1.default)();
|
||||||
|
const authKeyName = keynames.keyCookieName;
|
||||||
|
const csrfName = keynames.csrfCookieName;
|
||||||
|
const key = cookies[authKeyName];
|
||||||
|
const csrf = cookies[csrfName];
|
||||||
|
/**
|
||||||
|
* Grab the payload
|
||||||
|
*
|
||||||
|
* @description Grab the payload
|
||||||
|
*/
|
||||||
|
let userPayload = (0, decrypt_1.default)({
|
||||||
|
encryptedString: key,
|
||||||
|
encryptionKey,
|
||||||
|
encryptionSalt,
|
||||||
|
});
|
||||||
|
/**
|
||||||
|
* Grab the payload
|
||||||
|
*
|
||||||
|
* @description Grab the payload
|
||||||
|
*/
|
||||||
|
if (!userPayload) {
|
||||||
|
return { key: undefined, csrf: undefined };
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* Grab the payload
|
||||||
|
*
|
||||||
|
* @description Grab the payload
|
||||||
|
*/
|
||||||
|
let userObject = JSON.parse(userPayload);
|
||||||
|
if (!userObject.csrf_k) {
|
||||||
|
return { key: undefined, csrf: undefined };
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* Return User Object
|
||||||
|
*
|
||||||
|
* @description Return User Object
|
||||||
|
*/
|
||||||
|
return { key, csrf };
|
||||||
|
}
|
||||||
|
catch (error) {
|
||||||
|
console.log("Error Getting Token:", error.message);
|
||||||
|
/**
|
||||||
|
* Return User Object
|
||||||
|
*
|
||||||
|
* @description Return User Object
|
||||||
|
*/
|
||||||
|
return {
|
||||||
|
key: undefined,
|
||||||
|
csrf: undefined,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
import { APIResponseObject, GetUserParams } from "../../types";
|
||||||
|
/**
|
||||||
|
* # Get User
|
||||||
|
*/
|
||||||
|
export default function getUser({ apiKey, userId, database, fields, useLocal, apiVersion, dbUserId, selectAll, }: GetUserParams): Promise<APIResponseObject>;
|
||||||
+106
@@ -0,0 +1,106 @@
|
|||||||
|
"use strict";
|
||||||
|
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||||
|
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||||
|
return new (P || (P = Promise))(function (resolve, reject) {
|
||||||
|
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||||
|
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||||
|
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||||
|
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||||
|
});
|
||||||
|
};
|
||||||
|
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||||
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||||
|
};
|
||||||
|
Object.defineProperty(exports, "__esModule", { value: true });
|
||||||
|
exports.default = getUser;
|
||||||
|
const grab_host_names_1 = __importDefault(require("../../utils/grab-host-names"));
|
||||||
|
const api_get_user_1 = __importDefault(require("../../functions/api/users/api-get-user"));
|
||||||
|
const grab_api_path_1 = __importDefault(require("../../utils/backend/users/grab-api-path"));
|
||||||
|
/**
|
||||||
|
* # Get User
|
||||||
|
*/
|
||||||
|
function getUser(_a) {
|
||||||
|
return __awaiter(this, arguments, void 0, function* ({ apiKey, userId, database, fields, useLocal, apiVersion = "v1", dbUserId, selectAll, }) {
|
||||||
|
/**
|
||||||
|
* Initialize
|
||||||
|
*/
|
||||||
|
const defaultFields = [
|
||||||
|
"id",
|
||||||
|
"first_name",
|
||||||
|
"last_name",
|
||||||
|
"email",
|
||||||
|
"username",
|
||||||
|
"image",
|
||||||
|
"image_thumbnail",
|
||||||
|
"verification_status",
|
||||||
|
"date_created",
|
||||||
|
"date_created_code",
|
||||||
|
"date_created_timestamp",
|
||||||
|
"date_updated",
|
||||||
|
"date_updated_code",
|
||||||
|
"date_updated_timestamp",
|
||||||
|
];
|
||||||
|
const updatedFields = fields && fields[0] ? [...defaultFields, ...fields] : defaultFields;
|
||||||
|
const grabedHostNames = (0, grab_host_names_1.default)();
|
||||||
|
const { host, port, scheme } = grabedHostNames;
|
||||||
|
const getUserParams = {
|
||||||
|
userId,
|
||||||
|
fields: [...new Set(updatedFields)],
|
||||||
|
database,
|
||||||
|
dbUserId,
|
||||||
|
selectAll,
|
||||||
|
};
|
||||||
|
if (useLocal) {
|
||||||
|
return yield (0, api_get_user_1.default)(getUserParams);
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* Make https request
|
||||||
|
*
|
||||||
|
* @description make a request to datasquirel.com
|
||||||
|
*/
|
||||||
|
const httpResponse = yield new Promise((resolve, reject) => {
|
||||||
|
const reqPayload = JSON.stringify(getUserParams);
|
||||||
|
const finalAPIKey = apiKey ||
|
||||||
|
process.env.DSQL_API_KEY ||
|
||||||
|
process.env.DSQL_FULL_ACCESS_API_KEY ||
|
||||||
|
process.env.DSQL_READ_ONLY_API_KEY;
|
||||||
|
const httpsRequest = scheme.request({
|
||||||
|
method: "POST",
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
"Content-Length": Buffer.from(reqPayload).length,
|
||||||
|
Authorization: finalAPIKey,
|
||||||
|
},
|
||||||
|
port,
|
||||||
|
hostname: host,
|
||||||
|
path: (0, grab_api_path_1.default)({
|
||||||
|
paradigm: "auth",
|
||||||
|
action: "get",
|
||||||
|
database,
|
||||||
|
apiVersion,
|
||||||
|
userID: userId,
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
/**
|
||||||
|
* Callback Function
|
||||||
|
*
|
||||||
|
* @description https request callback
|
||||||
|
*/
|
||||||
|
(response) => {
|
||||||
|
var str = "";
|
||||||
|
response.on("data", function (chunk) {
|
||||||
|
str += chunk;
|
||||||
|
});
|
||||||
|
response.on("end", function () {
|
||||||
|
resolve(JSON.parse(str));
|
||||||
|
});
|
||||||
|
response.on("error", (err) => {
|
||||||
|
reject(err);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
httpsRequest.write(reqPayload);
|
||||||
|
httpsRequest.end();
|
||||||
|
});
|
||||||
|
return httpResponse;
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
import { APIResponseObject, LoginUserParam } from "../../types";
|
||||||
|
/**
|
||||||
|
* # Login A user
|
||||||
|
*/
|
||||||
|
export default function loginUser({ apiKey, payload, database, additionalFields, response, encryptionKey, encryptionSalt, email_login, email_login_code, temp_code_field, token, skipPassword, apiUserID, skipWriteAuthFile, dbUserId, debug, cleanupTokens, secureCookie, useLocal, apiVersion, }: LoginUserParam): Promise<APIResponseObject>;
|
||||||
+119
@@ -0,0 +1,119 @@
|
|||||||
|
"use strict";
|
||||||
|
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||||
|
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||||
|
return new (P || (P = Promise))(function (resolve, reject) {
|
||||||
|
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||||
|
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||||
|
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||||
|
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||||
|
});
|
||||||
|
};
|
||||||
|
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||||
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||||
|
};
|
||||||
|
Object.defineProperty(exports, "__esModule", { value: true });
|
||||||
|
exports.default = loginUser;
|
||||||
|
const api_login_1 = __importDefault(require("../../functions/api/users/api-login"));
|
||||||
|
const debug_log_1 = __importDefault(require("../../utils/logging/debug-log"));
|
||||||
|
const grab_cookie_expirt_date_1 = __importDefault(require("../../utils/grab-cookie-expirt-date"));
|
||||||
|
const grab_api_path_1 = __importDefault(require("../../utils/backend/users/grab-api-path"));
|
||||||
|
const query_dsql_api_1 = __importDefault(require("../../functions/api/query-dsql-api"));
|
||||||
|
const post_login_response_handler_1 = __importDefault(require("../../functions/backend/auth/post-login-response-handler"));
|
||||||
|
function debugFn(log, label) {
|
||||||
|
(0, debug_log_1.default)({ log, addTime: true, title: "loginUser", label });
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* # Login A user
|
||||||
|
*/
|
||||||
|
function loginUser(_a) {
|
||||||
|
return __awaiter(this, arguments, void 0, function* ({ apiKey, payload, database, additionalFields, response, encryptionKey, encryptionSalt, email_login, email_login_code, temp_code_field, token, skipPassword, apiUserID, skipWriteAuthFile, dbUserId, debug, cleanupTokens, secureCookie, useLocal, apiVersion = "v1", }) {
|
||||||
|
const COOKIE_EXPIRY_DATE = (0, grab_cookie_expirt_date_1.default)();
|
||||||
|
const defaultTempLoginFieldName = "temp_login_code";
|
||||||
|
const emailLoginTempCodeFieldName = email_login
|
||||||
|
? temp_code_field
|
||||||
|
? temp_code_field
|
||||||
|
: defaultTempLoginFieldName
|
||||||
|
: undefined;
|
||||||
|
const finalEncryptionKey = encryptionKey || process.env.DSQL_ENCRYPTION_PASSWORD;
|
||||||
|
const finalEncryptionSalt = encryptionSalt || process.env.DSQL_ENCRYPTION_SALT;
|
||||||
|
if (!(finalEncryptionKey === null || finalEncryptionKey === void 0 ? void 0 : finalEncryptionKey.match(/.{8,}/))) {
|
||||||
|
console.log("Encryption key is invalid");
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
payload: null,
|
||||||
|
msg: "Encryption key is invalid",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
if (!(finalEncryptionSalt === null || finalEncryptionSalt === void 0 ? void 0 : finalEncryptionSalt.match(/.{8,}/))) {
|
||||||
|
console.log("Encryption salt is invalid");
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
payload: null,
|
||||||
|
msg: "Encryption salt is invalid",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* Initialize HTTP response variable
|
||||||
|
*/
|
||||||
|
let httpResponse = {
|
||||||
|
success: false,
|
||||||
|
};
|
||||||
|
const apiLoginParams = {
|
||||||
|
database,
|
||||||
|
email: payload.email,
|
||||||
|
username: payload.username,
|
||||||
|
password: payload.password,
|
||||||
|
skipPassword,
|
||||||
|
encryptionKey: finalEncryptionKey,
|
||||||
|
additionalFields,
|
||||||
|
email_login,
|
||||||
|
email_login_code,
|
||||||
|
email_login_field: emailLoginTempCodeFieldName,
|
||||||
|
token,
|
||||||
|
dbUserId,
|
||||||
|
debug,
|
||||||
|
};
|
||||||
|
/**
|
||||||
|
* Check for local DB settings
|
||||||
|
*
|
||||||
|
* @description Look for local db settings in `.env` file and by pass the http request if available
|
||||||
|
*/
|
||||||
|
if (useLocal) {
|
||||||
|
httpResponse = yield (0, api_login_1.default)(apiLoginParams);
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
httpResponse = yield (0, query_dsql_api_1.default)({
|
||||||
|
path: (0, grab_api_path_1.default)({
|
||||||
|
paradigm: "auth",
|
||||||
|
action: "login",
|
||||||
|
database,
|
||||||
|
apiVersion,
|
||||||
|
}),
|
||||||
|
apiKey,
|
||||||
|
body: apiLoginParams,
|
||||||
|
method: "POST",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if (debug) {
|
||||||
|
debugFn(httpResponse, "httpResponse");
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* # Send Response
|
||||||
|
*/
|
||||||
|
if (httpResponse === null || httpResponse === void 0 ? void 0 : httpResponse.success) {
|
||||||
|
(0, post_login_response_handler_1.default)({
|
||||||
|
database,
|
||||||
|
httpResponse,
|
||||||
|
cleanupTokens,
|
||||||
|
debug,
|
||||||
|
encryptionKey,
|
||||||
|
encryptionSalt,
|
||||||
|
response,
|
||||||
|
secureCookie,
|
||||||
|
skipWriteAuthFile,
|
||||||
|
token,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return httpResponse;
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
import http from "http";
|
||||||
|
type Param = {
|
||||||
|
encryptedUserString?: string;
|
||||||
|
request?: http.IncomingMessage & {
|
||||||
|
[s: string]: any;
|
||||||
|
};
|
||||||
|
response?: http.ServerResponse & {
|
||||||
|
[s: string]: any;
|
||||||
|
};
|
||||||
|
cookieString?: string;
|
||||||
|
database?: string;
|
||||||
|
dsqlUserId?: string | number;
|
||||||
|
debug?: boolean;
|
||||||
|
};
|
||||||
|
type Return = {
|
||||||
|
success: boolean;
|
||||||
|
msg: string;
|
||||||
|
cookieNames?: any;
|
||||||
|
};
|
||||||
|
/**
|
||||||
|
* # Logout user
|
||||||
|
*/
|
||||||
|
export default function logoutUser({ response, database, dsqlUserId, encryptedUserString, request, cookieString, debug, }: Param): Return;
|
||||||
|
export {};
|
||||||
@@ -0,0 +1,88 @@
|
|||||||
|
"use strict";
|
||||||
|
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||||
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||||
|
};
|
||||||
|
Object.defineProperty(exports, "__esModule", { value: true });
|
||||||
|
exports.default = logoutUser;
|
||||||
|
const get_auth_cookie_names_1 = __importDefault(require("../../functions/backend/cookies/get-auth-cookie-names"));
|
||||||
|
const decrypt_1 = __importDefault(require("../../functions/dsql/decrypt"));
|
||||||
|
const ejson_1 = __importDefault(require("../../utils/ejson"));
|
||||||
|
const write_auth_files_1 = require("../../functions/backend/auth/write-auth-files");
|
||||||
|
const parseCookies_1 = __importDefault(require("../../utils/backend/parseCookies"));
|
||||||
|
const debug_log_1 = __importDefault(require("../../utils/logging/debug-log"));
|
||||||
|
/**
|
||||||
|
* # Logout user
|
||||||
|
*/
|
||||||
|
function logoutUser({ response, database, dsqlUserId, encryptedUserString, request, cookieString, debug, }) {
|
||||||
|
/**
|
||||||
|
* Check Encryption Keys
|
||||||
|
*
|
||||||
|
* @description Check Encryption Keys
|
||||||
|
*/
|
||||||
|
try {
|
||||||
|
const cookieNames = (0, get_auth_cookie_names_1.default)({
|
||||||
|
database,
|
||||||
|
});
|
||||||
|
function debugFn(log, label) {
|
||||||
|
(0, debug_log_1.default)({ log, addTime: true, title: "logoutUser", label });
|
||||||
|
}
|
||||||
|
if (debug) {
|
||||||
|
debugFn(cookieNames, "cookieNames");
|
||||||
|
}
|
||||||
|
const authKeyName = cookieNames.keyCookieName;
|
||||||
|
const csrfName = cookieNames.csrfCookieName;
|
||||||
|
const oneTimeCodeName = cookieNames.oneTimeCodeName;
|
||||||
|
const decryptedUserJSON = (() => {
|
||||||
|
try {
|
||||||
|
if (request) {
|
||||||
|
const cookiesObject = (0, parseCookies_1.default)({
|
||||||
|
request,
|
||||||
|
cookieString,
|
||||||
|
});
|
||||||
|
return (0, decrypt_1.default)({
|
||||||
|
encryptedString: cookiesObject[authKeyName],
|
||||||
|
});
|
||||||
|
}
|
||||||
|
else if (encryptedUserString) {
|
||||||
|
return (0, decrypt_1.default)({
|
||||||
|
encryptedString: encryptedUserString,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (error) {
|
||||||
|
console.log("Error getting decrypted User JSON to logout:", error.message);
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
})();
|
||||||
|
if (debug) {
|
||||||
|
debugFn(decryptedUserJSON, "decryptedUserJSON");
|
||||||
|
}
|
||||||
|
if (!decryptedUserJSON)
|
||||||
|
throw new Error("Invalid User");
|
||||||
|
const userObject = ejson_1.default.parse(decryptedUserJSON);
|
||||||
|
if (!(userObject === null || userObject === void 0 ? void 0 : userObject.csrf_k))
|
||||||
|
throw new Error("Invalid User. Please check key");
|
||||||
|
response === null || response === void 0 ? void 0 : response.setHeader("Set-Cookie", [
|
||||||
|
`${authKeyName}=null;max-age=0`,
|
||||||
|
`${csrfName}=null;max-age=0`,
|
||||||
|
`${oneTimeCodeName}=null;max-age=0`,
|
||||||
|
]);
|
||||||
|
const csrf = userObject.csrf_k;
|
||||||
|
(0, write_auth_files_1.deleteAuthFile)(csrf);
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
msg: "User Logged Out",
|
||||||
|
cookieNames,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
catch (error) {
|
||||||
|
console.log("Logout Error:", error.message);
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
msg: "Logout Failed",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
import { APIResponseObject, ResetPasswordParams } from "../../types";
|
||||||
|
/**
|
||||||
|
* # Reset User Password
|
||||||
|
*/
|
||||||
|
export default function resetPassword(params: ResetPasswordParams): Promise<APIResponseObject>;
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
"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 = resetPassword;
|
||||||
|
const query_dsql_api_1 = __importDefault(require("../../functions/api/query-dsql-api"));
|
||||||
|
const grab_api_path_1 = __importDefault(require("../../utils/backend/users/grab-api-path"));
|
||||||
|
const api_reset_user_password_1 = __importDefault(require("../../functions/api/users/api-reset-user-password"));
|
||||||
|
/**
|
||||||
|
* # Reset User Password
|
||||||
|
*/
|
||||||
|
function resetPassword(params) {
|
||||||
|
return __awaiter(this, void 0, void 0, function* () {
|
||||||
|
if (params.useLocal) {
|
||||||
|
return yield (0, api_reset_user_password_1.default)(params);
|
||||||
|
}
|
||||||
|
const httpResponse = yield (0, query_dsql_api_1.default)({
|
||||||
|
path: (0, grab_api_path_1.default)({
|
||||||
|
paradigm: "auth",
|
||||||
|
action: "reset-password",
|
||||||
|
database: params.database,
|
||||||
|
apiVersion: params.apiVersion,
|
||||||
|
}),
|
||||||
|
apiKey: params.apiKey,
|
||||||
|
body: params,
|
||||||
|
method: "POST",
|
||||||
|
});
|
||||||
|
return httpResponse;
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
import { APIResponseObject, SendEmailCodeParams } from "../../types";
|
||||||
|
/**
|
||||||
|
* # Send Email Code to a User
|
||||||
|
*/
|
||||||
|
export default function sendEmailCode(params: SendEmailCodeParams): Promise<APIResponseObject>;
|
||||||
@@ -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 = sendEmailCode;
|
||||||
|
const api_send_email_code_1 = __importDefault(require("../../functions/api/users/api-send-email-code"));
|
||||||
|
const grab_api_path_1 = __importDefault(require("../../utils/backend/users/grab-api-path"));
|
||||||
|
const query_dsql_api_1 = __importDefault(require("../../functions/api/query-dsql-api"));
|
||||||
|
/**
|
||||||
|
* # Send Email Code to a User
|
||||||
|
*/
|
||||||
|
function sendEmailCode(params) {
|
||||||
|
return __awaiter(this, void 0, void 0, function* () {
|
||||||
|
const { apiKey, email, database, temp_code_field_name, mail_domain, mail_password, mail_username, mail_port, sender, response, extraCookies, useLocal, apiVersion, html, } = params;
|
||||||
|
const defaultTempLoginFieldName = "temp_login_code";
|
||||||
|
const emailLoginTempCodeFieldName = temp_code_field_name
|
||||||
|
? temp_code_field_name
|
||||||
|
: defaultTempLoginFieldName;
|
||||||
|
const emailHtml = html ||
|
||||||
|
`<p>Please use this code to login</p>\n<h2>{{code}}</h2>\n<p>Please note that this code expires after 15 minutes</p>`;
|
||||||
|
const apiSendEmailCodeParams = {
|
||||||
|
database,
|
||||||
|
email,
|
||||||
|
email_login_field: emailLoginTempCodeFieldName,
|
||||||
|
html: emailHtml,
|
||||||
|
mail_domain,
|
||||||
|
mail_password,
|
||||||
|
mail_port,
|
||||||
|
mail_username,
|
||||||
|
sender,
|
||||||
|
response,
|
||||||
|
extraCookies,
|
||||||
|
};
|
||||||
|
if (useLocal) {
|
||||||
|
return yield (0, api_send_email_code_1.default)(apiSendEmailCodeParams);
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
const httpResponse = yield (0, query_dsql_api_1.default)({
|
||||||
|
path: (0, grab_api_path_1.default)({
|
||||||
|
paradigm: "auth",
|
||||||
|
action: "send-email-code",
|
||||||
|
database,
|
||||||
|
apiVersion,
|
||||||
|
}),
|
||||||
|
apiKey,
|
||||||
|
body: apiSendEmailCodeParams,
|
||||||
|
method: "POST",
|
||||||
|
});
|
||||||
|
return httpResponse;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
import http from "http";
|
||||||
|
interface FunctionReturn {
|
||||||
|
success: boolean;
|
||||||
|
user: {
|
||||||
|
id: number;
|
||||||
|
first_name: string;
|
||||||
|
last_name: string;
|
||||||
|
csrf_k: string;
|
||||||
|
social_id: string;
|
||||||
|
} | null;
|
||||||
|
dsqlUserId?: number;
|
||||||
|
msg?: string;
|
||||||
|
}
|
||||||
|
type Param = {
|
||||||
|
key: string;
|
||||||
|
code: string;
|
||||||
|
email: string | null;
|
||||||
|
database?: string;
|
||||||
|
clientId: string;
|
||||||
|
clientSecret: string;
|
||||||
|
response: http.ServerResponse;
|
||||||
|
encryptionKey: string;
|
||||||
|
encryptionSalt: string;
|
||||||
|
additionalFields?: string[];
|
||||||
|
additionalData?: {
|
||||||
|
[s: string]: string | number;
|
||||||
|
};
|
||||||
|
user_id?: boolean;
|
||||||
|
secureCookie?: boolean;
|
||||||
|
};
|
||||||
|
/**
|
||||||
|
* # SERVER FUNCTION: Login with google Function
|
||||||
|
*/
|
||||||
|
export default function githubAuth({ key, code, email, database, clientId, clientSecret, response, encryptionKey, encryptionSalt, additionalFields, user_id, additionalData, secureCookie, }: Param): Promise<FunctionReturn | undefined>;
|
||||||
|
export {};
|
||||||
@@ -0,0 +1,174 @@
|
|||||||
|
"use strict";
|
||||||
|
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||||
|
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||||
|
return new (P || (P = Promise))(function (resolve, reject) {
|
||||||
|
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||||
|
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||||
|
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||||
|
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||||
|
});
|
||||||
|
};
|
||||||
|
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||||
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||||
|
};
|
||||||
|
Object.defineProperty(exports, "__esModule", { value: true });
|
||||||
|
exports.default = githubAuth;
|
||||||
|
const fs_1 = __importDefault(require("fs"));
|
||||||
|
const path_1 = __importDefault(require("path"));
|
||||||
|
const encrypt_1 = __importDefault(require("../../../functions/dsql/encrypt"));
|
||||||
|
const grab_host_names_1 = __importDefault(require("../../../utils/grab-host-names"));
|
||||||
|
const api_github_login_1 = __importDefault(require("../../../functions/api/users/social/api-github-login"));
|
||||||
|
const grab_cookie_expirt_date_1 = __importDefault(require("../../../utils/grab-cookie-expirt-date"));
|
||||||
|
const grab_db_names_1 = __importDefault(require("../../../utils/grab-db-names"));
|
||||||
|
/**
|
||||||
|
* # SERVER FUNCTION: Login with google Function
|
||||||
|
*/
|
||||||
|
function githubAuth(_a) {
|
||||||
|
return __awaiter(this, arguments, void 0, function* ({ key, code, email, database, clientId, clientSecret, response, encryptionKey, encryptionSalt, additionalFields, user_id, additionalData, secureCookie, }) {
|
||||||
|
/**
|
||||||
|
* Check inputs
|
||||||
|
*
|
||||||
|
* @description Check inputs
|
||||||
|
*/
|
||||||
|
const grabedHostNames = (0, grab_host_names_1.default)();
|
||||||
|
const { host, port, scheme } = grabedHostNames;
|
||||||
|
const COOKIE_EXPIRY_DATE = (0, grab_cookie_expirt_date_1.default)();
|
||||||
|
if (!code || (code === null || code === void 0 ? void 0 : code.match(/ /))) {
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
user: null,
|
||||||
|
msg: "Please enter Github Access Token",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
if (!database || (database === null || database === void 0 ? void 0 : database.match(/ /))) {
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
user: null,
|
||||||
|
msg: "Please provide database slug name you want to access",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
if (!clientId || (clientId === null || clientId === void 0 ? void 0 : clientId.match(/ /))) {
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
user: null,
|
||||||
|
msg: "Please enter Github OAUTH client ID",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* Initialize HTTP response variable
|
||||||
|
*/
|
||||||
|
let httpResponse;
|
||||||
|
/**
|
||||||
|
* Check for local DB settings
|
||||||
|
*
|
||||||
|
* @description Look for local db settings in `.env` file and by pass the http request if available
|
||||||
|
*/
|
||||||
|
const { DSQL_DB_HOST, DSQL_DB_USERNAME, DSQL_DB_PASSWORD, DSQL_DB_NAME } = process.env;
|
||||||
|
if ((DSQL_DB_HOST === null || DSQL_DB_HOST === void 0 ? void 0 : DSQL_DB_HOST.match(/./)) &&
|
||||||
|
(DSQL_DB_USERNAME === null || DSQL_DB_USERNAME === void 0 ? void 0 : DSQL_DB_USERNAME.match(/./)) &&
|
||||||
|
(DSQL_DB_PASSWORD === null || DSQL_DB_PASSWORD === void 0 ? void 0 : DSQL_DB_PASSWORD.match(/./)) &&
|
||||||
|
(DSQL_DB_NAME === null || DSQL_DB_NAME === void 0 ? void 0 : DSQL_DB_NAME.match(/./))) {
|
||||||
|
/** @type {import("../../../types").DSQL_DatabaseSchemaType | undefined | undefined} */
|
||||||
|
let dbSchema;
|
||||||
|
try {
|
||||||
|
const localDbSchemaPath = path_1.default.resolve(process.cwd(), "dsql.schema.json");
|
||||||
|
dbSchema = JSON.parse(fs_1.default.readFileSync(localDbSchemaPath, "utf8"));
|
||||||
|
}
|
||||||
|
catch (error) { }
|
||||||
|
const { dbFullName } = (0, grab_db_names_1.default)({ dbName: database });
|
||||||
|
httpResponse = yield (0, api_github_login_1.default)({
|
||||||
|
code,
|
||||||
|
email: email || undefined,
|
||||||
|
clientId,
|
||||||
|
clientSecret,
|
||||||
|
additionalFields,
|
||||||
|
database: dbFullName,
|
||||||
|
additionalData,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
/**
|
||||||
|
* Make https request
|
||||||
|
*
|
||||||
|
* @description make a request to datasquirel.com
|
||||||
|
* @type {FunctionReturn} - Https response object
|
||||||
|
*/
|
||||||
|
httpResponse = (yield new Promise((resolve, reject) => {
|
||||||
|
const reqPayload = JSON.stringify({
|
||||||
|
code,
|
||||||
|
email,
|
||||||
|
clientId,
|
||||||
|
clientSecret,
|
||||||
|
database,
|
||||||
|
additionalFields,
|
||||||
|
additionalData,
|
||||||
|
});
|
||||||
|
const httpsRequest = scheme.request({
|
||||||
|
method: "POST",
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
"Content-Length": Buffer.from(reqPayload).length,
|
||||||
|
Authorization: key ||
|
||||||
|
process.env.DSQL_FULL_ACCESS_API_KEY ||
|
||||||
|
process.env.DSQL_API_KEY,
|
||||||
|
},
|
||||||
|
port,
|
||||||
|
hostname: host,
|
||||||
|
path: `/api/user/${user_id || grabedHostNames.user_id}/github-login`,
|
||||||
|
},
|
||||||
|
/**
|
||||||
|
* Callback Function
|
||||||
|
*
|
||||||
|
* @description https request callback
|
||||||
|
*/
|
||||||
|
(response) => {
|
||||||
|
var str = "";
|
||||||
|
response.on("data", function (chunk) {
|
||||||
|
str += chunk;
|
||||||
|
});
|
||||||
|
response.on("end", function () {
|
||||||
|
try {
|
||||||
|
resolve(JSON.parse(str));
|
||||||
|
}
|
||||||
|
catch (error) {
|
||||||
|
console.log("Github Auth Error:", error.message);
|
||||||
|
resolve({
|
||||||
|
success: false,
|
||||||
|
user: null,
|
||||||
|
msg: "Something went wrong",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
response.on("error", (err) => {
|
||||||
|
reject(err);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
httpsRequest.write(reqPayload);
|
||||||
|
httpsRequest.end();
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
////////////////////////////////////////
|
||||||
|
////////////////////////////////////////
|
||||||
|
////////////////////////////////////////
|
||||||
|
/**
|
||||||
|
* Make https request
|
||||||
|
*
|
||||||
|
* @description make a request to datasquirel.com
|
||||||
|
*/
|
||||||
|
if ((httpResponse === null || httpResponse === void 0 ? void 0 : httpResponse.success) && (httpResponse === null || httpResponse === void 0 ? void 0 : httpResponse.user)) {
|
||||||
|
let encryptedPayload = (0, encrypt_1.default)({
|
||||||
|
data: JSON.stringify(httpResponse.user),
|
||||||
|
encryptionKey,
|
||||||
|
encryptionSalt,
|
||||||
|
});
|
||||||
|
const { user, dsqlUserId } = httpResponse;
|
||||||
|
const authKeyName = `datasquirel_${dsqlUserId}_${database}_auth_key`;
|
||||||
|
const csrfName = `datasquirel_${dsqlUserId}_${database}_csrf`;
|
||||||
|
response.setHeader("Set-Cookie", [
|
||||||
|
`${authKeyName}=${encryptedPayload};samesite=strict;path=/;HttpOnly=true;Expires=${COOKIE_EXPIRY_DATE}${secureCookie ? ";Secure=true" : ""}`,
|
||||||
|
`${csrfName}=${user.csrf_k};samesite=strict;path=/;HttpOnly=true;Expires=${COOKIE_EXPIRY_DATE}`,
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
return httpResponse;
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
import { APIResponseObject, GoogleAuthParams } from "../../../types";
|
||||||
|
/**
|
||||||
|
* # SERVER FUNCTION: Login with google Function
|
||||||
|
*/
|
||||||
|
export default function googleAuth({ apiKey, token, database, response, encryptionKey, encryptionSalt, additionalFields, additionalData, debug, secureCookie, loginOnly, useLocal, apiVersion, skipWriteAuthFile, cleanupTokens, }: GoogleAuthParams): Promise<APIResponseObject>;
|
||||||
@@ -0,0 +1,108 @@
|
|||||||
|
"use strict";
|
||||||
|
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||||
|
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||||
|
return new (P || (P = Promise))(function (resolve, reject) {
|
||||||
|
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||||
|
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||||
|
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||||
|
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||||
|
});
|
||||||
|
};
|
||||||
|
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||||
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||||
|
};
|
||||||
|
Object.defineProperty(exports, "__esModule", { value: true });
|
||||||
|
exports.default = googleAuth;
|
||||||
|
const api_google_login_1 = __importDefault(require("../../../functions/api/users/social/api-google-login"));
|
||||||
|
const query_dsql_api_1 = __importDefault(require("../../../functions/api/query-dsql-api"));
|
||||||
|
const grab_api_path_1 = __importDefault(require("../../../utils/backend/users/grab-api-path"));
|
||||||
|
const post_login_response_handler_1 = __importDefault(require("../../../functions/backend/auth/post-login-response-handler"));
|
||||||
|
/**
|
||||||
|
* # SERVER FUNCTION: Login with google Function
|
||||||
|
*/
|
||||||
|
function googleAuth(_a) {
|
||||||
|
return __awaiter(this, arguments, void 0, function* ({ apiKey, token, database, response, encryptionKey, encryptionSalt, additionalFields, additionalData, debug, secureCookie, loginOnly, useLocal, apiVersion, skipWriteAuthFile, cleanupTokens, }) {
|
||||||
|
const finalEncryptionKey = encryptionKey || process.env.DSQL_ENCRYPTION_PASSWORD;
|
||||||
|
const finalEncryptionSalt = encryptionSalt || process.env.DSQL_ENCRYPTION_SALT;
|
||||||
|
if (!(finalEncryptionKey === null || finalEncryptionKey === void 0 ? void 0 : finalEncryptionKey.match(/.{8,}/))) {
|
||||||
|
console.log("Encryption key is invalid");
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
payload: null,
|
||||||
|
msg: "Encryption key is invalid",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
if (!(finalEncryptionSalt === null || finalEncryptionSalt === void 0 ? void 0 : finalEncryptionSalt.match(/.{8,}/))) {
|
||||||
|
console.log("Encryption salt is invalid");
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
payload: null,
|
||||||
|
msg: "Encryption salt is invalid",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* Check inputs
|
||||||
|
*
|
||||||
|
* @description Check inputs
|
||||||
|
*/
|
||||||
|
if (!token || (token === null || token === void 0 ? void 0 : token.match(/ /))) {
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
payload: null,
|
||||||
|
msg: "Please enter Google Access Token",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* Initialize HTTP response variable
|
||||||
|
*/
|
||||||
|
let httpResponse = {
|
||||||
|
success: false,
|
||||||
|
};
|
||||||
|
const googleAuthParams = {
|
||||||
|
token,
|
||||||
|
additionalFields,
|
||||||
|
additionalData,
|
||||||
|
debug,
|
||||||
|
loginOnly,
|
||||||
|
database,
|
||||||
|
};
|
||||||
|
if (useLocal) {
|
||||||
|
if (debug) {
|
||||||
|
console.log(`Google login with Local Paradigm ...`);
|
||||||
|
}
|
||||||
|
httpResponse = yield (0, api_google_login_1.default)(googleAuthParams);
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
httpResponse = yield (0, query_dsql_api_1.default)({
|
||||||
|
path: (0, grab_api_path_1.default)({
|
||||||
|
paradigm: "auth",
|
||||||
|
action: "google-login",
|
||||||
|
database,
|
||||||
|
apiVersion,
|
||||||
|
}),
|
||||||
|
apiKey,
|
||||||
|
body: googleAuthParams,
|
||||||
|
method: "POST",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* Make https request
|
||||||
|
*
|
||||||
|
* @description make a request to datasquirel.com
|
||||||
|
*/
|
||||||
|
if ((httpResponse === null || httpResponse === void 0 ? void 0 : httpResponse.success) && (httpResponse === null || httpResponse === void 0 ? void 0 : httpResponse.singleRes) && database) {
|
||||||
|
(0, post_login_response_handler_1.default)({
|
||||||
|
database,
|
||||||
|
httpResponse,
|
||||||
|
cleanupTokens,
|
||||||
|
debug,
|
||||||
|
encryptionKey,
|
||||||
|
encryptionSalt,
|
||||||
|
response,
|
||||||
|
secureCookie,
|
||||||
|
skipWriteAuthFile,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return httpResponse;
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
import { APIResponseObject, UpdateUserParams } from "../../types";
|
||||||
|
import { DSQL_DATASQUIREL_USERS } from "../../types/dsql";
|
||||||
|
/**
|
||||||
|
* # Update User
|
||||||
|
*/
|
||||||
|
export default function updateUser<T extends DSQL_DATASQUIREL_USERS = DSQL_DATASQUIREL_USERS & {
|
||||||
|
[k: string]: any;
|
||||||
|
}>({ payload, database, updatedUserId, useLocal, apiKey, apiVersion, dbUserId, }: UpdateUserParams<T>): Promise<APIResponseObject>;
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user