Updates
This commit is contained in:
		
							parent
							
								
									9192dae0b5
								
							
						
					
					
						commit
						a3561da53d
					
				
							
								
								
									
										27
									
								
								dist/cjs/index.js
									
									
									
									
										vendored
									
									
								
							
							
						
						
									
										27
									
								
								dist/cjs/index.js
									
									
									
									
										vendored
									
									
								
							
										
											
												File diff suppressed because one or more lines are too long
											
										
									
								
							
							
								
								
									
										13
									
								
								dist/client/auth/github/getAccessToken.d.ts
									
									
									
									
										vendored
									
									
										Normal file
									
								
							
							
						
						
									
										13
									
								
								dist/client/auth/github/getAccessToken.d.ts
									
									
									
									
										vendored
									
									
										Normal file
									
								
							| @ -0,0 +1,13 @@ | |||||||
|  | type Param = { | ||||||
|  |     clientId: string; | ||||||
|  |     redirectUrl: string; | ||||||
|  |     setLoading?: (arg0: boolean) => void; | ||||||
|  |     scopes?: string[]; | ||||||
|  | }; | ||||||
|  | /** | ||||||
|  |  * Login with Github Function | ||||||
|  |  * =============================================================================== | ||||||
|  |  * @description This function uses github api to login a user with datasquirel | ||||||
|  |  */ | ||||||
|  | export default function getAccessToken({ clientId, redirectUrl, setLoading, scopes, }: Param): void; | ||||||
|  | export {}; | ||||||
							
								
								
									
										15
									
								
								dist/client/auth/github/getAccessToken.js
									
									
									
									
										vendored
									
									
										Normal file
									
								
							
							
						
						
									
										15
									
								
								dist/client/auth/github/getAccessToken.js
									
									
									
									
										vendored
									
									
										Normal file
									
								
							| @ -0,0 +1,15 @@ | |||||||
|  | "use strict"; | ||||||
|  | Object.defineProperty(exports, "__esModule", { value: true }); | ||||||
|  | exports.default = getAccessToken; | ||||||
|  | /** | ||||||
|  |  * Login with Github Function | ||||||
|  |  * =============================================================================== | ||||||
|  |  * @description This function uses github api to login a user with datasquirel | ||||||
|  |  */ | ||||||
|  | function getAccessToken({ clientId, redirectUrl, setLoading, scopes, }) { | ||||||
|  |     if (setLoading) | ||||||
|  |         setLoading(true); | ||||||
|  |     const scopeString = scopes ? scopes.join("%20") : "read:user"; | ||||||
|  |     const fetchUrl = `https://github.com/login/oauth/authorize?client_id=${clientId}&scope=${scopeString}&redirect_uri=${redirectUrl}`; | ||||||
|  |     window.location.assign(fetchUrl); | ||||||
|  | } | ||||||
							
								
								
									
										18
									
								
								dist/client/auth/google/getAccessToken.d.ts
									
									
									
									
										vendored
									
									
										Normal file
									
								
							
							
						
						
									
										18
									
								
								dist/client/auth/google/getAccessToken.d.ts
									
									
									
									
										vendored
									
									
										Normal file
									
								
							| @ -0,0 +1,18 @@ | |||||||
|  | interface GoogleGetAccessTokenFunctionParams { | ||||||
|  |     clientId: string; | ||||||
|  |     triggerPrompt?: boolean; | ||||||
|  |     setLoading?: React.Dispatch<React.SetStateAction<boolean>>; | ||||||
|  | } | ||||||
|  | /** | ||||||
|  |  * Login with Google Function | ||||||
|  |  * =============================================================================== | ||||||
|  |  * @description This function uses google identity api to login a user with datasquirel | ||||||
|  |  */ | ||||||
|  | export default function getAccessToken(params: GoogleGetAccessTokenFunctionParams): Promise<string>; | ||||||
|  | /** | ||||||
|  |  * # Google Login Function | ||||||
|  |  */ | ||||||
|  | export declare function googleLogin({ google, clientId, setLoading, triggerPrompt, }: GoogleGetAccessTokenFunctionParams & { | ||||||
|  |     google: any; | ||||||
|  | }): Promise<unknown>; | ||||||
|  | export {}; | ||||||
							
								
								
									
										71
									
								
								dist/client/auth/google/getAccessToken.js
									
									
									
									
										vendored
									
									
										Normal file
									
								
							
							
						
						
									
										71
									
								
								dist/client/auth/google/getAccessToken.js
									
									
									
									
										vendored
									
									
										Normal file
									
								
							| @ -0,0 +1,71 @@ | |||||||
|  | "use strict"; | ||||||
|  | var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { | ||||||
|  |     function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } | ||||||
|  |     return new (P || (P = Promise))(function (resolve, reject) { | ||||||
|  |         function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } | ||||||
|  |         function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } | ||||||
|  |         function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } | ||||||
|  |         step((generator = generator.apply(thisArg, _arguments || [])).next()); | ||||||
|  |     }); | ||||||
|  | }; | ||||||
|  | Object.defineProperty(exports, "__esModule", { value: true }); | ||||||
|  | exports.default = getAccessToken; | ||||||
|  | exports.googleLogin = googleLogin; | ||||||
|  | let interval; | ||||||
|  | /** | ||||||
|  |  * Login with Google Function | ||||||
|  |  * =============================================================================== | ||||||
|  |  * @description This function uses google identity api to login a user with datasquirel | ||||||
|  |  */ | ||||||
|  | function getAccessToken(params) { | ||||||
|  |     return __awaiter(this, void 0, void 0, function* () { | ||||||
|  |         var _a, _b; | ||||||
|  |         (_a = params.setLoading) === null || _a === void 0 ? void 0 : _a.call(params, true); | ||||||
|  |         const response = (yield new Promise((resolve, reject) => { | ||||||
|  |             interval = setInterval(() => { | ||||||
|  |                 // @ts-ignore
 | ||||||
|  |                 let google = window.google; | ||||||
|  |                 if (google) { | ||||||
|  |                     window.clearInterval(interval); | ||||||
|  |                     resolve(googleLogin(Object.assign(Object.assign({}, params), { google }))); | ||||||
|  |                 } | ||||||
|  |             }, 500); | ||||||
|  |         })); | ||||||
|  |         (_b = params.setLoading) === null || _b === void 0 ? void 0 : _b.call(params, false); | ||||||
|  |         return response; | ||||||
|  |     }); | ||||||
|  | } | ||||||
|  | /** | ||||||
|  |  * # Google Login Function | ||||||
|  |  */ | ||||||
|  | function googleLogin({ google, clientId, setLoading, triggerPrompt, }) { | ||||||
|  |     setTimeout(() => { | ||||||
|  |         setLoading === null || setLoading === void 0 ? void 0 : setLoading(false); | ||||||
|  |     }, 3000); | ||||||
|  |     return new Promise((resolve, reject) => { | ||||||
|  |         /** | ||||||
|  |          * # Callback Function | ||||||
|  |          * @param {import("../../../package-shared/types").GoogleAccessTokenObject} response | ||||||
|  |          */ | ||||||
|  |         function handleCredentialResponse(response) { | ||||||
|  |             resolve(response.access_token); | ||||||
|  |         } | ||||||
|  |         const googleAuth = google.accounts.oauth2.initTokenClient({ | ||||||
|  |             client_id: clientId, | ||||||
|  |             scope: "email profile", | ||||||
|  |             callback: handleCredentialResponse, | ||||||
|  |         }); | ||||||
|  |         googleAuth.requestAccessToken(); | ||||||
|  |         if (triggerPrompt) { | ||||||
|  |             google.accounts.id.prompt(triggerGooglePromptCallback); | ||||||
|  |         } | ||||||
|  |         /** | ||||||
|  |          * Google prompt notification callback | ||||||
|  |          * ======================================================== | ||||||
|  |          * @param {import("../../../package-shared/types").GoogleIdentityPromptNotification} notification | ||||||
|  |          */ | ||||||
|  |         function triggerGooglePromptCallback(notification) { | ||||||
|  |             console.log(notification); | ||||||
|  |         } | ||||||
|  |     }); | ||||||
|  | } | ||||||
							
								
								
									
										8
									
								
								dist/client/auth/logout.d.ts
									
									
									
									
										vendored
									
									
										Normal file
									
								
							
							
						
						
									
										8
									
								
								dist/client/auth/logout.d.ts
									
									
									
									
										vendored
									
									
										Normal file
									
								
							| @ -0,0 +1,8 @@ | |||||||
|  | /** | ||||||
|  |  * Login with Google Function | ||||||
|  |  * =============================================================================== | ||||||
|  |  * @description This function uses google identity api to login a user with datasquirel | ||||||
|  |  */ | ||||||
|  | export default function logout(params: { | ||||||
|  |     [s: string]: any; | ||||||
|  | } | null): Promise<boolean>; | ||||||
							
								
								
									
										102
									
								
								dist/client/auth/logout.js
									
									
									
									
										vendored
									
									
										Normal file
									
								
							
							
						
						
									
										102
									
								
								dist/client/auth/logout.js
									
									
									
									
										vendored
									
									
										Normal file
									
								
							| @ -0,0 +1,102 @@ | |||||||
|  | "use strict"; | ||||||
|  | var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { | ||||||
|  |     function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } | ||||||
|  |     return new (P || (P = Promise))(function (resolve, reject) { | ||||||
|  |         function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } | ||||||
|  |         function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } | ||||||
|  |         function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } | ||||||
|  |         step((generator = generator.apply(thisArg, _arguments || [])).next()); | ||||||
|  |     }); | ||||||
|  | }; | ||||||
|  | var __importDefault = (this && this.__importDefault) || function (mod) { | ||||||
|  |     return (mod && mod.__esModule) ? mod : { "default": mod }; | ||||||
|  | }; | ||||||
|  | Object.defineProperty(exports, "__esModule", { value: true }); | ||||||
|  | exports.default = logout; | ||||||
|  | const parseClientCookies_1 = __importDefault(require("../utils/parseClientCookies")); | ||||||
|  | /** | ||||||
|  |  * Login with Google Function | ||||||
|  |  * =============================================================================== | ||||||
|  |  * @description This function uses google identity api to login a user with datasquirel | ||||||
|  |  */ | ||||||
|  | function logout(params) { | ||||||
|  |     return __awaiter(this, void 0, void 0, function* () { | ||||||
|  |         try { | ||||||
|  |             const localUser = localStorage.getItem("user"); | ||||||
|  |             let targetUser; | ||||||
|  |             try { | ||||||
|  |                 targetUser = JSON.parse(localUser || ""); | ||||||
|  |             } | ||||||
|  |             catch (error) { | ||||||
|  |                 console.log(error); | ||||||
|  |             } | ||||||
|  |             if (!targetUser) { | ||||||
|  |                 return false; | ||||||
|  |             } | ||||||
|  |             ////////////////////////////////////////
 | ||||||
|  |             ////////////////////////////////////////
 | ||||||
|  |             ////////////////////////////////////////
 | ||||||
|  |             const cookies = (0, parseClientCookies_1.default)(); | ||||||
|  |             const socialId = (cookies === null || cookies === void 0 ? void 0 : cookies.datasquirel_social_id) && | ||||||
|  |                 typeof cookies.datasquirel_social_id == "string" && | ||||||
|  |                 !cookies.datasquirel_social_id.match(/^null$/i) | ||||||
|  |                 ? cookies.datasquirel_social_id | ||||||
|  |                 : null; | ||||||
|  |             ////////////////////////////////////////
 | ||||||
|  |             ////////////////////////////////////////
 | ||||||
|  |             ////////////////////////////////////////
 | ||||||
|  |             localStorage.setItem("user", "{}"); | ||||||
|  |             localStorage.removeItem("csrf"); | ||||||
|  |             document.cookie = `datasquirel_social_id=null;samesite=strict;path=/`; | ||||||
|  |             ////////////////////////////////////////
 | ||||||
|  |             ////////////////////////////////////////
 | ||||||
|  |             ////////////////////////////////////////
 | ||||||
|  |             const response = yield new Promise((resolve, reject) => { | ||||||
|  |                 if (socialId && !(socialId === null || socialId === void 0 ? void 0 : socialId.match(/^null$/i))) { | ||||||
|  |                     const googleClientId = params === null || params === void 0 ? void 0 : params.googleClientId; | ||||||
|  |                     if (googleClientId) { | ||||||
|  |                         const googleScript = document.createElement("script"); | ||||||
|  |                         googleScript.src = "https://accounts.google.com/gsi/client"; | ||||||
|  |                         googleScript.className = "social-script-tag"; | ||||||
|  |                         document.body.appendChild(googleScript); | ||||||
|  |                         ////////////////////////////////////////
 | ||||||
|  |                         ////////////////////////////////////////
 | ||||||
|  |                         ////////////////////////////////////////
 | ||||||
|  |                         googleScript.onload = function (e) { | ||||||
|  |                             // @ts-ignore
 | ||||||
|  |                             const google = window.google; | ||||||
|  |                             if (google) { | ||||||
|  |                                 ////////////////////////////////////////
 | ||||||
|  |                                 ////////////////////////////////////////
 | ||||||
|  |                                 ////////////////////////////////////////
 | ||||||
|  |                                 google.accounts.id.initialize({ | ||||||
|  |                                     client_id: googleClientId, | ||||||
|  |                                 }); | ||||||
|  |                                 google.accounts.id.revoke(socialId, (done) => { | ||||||
|  |                                     console.log(done.error); | ||||||
|  |                                     resolve(true); | ||||||
|  |                                 }); | ||||||
|  |                                 ////////////////////////////////////////
 | ||||||
|  |                                 ////////////////////////////////////////
 | ||||||
|  |                                 ////////////////////////////////////////
 | ||||||
|  |                             } | ||||||
|  |                         }; | ||||||
|  |                     } | ||||||
|  |                     else { | ||||||
|  |                         resolve(true); | ||||||
|  |                     } | ||||||
|  |                     ////////////////////////////////////////
 | ||||||
|  |                     ////////////////////////////////////////
 | ||||||
|  |                     ////////////////////////////////////////
 | ||||||
|  |                 } | ||||||
|  |                 else { | ||||||
|  |                     resolve(true); | ||||||
|  |                 } | ||||||
|  |             }); | ||||||
|  |             return response; | ||||||
|  |         } | ||||||
|  |         catch (error) { | ||||||
|  |             return false; | ||||||
|  |         } | ||||||
|  |     }); | ||||||
|  | } | ||||||
							
								
								
									
										21
									
								
								dist/client/fetch/index.d.ts
									
									
									
									
										vendored
									
									
										Normal file
									
								
							
							
						
						
									
										21
									
								
								dist/client/fetch/index.d.ts
									
									
									
									
										vendored
									
									
										Normal file
									
								
							| @ -0,0 +1,21 @@ | |||||||
|  | type FetchApiOptions = { | ||||||
|  |     method: "POST" | "GET" | "DELETE" | "PUT" | "PATCH" | "post" | "get" | "delete" | "put" | "patch"; | ||||||
|  |     body?: object | string; | ||||||
|  |     headers?: FetchHeader; | ||||||
|  | }; | ||||||
|  | type FetchHeader = HeadersInit & { | ||||||
|  |     [key: string]: string | null; | ||||||
|  | }; | ||||||
|  | export type FetchApiReturn = { | ||||||
|  |     success: boolean; | ||||||
|  |     payload: any; | ||||||
|  |     msg?: string; | ||||||
|  |     [key: string]: any; | ||||||
|  | }; | ||||||
|  | /** | ||||||
|  |  * # Fetch API | ||||||
|  |  */ | ||||||
|  | export default function fetchApi(url: string, options?: FetchApiOptions, csrf?: boolean,  | ||||||
|  | /** Key to use to grab local Storage csrf value. */ | ||||||
|  | localStorageCSRFKey?: string): Promise<any>; | ||||||
|  | export {}; | ||||||
							
								
								
									
										89
									
								
								dist/client/fetch/index.js
									
									
									
									
										vendored
									
									
										Normal file
									
								
							
							
						
						
									
										89
									
								
								dist/client/fetch/index.js
									
									
									
									
										vendored
									
									
										Normal file
									
								
							| @ -0,0 +1,89 @@ | |||||||
|  | "use strict"; | ||||||
|  | var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { | ||||||
|  |     function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } | ||||||
|  |     return new (P || (P = Promise))(function (resolve, reject) { | ||||||
|  |         function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } | ||||||
|  |         function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } | ||||||
|  |         function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } | ||||||
|  |         step((generator = generator.apply(thisArg, _arguments || [])).next()); | ||||||
|  |     }); | ||||||
|  | }; | ||||||
|  | var __importDefault = (this && this.__importDefault) || function (mod) { | ||||||
|  |     return (mod && mod.__esModule) ? mod : { "default": mod }; | ||||||
|  | }; | ||||||
|  | Object.defineProperty(exports, "__esModule", { value: true }); | ||||||
|  | exports.default = fetchApi; | ||||||
|  | const lodash_1 = __importDefault(require("lodash")); | ||||||
|  | /** | ||||||
|  |  * # Fetch API | ||||||
|  |  */ | ||||||
|  | function fetchApi(url, options, csrf,  | ||||||
|  | /** Key to use to grab local Storage csrf value. */ | ||||||
|  | localStorageCSRFKey) { | ||||||
|  |     return __awaiter(this, void 0, void 0, function* () { | ||||||
|  |         let data; | ||||||
|  |         const csrfValue = localStorage.getItem(localStorageCSRFKey || "csrf"); | ||||||
|  |         let finalHeaders = { | ||||||
|  |             "Content-Type": "application/json", | ||||||
|  |         }; | ||||||
|  |         if (csrf && csrfValue) { | ||||||
|  |             finalHeaders[`'${csrfValue.replace(/\"/g, "")}'`] = "true"; | ||||||
|  |         } | ||||||
|  |         if (typeof options === "string") { | ||||||
|  |             try { | ||||||
|  |                 let fetchData; | ||||||
|  |                 switch (options) { | ||||||
|  |                     case "post": | ||||||
|  |                         fetchData = yield fetch(url, { | ||||||
|  |                             method: options, | ||||||
|  |                             headers: finalHeaders, | ||||||
|  |                         }); | ||||||
|  |                         data = fetchData.json(); | ||||||
|  |                         break; | ||||||
|  |                     default: | ||||||
|  |                         fetchData = yield fetch(url); | ||||||
|  |                         data = fetchData.json(); | ||||||
|  |                         break; | ||||||
|  |                 } | ||||||
|  |             } | ||||||
|  |             catch (error) { | ||||||
|  |                 console.log("FetchAPI error #1:", error.message); | ||||||
|  |                 data = null; | ||||||
|  |             } | ||||||
|  |         } | ||||||
|  |         else if (typeof options === "object") { | ||||||
|  |             try { | ||||||
|  |                 let fetchData; | ||||||
|  |                 if (options.body && typeof options.body === "object") { | ||||||
|  |                     let oldOptionsBody = lodash_1.default.cloneDeep(options.body); | ||||||
|  |                     options.body = JSON.stringify(oldOptionsBody); | ||||||
|  |                 } | ||||||
|  |                 if (options.headers) { | ||||||
|  |                     options.headers = lodash_1.default.merge(options.headers, finalHeaders); | ||||||
|  |                     const finalOptions = Object.assign({}, options); | ||||||
|  |                     fetchData = yield fetch(url, finalOptions); | ||||||
|  |                 } | ||||||
|  |                 else { | ||||||
|  |                     const finalOptions = Object.assign(Object.assign({}, options), { headers: finalHeaders }); | ||||||
|  |                     fetchData = yield fetch(url, finalOptions); | ||||||
|  |                 } | ||||||
|  |                 data = fetchData.json(); | ||||||
|  |             } | ||||||
|  |             catch (error) { | ||||||
|  |                 console.log("FetchAPI error #2:", error.message); | ||||||
|  |                 data = null; | ||||||
|  |             } | ||||||
|  |         } | ||||||
|  |         else { | ||||||
|  |             try { | ||||||
|  |                 let fetchData = yield fetch(url); | ||||||
|  |                 data = yield fetchData.json(); | ||||||
|  |             } | ||||||
|  |             catch (error) { | ||||||
|  |                 console.log("FetchAPI error #3:", error.message); | ||||||
|  |                 data = null; | ||||||
|  |             } | ||||||
|  |         } | ||||||
|  |         return data; | ||||||
|  |     }); | ||||||
|  | } | ||||||
							
								
								
									
										49
									
								
								dist/client/index.d.ts
									
									
									
									
										vendored
									
									
										Normal file
									
								
							
							
						
						
									
										49
									
								
								dist/client/index.d.ts
									
									
									
									
										vendored
									
									
										Normal file
									
								
							| @ -0,0 +1,49 @@ | |||||||
|  | import imageInputFileToBase64 from "./media/imageInputFileToBase64"; | ||||||
|  | import imageInputToBase64 from "./media/imageInputToBase64"; | ||||||
|  | import inputFileToBase64 from "./media/inputFileToBase64"; | ||||||
|  | import getAccessToken from "./auth/google/getAccessToken"; | ||||||
|  | import getGithubAccessToken from "./auth/github/getAccessToken"; | ||||||
|  | import logout from "./auth/logout"; | ||||||
|  | import fetchApi from "./fetch"; | ||||||
|  | import serializeQuery from "../package-shared/utils/serialize-query"; | ||||||
|  | import serializeCookies from "../package-shared/utils/serialize-cookies"; | ||||||
|  | import numberfy from "../package-shared/utils/numberfy"; | ||||||
|  | import slugify from "../package-shared/utils/slugify"; | ||||||
|  | /** | ||||||
|  |  * Main Export | ||||||
|  |  */ | ||||||
|  | declare const datasquirelClient: { | ||||||
|  |     media: { | ||||||
|  |         imageInputToBase64: typeof imageInputToBase64; | ||||||
|  |         imageInputFileToBase64: typeof imageInputFileToBase64; | ||||||
|  |         inputFileToBase64: typeof inputFileToBase64; | ||||||
|  |     }; | ||||||
|  |     auth: { | ||||||
|  |         google: { | ||||||
|  |             getAccessToken: typeof getAccessToken; | ||||||
|  |         }; | ||||||
|  |         github: { | ||||||
|  |             getAccessToken: typeof getGithubAccessToken; | ||||||
|  |         }; | ||||||
|  |         logout: typeof logout; | ||||||
|  |     }; | ||||||
|  |     fetch: { | ||||||
|  |         fetchApi: typeof fetchApi; | ||||||
|  |         clientFetch: typeof fetchApi; | ||||||
|  |     }; | ||||||
|  |     utils: { | ||||||
|  |         serializeQuery: typeof serializeQuery; | ||||||
|  |         serializeCookies: typeof serializeCookies; | ||||||
|  |         EJSON: { | ||||||
|  |             parse: (string: string | null | number, reviver?: (this: any, key: string, value: any) => any) => { | ||||||
|  |                 [s: string]: any; | ||||||
|  |             } | { | ||||||
|  |                 [s: string]: any; | ||||||
|  |             }[] | undefined; | ||||||
|  |             stringify: (value: any, replacer?: (this: any, key: string, value: any) => any, space?: string | number) => string | undefined; | ||||||
|  |         }; | ||||||
|  |         numberfy: typeof numberfy; | ||||||
|  |         slugify: typeof slugify; | ||||||
|  |     }; | ||||||
|  | }; | ||||||
|  | export default datasquirelClient; | ||||||
							
								
								
									
										60
									
								
								dist/client/index.js
									
									
									
									
										vendored
									
									
										Normal file
									
								
							
							
						
						
									
										60
									
								
								dist/client/index.js
									
									
									
									
										vendored
									
									
										Normal file
									
								
							| @ -0,0 +1,60 @@ | |||||||
|  | "use strict"; | ||||||
|  | var __importDefault = (this && this.__importDefault) || function (mod) { | ||||||
|  |     return (mod && mod.__esModule) ? mod : { "default": mod }; | ||||||
|  | }; | ||||||
|  | Object.defineProperty(exports, "__esModule", { value: true }); | ||||||
|  | const imageInputFileToBase64_1 = __importDefault(require("./media/imageInputFileToBase64")); | ||||||
|  | const imageInputToBase64_1 = __importDefault(require("./media/imageInputToBase64")); | ||||||
|  | const inputFileToBase64_1 = __importDefault(require("./media/inputFileToBase64")); | ||||||
|  | const getAccessToken_1 = __importDefault(require("./auth/google/getAccessToken")); | ||||||
|  | const getAccessToken_2 = __importDefault(require("./auth/github/getAccessToken")); | ||||||
|  | const logout_1 = __importDefault(require("./auth/logout")); | ||||||
|  | const fetch_1 = __importDefault(require("./fetch")); | ||||||
|  | const fetch_2 = __importDefault(require("./fetch")); | ||||||
|  | const serialize_query_1 = __importDefault(require("../package-shared/utils/serialize-query")); | ||||||
|  | const serialize_cookies_1 = __importDefault(require("../package-shared/utils/serialize-cookies")); | ||||||
|  | const ejson_1 = __importDefault(require("../package-shared/utils/ejson")); | ||||||
|  | const numberfy_1 = __importDefault(require("../package-shared/utils/numberfy")); | ||||||
|  | const slugify_1 = __importDefault(require("../package-shared/utils/slugify")); | ||||||
|  | ////////////////////////////////////////
 | ||||||
|  | ////////////////////////////////////////
 | ||||||
|  | ////////////////////////////////////////
 | ||||||
|  | /** | ||||||
|  |  * Media Functions Object | ||||||
|  |  */ | ||||||
|  | const media = { | ||||||
|  |     imageInputToBase64: imageInputToBase64_1.default, | ||||||
|  |     imageInputFileToBase64: imageInputFileToBase64_1.default, | ||||||
|  |     inputFileToBase64: inputFileToBase64_1.default, | ||||||
|  | }; | ||||||
|  | /** | ||||||
|  |  * User Auth Object | ||||||
|  |  */ | ||||||
|  | const auth = { | ||||||
|  |     google: { | ||||||
|  |         getAccessToken: getAccessToken_1.default, | ||||||
|  |     }, | ||||||
|  |     github: { | ||||||
|  |         getAccessToken: getAccessToken_2.default, | ||||||
|  |     }, | ||||||
|  |     logout: logout_1.default, | ||||||
|  | }; | ||||||
|  | const utils = { | ||||||
|  |     serializeQuery: serialize_query_1.default, | ||||||
|  |     serializeCookies: serialize_cookies_1.default, | ||||||
|  |     EJSON: ejson_1.default, | ||||||
|  |     numberfy: numberfy_1.default, | ||||||
|  |     slugify: slugify_1.default, | ||||||
|  | }; | ||||||
|  | /** | ||||||
|  |  * Fetch | ||||||
|  |  */ | ||||||
|  | const fetch = { | ||||||
|  |     fetchApi: fetch_1.default, | ||||||
|  |     clientFetch: fetch_2.default, | ||||||
|  | }; | ||||||
|  | /** | ||||||
|  |  * Main Export | ||||||
|  |  */ | ||||||
|  | const datasquirelClient = { media, auth, fetch, utils }; | ||||||
|  | exports.default = datasquirelClient; | ||||||
							
								
								
									
										14
									
								
								dist/client/media/client.d.ts
									
									
									
									
										vendored
									
									
										Normal file
									
								
							
							
						
						
									
										14
									
								
								dist/client/media/client.d.ts
									
									
									
									
										vendored
									
									
										Normal file
									
								
							| @ -0,0 +1,14 @@ | |||||||
|  | import imageInputFileToBase64 from "./imageInputFileToBase64"; | ||||||
|  | import imageInputToBase64 from "./imageInputToBase64"; | ||||||
|  | /** | ||||||
|  |  * ========================== | ||||||
|  |  * Main Export | ||||||
|  |  * ========================== | ||||||
|  |  */ | ||||||
|  | declare const datasquirelClient: { | ||||||
|  |     media: { | ||||||
|  |         imageInputToBase64: typeof imageInputToBase64; | ||||||
|  |         imageInputFileToBase64: typeof imageInputFileToBase64; | ||||||
|  |     }; | ||||||
|  | }; | ||||||
|  | export default datasquirelClient; | ||||||
							
								
								
									
										34
									
								
								dist/client/media/client.js
									
									
									
									
										vendored
									
									
										Normal file
									
								
							
							
						
						
									
										34
									
								
								dist/client/media/client.js
									
									
									
									
										vendored
									
									
										Normal file
									
								
							| @ -0,0 +1,34 @@ | |||||||
|  | "use strict"; | ||||||
|  | var __importDefault = (this && this.__importDefault) || function (mod) { | ||||||
|  |     return (mod && mod.__esModule) ? mod : { "default": mod }; | ||||||
|  | }; | ||||||
|  | Object.defineProperty(exports, "__esModule", { value: true }); | ||||||
|  | const imageInputFileToBase64_1 = __importDefault(require("./imageInputFileToBase64")); | ||||||
|  | const imageInputToBase64_1 = __importDefault(require("./imageInputToBase64")); | ||||||
|  | /** | ||||||
|  |  * ========================== | ||||||
|  |  * Media Functions Object | ||||||
|  |  * ========================== | ||||||
|  |  */ | ||||||
|  | const media = { | ||||||
|  |     imageInputToBase64: imageInputToBase64_1.default, | ||||||
|  |     imageInputFileToBase64: imageInputFileToBase64_1.default, | ||||||
|  | }; | ||||||
|  | /** | ||||||
|  |  * ========================== | ||||||
|  |  * Media Functions Object | ||||||
|  |  * ========================== | ||||||
|  |  */ | ||||||
|  | const auth = { | ||||||
|  |     imageInputToBase64: imageInputToBase64_1.default, | ||||||
|  |     imageInputFileToBase64: imageInputFileToBase64_1.default, | ||||||
|  | }; | ||||||
|  | /** | ||||||
|  |  * ========================== | ||||||
|  |  * Main Export | ||||||
|  |  * ========================== | ||||||
|  |  */ | ||||||
|  | const datasquirelClient = { | ||||||
|  |     media: media, | ||||||
|  | }; | ||||||
|  | exports.default = datasquirelClient; | ||||||
							
								
								
									
										11
									
								
								dist/client/media/imageInputFileToBase64.d.ts
									
									
									
									
										vendored
									
									
										Normal file
									
								
							
							
						
						
									
										11
									
								
								dist/client/media/imageInputFileToBase64.d.ts
									
									
									
									
										vendored
									
									
										Normal file
									
								
							| @ -0,0 +1,11 @@ | |||||||
|  | import { ImageInputFileToBase64FunctionReturn } from "../../package-shared/types"; | ||||||
|  | type Param = { | ||||||
|  |     imageInputFile: File; | ||||||
|  |     maxWidth?: number; | ||||||
|  |     imagePreviewNode?: HTMLImageElement; | ||||||
|  | }; | ||||||
|  | /** | ||||||
|  |  * # Image input File top Base64 | ||||||
|  |  */ | ||||||
|  | export default function imageInputFileToBase64({ imageInputFile, maxWidth, imagePreviewNode, }: Param): Promise<ImageInputFileToBase64FunctionReturn>; | ||||||
|  | export {}; | ||||||
							
								
								
									
										92
									
								
								dist/client/media/imageInputFileToBase64.js
									
									
									
									
										vendored
									
									
										Normal file
									
								
							
							
						
						
									
										92
									
								
								dist/client/media/imageInputFileToBase64.js
									
									
									
									
										vendored
									
									
										Normal file
									
								
							| @ -0,0 +1,92 @@ | |||||||
|  | "use strict"; | ||||||
|  | var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { | ||||||
|  |     function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } | ||||||
|  |     return new (P || (P = Promise))(function (resolve, reject) { | ||||||
|  |         function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } | ||||||
|  |         function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } | ||||||
|  |         function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } | ||||||
|  |         step((generator = generator.apply(thisArg, _arguments || [])).next()); | ||||||
|  |     }); | ||||||
|  | }; | ||||||
|  | Object.defineProperty(exports, "__esModule", { value: true }); | ||||||
|  | exports.default = imageInputFileToBase64; | ||||||
|  | /** | ||||||
|  |  * # Image input File top Base64 | ||||||
|  |  */ | ||||||
|  | function imageInputFileToBase64(_a) { | ||||||
|  |     return __awaiter(this, arguments, void 0, function* ({ imageInputFile, maxWidth, imagePreviewNode, }) { | ||||||
|  |         /** | ||||||
|  |          * Make https request | ||||||
|  |          * | ||||||
|  |          * @description make a request to datasquirel.com | ||||||
|  |          */ | ||||||
|  |         try { | ||||||
|  |             let imageName = imageInputFile.name.replace(/\..*/, ""); | ||||||
|  |             let imageDataBase64; | ||||||
|  |             let imageSize; | ||||||
|  |             let canvas = document.createElement("canvas"); | ||||||
|  |             const MIME_TYPE = imageInputFile.type; | ||||||
|  |             const QUALITY = 0.95; | ||||||
|  |             const MAX_WIDTH = maxWidth ? maxWidth : null; | ||||||
|  |             const file = imageInputFile; | ||||||
|  |             const blobURL = URL.createObjectURL(file); | ||||||
|  |             const img = new Image(); | ||||||
|  |             /** ********************* Add source to new image */ | ||||||
|  |             img.src = blobURL; | ||||||
|  |             imageDataBase64 = yield new Promise((res, rej) => { | ||||||
|  |                 /** ********************* Handle Errors in loading image */ | ||||||
|  |                 img.onerror = function () { | ||||||
|  |                     URL.revokeObjectURL(this.src); | ||||||
|  |                     console.log("Cannot load image"); | ||||||
|  |                 }; | ||||||
|  |                 /** ********************* Handle new image when loaded */ | ||||||
|  |                 img.onload = function (e) { | ||||||
|  |                     const imgEl = e.target; | ||||||
|  |                     URL.revokeObjectURL(imgEl.src); | ||||||
|  |                     if (MAX_WIDTH) { | ||||||
|  |                         const scaleSize = MAX_WIDTH / img.naturalWidth; | ||||||
|  |                         canvas.width = | ||||||
|  |                             img.naturalWidth < MAX_WIDTH | ||||||
|  |                                 ? img.naturalWidth | ||||||
|  |                                 : MAX_WIDTH; | ||||||
|  |                         canvas.height = | ||||||
|  |                             img.naturalWidth < MAX_WIDTH | ||||||
|  |                                 ? img.naturalHeight | ||||||
|  |                                 : img.naturalHeight * scaleSize; | ||||||
|  |                     } | ||||||
|  |                     else { | ||||||
|  |                         canvas.width = img.naturalWidth; | ||||||
|  |                         canvas.height = img.naturalHeight; | ||||||
|  |                     } | ||||||
|  |                     const ctx = canvas.getContext("2d"); | ||||||
|  |                     ctx === null || ctx === void 0 ? void 0 : ctx.drawImage(img, 0, 0, canvas.width, canvas.height); | ||||||
|  |                     const srcEncoded = canvas.toDataURL(MIME_TYPE, QUALITY); | ||||||
|  |                     if (imagePreviewNode) { | ||||||
|  |                         imagePreviewNode.src = srcEncoded; | ||||||
|  |                     } | ||||||
|  |                     res(srcEncoded); | ||||||
|  |                 }; | ||||||
|  |             }); | ||||||
|  |             imageSize = yield new Promise((res, rej) => { | ||||||
|  |                 canvas.toBlob((blob) => { | ||||||
|  |                     res(blob === null || blob === void 0 ? void 0 : blob.size); | ||||||
|  |                 }, MIME_TYPE, QUALITY); | ||||||
|  |             }); | ||||||
|  |             return { | ||||||
|  |                 imageBase64: imageDataBase64 === null || imageDataBase64 === void 0 ? void 0 : imageDataBase64.replace(/.*?base64,/, ""), | ||||||
|  |                 imageBase64Full: imageDataBase64, | ||||||
|  |                 imageName: imageName, | ||||||
|  |                 imageSize: imageSize, | ||||||
|  |             }; | ||||||
|  |         } | ||||||
|  |         catch (error) { | ||||||
|  |             console.log("Image Processing Error! =>", error.message); | ||||||
|  |             return { | ||||||
|  |                 imageBase64: undefined, | ||||||
|  |                 imageBase64Full: undefined, | ||||||
|  |                 imageName: undefined, | ||||||
|  |                 imageSize: undefined, | ||||||
|  |             }; | ||||||
|  |         } | ||||||
|  |     }); | ||||||
|  | } | ||||||
							
								
								
									
										15
									
								
								dist/client/media/imageInputToBase64.d.ts
									
									
									
									
										vendored
									
									
										Normal file
									
								
							
							
						
						
									
										15
									
								
								dist/client/media/imageInputToBase64.d.ts
									
									
									
									
										vendored
									
									
										Normal file
									
								
							| @ -0,0 +1,15 @@ | |||||||
|  | type FunctionReturn = { | ||||||
|  |     imageBase64?: string; | ||||||
|  |     imageBase64Full?: string; | ||||||
|  |     imageName?: string; | ||||||
|  | }; | ||||||
|  | type Param = { | ||||||
|  |     imageInput: HTMLInputElement; | ||||||
|  |     maxWidth?: number; | ||||||
|  |     mimeType?: string; | ||||||
|  | }; | ||||||
|  | /** | ||||||
|  |  * # Image Input Element to Base 64 | ||||||
|  |  */ | ||||||
|  | export default function imageInputToBase64({ imageInput, maxWidth, mimeType, }: Param): Promise<FunctionReturn>; | ||||||
|  | export {}; | ||||||
							
								
								
									
										90
									
								
								dist/client/media/imageInputToBase64.js
									
									
									
									
										vendored
									
									
										Normal file
									
								
							
							
						
						
									
										90
									
								
								dist/client/media/imageInputToBase64.js
									
									
									
									
										vendored
									
									
										Normal file
									
								
							| @ -0,0 +1,90 @@ | |||||||
|  | "use strict"; | ||||||
|  | var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { | ||||||
|  |     function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } | ||||||
|  |     return new (P || (P = Promise))(function (resolve, reject) { | ||||||
|  |         function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } | ||||||
|  |         function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } | ||||||
|  |         function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } | ||||||
|  |         step((generator = generator.apply(thisArg, _arguments || [])).next()); | ||||||
|  |     }); | ||||||
|  | }; | ||||||
|  | Object.defineProperty(exports, "__esModule", { value: true }); | ||||||
|  | exports.default = imageInputToBase64; | ||||||
|  | /** | ||||||
|  |  * # Image Input Element to Base 64 | ||||||
|  |  */ | ||||||
|  | function imageInputToBase64(_a) { | ||||||
|  |     return __awaiter(this, arguments, void 0, function* ({ imageInput, maxWidth, mimeType, }) { | ||||||
|  |         var _b, _c; | ||||||
|  |         /** | ||||||
|  |          * Make https request | ||||||
|  |          * | ||||||
|  |          * @description make a request to datasquirel.com | ||||||
|  |          */ | ||||||
|  |         try { | ||||||
|  |             let imagePreviewNode = document.querySelector(`[data-imagepreview='image']`); | ||||||
|  |             let imageName = (_b = imageInput.files) === null || _b === void 0 ? void 0 : _b[0].name.replace(/\..*/, ""); | ||||||
|  |             let imageDataBase64; | ||||||
|  |             const MIME_TYPE = mimeType ? mimeType : "image/jpeg"; | ||||||
|  |             const QUALITY = 0.95; | ||||||
|  |             const MAX_WIDTH = maxWidth ? maxWidth : null; | ||||||
|  |             const file = (_c = imageInput.files) === null || _c === void 0 ? void 0 : _c[0]; | ||||||
|  |             const blobURL = file ? URL.createObjectURL(file) : undefined; | ||||||
|  |             const img = new Image(); | ||||||
|  |             if (blobURL) { | ||||||
|  |                 img.src = blobURL; | ||||||
|  |                 imageDataBase64 = yield new Promise((res, rej) => { | ||||||
|  |                     /** ********************* Handle Errors in loading image */ | ||||||
|  |                     img.onerror = function () { | ||||||
|  |                         URL.revokeObjectURL(this.src); | ||||||
|  |                         window.alert("Cannot load image!"); | ||||||
|  |                     }; | ||||||
|  |                     img.onload = function (e) { | ||||||
|  |                         const imgEl = e.target; | ||||||
|  |                         URL.revokeObjectURL(imgEl.src); | ||||||
|  |                         const canvas = document.createElement("canvas"); | ||||||
|  |                         if (MAX_WIDTH) { | ||||||
|  |                             const scaleSize = MAX_WIDTH / img.naturalWidth; | ||||||
|  |                             canvas.width = | ||||||
|  |                                 img.naturalWidth < MAX_WIDTH | ||||||
|  |                                     ? img.naturalWidth | ||||||
|  |                                     : MAX_WIDTH; | ||||||
|  |                             canvas.height = | ||||||
|  |                                 img.naturalWidth < MAX_WIDTH | ||||||
|  |                                     ? img.naturalHeight | ||||||
|  |                                     : img.naturalHeight * scaleSize; | ||||||
|  |                         } | ||||||
|  |                         else { | ||||||
|  |                             canvas.width = img.naturalWidth; | ||||||
|  |                             canvas.height = img.naturalHeight; | ||||||
|  |                         } | ||||||
|  |                         const ctx = canvas.getContext("2d"); | ||||||
|  |                         ctx === null || ctx === void 0 ? void 0 : ctx.drawImage(img, 0, 0, canvas.width, canvas.height); | ||||||
|  |                         const srcEncoded = canvas.toDataURL(MIME_TYPE, QUALITY); | ||||||
|  |                         if (imagePreviewNode) { | ||||||
|  |                             document | ||||||
|  |                                 .querySelectorAll(`[data-imagepreview='image']`) | ||||||
|  |                                 .forEach((_img) => { | ||||||
|  |                                 const _imgEl = _img; | ||||||
|  |                                 _imgEl.src = srcEncoded; | ||||||
|  |                             }); | ||||||
|  |                         } | ||||||
|  |                         res(srcEncoded); | ||||||
|  |                     }; | ||||||
|  |                 }); | ||||||
|  |                 return { | ||||||
|  |                     imageBase64: imageDataBase64 === null || imageDataBase64 === void 0 ? void 0 : imageDataBase64.replace(/.*?base64,/, ""), | ||||||
|  |                     imageBase64Full: imageDataBase64, | ||||||
|  |                     imageName: imageName, | ||||||
|  |                 }; | ||||||
|  |             } | ||||||
|  |             else { | ||||||
|  |                 return {}; | ||||||
|  |             } | ||||||
|  |         } | ||||||
|  |         catch ( /** @type {*} */error) { | ||||||
|  |             console.log("Image Processing Error! =>", error.message); | ||||||
|  |             return {}; | ||||||
|  |         } | ||||||
|  |     }); | ||||||
|  | } | ||||||
							
								
								
									
										21
									
								
								dist/client/media/inputFileToBase64.d.ts
									
									
									
									
										vendored
									
									
										Normal file
									
								
							
							
						
						
									
										21
									
								
								dist/client/media/inputFileToBase64.d.ts
									
									
									
									
										vendored
									
									
										Normal file
									
								
							| @ -0,0 +1,21 @@ | |||||||
|  | type FunctionReturn = { | ||||||
|  |     fileBase64?: string; | ||||||
|  |     fileBase64Full?: string; | ||||||
|  |     fileName?: string; | ||||||
|  |     fileSize?: number; | ||||||
|  |     fileType?: string; | ||||||
|  | }; | ||||||
|  | type Param = { | ||||||
|  |     inputFile: File; | ||||||
|  |     allowedRegex?: RegExp; | ||||||
|  | }; | ||||||
|  | /** | ||||||
|  |  * Input File to base64 | ||||||
|  |  * ============================================================================== | ||||||
|  |  * | ||||||
|  |  * @description This function takes in a *SINGLE* input file from a HTML file input element. | ||||||
|  |  * HTML file input elements usually return an array of input objects, so be sure to select the target | ||||||
|  |  * file from the array. | ||||||
|  |  */ | ||||||
|  | export default function inputFileToBase64({ inputFile, allowedRegex, }: Param): Promise<FunctionReturn>; | ||||||
|  | export {}; | ||||||
							
								
								
									
										59
									
								
								dist/client/media/inputFileToBase64.js
									
									
									
									
										vendored
									
									
										Normal file
									
								
							
							
						
						
									
										59
									
								
								dist/client/media/inputFileToBase64.js
									
									
									
									
										vendored
									
									
										Normal file
									
								
							| @ -0,0 +1,59 @@ | |||||||
|  | "use strict"; | ||||||
|  | var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { | ||||||
|  |     function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } | ||||||
|  |     return new (P || (P = Promise))(function (resolve, reject) { | ||||||
|  |         function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } | ||||||
|  |         function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } | ||||||
|  |         function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } | ||||||
|  |         step((generator = generator.apply(thisArg, _arguments || [])).next()); | ||||||
|  |     }); | ||||||
|  | }; | ||||||
|  | Object.defineProperty(exports, "__esModule", { value: true }); | ||||||
|  | exports.default = inputFileToBase64; | ||||||
|  | /** | ||||||
|  |  * Input File to base64 | ||||||
|  |  * ============================================================================== | ||||||
|  |  * | ||||||
|  |  * @description This function takes in a *SINGLE* input file from a HTML file input element. | ||||||
|  |  * HTML file input elements usually return an array of input objects, so be sure to select the target | ||||||
|  |  * file from the array. | ||||||
|  |  */ | ||||||
|  | function inputFileToBase64(_a) { | ||||||
|  |     return __awaiter(this, arguments, void 0, function* ({ inputFile, allowedRegex, }) { | ||||||
|  |         var _b; | ||||||
|  |         const allowedTypesRegex = allowedRegex ? allowedRegex : /image\/*|\/pdf/; | ||||||
|  |         if (!((_b = inputFile === null || inputFile === void 0 ? void 0 : inputFile.type) === null || _b === void 0 ? void 0 : _b.match(allowedTypesRegex))) { | ||||||
|  |             window.alert(`We currently don't support ${inputFile.type} file types. Support is coming soon. For now we support only images and PDFs.`); | ||||||
|  |             return { | ||||||
|  |                 fileName: inputFile.name, | ||||||
|  |             }; | ||||||
|  |         } | ||||||
|  |         try { | ||||||
|  |             let fileName = inputFile.name.replace(/\..*/, ""); | ||||||
|  |             const fileData = yield new Promise((resolve, reject) => { | ||||||
|  |                 var reader = new FileReader(); | ||||||
|  |                 reader.readAsDataURL(inputFile); | ||||||
|  |                 reader.onload = function () { | ||||||
|  |                     var _a; | ||||||
|  |                     resolve((_a = reader.result) === null || _a === void 0 ? void 0 : _a.toString()); | ||||||
|  |                 }; | ||||||
|  |                 reader.onerror = function (/** @type {*} */ error) { | ||||||
|  |                     console.log("Error: ", error.message); | ||||||
|  |                 }; | ||||||
|  |             }); | ||||||
|  |             return { | ||||||
|  |                 fileBase64: fileData === null || fileData === void 0 ? void 0 : fileData.replace(/.*?base64,/, ""), | ||||||
|  |                 fileBase64Full: fileData, | ||||||
|  |                 fileName: fileName, | ||||||
|  |                 fileSize: inputFile.size, | ||||||
|  |                 fileType: inputFile.type, | ||||||
|  |             }; | ||||||
|  |         } | ||||||
|  |         catch (error) { | ||||||
|  |             console.log("File Processing Error! =>", error.message); | ||||||
|  |             return { | ||||||
|  |                 fileName: inputFile.name, | ||||||
|  |             }; | ||||||
|  |         } | ||||||
|  |     }); | ||||||
|  | } | ||||||
							
								
								
									
										8
									
								
								dist/client/utils/parseClientCookies.d.ts
									
									
									
									
										vendored
									
									
										Normal file
									
								
							
							
						
						
									
										8
									
								
								dist/client/utils/parseClientCookies.d.ts
									
									
									
									
										vendored
									
									
										Normal file
									
								
							| @ -0,0 +1,8 @@ | |||||||
|  | /** | ||||||
|  |  * Parse request cookies | ||||||
|  |  * ============================================================================== * | ||||||
|  |  * @description This function takes in a request object and returns the cookies as a JS object | ||||||
|  |  */ | ||||||
|  | export default function (): { | ||||||
|  |     [s: string]: any; | ||||||
|  | } | null; | ||||||
							
								
								
									
										31
									
								
								dist/client/utils/parseClientCookies.js
									
									
									
									
										vendored
									
									
										Normal file
									
								
							
							
						
						
									
										31
									
								
								dist/client/utils/parseClientCookies.js
									
									
									
									
										vendored
									
									
										Normal file
									
								
							| @ -0,0 +1,31 @@ | |||||||
|  | "use strict"; | ||||||
|  | Object.defineProperty(exports, "__esModule", { value: true }); | ||||||
|  | exports.default = default_1; | ||||||
|  | /** | ||||||
|  |  * Parse request cookies | ||||||
|  |  * ============================================================================== * | ||||||
|  |  * @description This function takes in a request object and returns the cookies as a JS object | ||||||
|  |  */ | ||||||
|  | function default_1() { | ||||||
|  |     /** | ||||||
|  |      * Check inputs | ||||||
|  |      * | ||||||
|  |      * @description Check inputs | ||||||
|  |      */ | ||||||
|  |     const cookieString = document.cookie; | ||||||
|  |     if (!cookieString || typeof cookieString !== "string") { | ||||||
|  |         return null; | ||||||
|  |     } | ||||||
|  |     const cookieSplitArray = cookieString.split(";"); | ||||||
|  |     let cookieObject = {}; | ||||||
|  |     cookieSplitArray.forEach((keyValueString) => { | ||||||
|  |         const [key, value] = keyValueString.split("="); | ||||||
|  |         if (key && typeof key == "string") { | ||||||
|  |             cookieObject[key.replace(/^ +| +$/, "")] = | ||||||
|  |                 value && typeof value == "string" | ||||||
|  |                     ? value.replace(/^ +| +$/, "") | ||||||
|  |                     : null; | ||||||
|  |         } | ||||||
|  |     }); | ||||||
|  |     return cookieObject; | ||||||
|  | } | ||||||
							
								
								
									
										28
									
								
								dist/console-colors.d.ts
									
									
									
									
										vendored
									
									
										Normal file
									
								
							
							
						
						
									
										28
									
								
								dist/console-colors.d.ts
									
									
									
									
										vendored
									
									
										Normal file
									
								
							| @ -0,0 +1,28 @@ | |||||||
|  | declare const colors: { | ||||||
|  |     Reset: string; | ||||||
|  |     Bright: string; | ||||||
|  |     Dim: string; | ||||||
|  |     Underscore: string; | ||||||
|  |     Blink: string; | ||||||
|  |     Reverse: string; | ||||||
|  |     Hidden: string; | ||||||
|  |     FgBlack: string; | ||||||
|  |     FgRed: string; | ||||||
|  |     FgGreen: string; | ||||||
|  |     FgYellow: string; | ||||||
|  |     FgBlue: string; | ||||||
|  |     FgMagenta: string; | ||||||
|  |     FgCyan: string; | ||||||
|  |     FgWhite: string; | ||||||
|  |     FgGray: string; | ||||||
|  |     BgBlack: string; | ||||||
|  |     BgRed: string; | ||||||
|  |     BgGreen: string; | ||||||
|  |     BgYellow: string; | ||||||
|  |     BgBlue: string; | ||||||
|  |     BgMagenta: string; | ||||||
|  |     BgCyan: string; | ||||||
|  |     BgWhite: string; | ||||||
|  |     BgGray: string; | ||||||
|  | }; | ||||||
|  | export default colors; | ||||||
							
								
								
									
										30
									
								
								dist/console-colors.js
									
									
									
									
										vendored
									
									
										Normal file
									
								
							
							
						
						
									
										30
									
								
								dist/console-colors.js
									
									
									
									
										vendored
									
									
										Normal file
									
								
							| @ -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; | ||||||
							
								
								
									
										2
									
								
								dist/engine/dsql.d.ts
									
									
									
									
										vendored
									
									
										Normal file
									
								
							
							
						
						
									
										2
									
								
								dist/engine/dsql.d.ts
									
									
									
									
										vendored
									
									
										Normal file
									
								
							| @ -0,0 +1,2 @@ | |||||||
|  | #! /usr/bin/env node | ||||||
|  | export default function run(): Promise<void>; | ||||||
							
								
								
									
										115
									
								
								dist/engine/dsql.js
									
									
									
									
										vendored
									
									
										Normal file
									
								
							
							
						
						
									
										115
									
								
								dist/engine/dsql.js
									
									
									
									
										vendored
									
									
										Normal file
									
								
							| @ -0,0 +1,115 @@ | |||||||
|  | #! /usr/bin/env node
 | ||||||
|  | "use strict"; | ||||||
|  | var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { | ||||||
|  |     function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } | ||||||
|  |     return new (P || (P = Promise))(function (resolve, reject) { | ||||||
|  |         function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } | ||||||
|  |         function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } | ||||||
|  |         function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } | ||||||
|  |         step((generator = generator.apply(thisArg, _arguments || [])).next()); | ||||||
|  |     }); | ||||||
|  | }; | ||||||
|  | var __importDefault = (this && this.__importDefault) || function (mod) { | ||||||
|  |     return (mod && mod.__esModule) ? mod : { "default": mod }; | ||||||
|  | }; | ||||||
|  | Object.defineProperty(exports, "__esModule", { value: true }); | ||||||
|  | exports.default = run; | ||||||
|  | const fs_1 = __importDefault(require("fs")); | ||||||
|  | const path_1 = __importDefault(require("path")); | ||||||
|  | require("dotenv").config({ | ||||||
|  |     path: path_1.default.resolve(process.cwd(), ".env"), | ||||||
|  | }); | ||||||
|  | const index_1 = __importDefault(require("../index")); | ||||||
|  | const console_colors_1 = __importDefault(require("../console-colors")); | ||||||
|  | const createDbFromSchema_1 = __importDefault(require("../package-shared/shell/createDbFromSchema")); | ||||||
|  | if (!fs_1.default.existsSync(path_1.default.resolve(process.cwd(), ".env"))) { | ||||||
|  |     console.log(".env file not found"); | ||||||
|  |     process.exit(); | ||||||
|  | } | ||||||
|  | const { DSQL_HOST, DSQL_USER, DSQL_PASS, DSQL_DB_NAME, DSQL_KEY, DSQL_REF_DB_NAME, DSQL_FULL_SYNC, } = process.env; | ||||||
|  | if (!(DSQL_HOST === null || DSQL_HOST === void 0 ? void 0 : DSQL_HOST.match(/./))) { | ||||||
|  |     console.log("DSQL_HOST is required in your `.env` file"); | ||||||
|  |     process.exit(); | ||||||
|  | } | ||||||
|  | if (!(DSQL_USER === null || DSQL_USER === void 0 ? void 0 : DSQL_USER.match(/./))) { | ||||||
|  |     console.log("DSQL_USER is required in your `.env` file"); | ||||||
|  |     process.exit(); | ||||||
|  | } | ||||||
|  | if (!(DSQL_PASS === null || DSQL_PASS === void 0 ? void 0 : DSQL_PASS.match(/./))) { | ||||||
|  |     console.log("DSQL_PASS is required in your `.env` file"); | ||||||
|  |     process.exit(); | ||||||
|  | } | ||||||
|  | const dbSchemaLocalFilePath = path_1.default.resolve(process.cwd(), "dsql.schema.json"); | ||||||
|  | function run() { | ||||||
|  |     return __awaiter(this, void 0, void 0, function* () { | ||||||
|  |         let schemaData; | ||||||
|  |         if (DSQL_KEY && (DSQL_REF_DB_NAME === null || DSQL_REF_DB_NAME === void 0 ? void 0 : DSQL_REF_DB_NAME.match(/./))) { | ||||||
|  |             const dbSchemaDataResponse = yield index_1.default.getSchema({ | ||||||
|  |                 key: DSQL_KEY, | ||||||
|  |                 database: DSQL_REF_DB_NAME || undefined, | ||||||
|  |             }); | ||||||
|  |             if (!dbSchemaDataResponse.payload || | ||||||
|  |                 Array.isArray(dbSchemaDataResponse.payload)) { | ||||||
|  |                 console.log("DSQL_KEY+DSQL_REF_DB_NAME => Error in fetching DB schema"); | ||||||
|  |                 console.log(dbSchemaDataResponse); | ||||||
|  |                 process.exit(); | ||||||
|  |             } | ||||||
|  |             let fetchedDbSchemaObject = dbSchemaDataResponse.payload; | ||||||
|  |             if (DSQL_DB_NAME) | ||||||
|  |                 fetchedDbSchemaObject.dbFullName = DSQL_DB_NAME; | ||||||
|  |             schemaData = [fetchedDbSchemaObject]; | ||||||
|  |         } | ||||||
|  |         else if (DSQL_KEY) { | ||||||
|  |             const dbSchemaDataResponse = yield index_1.default.getSchema({ | ||||||
|  |                 key: DSQL_KEY, | ||||||
|  |                 database: DSQL_REF_DB_NAME || undefined, | ||||||
|  |             }); | ||||||
|  |             if (!dbSchemaDataResponse.payload || | ||||||
|  |                 !Array.isArray(dbSchemaDataResponse.payload)) { | ||||||
|  |                 console.log("DSQL_KEY => Error in fetching DB schema"); | ||||||
|  |                 console.log(dbSchemaDataResponse); | ||||||
|  |                 process.exit(); | ||||||
|  |             } | ||||||
|  |             let fetchedDbSchemaObject = dbSchemaDataResponse.payload; | ||||||
|  |             // fetchedDbSchemaObject.forEach((db, index) => {
 | ||||||
|  |             //     db.dbFullName = db.dbFullName?.replace(/^datasquirel_user_\d+_/, "");
 | ||||||
|  |             // });
 | ||||||
|  |             schemaData = fetchedDbSchemaObject; | ||||||
|  |         } | ||||||
|  |         else if (fs_1.default.existsSync(dbSchemaLocalFilePath)) { | ||||||
|  |             schemaData = [ | ||||||
|  |                 JSON.parse(fs_1.default.readFileSync(dbSchemaLocalFilePath, "utf8")), | ||||||
|  |             ]; | ||||||
|  |         } | ||||||
|  |         else { | ||||||
|  |             console.log("No source for DB Schema. Please provide a local `dsql.schema.json` file, or provide `DSQL_KEY` and `DSQL_REF_DB_NAME` environment variables."); | ||||||
|  |             process.exit(); | ||||||
|  |         } | ||||||
|  |         if (!schemaData) { | ||||||
|  |             console.log("No schema found"); | ||||||
|  |             process.exit(); | ||||||
|  |         } | ||||||
|  |         if (DSQL_FULL_SYNC === null || DSQL_FULL_SYNC === void 0 ? void 0 : DSQL_FULL_SYNC.match(/true/i)) { | ||||||
|  |             fs_1.default.writeFileSync(dbSchemaLocalFilePath, JSON.stringify(schemaData[0], null, 4), "utf8"); | ||||||
|  |         } | ||||||
|  |         console.log(` - ${console_colors_1.default.FgBlue}Info:${console_colors_1.default.Reset} Now generating and mapping databases ...`); | ||||||
|  |         yield (0, createDbFromSchema_1.default)({ | ||||||
|  |             dbSchemaData: schemaData, | ||||||
|  |         }); | ||||||
|  |         console.log(` - ${console_colors_1.default.FgGreen}Success:${console_colors_1.default.Reset} Databases created Successfully!`); | ||||||
|  |     }); | ||||||
|  | } | ||||||
|  | let interval; | ||||||
|  | if (fs_1.default.existsSync(dbSchemaLocalFilePath) && !(DSQL_KEY === null || DSQL_KEY === void 0 ? void 0 : DSQL_KEY.match(/....../))) { | ||||||
|  |     fs_1.default.watchFile(dbSchemaLocalFilePath, { interval: 1000 }, (curr, prev) => { | ||||||
|  |         console.log(` - ${console_colors_1.default.FgBlue}Info:${console_colors_1.default.Reset} Syncing Databases Locally ...`); | ||||||
|  |         run(); | ||||||
|  |     }); | ||||||
|  | } | ||||||
|  | else if (DSQL_KEY === null || DSQL_KEY === void 0 ? void 0 : DSQL_KEY.match(/....../)) { | ||||||
|  |     interval = setInterval(() => { | ||||||
|  |         console.log(` - ${console_colors_1.default.FgMagenta}Info:${console_colors_1.default.Reset} Syncing Databases from the cloud ...`); | ||||||
|  |         run(); | ||||||
|  |     }, 20000); | ||||||
|  | } | ||||||
|  | run(); | ||||||
							
								
								
									
										2
									
								
								dist/engine/dump.d.ts
									
									
									
									
										vendored
									
									
										Normal file
									
								
							
							
						
						
									
										2
									
								
								dist/engine/dump.d.ts
									
									
									
									
										vendored
									
									
										Normal file
									
								
							| @ -0,0 +1,2 @@ | |||||||
|  | #! /usr/bin/env node | ||||||
|  | export {}; | ||||||
							
								
								
									
										50
									
								
								dist/engine/dump.js
									
									
									
									
										vendored
									
									
										Normal file
									
								
							
							
						
						
									
										50
									
								
								dist/engine/dump.js
									
									
									
									
										vendored
									
									
										Normal file
									
								
							| @ -0,0 +1,50 @@ | |||||||
|  | #! /usr/bin/env node
 | ||||||
|  | "use strict"; | ||||||
|  | var __importDefault = (this && this.__importDefault) || function (mod) { | ||||||
|  |     return (mod && mod.__esModule) ? mod : { "default": mod }; | ||||||
|  | }; | ||||||
|  | var _a, _b; | ||||||
|  | Object.defineProperty(exports, "__esModule", { value: true }); | ||||||
|  | const path_1 = __importDefault(require("path")); | ||||||
|  | const child_process_1 = require("child_process"); | ||||||
|  | require("dotenv").config({ | ||||||
|  |     path: path_1.default.resolve(process.cwd(), ".env"), | ||||||
|  | }); | ||||||
|  | const mysqlPath = ((_a = process.platform) === null || _a === void 0 ? void 0 : _a.match(/win/i)) | ||||||
|  |     ? "'" + "C:\\Program Files\\MySQL\\MySQL Server 8.0\\bin\\mysql.exe" + "'" | ||||||
|  |     : "mysql"; | ||||||
|  | const mysqlDumpPath = ((_b = process.platform) === null || _b === void 0 ? void 0 : _b.match(/win/i)) | ||||||
|  |     ? "'" + | ||||||
|  |         "C:\\Program Files\\MySQL\\MySQL Server 8.0\\bin\\mysqldump.exe" + | ||||||
|  |         "'" | ||||||
|  |     : "mysqldump"; | ||||||
|  | const { DSQL_USER, DSQL_PASS, DSQL_DB_NAME } = process.env; | ||||||
|  | const dbName = DSQL_DB_NAME || ""; | ||||||
|  | const dumpFilePathArg = process.argv.indexOf("--file"); | ||||||
|  | if (dumpFilePathArg < 0) { | ||||||
|  |     console.log("Please provide a dump file path using `--file` argument"); | ||||||
|  |     process.exit(); | ||||||
|  | } | ||||||
|  | const dumpFilePath = process.argv[dumpFilePathArg + 1]; | ||||||
|  | if (!(dbName === null || dbName === void 0 ? void 0 : dbName.match(/./))) { | ||||||
|  |     console.log("DSQL_DB_NAME is required in your `.env` file"); | ||||||
|  |     process.exit(); | ||||||
|  | } | ||||||
|  | if (!(DSQL_USER === null || DSQL_USER === void 0 ? void 0 : DSQL_USER.match(/./)) || !(DSQL_PASS === null || DSQL_PASS === void 0 ? void 0 : DSQL_PASS.match(/./))) { | ||||||
|  |     console.log("DSQL_USER and DSQL_PASS are required in your `.env` file"); | ||||||
|  |     process.exit(); | ||||||
|  | } | ||||||
|  | try { | ||||||
|  |     let execSyncOptions = { | ||||||
|  |         cwd: process.cwd(), | ||||||
|  |     }; | ||||||
|  |     // if (process.platform.match(/win/i)) execSyncOptions.shell = "bash.exe";
 | ||||||
|  |     const dump = (0, child_process_1.execSync)(`${mysqlPath} -u ${DSQL_USER} -p${DSQL_PASS} ${dbName} < ${dumpFilePath}`, execSyncOptions); | ||||||
|  |     console.log("Dumped successfully", dump.toString()); | ||||||
|  |     ////////////////////////////////////////
 | ||||||
|  |     ////////////////////////////////////////
 | ||||||
|  |     ////////////////////////////////////////
 | ||||||
|  | } | ||||||
|  | catch (error) { | ||||||
|  |     console.log("Dump Error: ", error.message); | ||||||
|  | } | ||||||
							
								
								
									
										108
									
								
								dist/index.d.ts
									
									
									
									
										vendored
									
									
										Normal file
									
								
							
							
						
						
									
										108
									
								
								dist/index.d.ts
									
									
									
									
										vendored
									
									
										Normal file
									
								
							| @ -0,0 +1,108 @@ | |||||||
|  | /** | ||||||
|  |  * Imports | ||||||
|  |  */ | ||||||
|  | import get from "./utils/get"; | ||||||
|  | import post from "./utils/post"; | ||||||
|  | import getSchema from "./utils/get-schema"; | ||||||
|  | import uploadImage from "./utils/upload-image"; | ||||||
|  | import uploadFile from "./utils/upload-file"; | ||||||
|  | import deleteFile from "./utils/delete-file"; | ||||||
|  | import createUser from "./users/add-user"; | ||||||
|  | import updateUser from "./users/update-user"; | ||||||
|  | import loginUser from "./users/login-user"; | ||||||
|  | import sendEmailCode from "./users/send-email-code"; | ||||||
|  | import logoutUser from "./users/logout-user"; | ||||||
|  | import userAuth from "./users/user-auth"; | ||||||
|  | import reAuthUser from "./users/reauth-user"; | ||||||
|  | import getUser from "./users/get-user"; | ||||||
|  | import loginWithGoogle from "./users/social/google-auth"; | ||||||
|  | import loginWithGithub from "./users/social/github-auth"; | ||||||
|  | import getToken from "./users/get-token"; | ||||||
|  | import validateToken from "./users/validate-token"; | ||||||
|  | import sqlGenerator from "./package-shared/functions/dsql/sql/sql-generator"; | ||||||
|  | import sqlInsertGenerator from "./package-shared/functions/dsql/sql/sql-insert-generator"; | ||||||
|  | import sqlDeleteGenerator from "./package-shared/functions/dsql/sql/sql-delete-generator"; | ||||||
|  | import trimSql from "./package-shared/utils/trim-sql"; | ||||||
|  | import parseCookies from "./package-shared/utils/backend/parseCookies"; | ||||||
|  | import httpRequest from "./package-shared/functions/backend/httpRequest"; | ||||||
|  | /** | ||||||
|  |  * Main Export | ||||||
|  |  */ | ||||||
|  | declare const datasquirel: { | ||||||
|  |     get: typeof get; | ||||||
|  |     post: typeof post; | ||||||
|  |     media: { | ||||||
|  |         uploadImage: typeof uploadImage; | ||||||
|  |         uploadFile: typeof uploadFile; | ||||||
|  |         deleteFile: typeof deleteFile; | ||||||
|  |     }; | ||||||
|  |     user: { | ||||||
|  |         createUser: typeof createUser; | ||||||
|  |         deleteUser: any; | ||||||
|  |         loginUser: typeof loginUser; | ||||||
|  |         sendEmailCode: typeof sendEmailCode; | ||||||
|  |         logoutUser: typeof logoutUser; | ||||||
|  |         userAuth: typeof userAuth; | ||||||
|  |         reAuthUser: typeof reAuthUser; | ||||||
|  |         updateUser: typeof updateUser; | ||||||
|  |         getUser: typeof getUser; | ||||||
|  |         getToken: typeof getToken; | ||||||
|  |         validateToken: typeof validateToken; | ||||||
|  |         validateTempEmailCode: any; | ||||||
|  |         social: { | ||||||
|  |             loginWithGoogle: typeof loginWithGoogle; | ||||||
|  |             loginWithGithub: typeof loginWithGithub; | ||||||
|  |         }; | ||||||
|  |     }; | ||||||
|  |     getSchema: typeof getSchema; | ||||||
|  |     client: { | ||||||
|  |         media: { | ||||||
|  |             imageInputToBase64: typeof import("./client/media/imageInputToBase64").default; | ||||||
|  |             imageInputFileToBase64: typeof import("./client/media/imageInputFileToBase64").default; | ||||||
|  |             inputFileToBase64: typeof import("./client/media/inputFileToBase64").default; | ||||||
|  |         }; | ||||||
|  |         auth: { | ||||||
|  |             google: { | ||||||
|  |                 getAccessToken: typeof import("./client/auth/google/getAccessToken").default; | ||||||
|  |             }; | ||||||
|  |             github: { | ||||||
|  |                 getAccessToken: typeof import("./client/auth/github/getAccessToken").default; | ||||||
|  |             }; | ||||||
|  |             logout: typeof import("./client/auth/logout").default; | ||||||
|  |         }; | ||||||
|  |         fetch: { | ||||||
|  |             fetchApi: typeof import("./client/fetch").default; | ||||||
|  |             clientFetch: typeof import("./client/fetch").default; | ||||||
|  |         }; | ||||||
|  |         utils: { | ||||||
|  |             serializeQuery: typeof import("./package-shared/utils/serialize-query").default; | ||||||
|  |             serializeCookies: typeof import("./package-shared/utils/serialize-cookies").default; | ||||||
|  |             EJSON: { | ||||||
|  |                 parse: (string: string | null | number, reviver?: (this: any, key: string, value: any) => any) => { | ||||||
|  |                     [s: string]: any; | ||||||
|  |                 } | { | ||||||
|  |                     [s: string]: any; | ||||||
|  |                 }[] | undefined; | ||||||
|  |                 stringify: (value: any, replacer?: (this: any, key: string, value: any) => any, space?: string | number) => string | undefined; | ||||||
|  |             }; | ||||||
|  |             numberfy: typeof import("./package-shared/utils/numberfy").default; | ||||||
|  |             slugify: typeof import("./package-shared/utils/slugify").default; | ||||||
|  |         }; | ||||||
|  |     }; | ||||||
|  |     sql: { | ||||||
|  |         sqlGenerator: typeof sqlGenerator; | ||||||
|  |         sqlInsertGenerator: typeof sqlInsertGenerator; | ||||||
|  |         sqlDeleteGenerator: typeof sqlDeleteGenerator; | ||||||
|  |         trim: typeof trimSql; | ||||||
|  |     }; | ||||||
|  |     utils: { | ||||||
|  |         crypto: { | ||||||
|  |             encrypt: any; | ||||||
|  |             decrypt: any; | ||||||
|  |             hash: any; | ||||||
|  |         }; | ||||||
|  |         parseCookies: typeof parseCookies; | ||||||
|  |         httpRequest: typeof httpRequest; | ||||||
|  |     }; | ||||||
|  | }; | ||||||
|  | export default datasquirel; | ||||||
							
								
								
									
										42629
									
								
								dist/index.js
									
									
									
									
										vendored
									
									
								
							
							
						
						
									
										42629
									
								
								dist/index.js
									
									
									
									
										vendored
									
									
								
							
										
											
												File diff suppressed because one or more lines are too long
											
										
									
								
							
							
								
								
									
										13
									
								
								dist/package-shared/functions/api/query/get.d.ts
									
									
									
									
										vendored
									
									
										Normal file
									
								
							
							
						
						
									
										13
									
								
								dist/package-shared/functions/api/query/get.d.ts
									
									
									
									
										vendored
									
									
										Normal file
									
								
							| @ -0,0 +1,13 @@ | |||||||
|  | type Param = { | ||||||
|  |     query: string; | ||||||
|  |     queryValues?: (string | number)[]; | ||||||
|  |     dbFullName: string; | ||||||
|  |     tableName?: string; | ||||||
|  |     dbSchema?: import("../../../types").DSQL_DatabaseSchemaType; | ||||||
|  |     useLocal?: boolean; | ||||||
|  | }; | ||||||
|  | /** | ||||||
|  |  * # Get Function FOr API | ||||||
|  |  */ | ||||||
|  | export default function apiGet({ query, dbFullName, queryValues, tableName, dbSchema, useLocal, }: Param): Promise<import("../../../types").GetReturn>; | ||||||
|  | export {}; | ||||||
							
								
								
									
										82
									
								
								dist/package-shared/functions/api/query/get.js
									
									
									
									
										vendored
									
									
										Normal file
									
								
							
							
						
						
									
										82
									
								
								dist/package-shared/functions/api/query/get.js
									
									
									
									
										vendored
									
									
										Normal file
									
								
							| @ -0,0 +1,82 @@ | |||||||
|  | "use strict"; | ||||||
|  | // @ts-check
 | ||||||
|  | var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { | ||||||
|  |     function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } | ||||||
|  |     return new (P || (P = Promise))(function (resolve, reject) { | ||||||
|  |         function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } | ||||||
|  |         function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } | ||||||
|  |         function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } | ||||||
|  |         step((generator = generator.apply(thisArg, _arguments || [])).next()); | ||||||
|  |     }); | ||||||
|  | }; | ||||||
|  | var __importDefault = (this && this.__importDefault) || function (mod) { | ||||||
|  |     return (mod && mod.__esModule) ? mod : { "default": mod }; | ||||||
|  | }; | ||||||
|  | Object.defineProperty(exports, "__esModule", { value: true }); | ||||||
|  | exports.default = apiGet; | ||||||
|  | const lodash_1 = __importDefault(require("lodash")); | ||||||
|  | const serverError_1 = __importDefault(require("../../backend/serverError")); | ||||||
|  | const runQuery_1 = __importDefault(require("../../backend/db/runQuery")); | ||||||
|  | /** | ||||||
|  |  * # Get Function FOr API | ||||||
|  |  */ | ||||||
|  | function apiGet(_a) { | ||||||
|  |     return __awaiter(this, arguments, void 0, function* ({ query, dbFullName, queryValues, tableName, dbSchema, useLocal, }) { | ||||||
|  |         if (typeof query == "string" && | ||||||
|  |             query.match(/^alter|^delete|information_schema|databases|^create/i)) { | ||||||
|  |             return { success: false, msg: "Wrong Input." }; | ||||||
|  |         } | ||||||
|  |         /** | ||||||
|  |          * Create new user folder and file | ||||||
|  |          * | ||||||
|  |          * @description Create new user folder and file | ||||||
|  |          */ | ||||||
|  |         let results; | ||||||
|  |         try { | ||||||
|  |             let { result, error } = yield (0, runQuery_1.default)({ | ||||||
|  |                 dbFullName: dbFullName, | ||||||
|  |                 query: query, | ||||||
|  |                 queryValuesArray: queryValues, | ||||||
|  |                 readOnly: true, | ||||||
|  |                 dbSchema, | ||||||
|  |                 tableName, | ||||||
|  |                 local: useLocal, | ||||||
|  |             }); | ||||||
|  |             /** @type {import("../../../types").DSQL_TableSchemaType | undefined} */ | ||||||
|  |             let tableSchema; | ||||||
|  |             if (dbSchema) { | ||||||
|  |                 const targetTable = dbSchema.tables.find((table) => table.tableName === tableName); | ||||||
|  |                 if (targetTable) { | ||||||
|  |                     const clonedTargetTable = lodash_1.default.cloneDeep(targetTable); | ||||||
|  |                     delete clonedTargetTable.childTable; | ||||||
|  |                     delete clonedTargetTable.childTableDbFullName; | ||||||
|  |                     delete clonedTargetTable.childTableName; | ||||||
|  |                     delete clonedTargetTable.childrenTables; | ||||||
|  |                     delete clonedTargetTable.updateData; | ||||||
|  |                     delete clonedTargetTable.tableNameOld; | ||||||
|  |                     delete clonedTargetTable.indexes; | ||||||
|  |                     tableSchema = clonedTargetTable; | ||||||
|  |                 } | ||||||
|  |             } | ||||||
|  |             if (error) | ||||||
|  |                 throw error; | ||||||
|  |             if (result.error) | ||||||
|  |                 throw new Error(result.error); | ||||||
|  |             results = result; | ||||||
|  |             /** @type {import("../../../types").GetReturn} */ | ||||||
|  |             const resObject = { | ||||||
|  |                 success: true, | ||||||
|  |                 payload: results, | ||||||
|  |                 schema: tableName && tableSchema ? tableSchema : undefined, | ||||||
|  |             }; | ||||||
|  |             return resObject; | ||||||
|  |         } | ||||||
|  |         catch ( /** @type {any} */error) { | ||||||
|  |             (0, serverError_1.default)({ | ||||||
|  |                 component: "/api/query/get/lines-85-94", | ||||||
|  |                 message: error.message, | ||||||
|  |             }); | ||||||
|  |             return { success: false, payload: null, error: error.message }; | ||||||
|  |         } | ||||||
|  |     }); | ||||||
|  | } | ||||||
							
								
								
									
										14
									
								
								dist/package-shared/functions/api/query/post.d.ts
									
									
									
									
										vendored
									
									
										Normal file
									
								
							
							
						
						
									
										14
									
								
								dist/package-shared/functions/api/query/post.d.ts
									
									
									
									
										vendored
									
									
										Normal file
									
								
							| @ -0,0 +1,14 @@ | |||||||
|  | import { DSQL_DatabaseSchemaType, PostReturn } from "../../../types"; | ||||||
|  | type Param = { | ||||||
|  |     query: any; | ||||||
|  |     queryValues?: (string | number)[]; | ||||||
|  |     dbFullName: string; | ||||||
|  |     tableName?: string; | ||||||
|  |     dbSchema?: DSQL_DatabaseSchemaType; | ||||||
|  |     useLocal?: boolean; | ||||||
|  | }; | ||||||
|  | /** | ||||||
|  |  * # Post Function For API | ||||||
|  |  */ | ||||||
|  | export default function apiPost({ query, dbFullName, queryValues, tableName, dbSchema, useLocal, }: Param): Promise<PostReturn>; | ||||||
|  | export {}; | ||||||
							
								
								
									
										86
									
								
								dist/package-shared/functions/api/query/post.js
									
									
									
									
										vendored
									
									
										Normal file
									
								
							
							
						
						
									
										86
									
								
								dist/package-shared/functions/api/query/post.js
									
									
									
									
										vendored
									
									
										Normal file
									
								
							| @ -0,0 +1,86 @@ | |||||||
|  | "use strict"; | ||||||
|  | var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { | ||||||
|  |     function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } | ||||||
|  |     return new (P || (P = Promise))(function (resolve, reject) { | ||||||
|  |         function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } | ||||||
|  |         function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } | ||||||
|  |         function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } | ||||||
|  |         step((generator = generator.apply(thisArg, _arguments || [])).next()); | ||||||
|  |     }); | ||||||
|  | }; | ||||||
|  | var __importDefault = (this && this.__importDefault) || function (mod) { | ||||||
|  |     return (mod && mod.__esModule) ? mod : { "default": mod }; | ||||||
|  | }; | ||||||
|  | Object.defineProperty(exports, "__esModule", { value: true }); | ||||||
|  | exports.default = apiPost; | ||||||
|  | const lodash_1 = __importDefault(require("lodash")); | ||||||
|  | const serverError_1 = __importDefault(require("../../backend/serverError")); | ||||||
|  | const runQuery_1 = __importDefault(require("../../backend/db/runQuery")); | ||||||
|  | /** | ||||||
|  |  * # Post Function For API | ||||||
|  |  */ | ||||||
|  | function apiPost(_a) { | ||||||
|  |     return __awaiter(this, arguments, void 0, function* ({ query, dbFullName, queryValues, tableName, dbSchema, useLocal, }) { | ||||||
|  |         var _b; | ||||||
|  |         if (typeof query === "string" && (query === null || query === void 0 ? void 0 : query.match(/^create |^alter |^drop /i))) { | ||||||
|  |             return { success: false, msg: "Wrong Input" }; | ||||||
|  |         } | ||||||
|  |         if (typeof query === "object" && | ||||||
|  |             ((_b = query === null || query === void 0 ? void 0 : query.action) === null || _b === void 0 ? void 0 : _b.match(/^create |^alter |^drop /i))) { | ||||||
|  |             return { success: false, msg: "Wrong Input" }; | ||||||
|  |         } | ||||||
|  |         /** @type {any} */ | ||||||
|  |         let results; | ||||||
|  |         /** | ||||||
|  |          * Create new user folder and file | ||||||
|  |          * | ||||||
|  |          * @description Create new user folder and file | ||||||
|  |          */ | ||||||
|  |         try { | ||||||
|  |             let { result, error } = yield (0, runQuery_1.default)({ | ||||||
|  |                 dbFullName: dbFullName, | ||||||
|  |                 query: query, | ||||||
|  |                 dbSchema: dbSchema, | ||||||
|  |                 queryValuesArray: queryValues, | ||||||
|  |                 tableName, | ||||||
|  |                 local: useLocal, | ||||||
|  |             }); | ||||||
|  |             results = result; | ||||||
|  |             if (error) | ||||||
|  |                 throw error; | ||||||
|  |             /** @type {import("../../../types").DSQL_TableSchemaType | undefined} */ | ||||||
|  |             let tableSchema; | ||||||
|  |             if (dbSchema) { | ||||||
|  |                 const targetTable = dbSchema.tables.find((table) => table.tableName === tableName); | ||||||
|  |                 if (targetTable) { | ||||||
|  |                     const clonedTargetTable = lodash_1.default.cloneDeep(targetTable); | ||||||
|  |                     delete clonedTargetTable.childTable; | ||||||
|  |                     delete clonedTargetTable.childTableDbFullName; | ||||||
|  |                     delete clonedTargetTable.childTableName; | ||||||
|  |                     delete clonedTargetTable.childrenTables; | ||||||
|  |                     delete clonedTargetTable.updateData; | ||||||
|  |                     delete clonedTargetTable.tableNameOld; | ||||||
|  |                     delete clonedTargetTable.indexes; | ||||||
|  |                     tableSchema = clonedTargetTable; | ||||||
|  |                 } | ||||||
|  |             } | ||||||
|  |             return { | ||||||
|  |                 success: true, | ||||||
|  |                 payload: results, | ||||||
|  |                 error: error, | ||||||
|  |                 schema: tableName && tableSchema ? tableSchema : undefined, | ||||||
|  |             }; | ||||||
|  |         } | ||||||
|  |         catch (error) { | ||||||
|  |             (0, serverError_1.default)({ | ||||||
|  |                 component: "/api/query/post/lines-132-142", | ||||||
|  |                 message: error.message, | ||||||
|  |             }); | ||||||
|  |             return { | ||||||
|  |                 success: false, | ||||||
|  |                 payload: results, | ||||||
|  |                 error: error.message, | ||||||
|  |             }; | ||||||
|  |         } | ||||||
|  |     }); | ||||||
|  | } | ||||||
							
								
								
									
										8
									
								
								dist/package-shared/functions/api/social-login/facebookLogin.d.ts
									
									
									
									
										vendored
									
									
										Normal file
									
								
							
							
						
						
									
										8
									
								
								dist/package-shared/functions/api/social-login/facebookLogin.d.ts
									
									
									
									
										vendored
									
									
										Normal file
									
								
							| @ -0,0 +1,8 @@ | |||||||
|  | import { UserType } from "../../../types"; | ||||||
|  | /** | ||||||
|  |  * # Facebook Login | ||||||
|  |  */ | ||||||
|  | export default function facebookLogin({ usertype, body, }: { | ||||||
|  |     body: any; | ||||||
|  |     usertype: UserType; | ||||||
|  | }): Promise<any>; | ||||||
							
								
								
									
										78
									
								
								dist/package-shared/functions/api/social-login/facebookLogin.js
									
									
									
									
										vendored
									
									
										Normal file
									
								
							
							
						
						
									
										78
									
								
								dist/package-shared/functions/api/social-login/facebookLogin.js
									
									
									
									
										vendored
									
									
										Normal file
									
								
							| @ -0,0 +1,78 @@ | |||||||
|  | "use strict"; | ||||||
|  | var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { | ||||||
|  |     function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } | ||||||
|  |     return new (P || (P = Promise))(function (resolve, reject) { | ||||||
|  |         function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } | ||||||
|  |         function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } | ||||||
|  |         function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } | ||||||
|  |         step((generator = generator.apply(thisArg, _arguments || [])).next()); | ||||||
|  |     }); | ||||||
|  | }; | ||||||
|  | var __importDefault = (this && this.__importDefault) || function (mod) { | ||||||
|  |     return (mod && mod.__esModule) ? mod : { "default": mod }; | ||||||
|  | }; | ||||||
|  | Object.defineProperty(exports, "__esModule", { value: true }); | ||||||
|  | exports.default = facebookLogin; | ||||||
|  | const DB_HANDLER_1 = __importDefault(require("../../../utils/backend/global-db/DB_HANDLER")); | ||||||
|  | const serverError_1 = __importDefault(require("../../backend/serverError")); | ||||||
|  | const hashPassword_1 = __importDefault(require("../../dsql/hashPassword")); | ||||||
|  | /** | ||||||
|  |  * # Facebook Login | ||||||
|  |  */ | ||||||
|  | function facebookLogin(_a) { | ||||||
|  |     return __awaiter(this, arguments, void 0, function* ({ usertype, body, }) { | ||||||
|  |         try { | ||||||
|  |             const foundUser = yield (0, DB_HANDLER_1.default)(`SELECT * FROM users WHERE email='${body.facebookUserEmail}' AND social_login='1'`); | ||||||
|  |             if (foundUser && foundUser[0]) { | ||||||
|  |                 return foundUser[0]; | ||||||
|  |             } | ||||||
|  |             let socialHashedPassword = (0, hashPassword_1.default)({ | ||||||
|  |                 password: body.facebookUserId, | ||||||
|  |             }); | ||||||
|  |             let newUser = yield (0, DB_HANDLER_1.default)(`INSERT INTO ${usertype} (
 | ||||||
|  |             first_name, | ||||||
|  |             last_name, | ||||||
|  |             social_platform, | ||||||
|  |             social_name, | ||||||
|  |             email, | ||||||
|  |             image, | ||||||
|  |             image_thumbnail, | ||||||
|  |             password, | ||||||
|  |             verification_status, | ||||||
|  |             social_login, | ||||||
|  |             social_id, | ||||||
|  |             terms_agreement, | ||||||
|  |             date_created, | ||||||
|  |             date_code | ||||||
|  |             ) VALUES ( | ||||||
|  |                 '${body.facebookUserFirstName}', | ||||||
|  |                 '${body.facebookUserLastName}', | ||||||
|  |                 'facebook', | ||||||
|  |                 'facebook_${body.facebookUserEmail | ||||||
|  |                 ? body.facebookUserEmail.replace(/@.*/, "") | ||||||
|  |                 : body.facebookUserFirstName.toLowerCase()}', | ||||||
|  |                 '${body.facebookUserEmail}', | ||||||
|  |                 '${body.facebookUserImage}', | ||||||
|  |                 '${body.facebookUserImage}', | ||||||
|  |                 '${socialHashedPassword}', | ||||||
|  |                 '1', | ||||||
|  |                 '1', | ||||||
|  |                 '${body.facebookUserId}', | ||||||
|  |                 '1', | ||||||
|  |                 '${Date()}', | ||||||
|  |                 '${Date.now()}' | ||||||
|  |                 )`);
 | ||||||
|  |             const newFoundUser = yield (0, DB_HANDLER_1.default)(`SELECT * FROM ${usertype} WHERE id='${newUser.insertId}'`); | ||||||
|  |         } | ||||||
|  |         catch ( /** @type {any} */error) { | ||||||
|  |             (0, serverError_1.default)({ | ||||||
|  |                 component: "functions/backend/facebookLogin", | ||||||
|  |                 message: error.message, | ||||||
|  |             }); | ||||||
|  |         } | ||||||
|  |         return { | ||||||
|  |             isFacebookAuthValid: false, | ||||||
|  |             newFoundUser: null, | ||||||
|  |         }; | ||||||
|  |     }); | ||||||
|  | } | ||||||
							
								
								
									
										43
									
								
								dist/package-shared/functions/api/social-login/githubLogin.d.ts
									
									
									
									
										vendored
									
									
										Normal file
									
								
							
							
						
						
									
										43
									
								
								dist/package-shared/functions/api/social-login/githubLogin.d.ts
									
									
									
									
										vendored
									
									
										Normal file
									
								
							| @ -0,0 +1,43 @@ | |||||||
|  | export interface GithubUserPayload { | ||||||
|  |     login: string; | ||||||
|  |     id: number; | ||||||
|  |     node_id: string; | ||||||
|  |     avatar_url: string; | ||||||
|  |     gravatar_id: string; | ||||||
|  |     url: string; | ||||||
|  |     html_url: string; | ||||||
|  |     followers_url: string; | ||||||
|  |     following_url: string; | ||||||
|  |     gists_url: string; | ||||||
|  |     starred_url: string; | ||||||
|  |     subscriptions_url: string; | ||||||
|  |     organizations_url: string; | ||||||
|  |     repos_url: string; | ||||||
|  |     received_events_url: string; | ||||||
|  |     type: string; | ||||||
|  |     site_admin: boolean; | ||||||
|  |     name: string; | ||||||
|  |     company: string; | ||||||
|  |     blog: string; | ||||||
|  |     location: string; | ||||||
|  |     email: string; | ||||||
|  |     hireable: string; | ||||||
|  |     bio: string; | ||||||
|  |     twitter_username: string; | ||||||
|  |     public_repos: number; | ||||||
|  |     public_gists: number; | ||||||
|  |     followers: number; | ||||||
|  |     following: number; | ||||||
|  |     created_at: string; | ||||||
|  |     updated_at: string; | ||||||
|  | } | ||||||
|  | type Param = { | ||||||
|  |     code: string; | ||||||
|  |     clientId: string; | ||||||
|  |     clientSecret: string; | ||||||
|  | }; | ||||||
|  | /** | ||||||
|  |  * # Login/signup a github user | ||||||
|  |  */ | ||||||
|  | export default function githubLogin({ code, clientId, clientSecret, }: Param): Promise<GithubUserPayload | null | undefined>; | ||||||
|  | export {}; | ||||||
							
								
								
									
										62
									
								
								dist/package-shared/functions/api/social-login/githubLogin.js
									
									
									
									
										vendored
									
									
										Normal file
									
								
							
							
						
						
									
										62
									
								
								dist/package-shared/functions/api/social-login/githubLogin.js
									
									
									
									
										vendored
									
									
										Normal file
									
								
							| @ -0,0 +1,62 @@ | |||||||
|  | "use strict"; | ||||||
|  | var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { | ||||||
|  |     function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } | ||||||
|  |     return new (P || (P = Promise))(function (resolve, reject) { | ||||||
|  |         function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } | ||||||
|  |         function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } | ||||||
|  |         function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } | ||||||
|  |         step((generator = generator.apply(thisArg, _arguments || [])).next()); | ||||||
|  |     }); | ||||||
|  | }; | ||||||
|  | var __importDefault = (this && this.__importDefault) || function (mod) { | ||||||
|  |     return (mod && mod.__esModule) ? mod : { "default": mod }; | ||||||
|  | }; | ||||||
|  | Object.defineProperty(exports, "__esModule", { value: true }); | ||||||
|  | exports.default = githubLogin; | ||||||
|  | const DB_HANDLER_1 = __importDefault(require("../../../utils/backend/global-db/DB_HANDLER")); | ||||||
|  | const httpsRequest_1 = __importDefault(require("../../backend/httpsRequest")); | ||||||
|  | /** | ||||||
|  |  * # Login/signup a github user | ||||||
|  |  */ | ||||||
|  | function githubLogin(_a) { | ||||||
|  |     return __awaiter(this, arguments, void 0, function* ({ code, clientId, clientSecret, }) { | ||||||
|  |         let gitHubUser; | ||||||
|  |         try { | ||||||
|  |             const response = yield (0, httpsRequest_1.default)({ | ||||||
|  |                 method: "POST", | ||||||
|  |                 hostname: "github.com", | ||||||
|  |                 path: `/login/oauth/access_token?client_id=${clientId}&client_secret=${clientSecret}&code=${code}`, | ||||||
|  |                 headers: { | ||||||
|  |                     Accept: "application/json", | ||||||
|  |                     "User-Agent": "*", | ||||||
|  |                 }, | ||||||
|  |                 scheme: "https", | ||||||
|  |             }); | ||||||
|  |             const accessTokenObject = JSON.parse(response); | ||||||
|  |             if (!(accessTokenObject === null || accessTokenObject === void 0 ? void 0 : accessTokenObject.access_token)) { | ||||||
|  |                 return gitHubUser; | ||||||
|  |             } | ||||||
|  |             const userDataResponse = yield (0, httpsRequest_1.default)({ | ||||||
|  |                 method: "GET", | ||||||
|  |                 hostname: "api.github.com", | ||||||
|  |                 path: "/user", | ||||||
|  |                 headers: { | ||||||
|  |                     Authorization: `Bearer ${accessTokenObject.access_token}`, | ||||||
|  |                     "User-Agent": "*", | ||||||
|  |                 }, | ||||||
|  |                 scheme: "https", | ||||||
|  |             }); | ||||||
|  |             gitHubUser = JSON.parse(userDataResponse); | ||||||
|  |             if (!(gitHubUser === null || gitHubUser === void 0 ? void 0 : gitHubUser.email) && gitHubUser) { | ||||||
|  |                 const existingGithubUser = yield (0, DB_HANDLER_1.default)(`SELECT email FROM users WHERE social_login='1' AND social_platform='github' AND social_id='${gitHubUser.id}'`); | ||||||
|  |                 if (existingGithubUser && existingGithubUser[0]) { | ||||||
|  |                     gitHubUser.email = existingGithubUser[0].email; | ||||||
|  |                 } | ||||||
|  |             } | ||||||
|  |         } | ||||||
|  |         catch ( /** @type {any} */error) { | ||||||
|  |             console.log("ERROR in githubLogin.js backend function =>", error.message); | ||||||
|  |         } | ||||||
|  |         return gitHubUser; | ||||||
|  |     }); | ||||||
|  | } | ||||||
							
								
								
									
										22
									
								
								dist/package-shared/functions/api/social-login/googleLogin.d.ts
									
									
									
									
										vendored
									
									
										Normal file
									
								
							
							
						
						
									
										22
									
								
								dist/package-shared/functions/api/social-login/googleLogin.d.ts
									
									
									
									
										vendored
									
									
										Normal file
									
								
							| @ -0,0 +1,22 @@ | |||||||
|  | type Param = { | ||||||
|  |     usertype: string; | ||||||
|  |     foundUser: any; | ||||||
|  |     isSocialValidated: boolean; | ||||||
|  |     isUserValid: boolean; | ||||||
|  |     reqBody: any; | ||||||
|  |     serverRes: any; | ||||||
|  |     loginFailureReason: any; | ||||||
|  | }; | ||||||
|  | /** | ||||||
|  |  * # Google Login | ||||||
|  |  */ | ||||||
|  | export default function googleLogin({ usertype, foundUser, isSocialValidated, isUserValid, reqBody, serverRes, loginFailureReason, }: Param): Promise<{ | ||||||
|  |     isGoogleAuthValid: boolean; | ||||||
|  |     newFoundUser: null; | ||||||
|  |     loginFailureReason: any; | ||||||
|  | } | { | ||||||
|  |     isGoogleAuthValid: boolean; | ||||||
|  |     newFoundUser: any; | ||||||
|  |     loginFailureReason?: undefined; | ||||||
|  | } | undefined>; | ||||||
|  | export {}; | ||||||
							
								
								
									
										123
									
								
								dist/package-shared/functions/api/social-login/googleLogin.js
									
									
									
									
										vendored
									
									
										Normal file
									
								
							
							
						
						
									
										123
									
								
								dist/package-shared/functions/api/social-login/googleLogin.js
									
									
									
									
										vendored
									
									
										Normal file
									
								
							| @ -0,0 +1,123 @@ | |||||||
|  | "use strict"; | ||||||
|  | var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { | ||||||
|  |     function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } | ||||||
|  |     return new (P || (P = Promise))(function (resolve, reject) { | ||||||
|  |         function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } | ||||||
|  |         function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } | ||||||
|  |         function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } | ||||||
|  |         step((generator = generator.apply(thisArg, _arguments || [])).next()); | ||||||
|  |     }); | ||||||
|  | }; | ||||||
|  | var __importDefault = (this && this.__importDefault) || function (mod) { | ||||||
|  |     return (mod && mod.__esModule) ? mod : { "default": mod }; | ||||||
|  | }; | ||||||
|  | Object.defineProperty(exports, "__esModule", { value: true }); | ||||||
|  | exports.default = googleLogin; | ||||||
|  | const google_auth_library_1 = require("google-auth-library"); | ||||||
|  | const serverError_1 = __importDefault(require("../../backend/serverError")); | ||||||
|  | const DB_HANDLER_1 = __importDefault(require("../../../utils/backend/global-db/DB_HANDLER")); | ||||||
|  | const hashPassword_1 = __importDefault(require("../../dsql/hashPassword")); | ||||||
|  | /** | ||||||
|  |  * # Google Login | ||||||
|  |  */ | ||||||
|  | function googleLogin(_a) { | ||||||
|  |     return __awaiter(this, arguments, void 0, function* ({ usertype, foundUser, isSocialValidated, isUserValid, reqBody, serverRes, loginFailureReason, }) { | ||||||
|  |         var _b; | ||||||
|  |         const client = new google_auth_library_1.OAuth2Client(process.env.NEXT_PUBLIC_DSQL_GOOGLE_CLIENT_ID); | ||||||
|  |         let isGoogleAuthValid = false; | ||||||
|  |         let newFoundUser = null; | ||||||
|  |         ////////////////////////////////////////////////
 | ||||||
|  |         ////////////////////////////////////////////////
 | ||||||
|  |         ////////////////////////////////////////////////
 | ||||||
|  |         try { | ||||||
|  |             const ticket = yield client.verifyIdToken({ | ||||||
|  |                 idToken: reqBody.token, | ||||||
|  |                 audience: process.env.NEXT_PUBLIC_DSQL_GOOGLE_CLIENT_ID, // Specify the CLIENT_ID of the app that accesses the backend
 | ||||||
|  |                 // Or, if multiple clients access the backend:
 | ||||||
|  |                 //[CLIENT_ID_1, CLIENT_ID_2, CLIENT_ID_3]
 | ||||||
|  |             }); | ||||||
|  |             const payload = ticket.getPayload(); | ||||||
|  |             const userid = payload === null || payload === void 0 ? void 0 : payload["sub"]; | ||||||
|  |             if (!payload) | ||||||
|  |                 throw new Error("Google login failed. Credentials invalid"); | ||||||
|  |             isUserValid = Boolean(payload.email_verified); | ||||||
|  |             if (!isUserValid || !payload || !payload.email_verified) | ||||||
|  |                 return; | ||||||
|  |             serverRes.isUserValid = payload.email_verified; | ||||||
|  |             isSocialValidated = payload.email_verified; | ||||||
|  |             isGoogleAuthValid = payload.email_verified; | ||||||
|  |             ////// If request specified a G Suite domain:
 | ||||||
|  |             ////// const domain = payload['hd'];
 | ||||||
|  |             let socialHashedPassword = (0, hashPassword_1.default)({ | ||||||
|  |                 password: payload.at_hash || "", | ||||||
|  |             }); | ||||||
|  |             ////////////////////////////////////////////////
 | ||||||
|  |             ////////////////////////////////////////////////
 | ||||||
|  |             ////////////////////////////////////////////////
 | ||||||
|  |             let existinEmail = yield (0, DB_HANDLER_1.default)(`SELECT * FROM ${usertype} WHERE email='${payload.email}' AND social_login!='1' AND social_platform!='google'`); | ||||||
|  |             if (existinEmail && existinEmail[0]) { | ||||||
|  |                 loginFailureReason = "Email Exists Already"; | ||||||
|  |                 isGoogleAuthValid = false; | ||||||
|  |                 return { | ||||||
|  |                     isGoogleAuthValid: isGoogleAuthValid, | ||||||
|  |                     newFoundUser: newFoundUser, | ||||||
|  |                     loginFailureReason: loginFailureReason, | ||||||
|  |                 }; | ||||||
|  |             } | ||||||
|  |             ////////////////////////////////////////
 | ||||||
|  |             foundUser = yield (0, DB_HANDLER_1.default)(`SELECT * FROM ${usertype} WHERE email='${payload.email}' AND social_login='1' AND social_platform='google'`); | ||||||
|  |             if (foundUser && foundUser[0]) { | ||||||
|  |                 newFoundUser = foundUser; | ||||||
|  |                 return { | ||||||
|  |                     isGoogleAuthValid: isGoogleAuthValid, | ||||||
|  |                     newFoundUser: newFoundUser, | ||||||
|  |                 }; | ||||||
|  |             } | ||||||
|  |             ////////////////////////////////////////////////
 | ||||||
|  |             ////////////////////////////////////////////////
 | ||||||
|  |             ////////////////////////////////////////////////
 | ||||||
|  |             let newUser = yield (0, DB_HANDLER_1.default)(`INSERT INTO ${usertype} (
 | ||||||
|  |             first_name, | ||||||
|  |             last_name, | ||||||
|  |             social_platform, | ||||||
|  |             social_name, | ||||||
|  |             social_id, | ||||||
|  |             email, | ||||||
|  |             image, | ||||||
|  |             image_thumbnail, | ||||||
|  |             password, | ||||||
|  |             verification_status, | ||||||
|  |             social_login, | ||||||
|  |             terms_agreement, | ||||||
|  |             date_created, | ||||||
|  |             date_code | ||||||
|  |         ) VALUES ( | ||||||
|  |             '${payload.given_name}', | ||||||
|  |             '${payload.family_name}', | ||||||
|  |             'google', | ||||||
|  |             'google_${(_b = payload.email) === null || _b === void 0 ? void 0 : _b.replace(/@.*/, "")}', | ||||||
|  |             '${payload.sub}', | ||||||
|  |             '${payload.email}', | ||||||
|  |             '${payload.picture}', | ||||||
|  |             '${payload.picture}', | ||||||
|  |             '${socialHashedPassword}', | ||||||
|  |             '1', | ||||||
|  |             '1', | ||||||
|  |             '1', | ||||||
|  |             '${Date()}', | ||||||
|  |             '${Date.now()}' | ||||||
|  |         )`);
 | ||||||
|  |             newFoundUser = yield (0, DB_HANDLER_1.default)(`SELECT * FROM ${usertype} WHERE id='${newUser.insertId}'`); | ||||||
|  |         } | ||||||
|  |         catch (error) { | ||||||
|  |             (0, serverError_1.default)({ | ||||||
|  |                 component: "googleLogin", | ||||||
|  |                 message: error.message, | ||||||
|  |             }); | ||||||
|  |             loginFailureReason = error; | ||||||
|  |             isUserValid = false; | ||||||
|  |             isSocialValidated = false; | ||||||
|  |         } | ||||||
|  |         return { isGoogleAuthValid: isGoogleAuthValid, newFoundUser: newFoundUser }; | ||||||
|  |     }); | ||||||
|  | } | ||||||
							
								
								
									
										5
									
								
								dist/package-shared/functions/api/social-login/handleSocialDb.d.ts
									
									
									
									
										vendored
									
									
										Normal file
									
								
							
							
						
						
									
										5
									
								
								dist/package-shared/functions/api/social-login/handleSocialDb.d.ts
									
									
									
									
										vendored
									
									
										Normal file
									
								
							| @ -0,0 +1,5 @@ | |||||||
|  | import { APILoginFunctionReturn, HandleSocialDbFunctionParams } from "../../../types"; | ||||||
|  | /** | ||||||
|  |  * # Handle Social DB | ||||||
|  |  */ | ||||||
|  | export default function handleSocialDb({ database, social_id, email, social_platform, payload, invitation, supEmail, additionalFields, useLocal, }: HandleSocialDbFunctionParams): Promise<APILoginFunctionReturn>; | ||||||
							
								
								
									
										202
									
								
								dist/package-shared/functions/api/social-login/handleSocialDb.js
									
									
									
									
										vendored
									
									
										Normal file
									
								
							
							
						
						
									
										202
									
								
								dist/package-shared/functions/api/social-login/handleSocialDb.js
									
									
									
									
										vendored
									
									
										Normal file
									
								
							| @ -0,0 +1,202 @@ | |||||||
|  | "use strict"; | ||||||
|  | var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { | ||||||
|  |     function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } | ||||||
|  |     return new (P || (P = Promise))(function (resolve, reject) { | ||||||
|  |         function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } | ||||||
|  |         function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } | ||||||
|  |         function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } | ||||||
|  |         step((generator = generator.apply(thisArg, _arguments || [])).next()); | ||||||
|  |     }); | ||||||
|  | }; | ||||||
|  | var __importDefault = (this && this.__importDefault) || function (mod) { | ||||||
|  |     return (mod && mod.__esModule) ? mod : { "default": mod }; | ||||||
|  | }; | ||||||
|  | Object.defineProperty(exports, "__esModule", { value: true }); | ||||||
|  | exports.default = handleSocialDb; | ||||||
|  | const fs_1 = __importDefault(require("fs")); | ||||||
|  | const handleNodemailer_1 = __importDefault(require("../../backend/handleNodemailer")); | ||||||
|  | const path_1 = __importDefault(require("path")); | ||||||
|  | const addMariadbUser_1 = __importDefault(require("../../backend/addMariadbUser")); | ||||||
|  | const varDatabaseDbHandler_1 = __importDefault(require("../../backend/varDatabaseDbHandler")); | ||||||
|  | const encrypt_1 = __importDefault(require("../../dsql/encrypt")); | ||||||
|  | const addDbEntry_1 = __importDefault(require("../../backend/db/addDbEntry")); | ||||||
|  | const loginSocialUser_1 = __importDefault(require("./loginSocialUser")); | ||||||
|  | /** | ||||||
|  |  * # Handle Social DB | ||||||
|  |  */ | ||||||
|  | function handleSocialDb(_a) { | ||||||
|  |     return __awaiter(this, arguments, void 0, function* ({ database, social_id, email, social_platform, payload, invitation, supEmail, additionalFields, useLocal, }) { | ||||||
|  |         try { | ||||||
|  |             const existingSocialIdUserQuery = `SELECT * FROM users WHERE social_id = ? AND social_login='1' AND social_platform = ? `; | ||||||
|  |             const existingSocialIdUserValues = [ | ||||||
|  |                 social_id.toString(), | ||||||
|  |                 social_platform, | ||||||
|  |             ]; | ||||||
|  |             let existingSocialIdUser = yield (0, varDatabaseDbHandler_1.default)({ | ||||||
|  |                 database: database ? database : "datasquirel", | ||||||
|  |                 queryString: existingSocialIdUserQuery, | ||||||
|  |                 queryValuesArray: existingSocialIdUserValues, | ||||||
|  |                 useLocal, | ||||||
|  |             }); | ||||||
|  |             if (existingSocialIdUser && existingSocialIdUser[0]) { | ||||||
|  |                 return yield (0, loginSocialUser_1.default)({ | ||||||
|  |                     user: existingSocialIdUser[0], | ||||||
|  |                     social_platform, | ||||||
|  |                     invitation, | ||||||
|  |                     database, | ||||||
|  |                     additionalFields, | ||||||
|  |                     useLocal, | ||||||
|  |                 }); | ||||||
|  |             } | ||||||
|  |             const finalEmail = email ? email : supEmail ? supEmail : null; | ||||||
|  |             if (!finalEmail) { | ||||||
|  |                 return { | ||||||
|  |                     success: false, | ||||||
|  |                     payload: null, | ||||||
|  |                     msg: "No Email Present", | ||||||
|  |                 }; | ||||||
|  |             } | ||||||
|  |             const existingEmailOnlyQuery = `SELECT * FROM users WHERE email='${finalEmail}'`; | ||||||
|  |             let existingEmailOnly = yield (0, varDatabaseDbHandler_1.default)({ | ||||||
|  |                 database: database ? database : "datasquirel", | ||||||
|  |                 queryString: existingEmailOnlyQuery, | ||||||
|  |                 useLocal, | ||||||
|  |             }); | ||||||
|  |             if (existingEmailOnly && existingEmailOnly[0]) { | ||||||
|  |                 return { | ||||||
|  |                     success: false, | ||||||
|  |                     payload: null, | ||||||
|  |                     msg: "This Email is already taken", | ||||||
|  |                 }; | ||||||
|  |             } | ||||||
|  |             const foundUserQuery = `SELECT * FROM users WHERE email=? AND social_login='1' AND social_platform=? AND social_id=?`; | ||||||
|  |             const foundUserQueryValues = [finalEmail, social_platform, social_id]; | ||||||
|  |             const foundUser = yield (0, varDatabaseDbHandler_1.default)({ | ||||||
|  |                 database: database ? database : "datasquirel", | ||||||
|  |                 queryString: foundUserQuery, | ||||||
|  |                 queryValuesArray: foundUserQueryValues, | ||||||
|  |                 useLocal, | ||||||
|  |             }); | ||||||
|  |             if (foundUser && foundUser[0]) { | ||||||
|  |                 return yield (0, loginSocialUser_1.default)({ | ||||||
|  |                     user: payload, | ||||||
|  |                     social_platform, | ||||||
|  |                     invitation, | ||||||
|  |                     database, | ||||||
|  |                     additionalFields, | ||||||
|  |                     useLocal, | ||||||
|  |                 }); | ||||||
|  |             } | ||||||
|  |             const socialHashedPassword = (0, encrypt_1.default)({ | ||||||
|  |                 data: social_id.toString(), | ||||||
|  |             }); | ||||||
|  |             const data = { | ||||||
|  |                 social_login: "1", | ||||||
|  |                 verification_status: supEmail ? "0" : "1", | ||||||
|  |                 password: socialHashedPassword, | ||||||
|  |             }; | ||||||
|  |             Object.keys(payload).forEach((key) => { | ||||||
|  |                 data[key] = payload[key]; | ||||||
|  |             }); | ||||||
|  |             /** @type {any} */ | ||||||
|  |             const newUser = yield (0, addDbEntry_1.default)({ | ||||||
|  |                 dbContext: database ? "Dsql User" : undefined, | ||||||
|  |                 paradigm: database ? "Full Access" : undefined, | ||||||
|  |                 dbFullName: database ? database : "datasquirel", | ||||||
|  |                 tableName: "users", | ||||||
|  |                 duplicateColumnName: "email", | ||||||
|  |                 duplicateColumnValue: finalEmail, | ||||||
|  |                 data: Object.assign(Object.assign({}, data), { email: finalEmail }), | ||||||
|  |                 useLocal, | ||||||
|  |             }); | ||||||
|  |             if (newUser === null || newUser === void 0 ? void 0 : newUser.insertId) { | ||||||
|  |                 if (!database) { | ||||||
|  |                     /** | ||||||
|  |                      * Add a Mariadb User for this User | ||||||
|  |                      */ | ||||||
|  |                     yield (0, addMariadbUser_1.default)({ userId: newUser.insertId, useLocal }); | ||||||
|  |                 } | ||||||
|  |                 const newUserQueriedQuery = `SELECT * FROM users WHERE id='${newUser.insertId}'`; | ||||||
|  |                 const newUserQueried = yield (0, varDatabaseDbHandler_1.default)({ | ||||||
|  |                     database: database ? database : "datasquirel", | ||||||
|  |                     queryString: newUserQueriedQuery, | ||||||
|  |                     useLocal, | ||||||
|  |                 }); | ||||||
|  |                 if (!newUserQueried || !newUserQueried[0]) | ||||||
|  |                     return { | ||||||
|  |                         success: false, | ||||||
|  |                         payload: null, | ||||||
|  |                         msg: "User Insertion Failed!", | ||||||
|  |                     }; | ||||||
|  |                 if (supEmail && (database === null || database === void 0 ? void 0 : database.match(/^datasquirel$/))) { | ||||||
|  |                     /** | ||||||
|  |                      * Send email Verification | ||||||
|  |                      * | ||||||
|  |                      * @description Send verification email to newly created agent | ||||||
|  |                      */ | ||||||
|  |                     let generatedToken = (0, encrypt_1.default)({ | ||||||
|  |                         data: JSON.stringify({ | ||||||
|  |                             id: newUser.insertId, | ||||||
|  |                             email: supEmail, | ||||||
|  |                             dateCode: Date.now(), | ||||||
|  |                         }), | ||||||
|  |                     }); | ||||||
|  |                     (0, handleNodemailer_1.default)({ | ||||||
|  |                         to: supEmail, | ||||||
|  |                         subject: "Verify Email Address", | ||||||
|  |                         text: "Please click the link to verify your email address", | ||||||
|  |                         html: fs_1.default | ||||||
|  |                             .readFileSync("./email/send-email-verification-link.html", "utf8") | ||||||
|  |                             .replace(/{{host}}/, process.env.DSQL_HOST || "") | ||||||
|  |                             .replace(/{{token}}/, generatedToken || ""), | ||||||
|  |                     }).then(() => { }); | ||||||
|  |                 } | ||||||
|  |                 const STATIC_ROOT = process.env.DSQL_STATIC_SERVER_DIR; | ||||||
|  |                 if (!STATIC_ROOT) { | ||||||
|  |                     console.log("Static File ENV not Found!"); | ||||||
|  |                     return { | ||||||
|  |                         success: false, | ||||||
|  |                         payload: null, | ||||||
|  |                         msg: "Static File ENV not Found!", | ||||||
|  |                     }; | ||||||
|  |                 } | ||||||
|  |                 /** | ||||||
|  |                  * Create new user folder and file | ||||||
|  |                  * | ||||||
|  |                  * @description Create new user folder and file | ||||||
|  |                  */ | ||||||
|  |                 if (!database || (database === null || database === void 0 ? void 0 : database.match(/^datasquirel$/))) { | ||||||
|  |                     let newUserSchemaFolderPath = `${process.env.DSQL_USER_DB_SCHEMA_PATH}/user-${newUser.insertId}`; | ||||||
|  |                     let newUserMediaFolderPath = path_1.default.join(STATIC_ROOT, `images/user-images/user-${newUser.insertId}`); | ||||||
|  |                     fs_1.default.mkdirSync(newUserSchemaFolderPath); | ||||||
|  |                     fs_1.default.mkdirSync(newUserMediaFolderPath); | ||||||
|  |                     fs_1.default.writeFileSync(`${newUserSchemaFolderPath}/main.json`, JSON.stringify([]), "utf8"); | ||||||
|  |                 } | ||||||
|  |                 return yield (0, loginSocialUser_1.default)({ | ||||||
|  |                     user: newUserQueried[0], | ||||||
|  |                     social_platform, | ||||||
|  |                     invitation, | ||||||
|  |                     database, | ||||||
|  |                     additionalFields, | ||||||
|  |                     useLocal, | ||||||
|  |                 }); | ||||||
|  |             } | ||||||
|  |             else { | ||||||
|  |                 console.log("Social User Failed to insert in 'handleSocialDb.js' backend function =>", newUser); | ||||||
|  |                 return { | ||||||
|  |                     success: false, | ||||||
|  |                     payload: null, | ||||||
|  |                     msg: "Social User Failed to insert in 'handleSocialDb.js' backend function", | ||||||
|  |                 }; | ||||||
|  |             } | ||||||
|  |         } | ||||||
|  |         catch (error) { | ||||||
|  |             console.log("ERROR in 'handleSocialDb.js' backend function =>", error.message); | ||||||
|  |             return { | ||||||
|  |                 success: false, | ||||||
|  |                 payload: null, | ||||||
|  |                 msg: error.message, | ||||||
|  |             }; | ||||||
|  |         } | ||||||
|  |     }); | ||||||
|  | } | ||||||
							
								
								
									
										22
									
								
								dist/package-shared/functions/api/social-login/loginSocialUser.d.ts
									
									
									
									
										vendored
									
									
										Normal file
									
								
							
							
						
						
									
										22
									
								
								dist/package-shared/functions/api/social-login/loginSocialUser.d.ts
									
									
									
									
										vendored
									
									
										Normal file
									
								
							| @ -0,0 +1,22 @@ | |||||||
|  | import { APILoginFunctionReturn } from "../../../types"; | ||||||
|  | type Param = { | ||||||
|  |     user: { | ||||||
|  |         first_name: string; | ||||||
|  |         last_name: string; | ||||||
|  |         email: string; | ||||||
|  |         social_id: string | number; | ||||||
|  |     }; | ||||||
|  |     social_platform: string; | ||||||
|  |     invitation?: any; | ||||||
|  |     database?: string; | ||||||
|  |     additionalFields?: string[]; | ||||||
|  |     useLocal?: boolean; | ||||||
|  | }; | ||||||
|  | /** | ||||||
|  |  * Function to login social user | ||||||
|  |  * ============================================================================== | ||||||
|  |  * @description This function logs in the user after 'handleSocialDb' function finishes | ||||||
|  |  * the user creation or confirmation process | ||||||
|  |  */ | ||||||
|  | export default function loginSocialUser({ user, social_platform, invitation, database, additionalFields, useLocal, }: Param): Promise<APILoginFunctionReturn>; | ||||||
|  | export {}; | ||||||
							
								
								
									
										80
									
								
								dist/package-shared/functions/api/social-login/loginSocialUser.js
									
									
									
									
										vendored
									
									
										Normal file
									
								
							
							
						
						
									
										80
									
								
								dist/package-shared/functions/api/social-login/loginSocialUser.js
									
									
									
									
										vendored
									
									
										Normal file
									
								
							| @ -0,0 +1,80 @@ | |||||||
|  | "use strict"; | ||||||
|  | var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { | ||||||
|  |     function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } | ||||||
|  |     return new (P || (P = Promise))(function (resolve, reject) { | ||||||
|  |         function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } | ||||||
|  |         function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } | ||||||
|  |         function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } | ||||||
|  |         step((generator = generator.apply(thisArg, _arguments || [])).next()); | ||||||
|  |     }); | ||||||
|  | }; | ||||||
|  | var __importDefault = (this && this.__importDefault) || function (mod) { | ||||||
|  |     return (mod && mod.__esModule) ? mod : { "default": mod }; | ||||||
|  | }; | ||||||
|  | Object.defineProperty(exports, "__esModule", { value: true }); | ||||||
|  | exports.default = loginSocialUser; | ||||||
|  | const addAdminUserOnLogin_1 = __importDefault(require("../../backend/addAdminUserOnLogin")); | ||||||
|  | const varDatabaseDbHandler_1 = __importDefault(require("../../backend/varDatabaseDbHandler")); | ||||||
|  | /** | ||||||
|  |  * Function to login social user | ||||||
|  |  * ============================================================================== | ||||||
|  |  * @description This function logs in the user after 'handleSocialDb' function finishes | ||||||
|  |  * the user creation or confirmation process | ||||||
|  |  */ | ||||||
|  | function loginSocialUser(_a) { | ||||||
|  |     return __awaiter(this, arguments, void 0, function* ({ user, social_platform, invitation, database, additionalFields, useLocal, }) { | ||||||
|  |         const foundUserQuery = `SELECT * FROM users WHERE email=? AND social_id=? AND social_platform=?`; | ||||||
|  |         const foundUserValues = [user.email, user.social_id, social_platform]; | ||||||
|  |         const foundUser = yield (0, varDatabaseDbHandler_1.default)({ | ||||||
|  |             database: database ? database : "datasquirel", | ||||||
|  |             queryString: foundUserQuery, | ||||||
|  |             queryValuesArray: foundUserValues, | ||||||
|  |             useLocal, | ||||||
|  |         }); | ||||||
|  |         if (!(foundUser === null || foundUser === void 0 ? void 0 : foundUser[0])) | ||||||
|  |             return { | ||||||
|  |                 success: false, | ||||||
|  |                 payload: null, | ||||||
|  |             }; | ||||||
|  |         let csrfKey = Math.random().toString(36).substring(2) + | ||||||
|  |             "-" + | ||||||
|  |             Math.random().toString(36).substring(2); | ||||||
|  |         /** @type {import("../../../types").DATASQUIREL_LoggedInUser} */ | ||||||
|  |         let userPayload = { | ||||||
|  |             id: foundUser[0].id, | ||||||
|  |             first_name: foundUser[0].first_name, | ||||||
|  |             last_name: foundUser[0].last_name, | ||||||
|  |             username: foundUser[0].username, | ||||||
|  |             user_type: foundUser[0].user_type, | ||||||
|  |             email: foundUser[0].email, | ||||||
|  |             social_id: foundUser[0].social_id, | ||||||
|  |             image: foundUser[0].image, | ||||||
|  |             image_thumbnail: foundUser[0].image_thumbnail, | ||||||
|  |             verification_status: foundUser[0].verification_status, | ||||||
|  |             social_login: foundUser[0].social_login, | ||||||
|  |             social_platform: foundUser[0].social_platform, | ||||||
|  |             csrf_k: csrfKey, | ||||||
|  |             logged_in_status: true, | ||||||
|  |             date: Date.now(), | ||||||
|  |         }; | ||||||
|  |         if (additionalFields === null || additionalFields === void 0 ? void 0 : additionalFields[0]) { | ||||||
|  |             additionalFields.forEach((key) => { | ||||||
|  |                 userPayload[key] = foundUser[0][key]; | ||||||
|  |             }); | ||||||
|  |         } | ||||||
|  |         if (invitation && (!database || (database === null || database === void 0 ? void 0 : database.match(/^datasquirel$/)))) { | ||||||
|  |             (0, addAdminUserOnLogin_1.default)({ | ||||||
|  |                 query: invitation, | ||||||
|  |                 user: userPayload, | ||||||
|  |                 useLocal, | ||||||
|  |             }); | ||||||
|  |         } | ||||||
|  |         /** @type {import("../../../types").APILoginFunctionReturn} */ | ||||||
|  |         let result = { | ||||||
|  |             success: true, | ||||||
|  |             payload: userPayload, | ||||||
|  |             csrf: csrfKey, | ||||||
|  |         }; | ||||||
|  |         return result; | ||||||
|  |     }); | ||||||
|  | } | ||||||
							
								
								
									
										25
									
								
								dist/package-shared/functions/api/users/api-create-user.d.ts
									
									
									
									
										vendored
									
									
										Normal file
									
								
							
							
						
						
									
										25
									
								
								dist/package-shared/functions/api/users/api-create-user.d.ts
									
									
									
									
										vendored
									
									
										Normal file
									
								
							| @ -0,0 +1,25 @@ | |||||||
|  | import { APICreateUserFunctionParams } from "../../../types"; | ||||||
|  | /** | ||||||
|  |  * # API Create User | ||||||
|  |  */ | ||||||
|  | export default function apiCreateUser({ encryptionKey, payload, database, userId, useLocal, }: APICreateUserFunctionParams): Promise<{ | ||||||
|  |     success: boolean; | ||||||
|  |     msg: string; | ||||||
|  |     payload: null; | ||||||
|  |     sqlResult?: undefined; | ||||||
|  | } | { | ||||||
|  |     success: boolean; | ||||||
|  |     msg: string; | ||||||
|  |     payload?: undefined; | ||||||
|  |     sqlResult?: undefined; | ||||||
|  | } | { | ||||||
|  |     success: boolean; | ||||||
|  |     payload: any; | ||||||
|  |     msg?: undefined; | ||||||
|  |     sqlResult?: undefined; | ||||||
|  | } | { | ||||||
|  |     success: boolean; | ||||||
|  |     msg: string; | ||||||
|  |     sqlResult: any; | ||||||
|  |     payload: null; | ||||||
|  | }>; | ||||||
							
								
								
									
										142
									
								
								dist/package-shared/functions/api/users/api-create-user.js
									
									
									
									
										vendored
									
									
										Normal file
									
								
							
							
						
						
									
										142
									
								
								dist/package-shared/functions/api/users/api-create-user.js
									
									
									
									
										vendored
									
									
										Normal file
									
								
							| @ -0,0 +1,142 @@ | |||||||
|  | "use strict"; | ||||||
|  | // @ts-check
 | ||||||
|  | var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { | ||||||
|  |     function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } | ||||||
|  |     return new (P || (P = Promise))(function (resolve, reject) { | ||||||
|  |         function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } | ||||||
|  |         function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } | ||||||
|  |         function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } | ||||||
|  |         step((generator = generator.apply(thisArg, _arguments || [])).next()); | ||||||
|  |     }); | ||||||
|  | }; | ||||||
|  | var __importDefault = (this && this.__importDefault) || function (mod) { | ||||||
|  |     return (mod && mod.__esModule) ? mod : { "default": mod }; | ||||||
|  | }; | ||||||
|  | Object.defineProperty(exports, "__esModule", { value: true }); | ||||||
|  | exports.default = apiCreateUser; | ||||||
|  | const addUsersTableToDb_1 = __importDefault(require("../../backend/addUsersTableToDb")); | ||||||
|  | const addDbEntry_1 = __importDefault(require("../../backend/db/addDbEntry")); | ||||||
|  | const updateUsersTableSchema_1 = __importDefault(require("../../backend/updateUsersTableSchema")); | ||||||
|  | const varDatabaseDbHandler_1 = __importDefault(require("../../backend/varDatabaseDbHandler")); | ||||||
|  | const hashPassword_1 = __importDefault(require("../../dsql/hashPassword")); | ||||||
|  | /** | ||||||
|  |  * # API Create User | ||||||
|  |  */ | ||||||
|  | function apiCreateUser(_a) { | ||||||
|  |     return __awaiter(this, arguments, void 0, function* ({ encryptionKey, payload, database, userId, useLocal, }) { | ||||||
|  |         const dbFullName = database; | ||||||
|  |         const API_USER_ID = userId || process.env.DSQL_API_USER_ID; | ||||||
|  |         const finalEncryptionKey = encryptionKey || process.env.DSQL_ENCRYPTION_PASSWORD; | ||||||
|  |         if (!finalEncryptionKey) { | ||||||
|  |             return { | ||||||
|  |                 success: false, | ||||||
|  |                 msg: "No encryption key provided", | ||||||
|  |                 payload: null, | ||||||
|  |             }; | ||||||
|  |         } | ||||||
|  |         if (!(finalEncryptionKey === null || finalEncryptionKey === void 0 ? void 0 : finalEncryptionKey.match(/.{8,}/))) { | ||||||
|  |             return { | ||||||
|  |                 success: false, | ||||||
|  |                 msg: "Encryption key must be at least 8 characters long", | ||||||
|  |                 payload: null, | ||||||
|  |             }; | ||||||
|  |         } | ||||||
|  |         const hashedPassword = (0, hashPassword_1.default)({ | ||||||
|  |             encryptionKey: finalEncryptionKey, | ||||||
|  |             password: String(payload.password), | ||||||
|  |         }); | ||||||
|  |         payload.password = hashedPassword; | ||||||
|  |         const fieldsQuery = `SHOW COLUMNS FROM users`; | ||||||
|  |         let fields = yield (0, varDatabaseDbHandler_1.default)({ | ||||||
|  |             queryString: fieldsQuery, | ||||||
|  |             database: dbFullName, | ||||||
|  |             useLocal, | ||||||
|  |         }); | ||||||
|  |         if (!(fields === null || fields === void 0 ? void 0 : fields[0])) { | ||||||
|  |             const newTable = yield (0, addUsersTableToDb_1.default)({ | ||||||
|  |                 userId: Number(API_USER_ID), | ||||||
|  |                 database: dbFullName, | ||||||
|  |                 useLocal, | ||||||
|  |                 payload: payload, | ||||||
|  |             }); | ||||||
|  |             fields = yield (0, varDatabaseDbHandler_1.default)({ | ||||||
|  |                 queryString: fieldsQuery, | ||||||
|  |                 database: dbFullName, | ||||||
|  |                 useLocal, | ||||||
|  |             }); | ||||||
|  |         } | ||||||
|  |         if (!(fields === null || fields === void 0 ? void 0 : fields[0])) { | ||||||
|  |             return { | ||||||
|  |                 success: false, | ||||||
|  |                 msg: "Could not create users table", | ||||||
|  |             }; | ||||||
|  |         } | ||||||
|  |         const fieldsTitles = fields.map((fieldObject) => fieldObject.Field); | ||||||
|  |         let invalidField = null; | ||||||
|  |         for (let i = 0; i < Object.keys(payload).length; i++) { | ||||||
|  |             const key = Object.keys(payload)[i]; | ||||||
|  |             if (!fieldsTitles.includes(key)) { | ||||||
|  |                 yield (0, updateUsersTableSchema_1.default)({ | ||||||
|  |                     userId: Number(API_USER_ID), | ||||||
|  |                     database: dbFullName, | ||||||
|  |                     newPayload: { | ||||||
|  |                         [key]: payload[key], | ||||||
|  |                     }, | ||||||
|  |                 }); | ||||||
|  |             } | ||||||
|  |         } | ||||||
|  |         if (invalidField) { | ||||||
|  |             return { | ||||||
|  |                 success: false, | ||||||
|  |                 msg: `${invalidField} is not a valid field!`, | ||||||
|  |             }; | ||||||
|  |         } | ||||||
|  |         const existingUserQuery = `SELECT * FROM users WHERE email = ?${payload.username ? " OR username = ?" : ""}`; | ||||||
|  |         const existingUserValues = payload.username | ||||||
|  |             ? [payload.email, payload.username] | ||||||
|  |             : [payload.email]; | ||||||
|  |         const existingUser = yield (0, varDatabaseDbHandler_1.default)({ | ||||||
|  |             queryString: existingUserQuery, | ||||||
|  |             queryValuesArray: existingUserValues, | ||||||
|  |             database: dbFullName, | ||||||
|  |             useLocal, | ||||||
|  |         }); | ||||||
|  |         if (existingUser === null || existingUser === void 0 ? void 0 : existingUser[0]) { | ||||||
|  |             return { | ||||||
|  |                 success: false, | ||||||
|  |                 msg: "User Already Exists", | ||||||
|  |                 payload: null, | ||||||
|  |             }; | ||||||
|  |         } | ||||||
|  |         const addUser = yield (0, addDbEntry_1.default)({ | ||||||
|  |             dbContext: "Dsql User", | ||||||
|  |             paradigm: "Full Access", | ||||||
|  |             dbFullName: dbFullName, | ||||||
|  |             tableName: "users", | ||||||
|  |             data: Object.assign(Object.assign({}, payload), { image: process.env.DSQL_DEFAULT_USER_IMAGE || | ||||||
|  |                     "/images/user-preset.png", image_thumbnail: process.env.DSQL_DEFAULT_USER_IMAGE || | ||||||
|  |                     "/images/user-preset-thumbnail.png" }), | ||||||
|  |             useLocal, | ||||||
|  |         }); | ||||||
|  |         if (addUser === null || addUser === void 0 ? void 0 : addUser.insertId) { | ||||||
|  |             const newlyAddedUserQuery = `SELECT id,first_name,last_name,email,username,phone,image,image_thumbnail,city,state,country,zip_code,address,verification_status,more_user_data FROM users WHERE id='${addUser.insertId}'`; | ||||||
|  |             const newlyAddedUser = yield (0, varDatabaseDbHandler_1.default)({ | ||||||
|  |                 queryString: newlyAddedUserQuery, | ||||||
|  |                 database: dbFullName, | ||||||
|  |                 useLocal, | ||||||
|  |             }); | ||||||
|  |             return { | ||||||
|  |                 success: true, | ||||||
|  |                 payload: newlyAddedUser[0], | ||||||
|  |             }; | ||||||
|  |         } | ||||||
|  |         else { | ||||||
|  |             return { | ||||||
|  |                 success: false, | ||||||
|  |                 msg: "Could not create user", | ||||||
|  |                 sqlResult: addUser, | ||||||
|  |                 payload: null, | ||||||
|  |             }; | ||||||
|  |         } | ||||||
|  |     }); | ||||||
|  | } | ||||||
							
								
								
									
										15
									
								
								dist/package-shared/functions/api/users/api-delete-user.d.ts
									
									
									
									
										vendored
									
									
										Normal file
									
								
							
							
						
						
									
										15
									
								
								dist/package-shared/functions/api/users/api-delete-user.d.ts
									
									
									
									
										vendored
									
									
										Normal file
									
								
							| @ -0,0 +1,15 @@ | |||||||
|  | type Param = { | ||||||
|  |     dbFullName: string; | ||||||
|  |     deletedUserId: string | number; | ||||||
|  |     useLocal?: boolean; | ||||||
|  | }; | ||||||
|  | type Return = { | ||||||
|  |     success: boolean; | ||||||
|  |     result?: any; | ||||||
|  |     msg?: string; | ||||||
|  | }; | ||||||
|  | /** | ||||||
|  |  * # Update API User Function | ||||||
|  |  */ | ||||||
|  | export default function apiDeleteUser({ dbFullName, deletedUserId, useLocal, }: Param): Promise<Return>; | ||||||
|  | export {}; | ||||||
							
								
								
									
										51
									
								
								dist/package-shared/functions/api/users/api-delete-user.js
									
									
									
									
										vendored
									
									
										Normal file
									
								
							
							
						
						
									
										51
									
								
								dist/package-shared/functions/api/users/api-delete-user.js
									
									
									
									
										vendored
									
									
										Normal file
									
								
							| @ -0,0 +1,51 @@ | |||||||
|  | "use strict"; | ||||||
|  | var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { | ||||||
|  |     function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } | ||||||
|  |     return new (P || (P = Promise))(function (resolve, reject) { | ||||||
|  |         function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } | ||||||
|  |         function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } | ||||||
|  |         function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } | ||||||
|  |         step((generator = generator.apply(thisArg, _arguments || [])).next()); | ||||||
|  |     }); | ||||||
|  | }; | ||||||
|  | var __importDefault = (this && this.__importDefault) || function (mod) { | ||||||
|  |     return (mod && mod.__esModule) ? mod : { "default": mod }; | ||||||
|  | }; | ||||||
|  | Object.defineProperty(exports, "__esModule", { value: true }); | ||||||
|  | exports.default = apiDeleteUser; | ||||||
|  | const deleteDbEntry_1 = __importDefault(require("../../backend/db/deleteDbEntry")); | ||||||
|  | const varDatabaseDbHandler_1 = __importDefault(require("../../backend/varDatabaseDbHandler")); | ||||||
|  | /** | ||||||
|  |  * # Update API User Function | ||||||
|  |  */ | ||||||
|  | function apiDeleteUser(_a) { | ||||||
|  |     return __awaiter(this, arguments, void 0, function* ({ dbFullName, deletedUserId, useLocal, }) { | ||||||
|  |         const existingUserQuery = `SELECT * FROM users WHERE id = ?`; | ||||||
|  |         const existingUserValues = [deletedUserId]; | ||||||
|  |         const existingUser = yield (0, varDatabaseDbHandler_1.default)({ | ||||||
|  |             queryString: existingUserQuery, | ||||||
|  |             queryValuesArray: existingUserValues, | ||||||
|  |             database: dbFullName, | ||||||
|  |             useLocal, | ||||||
|  |         }); | ||||||
|  |         if (!(existingUser === null || existingUser === void 0 ? void 0 : existingUser[0])) { | ||||||
|  |             return { | ||||||
|  |                 success: false, | ||||||
|  |                 msg: "User not found", | ||||||
|  |             }; | ||||||
|  |         } | ||||||
|  |         const deleteUser = yield (0, deleteDbEntry_1.default)({ | ||||||
|  |             dbContext: "Dsql User", | ||||||
|  |             paradigm: "Full Access", | ||||||
|  |             dbFullName, | ||||||
|  |             tableName: "users", | ||||||
|  |             identifierColumnName: "id", | ||||||
|  |             identifierValue: deletedUserId, | ||||||
|  |             useLocal, | ||||||
|  |         }); | ||||||
|  |         return { | ||||||
|  |             success: true, | ||||||
|  |             result: deleteUser, | ||||||
|  |         }; | ||||||
|  |     }); | ||||||
|  | } | ||||||
							
								
								
									
										5
									
								
								dist/package-shared/functions/api/users/api-get-user.d.ts
									
									
									
									
										vendored
									
									
										Normal file
									
								
							
							
						
						
									
										5
									
								
								dist/package-shared/functions/api/users/api-get-user.d.ts
									
									
									
									
										vendored
									
									
										Normal file
									
								
							| @ -0,0 +1,5 @@ | |||||||
|  | import { APIGetUserFunctionParams, GetUserFunctionReturn } from "../../../types"; | ||||||
|  | /** | ||||||
|  |  * # API Get User | ||||||
|  |  */ | ||||||
|  | export default function apiGetUser({ fields, dbFullName, userId, useLocal, }: APIGetUserFunctionParams): Promise<GetUserFunctionReturn>; | ||||||
							
								
								
									
										41
									
								
								dist/package-shared/functions/api/users/api-get-user.js
									
									
									
									
										vendored
									
									
										Normal file
									
								
							
							
						
						
									
										41
									
								
								dist/package-shared/functions/api/users/api-get-user.js
									
									
									
									
										vendored
									
									
										Normal file
									
								
							| @ -0,0 +1,41 @@ | |||||||
|  | "use strict"; | ||||||
|  | var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { | ||||||
|  |     function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } | ||||||
|  |     return new (P || (P = Promise))(function (resolve, reject) { | ||||||
|  |         function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } | ||||||
|  |         function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } | ||||||
|  |         function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } | ||||||
|  |         step((generator = generator.apply(thisArg, _arguments || [])).next()); | ||||||
|  |     }); | ||||||
|  | }; | ||||||
|  | var __importDefault = (this && this.__importDefault) || function (mod) { | ||||||
|  |     return (mod && mod.__esModule) ? mod : { "default": mod }; | ||||||
|  | }; | ||||||
|  | Object.defineProperty(exports, "__esModule", { value: true }); | ||||||
|  | exports.default = apiGetUser; | ||||||
|  | const varDatabaseDbHandler_1 = __importDefault(require("../../backend/varDatabaseDbHandler")); | ||||||
|  | /** | ||||||
|  |  * # API Get User | ||||||
|  |  */ | ||||||
|  | function apiGetUser(_a) { | ||||||
|  |     return __awaiter(this, arguments, void 0, function* ({ fields, dbFullName, userId, useLocal, }) { | ||||||
|  |         const query = `SELECT ${fields.join(",")} FROM users WHERE id=?`; | ||||||
|  |         const API_USER_ID = userId || process.env.DSQL_API_USER_ID; | ||||||
|  |         let foundUser = yield (0, varDatabaseDbHandler_1.default)({ | ||||||
|  |             queryString: query, | ||||||
|  |             queryValuesArray: [API_USER_ID], | ||||||
|  |             database: dbFullName.replace(/[^a-z0-9_]/g, ""), | ||||||
|  |             useLocal, | ||||||
|  |         }); | ||||||
|  |         if (!foundUser || !foundUser[0]) { | ||||||
|  |             return { | ||||||
|  |                 success: false, | ||||||
|  |                 payload: null, | ||||||
|  |             }; | ||||||
|  |         } | ||||||
|  |         return { | ||||||
|  |             success: true, | ||||||
|  |             payload: foundUser[0], | ||||||
|  |         }; | ||||||
|  |     }); | ||||||
|  | } | ||||||
							
								
								
									
										5
									
								
								dist/package-shared/functions/api/users/api-login.d.ts
									
									
									
									
										vendored
									
									
										Normal file
									
								
							
							
						
						
									
										5
									
								
								dist/package-shared/functions/api/users/api-login.d.ts
									
									
									
									
										vendored
									
									
										Normal file
									
								
							| @ -0,0 +1,5 @@ | |||||||
|  | import { APILoginFunctionParams, APILoginFunctionReturn } from "../../../types"; | ||||||
|  | /** | ||||||
|  |  * # API Login | ||||||
|  |  */ | ||||||
|  | export default function apiLoginUser({ encryptionKey, email, username, password, database, additionalFields, email_login, email_login_code, email_login_field, token, skipPassword, social, useLocal, }: APILoginFunctionParams): Promise<APILoginFunctionReturn>; | ||||||
							
								
								
									
										137
									
								
								dist/package-shared/functions/api/users/api-login.js
									
									
									
									
										vendored
									
									
										Normal file
									
								
							
							
						
						
									
										137
									
								
								dist/package-shared/functions/api/users/api-login.js
									
									
									
									
										vendored
									
									
										Normal file
									
								
							| @ -0,0 +1,137 @@ | |||||||
|  | "use strict"; | ||||||
|  | var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { | ||||||
|  |     function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } | ||||||
|  |     return new (P || (P = Promise))(function (resolve, reject) { | ||||||
|  |         function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } | ||||||
|  |         function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } | ||||||
|  |         function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } | ||||||
|  |         step((generator = generator.apply(thisArg, _arguments || [])).next()); | ||||||
|  |     }); | ||||||
|  | }; | ||||||
|  | var __importDefault = (this && this.__importDefault) || function (mod) { | ||||||
|  |     return (mod && mod.__esModule) ? mod : { "default": mod }; | ||||||
|  | }; | ||||||
|  | Object.defineProperty(exports, "__esModule", { value: true }); | ||||||
|  | exports.default = apiLoginUser; | ||||||
|  | const varDatabaseDbHandler_1 = __importDefault(require("../../backend/varDatabaseDbHandler")); | ||||||
|  | const hashPassword_1 = __importDefault(require("../../dsql/hashPassword")); | ||||||
|  | /** | ||||||
|  |  * # API Login | ||||||
|  |  */ | ||||||
|  | function apiLoginUser(_a) { | ||||||
|  |     return __awaiter(this, arguments, void 0, function* ({ encryptionKey, email, username, password, database, additionalFields, email_login, email_login_code, email_login_field, token, skipPassword, social, useLocal, }) { | ||||||
|  |         const dbFullName = database; | ||||||
|  |         /** | ||||||
|  |          * Check input validity | ||||||
|  |          * | ||||||
|  |          * @description Check input validity | ||||||
|  |          */ | ||||||
|  |         if ((email === null || email === void 0 ? void 0 : email.match(/ /)) || | ||||||
|  |             (username && (username === null || username === void 0 ? void 0 : username.match(/ /))) || | ||||||
|  |             (password && (password === null || password === void 0 ? void 0 : password.match(/ /)))) { | ||||||
|  |             return { | ||||||
|  |                 success: false, | ||||||
|  |                 msg: "Invalid Email/Password format", | ||||||
|  |             }; | ||||||
|  |         } | ||||||
|  |         /** | ||||||
|  |          * Password hash | ||||||
|  |          * | ||||||
|  |          * @description Password hash | ||||||
|  |          */ | ||||||
|  |         let hashedPassword = password | ||||||
|  |             ? (0, hashPassword_1.default)({ | ||||||
|  |                 encryptionKey: encryptionKey, | ||||||
|  |                 password: password, | ||||||
|  |             }) | ||||||
|  |             : null; | ||||||
|  |         let foundUser = yield (0, varDatabaseDbHandler_1.default)({ | ||||||
|  |             queryString: `SELECT * FROM users WHERE email = ? OR username = ?`, | ||||||
|  |             queryValuesArray: [email, username], | ||||||
|  |             database: dbFullName.replace(/[^a-z0-9_]/g, ""), | ||||||
|  |             useLocal, | ||||||
|  |         }); | ||||||
|  |         if ((!foundUser || !foundUser[0]) && !social) | ||||||
|  |             return { | ||||||
|  |                 success: false, | ||||||
|  |                 payload: null, | ||||||
|  |                 msg: "No user found", | ||||||
|  |             }; | ||||||
|  |         let isPasswordCorrect = false; | ||||||
|  |         if ((foundUser === null || foundUser === void 0 ? void 0 : foundUser[0]) && !email_login && skipPassword) { | ||||||
|  |             isPasswordCorrect = true; | ||||||
|  |         } | ||||||
|  |         else if ((foundUser === null || foundUser === void 0 ? void 0 : foundUser[0]) && !email_login) { | ||||||
|  |             isPasswordCorrect = hashedPassword === foundUser[0].password; | ||||||
|  |         } | ||||||
|  |         else if (foundUser && | ||||||
|  |             foundUser[0] && | ||||||
|  |             email_login && | ||||||
|  |             email_login_code && | ||||||
|  |             email_login_field) { | ||||||
|  |             /** @type {string} */ | ||||||
|  |             const tempCode = foundUser[0][email_login_field]; | ||||||
|  |             if (!tempCode) | ||||||
|  |                 throw new Error("No code Found!"); | ||||||
|  |             const tempCodeArray = tempCode.split("-"); | ||||||
|  |             const [code, codeDate] = tempCodeArray; | ||||||
|  |             const millisecond15mins = 1000 * 60 * 15; | ||||||
|  |             if (Date.now() - Number(codeDate) > millisecond15mins) { | ||||||
|  |                 throw new Error("Code Expired"); | ||||||
|  |             } | ||||||
|  |             isPasswordCorrect = code === email_login_code; | ||||||
|  |         } | ||||||
|  |         let socialUserValid = false; | ||||||
|  |         if (!isPasswordCorrect && !socialUserValid) { | ||||||
|  |             return { | ||||||
|  |                 success: false, | ||||||
|  |                 msg: "Wrong password, no social login validity", | ||||||
|  |                 payload: null, | ||||||
|  |             }; | ||||||
|  |         } | ||||||
|  |         if (isPasswordCorrect && email_login) { | ||||||
|  |             const resetTempCode = yield (0, varDatabaseDbHandler_1.default)({ | ||||||
|  |                 queryString: `UPDATE users SET ${email_login_field} = '' WHERE email = ? OR username = ?`, | ||||||
|  |                 queryValuesArray: [email, username], | ||||||
|  |                 database: dbFullName.replace(/[^a-z0-9_]/g, ""), | ||||||
|  |                 useLocal, | ||||||
|  |             }); | ||||||
|  |         } | ||||||
|  |         let csrfKey = Math.random().toString(36).substring(2) + | ||||||
|  |             "-" + | ||||||
|  |             Math.random().toString(36).substring(2); | ||||||
|  |         let userPayload = { | ||||||
|  |             id: foundUser[0].id, | ||||||
|  |             first_name: foundUser[0].first_name, | ||||||
|  |             last_name: foundUser[0].last_name, | ||||||
|  |             username: foundUser[0].username, | ||||||
|  |             email: foundUser[0].email, | ||||||
|  |             phone: foundUser[0].phone, | ||||||
|  |             social_id: foundUser[0].social_id, | ||||||
|  |             image: foundUser[0].image, | ||||||
|  |             image_thumbnail: foundUser[0].image_thumbnail, | ||||||
|  |             verification_status: foundUser[0].verification_status, | ||||||
|  |             social_login: foundUser[0].social_login, | ||||||
|  |             social_platform: foundUser[0].social_platform, | ||||||
|  |             csrf_k: csrfKey, | ||||||
|  |             more_data: foundUser[0].more_user_data, | ||||||
|  |             logged_in_status: true, | ||||||
|  |             date: Date.now(), | ||||||
|  |         }; | ||||||
|  |         const resposeObject = { | ||||||
|  |             success: true, | ||||||
|  |             msg: "Login Successful", | ||||||
|  |             payload: userPayload, | ||||||
|  |             userId: foundUser[0].id, | ||||||
|  |             csrf: csrfKey, | ||||||
|  |         }; | ||||||
|  |         if (additionalFields && | ||||||
|  |             Array.isArray(additionalFields) && | ||||||
|  |             additionalFields.length > 0) { | ||||||
|  |             additionalFields.forEach((key) => { | ||||||
|  |                 userPayload[key] = foundUser[0][key]; | ||||||
|  |             }); | ||||||
|  |         } | ||||||
|  |         return resposeObject; | ||||||
|  |     }); | ||||||
|  | } | ||||||
							
								
								
									
										14
									
								
								dist/package-shared/functions/api/users/api-reauth-user.d.ts
									
									
									
									
										vendored
									
									
										Normal file
									
								
							
							
						
						
									
										14
									
								
								dist/package-shared/functions/api/users/api-reauth-user.d.ts
									
									
									
									
										vendored
									
									
										Normal file
									
								
							| @ -0,0 +1,14 @@ | |||||||
|  | import { APILoginFunctionReturn } from "../../../types"; | ||||||
|  | type Param = { | ||||||
|  |     existingUser: { | ||||||
|  |         [s: string]: any; | ||||||
|  |     }; | ||||||
|  |     database?: string; | ||||||
|  |     additionalFields?: string[]; | ||||||
|  |     useLocal?: boolean; | ||||||
|  | }; | ||||||
|  | /** | ||||||
|  |  * # Re-authenticate API user | ||||||
|  |  */ | ||||||
|  | export default function apiReauthUser({ existingUser, database, additionalFields, useLocal, }: Param): Promise<APILoginFunctionReturn>; | ||||||
|  | export {}; | ||||||
							
								
								
									
										72
									
								
								dist/package-shared/functions/api/users/api-reauth-user.js
									
									
									
									
										vendored
									
									
										Normal file
									
								
							
							
						
						
									
										72
									
								
								dist/package-shared/functions/api/users/api-reauth-user.js
									
									
									
									
										vendored
									
									
										Normal file
									
								
							| @ -0,0 +1,72 @@ | |||||||
|  | "use strict"; | ||||||
|  | var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { | ||||||
|  |     function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } | ||||||
|  |     return new (P || (P = Promise))(function (resolve, reject) { | ||||||
|  |         function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } | ||||||
|  |         function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } | ||||||
|  |         function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } | ||||||
|  |         step((generator = generator.apply(thisArg, _arguments || [])).next()); | ||||||
|  |     }); | ||||||
|  | }; | ||||||
|  | var __importDefault = (this && this.__importDefault) || function (mod) { | ||||||
|  |     return (mod && mod.__esModule) ? mod : { "default": mod }; | ||||||
|  | }; | ||||||
|  | Object.defineProperty(exports, "__esModule", { value: true }); | ||||||
|  | exports.default = apiReauthUser; | ||||||
|  | const varDatabaseDbHandler_1 = __importDefault(require("../../backend/varDatabaseDbHandler")); | ||||||
|  | /** | ||||||
|  |  * # Re-authenticate API user | ||||||
|  |  */ | ||||||
|  | function apiReauthUser(_a) { | ||||||
|  |     return __awaiter(this, arguments, void 0, function* ({ existingUser, database, additionalFields, useLocal, }) { | ||||||
|  |         let foundUser = (existingUser === null || existingUser === void 0 ? void 0 : existingUser.id) && existingUser.id.toString().match(/./) | ||||||
|  |             ? yield (0, varDatabaseDbHandler_1.default)({ | ||||||
|  |                 queryString: `SELECT * FROM users WHERE id=?`, | ||||||
|  |                 queryValuesArray: [existingUser.id.toString()], | ||||||
|  |                 database, | ||||||
|  |                 useLocal, | ||||||
|  |             }) | ||||||
|  |             : null; | ||||||
|  |         if (!foundUser || !foundUser[0]) | ||||||
|  |             return { | ||||||
|  |                 success: false, | ||||||
|  |                 payload: null, | ||||||
|  |                 msg: "No user found", | ||||||
|  |             }; | ||||||
|  |         let csrfKey = Math.random().toString(36).substring(2) + | ||||||
|  |             "-" + | ||||||
|  |             Math.random().toString(36).substring(2); | ||||||
|  |         /** @type {import("../../../types").DATASQUIREL_LoggedInUser} */ | ||||||
|  |         let userPayload = { | ||||||
|  |             id: foundUser[0].id, | ||||||
|  |             first_name: foundUser[0].first_name, | ||||||
|  |             last_name: foundUser[0].last_name, | ||||||
|  |             username: foundUser[0].username, | ||||||
|  |             email: foundUser[0].email, | ||||||
|  |             phone: foundUser[0].phone, | ||||||
|  |             social_id: foundUser[0].social_id, | ||||||
|  |             image: foundUser[0].image, | ||||||
|  |             image_thumbnail: foundUser[0].image_thumbnail, | ||||||
|  |             verification_status: foundUser[0].verification_status, | ||||||
|  |             social_login: foundUser[0].social_login, | ||||||
|  |             social_platform: foundUser[0].social_platform, | ||||||
|  |             csrf_k: csrfKey, | ||||||
|  |             more_data: foundUser[0].more_user_data, | ||||||
|  |             logged_in_status: true, | ||||||
|  |             date: Date.now(), | ||||||
|  |         }; | ||||||
|  |         if (additionalFields && | ||||||
|  |             Array.isArray(additionalFields) && | ||||||
|  |             additionalFields.length > 0) { | ||||||
|  |             additionalFields.forEach((key) => { | ||||||
|  |                 userPayload[key] = foundUser[0][key]; | ||||||
|  |             }); | ||||||
|  |         } | ||||||
|  |         return { | ||||||
|  |             success: true, | ||||||
|  |             msg: "Login Successful", | ||||||
|  |             payload: userPayload, | ||||||
|  |             csrf: csrfKey, | ||||||
|  |         }; | ||||||
|  |     }); | ||||||
|  | } | ||||||
							
								
								
									
										23
									
								
								dist/package-shared/functions/api/users/api-send-email-code.d.ts
									
									
									
									
										vendored
									
									
										Normal file
									
								
							
							
						
						
									
										23
									
								
								dist/package-shared/functions/api/users/api-send-email-code.d.ts
									
									
									
									
										vendored
									
									
										Normal file
									
								
							| @ -0,0 +1,23 @@ | |||||||
|  | import http from "http"; | ||||||
|  | import { SendOneTimeCodeEmailResponse } from "../../../types"; | ||||||
|  | type Param = { | ||||||
|  |     email: string; | ||||||
|  |     database: string; | ||||||
|  |     email_login_field?: string; | ||||||
|  |     mail_domain?: string; | ||||||
|  |     mail_port?: number; | ||||||
|  |     sender?: string; | ||||||
|  |     mail_username?: string; | ||||||
|  |     mail_password?: string; | ||||||
|  |     html: string; | ||||||
|  |     useLocal?: boolean; | ||||||
|  |     response?: http.ServerResponse & { | ||||||
|  |         [s: string]: any; | ||||||
|  |     }; | ||||||
|  |     extraCookies?: import("../../../../package-shared/types").CookieObject[]; | ||||||
|  | }; | ||||||
|  | /** | ||||||
|  |  * # Send Email Login Code | ||||||
|  |  */ | ||||||
|  | export default function apiSendEmailCode({ email, database, email_login_field, mail_domain, mail_port, sender, mail_username, mail_password, html, useLocal, response, extraCookies, }: Param): Promise<SendOneTimeCodeEmailResponse>; | ||||||
|  | export {}; | ||||||
							
								
								
									
										134
									
								
								dist/package-shared/functions/api/users/api-send-email-code.js
									
									
									
									
										vendored
									
									
										Normal file
									
								
							
							
						
						
									
										134
									
								
								dist/package-shared/functions/api/users/api-send-email-code.js
									
									
									
									
										vendored
									
									
										Normal file
									
								
							| @ -0,0 +1,134 @@ | |||||||
|  | "use strict"; | ||||||
|  | var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { | ||||||
|  |     function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } | ||||||
|  |     return new (P || (P = Promise))(function (resolve, reject) { | ||||||
|  |         function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } | ||||||
|  |         function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } | ||||||
|  |         function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } | ||||||
|  |         step((generator = generator.apply(thisArg, _arguments || [])).next()); | ||||||
|  |     }); | ||||||
|  | }; | ||||||
|  | var __importDefault = (this && this.__importDefault) || function (mod) { | ||||||
|  |     return (mod && mod.__esModule) ? mod : { "default": mod }; | ||||||
|  | }; | ||||||
|  | Object.defineProperty(exports, "__esModule", { value: true }); | ||||||
|  | exports.default = apiSendEmailCode; | ||||||
|  | const varDatabaseDbHandler_1 = __importDefault(require("../../backend/varDatabaseDbHandler")); | ||||||
|  | const nodemailer_1 = __importDefault(require("nodemailer")); | ||||||
|  | const get_auth_cookie_names_1 = __importDefault(require("../../backend/cookies/get-auth-cookie-names")); | ||||||
|  | const encrypt_1 = __importDefault(require("../../dsql/encrypt")); | ||||||
|  | const serialize_cookies_1 = __importDefault(require("../../../utils/serialize-cookies")); | ||||||
|  | /** | ||||||
|  |  * # Send Email Login Code | ||||||
|  |  */ | ||||||
|  | function apiSendEmailCode(_a) { | ||||||
|  |     return __awaiter(this, arguments, void 0, function* ({ email, database, email_login_field, mail_domain, mail_port, sender, mail_username, mail_password, html, useLocal, response, extraCookies, }) { | ||||||
|  |         if (email === null || email === void 0 ? void 0 : email.match(/ /)) { | ||||||
|  |             return { | ||||||
|  |                 success: false, | ||||||
|  |                 msg: "Invalid Email/Password format", | ||||||
|  |             }; | ||||||
|  |         } | ||||||
|  |         const createdAt = Date.now(); | ||||||
|  |         const foundUserQuery = `SELECT * FROM users WHERE email = ?`; | ||||||
|  |         const foundUserValues = [email]; | ||||||
|  |         let foundUser = yield (0, varDatabaseDbHandler_1.default)({ | ||||||
|  |             queryString: foundUserQuery, | ||||||
|  |             queryValuesArray: foundUserValues, | ||||||
|  |             database, | ||||||
|  |             useLocal, | ||||||
|  |         }); | ||||||
|  |         ////////////////////////////////////////
 | ||||||
|  |         ////////////////////////////////////////
 | ||||||
|  |         ////////////////////////////////////////
 | ||||||
|  |         if (!foundUser || !foundUser[0]) { | ||||||
|  |             return { | ||||||
|  |                 success: false, | ||||||
|  |                 msg: "No user found", | ||||||
|  |             }; | ||||||
|  |         } | ||||||
|  |         function generateCode() { | ||||||
|  |             const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; | ||||||
|  |             let code = ""; | ||||||
|  |             for (let i = 0; i < 8; i++) { | ||||||
|  |                 code += chars[Math.floor(Math.random() * chars.length)]; | ||||||
|  |             } | ||||||
|  |             return code; | ||||||
|  |         } | ||||||
|  |         if ((foundUser === null || foundUser === void 0 ? void 0 : foundUser[0]) && email_login_field) { | ||||||
|  |             const tempCode = generateCode(); | ||||||
|  |             let transporter = nodemailer_1.default.createTransport({ | ||||||
|  |                 host: mail_domain || process.env.DSQL_MAIL_HOST, | ||||||
|  |                 port: mail_port | ||||||
|  |                     ? mail_port | ||||||
|  |                     : process.env.DSQL_MAIL_PORT | ||||||
|  |                         ? Number(process.env.DSQL_MAIL_PORT) | ||||||
|  |                         : 465, | ||||||
|  |                 secure: true, | ||||||
|  |                 auth: { | ||||||
|  |                     user: mail_username || process.env.DSQL_MAIL_EMAIL, | ||||||
|  |                     pass: mail_password || process.env.DSQL_MAIL_PASSWORD, | ||||||
|  |                 }, | ||||||
|  |             }); | ||||||
|  |             let mailObject = {}; | ||||||
|  |             mailObject["from"] = `"Datasquirel SSO" <${sender || "support@datasquirel.com"}>`; | ||||||
|  |             mailObject["sender"] = sender || "support@datasquirel.com"; | ||||||
|  |             mailObject["to"] = email; | ||||||
|  |             mailObject["subject"] = "One Time Login Code"; | ||||||
|  |             mailObject["html"] = html.replace(/{{code}}/, tempCode); | ||||||
|  |             const info = yield transporter.sendMail(mailObject); | ||||||
|  |             if (!(info === null || info === void 0 ? void 0 : info.accepted)) | ||||||
|  |                 throw new Error("Mail not Sent!"); | ||||||
|  |             const setTempCodeQuery = `UPDATE users SET ${email_login_field} = ? WHERE email = ?`; | ||||||
|  |             const setTempCodeValues = [tempCode + `-${createdAt}`, email]; | ||||||
|  |             let setTempCode = yield (0, varDatabaseDbHandler_1.default)({ | ||||||
|  |                 queryString: setTempCodeQuery, | ||||||
|  |                 queryValuesArray: setTempCodeValues, | ||||||
|  |                 database: database, | ||||||
|  |                 useLocal, | ||||||
|  |             }); | ||||||
|  |             /** @type {import("../../../types").SendOneTimeCodeEmailResponse} */ | ||||||
|  |             const resObject = { | ||||||
|  |                 success: true, | ||||||
|  |                 code: tempCode, | ||||||
|  |                 email: email, | ||||||
|  |                 createdAt, | ||||||
|  |                 msg: "Success", | ||||||
|  |             }; | ||||||
|  |             if (response) { | ||||||
|  |                 const cookieKeyNames = (0, get_auth_cookie_names_1.default)(); | ||||||
|  |                 const oneTimeCodeCookieName = cookieKeyNames.oneTimeCodeName; | ||||||
|  |                 const encryptedPayload = (0, encrypt_1.default)({ | ||||||
|  |                     data: JSON.stringify(resObject), | ||||||
|  |                 }); | ||||||
|  |                 if (!encryptedPayload) { | ||||||
|  |                     throw new Error("apiSendEmailCode Error: Failed to encrypt payload"); | ||||||
|  |                 } | ||||||
|  |                 /** @type {import("../../../../package-shared/types").CookieObject} */ | ||||||
|  |                 const oneTimeCookieObject = { | ||||||
|  |                     name: oneTimeCodeCookieName, | ||||||
|  |                     value: encryptedPayload, | ||||||
|  |                     sameSite: "Strict", | ||||||
|  |                     path: "/", | ||||||
|  |                     httpOnly: true, | ||||||
|  |                     secure: true, | ||||||
|  |                 }; | ||||||
|  |                 /** @type {import("../../../../package-shared/types").CookieObject[]} */ | ||||||
|  |                 const cookiesObjectArray = extraCookies | ||||||
|  |                     ? [...extraCookies, oneTimeCookieObject] | ||||||
|  |                     : [oneTimeCookieObject]; | ||||||
|  |                 const serializedCookies = (0, serialize_cookies_1.default)({ | ||||||
|  |                     cookies: cookiesObjectArray, | ||||||
|  |                 }); | ||||||
|  |                 response.setHeader("Set-Cookie", serializedCookies); | ||||||
|  |             } | ||||||
|  |             return resObject; | ||||||
|  |         } | ||||||
|  |         else { | ||||||
|  |             return { | ||||||
|  |                 success: false, | ||||||
|  |                 msg: "Invalid Email/Password format", | ||||||
|  |             }; | ||||||
|  |         } | ||||||
|  |     }); | ||||||
|  | } | ||||||
							
								
								
									
										19
									
								
								dist/package-shared/functions/api/users/api-update-user.d.ts
									
									
									
									
										vendored
									
									
										Normal file
									
								
							
							
						
						
									
										19
									
								
								dist/package-shared/functions/api/users/api-update-user.d.ts
									
									
									
									
										vendored
									
									
										Normal file
									
								
							| @ -0,0 +1,19 @@ | |||||||
|  | type Param = { | ||||||
|  |     payload: { | ||||||
|  |         [s: string]: any; | ||||||
|  |     }; | ||||||
|  |     dbFullName: string; | ||||||
|  |     updatedUserId: string | number; | ||||||
|  |     useLocal?: boolean; | ||||||
|  |     dbSchema?: import("../../../types").DSQL_DatabaseSchemaType; | ||||||
|  | }; | ||||||
|  | type Return = { | ||||||
|  |     success: boolean; | ||||||
|  |     payload?: any; | ||||||
|  |     msg?: string; | ||||||
|  | }; | ||||||
|  | /** | ||||||
|  |  * # Update API User Function | ||||||
|  |  */ | ||||||
|  | export default function apiUpdateUser({ payload, dbFullName, updatedUserId, useLocal, dbSchema, }: Param): Promise<Return>; | ||||||
|  | export {}; | ||||||
							
								
								
									
										85
									
								
								dist/package-shared/functions/api/users/api-update-user.js
									
									
									
									
										vendored
									
									
										Normal file
									
								
							
							
						
						
									
										85
									
								
								dist/package-shared/functions/api/users/api-update-user.js
									
									
									
									
										vendored
									
									
										Normal file
									
								
							| @ -0,0 +1,85 @@ | |||||||
|  | "use strict"; | ||||||
|  | // @ts-check
 | ||||||
|  | var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { | ||||||
|  |     function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } | ||||||
|  |     return new (P || (P = Promise))(function (resolve, reject) { | ||||||
|  |         function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } | ||||||
|  |         function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } | ||||||
|  |         function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } | ||||||
|  |         step((generator = generator.apply(thisArg, _arguments || [])).next()); | ||||||
|  |     }); | ||||||
|  | }; | ||||||
|  | var __importDefault = (this && this.__importDefault) || function (mod) { | ||||||
|  |     return (mod && mod.__esModule) ? mod : { "default": mod }; | ||||||
|  | }; | ||||||
|  | Object.defineProperty(exports, "__esModule", { value: true }); | ||||||
|  | exports.default = apiUpdateUser; | ||||||
|  | const updateDbEntry_1 = __importDefault(require("../../backend/db/updateDbEntry")); | ||||||
|  | const encrypt_1 = __importDefault(require("../../dsql/encrypt")); | ||||||
|  | const hashPassword_1 = __importDefault(require("../../dsql/hashPassword")); | ||||||
|  | const varDatabaseDbHandler_1 = __importDefault(require("../../backend/varDatabaseDbHandler")); | ||||||
|  | /** | ||||||
|  |  * # Update API User Function | ||||||
|  |  */ | ||||||
|  | function apiUpdateUser(_a) { | ||||||
|  |     return __awaiter(this, arguments, void 0, function* ({ payload, dbFullName, updatedUserId, useLocal, dbSchema, }) { | ||||||
|  |         const existingUserQuery = `SELECT * FROM users WHERE id = ?`; | ||||||
|  |         const existingUserValues = [updatedUserId]; | ||||||
|  |         const existingUser = yield (0, varDatabaseDbHandler_1.default)({ | ||||||
|  |             queryString: existingUserQuery, | ||||||
|  |             queryValuesArray: existingUserValues, | ||||||
|  |             database: dbFullName, | ||||||
|  |             useLocal, | ||||||
|  |         }); | ||||||
|  |         if (!(existingUser === null || existingUser === void 0 ? void 0 : existingUser[0])) { | ||||||
|  |             return { | ||||||
|  |                 success: false, | ||||||
|  |                 msg: "User not found", | ||||||
|  |             }; | ||||||
|  |         } | ||||||
|  |         const data = (() => { | ||||||
|  |             const reqBodyKeys = Object.keys(payload); | ||||||
|  |             const targetTableSchema = (() => { | ||||||
|  |                 var _a; | ||||||
|  |                 try { | ||||||
|  |                     const targetDatabaseSchema = (_a = dbSchema === null || dbSchema === void 0 ? void 0 : dbSchema.tables) === null || _a === void 0 ? void 0 : _a.find((tbl) => tbl.tableName == "users"); | ||||||
|  |                     return targetDatabaseSchema; | ||||||
|  |                 } | ||||||
|  |                 catch (error) { | ||||||
|  |                     return undefined; | ||||||
|  |                 } | ||||||
|  |             })(); | ||||||
|  |             /** @type {any} */ | ||||||
|  |             const finalData = {}; | ||||||
|  |             reqBodyKeys.forEach((key) => { | ||||||
|  |                 var _a; | ||||||
|  |                 const targetFieldSchema = (_a = targetTableSchema === null || targetTableSchema === void 0 ? void 0 : targetTableSchema.fields) === null || _a === void 0 ? void 0 : _a.find((field) => field.fieldName == key); | ||||||
|  |                 if (key === null || key === void 0 ? void 0 : key.match(/^date_|^id$|^uuid$/)) | ||||||
|  |                     return; | ||||||
|  |                 let value = payload[key]; | ||||||
|  |                 if (targetFieldSchema === null || targetFieldSchema === void 0 ? void 0 : targetFieldSchema.encrypted) { | ||||||
|  |                     value = (0, encrypt_1.default)({ data: value }); | ||||||
|  |                 } | ||||||
|  |                 finalData[key] = value; | ||||||
|  |             }); | ||||||
|  |             if (finalData.password && typeof finalData.password == "string") { | ||||||
|  |                 finalData.password = (0, hashPassword_1.default)({ password: finalData.password }); | ||||||
|  |             } | ||||||
|  |             return finalData; | ||||||
|  |         })(); | ||||||
|  |         const updateUser = yield (0, updateDbEntry_1.default)({ | ||||||
|  |             dbContext: "Dsql User", | ||||||
|  |             paradigm: "Full Access", | ||||||
|  |             dbFullName, | ||||||
|  |             tableName: "users", | ||||||
|  |             identifierColumnName: "id", | ||||||
|  |             identifierValue: updatedUserId, | ||||||
|  |             data: data, | ||||||
|  |             useLocal, | ||||||
|  |         }); | ||||||
|  |         return { | ||||||
|  |             success: true, | ||||||
|  |             payload: updateUser, | ||||||
|  |         }; | ||||||
|  |     }); | ||||||
|  | } | ||||||
							
								
								
									
										17
									
								
								dist/package-shared/functions/api/users/social/api-github-login.d.ts
									
									
									
									
										vendored
									
									
										Normal file
									
								
							
							
						
						
									
										17
									
								
								dist/package-shared/functions/api/users/social/api-github-login.d.ts
									
									
									
									
										vendored
									
									
										Normal file
									
								
							| @ -0,0 +1,17 @@ | |||||||
|  | import { APILoginFunctionReturn } from "../../../../types"; | ||||||
|  | type Param = { | ||||||
|  |     code?: string; | ||||||
|  |     clientId?: string; | ||||||
|  |     clientSecret?: string; | ||||||
|  |     database?: string; | ||||||
|  |     additionalFields?: string[]; | ||||||
|  |     additionalData?: { | ||||||
|  |         [s: string]: string | number; | ||||||
|  |     }; | ||||||
|  |     email?: string; | ||||||
|  | }; | ||||||
|  | /** | ||||||
|  |  * # API Login with Github | ||||||
|  |  */ | ||||||
|  | export default function apiGithubLogin({ code, clientId, clientSecret, database, additionalFields, email, additionalData, }: Param): Promise<APILoginFunctionReturn>; | ||||||
|  | export {}; | ||||||
							
								
								
									
										89
									
								
								dist/package-shared/functions/api/users/social/api-github-login.js
									
									
									
									
										vendored
									
									
										Normal file
									
								
							
							
						
						
									
										89
									
								
								dist/package-shared/functions/api/users/social/api-github-login.js
									
									
									
									
										vendored
									
									
										Normal file
									
								
							| @ -0,0 +1,89 @@ | |||||||
|  | "use strict"; | ||||||
|  | var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { | ||||||
|  |     function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } | ||||||
|  |     return new (P || (P = Promise))(function (resolve, reject) { | ||||||
|  |         function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } | ||||||
|  |         function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } | ||||||
|  |         function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } | ||||||
|  |         step((generator = generator.apply(thisArg, _arguments || [])).next()); | ||||||
|  |     }); | ||||||
|  | }; | ||||||
|  | var __importDefault = (this && this.__importDefault) || function (mod) { | ||||||
|  |     return (mod && mod.__esModule) ? mod : { "default": mod }; | ||||||
|  | }; | ||||||
|  | Object.defineProperty(exports, "__esModule", { value: true }); | ||||||
|  | exports.default = apiGithubLogin; | ||||||
|  | const handleSocialDb_1 = __importDefault(require("../../social-login/handleSocialDb")); | ||||||
|  | const githubLogin_1 = __importDefault(require("../../social-login/githubLogin")); | ||||||
|  | const camelJoinedtoCamelSpace_1 = __importDefault(require("../../../../utils/camelJoinedtoCamelSpace")); | ||||||
|  | /** | ||||||
|  |  * # API Login with Github | ||||||
|  |  */ | ||||||
|  | function apiGithubLogin(_a) { | ||||||
|  |     return __awaiter(this, arguments, void 0, function* ({ code, clientId, clientSecret, database, additionalFields, email, additionalData, }) { | ||||||
|  |         if (!code || !clientId || !clientSecret || !database) { | ||||||
|  |             return { | ||||||
|  |                 success: false, | ||||||
|  |                 msg: "Missing query params", | ||||||
|  |             }; | ||||||
|  |         } | ||||||
|  |         if (typeof code !== "string" || | ||||||
|  |             typeof clientId !== "string" || | ||||||
|  |             typeof clientSecret !== "string" || | ||||||
|  |             typeof database !== "string") { | ||||||
|  |             return { | ||||||
|  |                 success: false, | ||||||
|  |                 msg: "Wrong Parameters", | ||||||
|  |             }; | ||||||
|  |         } | ||||||
|  |         /** | ||||||
|  |          * Create new user folder and file | ||||||
|  |          * | ||||||
|  |          * @description Create new user folder and file | ||||||
|  |          */ | ||||||
|  |         const gitHubUser = yield (0, githubLogin_1.default)({ | ||||||
|  |             code: code, | ||||||
|  |             clientId: clientId, | ||||||
|  |             clientSecret: clientSecret, | ||||||
|  |         }); | ||||||
|  |         if (!gitHubUser) { | ||||||
|  |             return { | ||||||
|  |                 success: false, | ||||||
|  |                 msg: "No github user returned", | ||||||
|  |             }; | ||||||
|  |         } | ||||||
|  |         const socialId = gitHubUser.name || gitHubUser.id || gitHubUser.login; | ||||||
|  |         const targetName = gitHubUser.name || gitHubUser.login; | ||||||
|  |         const nameArray = (targetName === null || targetName === void 0 ? void 0 : targetName.match(/ /)) | ||||||
|  |             ? targetName === null || targetName === void 0 ? void 0 : targetName.split(" ") | ||||||
|  |             : (targetName === null || targetName === void 0 ? void 0 : targetName.match(/\-/)) | ||||||
|  |                 ? targetName === null || targetName === void 0 ? void 0 : targetName.split("-") | ||||||
|  |                 : [targetName]; | ||||||
|  |         let payload = { | ||||||
|  |             email: gitHubUser.email, | ||||||
|  |             first_name: (0, camelJoinedtoCamelSpace_1.default)(nameArray[0]), | ||||||
|  |             last_name: (0, camelJoinedtoCamelSpace_1.default)(nameArray[1]), | ||||||
|  |             social_id: socialId, | ||||||
|  |             social_platform: "github", | ||||||
|  |             image: gitHubUser.avatar_url, | ||||||
|  |             image_thumbnail: gitHubUser.avatar_url, | ||||||
|  |             username: "github-user-" + socialId, | ||||||
|  |         }; | ||||||
|  |         if (additionalData) { | ||||||
|  |             payload = Object.assign(Object.assign({}, payload), additionalData); | ||||||
|  |         } | ||||||
|  |         const loggedInGithubUser = yield (0, handleSocialDb_1.default)({ | ||||||
|  |             database, | ||||||
|  |             email: gitHubUser.email, | ||||||
|  |             payload, | ||||||
|  |             social_platform: "github", | ||||||
|  |             social_id: socialId, | ||||||
|  |             supEmail: email, | ||||||
|  |             additionalFields, | ||||||
|  |         }); | ||||||
|  |         ////////////////////////////////////////////////
 | ||||||
|  |         ////////////////////////////////////////////////
 | ||||||
|  |         ////////////////////////////////////////////////
 | ||||||
|  |         return Object.assign({}, loggedInGithubUser); | ||||||
|  |     }); | ||||||
|  | } | ||||||
							
								
								
									
										5
									
								
								dist/package-shared/functions/api/users/social/api-google-login.d.ts
									
									
									
									
										vendored
									
									
										Normal file
									
								
							
							
						
						
									
										5
									
								
								dist/package-shared/functions/api/users/social/api-google-login.d.ts
									
									
									
									
										vendored
									
									
										Normal file
									
								
							| @ -0,0 +1,5 @@ | |||||||
|  | import { APIGoogleLoginFunctionParams, APILoginFunctionReturn } from "../../../../types"; | ||||||
|  | /** | ||||||
|  |  * # API google login | ||||||
|  |  */ | ||||||
|  | export default function apiGoogleLogin({ token, database, additionalFields, additionalData, }: APIGoogleLoginFunctionParams): Promise<APILoginFunctionReturn>; | ||||||
							
								
								
									
										99
									
								
								dist/package-shared/functions/api/users/social/api-google-login.js
									
									
									
									
										vendored
									
									
										Normal file
									
								
							
							
						
						
									
										99
									
								
								dist/package-shared/functions/api/users/social/api-google-login.js
									
									
									
									
										vendored
									
									
										Normal file
									
								
							| @ -0,0 +1,99 @@ | |||||||
|  | "use strict"; | ||||||
|  | var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { | ||||||
|  |     function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } | ||||||
|  |     return new (P || (P = Promise))(function (resolve, reject) { | ||||||
|  |         function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } | ||||||
|  |         function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } | ||||||
|  |         function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } | ||||||
|  |         step((generator = generator.apply(thisArg, _arguments || [])).next()); | ||||||
|  |     }); | ||||||
|  | }; | ||||||
|  | var __importDefault = (this && this.__importDefault) || function (mod) { | ||||||
|  |     return (mod && mod.__esModule) ? mod : { "default": mod }; | ||||||
|  | }; | ||||||
|  | Object.defineProperty(exports, "__esModule", { value: true }); | ||||||
|  | exports.default = apiGoogleLogin; | ||||||
|  | const https_1 = __importDefault(require("https")); | ||||||
|  | const handleSocialDb_1 = __importDefault(require("../../social-login/handleSocialDb")); | ||||||
|  | const ejson_1 = __importDefault(require("../../../../utils/ejson")); | ||||||
|  | /** | ||||||
|  |  * # API google login | ||||||
|  |  */ | ||||||
|  | function apiGoogleLogin(_a) { | ||||||
|  |     return __awaiter(this, arguments, void 0, function* ({ token, database, additionalFields, additionalData, }) { | ||||||
|  |         try { | ||||||
|  |             const gUser = yield new Promise((resolve, reject) => { | ||||||
|  |                 https_1.default | ||||||
|  |                     .request({ | ||||||
|  |                     method: "GET", | ||||||
|  |                     hostname: "www.googleapis.com", | ||||||
|  |                     path: "/oauth2/v3/userinfo", | ||||||
|  |                     headers: { | ||||||
|  |                         Authorization: `Bearer ${token}`, | ||||||
|  |                     }, | ||||||
|  |                 }, (res) => { | ||||||
|  |                     let data = ""; | ||||||
|  |                     res.on("data", (chunk) => { | ||||||
|  |                         data += chunk; | ||||||
|  |                     }); | ||||||
|  |                     res.on("end", () => { | ||||||
|  |                         resolve(ejson_1.default.parse(data)); | ||||||
|  |                     }); | ||||||
|  |                 }) | ||||||
|  |                     .end(); | ||||||
|  |             }); | ||||||
|  |             if (!(gUser === null || gUser === void 0 ? void 0 : gUser.email_verified)) | ||||||
|  |                 throw new Error("No Google User."); | ||||||
|  |             ////////////////////////////////////////
 | ||||||
|  |             ////////////////////////////////////////
 | ||||||
|  |             ////////////////////////////////////////
 | ||||||
|  |             if (!database || typeof database != "string" || (database === null || database === void 0 ? void 0 : database.match(/ /))) { | ||||||
|  |                 return { | ||||||
|  |                     success: false, | ||||||
|  |                     payload: undefined, | ||||||
|  |                     msg: "Please provide a database slug(database name in lowercase with no spaces)", | ||||||
|  |                 }; | ||||||
|  |             } | ||||||
|  |             /** | ||||||
|  |              * Create new user folder and file | ||||||
|  |              * | ||||||
|  |              * @description Create new user folder and file | ||||||
|  |              */ | ||||||
|  |             const { given_name, family_name, email, sub, picture } = gUser; | ||||||
|  |             /** @type {Object<string, any>} */ | ||||||
|  |             let payloadObject = { | ||||||
|  |                 email: email, | ||||||
|  |                 first_name: given_name, | ||||||
|  |                 last_name: family_name, | ||||||
|  |                 social_id: sub, | ||||||
|  |                 social_platform: "google", | ||||||
|  |                 image: picture, | ||||||
|  |                 image_thumbnail: picture, | ||||||
|  |                 username: `google-user-${sub}`, | ||||||
|  |             }; | ||||||
|  |             if (additionalData) { | ||||||
|  |                 payloadObject = Object.assign(Object.assign({}, payloadObject), additionalData); | ||||||
|  |             } | ||||||
|  |             const loggedInGoogleUser = yield (0, handleSocialDb_1.default)({ | ||||||
|  |                 database, | ||||||
|  |                 email: email || "", | ||||||
|  |                 payload: payloadObject, | ||||||
|  |                 social_platform: "google", | ||||||
|  |                 social_id: sub, | ||||||
|  |                 additionalFields, | ||||||
|  |             }); | ||||||
|  |             ////////////////////////////////////////
 | ||||||
|  |             ////////////////////////////////////////
 | ||||||
|  |             ////////////////////////////////////////
 | ||||||
|  |             return Object.assign({}, loggedInGoogleUser); | ||||||
|  |         } | ||||||
|  |         catch ( /** @type {any} */error) { | ||||||
|  |             console.log(`apo-google-login.js ERROR: ${error.message}`); | ||||||
|  |             return { | ||||||
|  |                 success: false, | ||||||
|  |                 payload: undefined, | ||||||
|  |                 msg: error.message, | ||||||
|  |             }; | ||||||
|  |         } | ||||||
|  |     }); | ||||||
|  | } | ||||||
							
								
								
									
										21
									
								
								dist/package-shared/functions/backend/addAdminUserOnLogin.d.ts
									
									
									
									
										vendored
									
									
										Normal file
									
								
							
							
						
						
									
										21
									
								
								dist/package-shared/functions/backend/addAdminUserOnLogin.d.ts
									
									
									
									
										vendored
									
									
										Normal file
									
								
							| @ -0,0 +1,21 @@ | |||||||
|  | import { DATASQUIREL_LoggedInUser } from "../../types"; | ||||||
|  | type Param = { | ||||||
|  |     query: { | ||||||
|  |         invite: number; | ||||||
|  |         database_access: string; | ||||||
|  |         priviledge: string; | ||||||
|  |         email: string; | ||||||
|  |     }; | ||||||
|  |     useLocal?: boolean; | ||||||
|  |     user: DATASQUIREL_LoggedInUser; | ||||||
|  | }; | ||||||
|  | /** | ||||||
|  |  * Add Admin User on Login | ||||||
|  |  * ============================================================================== | ||||||
|  |  * | ||||||
|  |  * @description this function handles admin users that have been invited by another | ||||||
|  |  * admin user. This fires when the invited user has been logged in or a new account | ||||||
|  |  * has been created for the invited user | ||||||
|  |  */ | ||||||
|  | export default function addAdminUserOnLogin({ query, user, useLocal, }: Param): Promise<any>; | ||||||
|  | export {}; | ||||||
							
								
								
									
										110
									
								
								dist/package-shared/functions/backend/addAdminUserOnLogin.js
									
									
									
									
										vendored
									
									
										Normal file
									
								
							
							
						
						
									
										110
									
								
								dist/package-shared/functions/backend/addAdminUserOnLogin.js
									
									
									
									
										vendored
									
									
										Normal file
									
								
							| @ -0,0 +1,110 @@ | |||||||
|  | "use strict"; | ||||||
|  | var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { | ||||||
|  |     function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } | ||||||
|  |     return new (P || (P = Promise))(function (resolve, reject) { | ||||||
|  |         function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } | ||||||
|  |         function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } | ||||||
|  |         function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } | ||||||
|  |         step((generator = generator.apply(thisArg, _arguments || [])).next()); | ||||||
|  |     }); | ||||||
|  | }; | ||||||
|  | var __importDefault = (this && this.__importDefault) || function (mod) { | ||||||
|  |     return (mod && mod.__esModule) ? mod : { "default": mod }; | ||||||
|  | }; | ||||||
|  | Object.defineProperty(exports, "__esModule", { value: true }); | ||||||
|  | exports.default = addAdminUserOnLogin; | ||||||
|  | const serverError_1 = __importDefault(require("./serverError")); | ||||||
|  | const DB_HANDLER_1 = __importDefault(require("../../utils/backend/global-db/DB_HANDLER")); | ||||||
|  | const addDbEntry_1 = __importDefault(require("./db/addDbEntry")); | ||||||
|  | const LOCAL_DB_HANDLER_1 = __importDefault(require("../../utils/backend/global-db/LOCAL_DB_HANDLER")); | ||||||
|  | /** | ||||||
|  |  * Add Admin User on Login | ||||||
|  |  * ============================================================================== | ||||||
|  |  * | ||||||
|  |  * @description this function handles admin users that have been invited by another | ||||||
|  |  * admin user. This fires when the invited user has been logged in or a new account | ||||||
|  |  * has been created for the invited user | ||||||
|  |  */ | ||||||
|  | function addAdminUserOnLogin(_a) { | ||||||
|  |     return __awaiter(this, arguments, void 0, function* ({ query, user, useLocal, }) { | ||||||
|  |         try { | ||||||
|  |             const finalDbHandler = useLocal ? LOCAL_DB_HANDLER_1.default : DB_HANDLER_1.default; | ||||||
|  |             const { invite, database_access, priviledge, email } = query; | ||||||
|  |             const lastInviteTimeQuery = `SELECT date_created_code FROM invitations WHERE inviting_user_id=? AND invited_user_email=?`; | ||||||
|  |             const lastInviteTimeValues = [invite, email]; | ||||||
|  |             const lastInviteTimeArray = yield finalDbHandler(lastInviteTimeQuery, lastInviteTimeValues); | ||||||
|  |             if (!lastInviteTimeArray || !lastInviteTimeArray[0]) { | ||||||
|  |                 throw new Error("No Invitation Found"); | ||||||
|  |             } | ||||||
|  |             ////////////////////////////////////////////////
 | ||||||
|  |             ////////////////////////////////////////////////
 | ||||||
|  |             ////////////////////////////////////////////////
 | ||||||
|  |             const invitingUserDbQuery = `SELECT first_name,last_name,email FROM users WHERE id=?`; | ||||||
|  |             const invitingUserDbValues = [invite]; | ||||||
|  |             const invitingUserDb = yield finalDbHandler(invitingUserDbQuery, invitingUserDbValues); | ||||||
|  |             if (invitingUserDb === null || invitingUserDb === void 0 ? void 0 : invitingUserDb[0]) { | ||||||
|  |                 const existingUserUser = yield finalDbHandler(`SELECT email FROM user_users WHERE user_id=? AND invited_user_id=? AND user_type='admin' AND email=?`, [invite, user.id, email]); | ||||||
|  |                 if (existingUserUser === null || existingUserUser === void 0 ? void 0 : existingUserUser[0]) { | ||||||
|  |                     console.log("User already added"); | ||||||
|  |                 } | ||||||
|  |                 else { | ||||||
|  |                     (0, addDbEntry_1.default)({ | ||||||
|  |                         dbFullName: "datasquirel", | ||||||
|  |                         tableName: "user_users", | ||||||
|  |                         data: { | ||||||
|  |                             user_id: invite, | ||||||
|  |                             invited_user_id: user.id, | ||||||
|  |                             database_access: database_access, | ||||||
|  |                             first_name: user.first_name, | ||||||
|  |                             last_name: user.last_name, | ||||||
|  |                             phone: user.phone, | ||||||
|  |                             email: user.email, | ||||||
|  |                             username: user.username, | ||||||
|  |                             user_type: "admin", | ||||||
|  |                             user_priviledge: priviledge, | ||||||
|  |                             image: user.image, | ||||||
|  |                             image_thumbnail: user.image_thumbnail, | ||||||
|  |                         }, | ||||||
|  |                         useLocal, | ||||||
|  |                     }); | ||||||
|  |                     ////////////////////////////////////////////////
 | ||||||
|  |                     ////////////////////////////////////////////////
 | ||||||
|  |                     ////////////////////////////////////////////////
 | ||||||
|  |                     const dbTableData = yield finalDbHandler(`SELECT db_tables_data FROM invitations WHERE inviting_user_id=? AND invited_user_email=?`, [invite, email]); | ||||||
|  |                     const clearEntries = yield finalDbHandler(`DELETE FROM delegated_user_tables WHERE root_user_id=? AND delegated_user_id=?`, [invite, user.id]); | ||||||
|  |                     ////////////////////////////////////////////////
 | ||||||
|  |                     ////////////////////////////////////////////////
 | ||||||
|  |                     ////////////////////////////////////////////////
 | ||||||
|  |                     if (dbTableData && dbTableData[0]) { | ||||||
|  |                         const dbTableEntries = dbTableData[0].db_tables_data.split("|"); | ||||||
|  |                         for (let i = 0; i < dbTableEntries.length; i++) { | ||||||
|  |                             const dbTableEntry = dbTableEntries[i]; | ||||||
|  |                             const dbTableEntryArray = dbTableEntry.split("-"); | ||||||
|  |                             const [db_slug, table_slug] = dbTableEntryArray; | ||||||
|  |                             const newEntry = yield (0, addDbEntry_1.default)({ | ||||||
|  |                                 dbFullName: "datasquirel", | ||||||
|  |                                 tableName: "delegated_user_tables", | ||||||
|  |                                 data: { | ||||||
|  |                                     delegated_user_id: user.id, | ||||||
|  |                                     root_user_id: invite, | ||||||
|  |                                     database: db_slug, | ||||||
|  |                                     table: table_slug, | ||||||
|  |                                     priviledge: priviledge, | ||||||
|  |                                 }, | ||||||
|  |                                 useLocal, | ||||||
|  |                             }); | ||||||
|  |                         } | ||||||
|  |                     } | ||||||
|  |                 } | ||||||
|  |                 const inviteAccepted = yield finalDbHandler(`UPDATE invitations SET invitation_status='Accepted' WHERE inviting_user_id=? AND invited_user_email=?`, [invite, email]); | ||||||
|  |             } | ||||||
|  |         } | ||||||
|  |         catch (error) { | ||||||
|  |             (0, serverError_1.default)({ | ||||||
|  |                 component: "addAdminUserOnLogin", | ||||||
|  |                 message: error.message, | ||||||
|  |                 user: user, | ||||||
|  |             }); | ||||||
|  |         } | ||||||
|  |     }); | ||||||
|  | } | ||||||
							
								
								
									
										9
									
								
								dist/package-shared/functions/backend/addMariadbUser.d.ts
									
									
									
									
										vendored
									
									
										Normal file
									
								
							
							
						
						
									
										9
									
								
								dist/package-shared/functions/backend/addMariadbUser.d.ts
									
									
									
									
										vendored
									
									
										Normal file
									
								
							| @ -0,0 +1,9 @@ | |||||||
|  | type Param = { | ||||||
|  |     userId: number | string; | ||||||
|  |     useLocal?: boolean; | ||||||
|  | }; | ||||||
|  | /** | ||||||
|  |  * # Add Mariadb User | ||||||
|  |  */ | ||||||
|  | export default function addMariadbUser({ userId, useLocal, }: Param): Promise<any>; | ||||||
|  | export {}; | ||||||
							
								
								
									
										72
									
								
								dist/package-shared/functions/backend/addMariadbUser.js
									
									
									
									
										vendored
									
									
										Normal file
									
								
							
							
						
						
									
										72
									
								
								dist/package-shared/functions/backend/addMariadbUser.js
									
									
									
									
										vendored
									
									
										Normal file
									
								
							| @ -0,0 +1,72 @@ | |||||||
|  | "use strict"; | ||||||
|  | var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { | ||||||
|  |     function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } | ||||||
|  |     return new (P || (P = Promise))(function (resolve, reject) { | ||||||
|  |         function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } | ||||||
|  |         function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } | ||||||
|  |         function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } | ||||||
|  |         step((generator = generator.apply(thisArg, _arguments || [])).next()); | ||||||
|  |     }); | ||||||
|  | }; | ||||||
|  | var __importDefault = (this && this.__importDefault) || function (mod) { | ||||||
|  |     return (mod && mod.__esModule) ? mod : { "default": mod }; | ||||||
|  | }; | ||||||
|  | Object.defineProperty(exports, "__esModule", { value: true }); | ||||||
|  | exports.default = addMariadbUser; | ||||||
|  | const generate_password_1 = __importDefault(require("generate-password")); | ||||||
|  | const DB_HANDLER_1 = __importDefault(require("../../utils/backend/global-db/DB_HANDLER")); | ||||||
|  | const NO_DB_HANDLER_1 = __importDefault(require("../../utils/backend/global-db/NO_DB_HANDLER")); | ||||||
|  | const addDbEntry_1 = __importDefault(require("./db/addDbEntry")); | ||||||
|  | const encrypt_1 = __importDefault(require("../dsql/encrypt")); | ||||||
|  | const LOCAL_DB_HANDLER_1 = __importDefault(require("../../utils/backend/global-db/LOCAL_DB_HANDLER")); | ||||||
|  | /** | ||||||
|  |  * # Add Mariadb User | ||||||
|  |  */ | ||||||
|  | function addMariadbUser(_a) { | ||||||
|  |     return __awaiter(this, arguments, void 0, function* ({ userId, useLocal, }) { | ||||||
|  |         try { | ||||||
|  |             const defaultMariadbUserHost = process.env.DSQL_DB_HOST || "127.0.0.1"; | ||||||
|  |             const username = `dsql_user_${userId}`; | ||||||
|  |             const password = generate_password_1.default.generate({ | ||||||
|  |                 length: 16, | ||||||
|  |                 numbers: true, | ||||||
|  |                 symbols: true, | ||||||
|  |                 uppercase: true, | ||||||
|  |                 exclude: "*#.'`\"", | ||||||
|  |             }); | ||||||
|  |             const encryptedPassword = (0, encrypt_1.default)({ data: password }); | ||||||
|  |             const createMariadbUsersQuery = `CREATE USER IF NOT EXISTS '${username}'@'127.0.0.1' IDENTIFIED BY '${password}'`; | ||||||
|  |             if (useLocal) { | ||||||
|  |                 yield (0, LOCAL_DB_HANDLER_1.default)(createMariadbUsersQuery); | ||||||
|  |             } | ||||||
|  |             else { | ||||||
|  |                 yield (0, NO_DB_HANDLER_1.default)(createMariadbUsersQuery); | ||||||
|  |             } | ||||||
|  |             const updateUserQuery = `UPDATE users SET mariadb_user = ?, mariadb_host = '127.0.0.1', mariadb_pass = ? WHERE id = ?`; | ||||||
|  |             const updateUserValues = [username, encryptedPassword, userId]; | ||||||
|  |             const updateUser = useLocal | ||||||
|  |                 ? yield (0, LOCAL_DB_HANDLER_1.default)(updateUserQuery, updateUserValues) | ||||||
|  |                 : yield (0, DB_HANDLER_1.default)(updateUserQuery, updateUserValues); | ||||||
|  |             const addMariadbUser = yield (0, addDbEntry_1.default)({ | ||||||
|  |                 tableName: "mariadb_users", | ||||||
|  |                 data: { | ||||||
|  |                     user_id: userId, | ||||||
|  |                     username, | ||||||
|  |                     host: defaultMariadbUserHost, | ||||||
|  |                     password: encryptedPassword, | ||||||
|  |                     primary: "1", | ||||||
|  |                     grants: '[{"database":"*","table":"*","privileges":["ALL"]}]', | ||||||
|  |                 }, | ||||||
|  |                 dbContext: "Master", | ||||||
|  |                 useLocal, | ||||||
|  |             }); | ||||||
|  |             console.log(`User ${userId} SQL credentials successfully added.`); | ||||||
|  |         } | ||||||
|  |         catch ( /** @type {any} */error) { | ||||||
|  |             console.log(`Error in adding SQL user in 'addMariadbUser' function =>`, error.message); | ||||||
|  |         } | ||||||
|  |     }); | ||||||
|  | } | ||||||
|  | ////////////////////////////////////////////////
 | ||||||
|  | ////////////////////////////////////////////////
 | ||||||
|  | ////////////////////////////////////////////////
 | ||||||
							
								
								
									
										13
									
								
								dist/package-shared/functions/backend/addUsersTableToDb.d.ts
									
									
									
									
										vendored
									
									
										Normal file
									
								
							
							
						
						
									
										13
									
								
								dist/package-shared/functions/backend/addUsersTableToDb.d.ts
									
									
									
									
										vendored
									
									
										Normal file
									
								
							| @ -0,0 +1,13 @@ | |||||||
|  | type Param = { | ||||||
|  |     userId: number; | ||||||
|  |     database: string; | ||||||
|  |     useLocal?: boolean; | ||||||
|  |     payload?: { | ||||||
|  |         [s: string]: any; | ||||||
|  |     }; | ||||||
|  | }; | ||||||
|  | /** | ||||||
|  |  * # Add User Table to Database | ||||||
|  |  */ | ||||||
|  | export default function addUsersTableToDb({ userId, database, useLocal, payload, }: Param): Promise<any>; | ||||||
|  | export {}; | ||||||
							
								
								
									
										83
									
								
								dist/package-shared/functions/backend/addUsersTableToDb.js
									
									
									
									
										vendored
									
									
										Normal file
									
								
							
							
						
						
									
										83
									
								
								dist/package-shared/functions/backend/addUsersTableToDb.js
									
									
									
									
										vendored
									
									
										Normal file
									
								
							| @ -0,0 +1,83 @@ | |||||||
|  | "use strict"; | ||||||
|  | var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { | ||||||
|  |     function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } | ||||||
|  |     return new (P || (P = Promise))(function (resolve, reject) { | ||||||
|  |         function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } | ||||||
|  |         function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } | ||||||
|  |         function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } | ||||||
|  |         step((generator = generator.apply(thisArg, _arguments || [])).next()); | ||||||
|  |     }); | ||||||
|  | }; | ||||||
|  | var __importDefault = (this && this.__importDefault) || function (mod) { | ||||||
|  |     return (mod && mod.__esModule) ? mod : { "default": mod }; | ||||||
|  | }; | ||||||
|  | Object.defineProperty(exports, "__esModule", { value: true }); | ||||||
|  | exports.default = addUsersTableToDb; | ||||||
|  | const serverError_1 = __importDefault(require("./serverError")); | ||||||
|  | const DB_HANDLER_1 = __importDefault(require("../../utils/backend/global-db/DB_HANDLER")); | ||||||
|  | const grabUserSchemaData_1 = __importDefault(require("./grabUserSchemaData")); | ||||||
|  | const setUserSchemaData_1 = __importDefault(require("./setUserSchemaData")); | ||||||
|  | const addDbEntry_1 = __importDefault(require("./db/addDbEntry")); | ||||||
|  | const createDbFromSchema_1 = __importDefault(require("../../shell/createDbFromSchema")); | ||||||
|  | const LOCAL_DB_HANDLER_1 = __importDefault(require("../../utils/backend/global-db/LOCAL_DB_HANDLER")); | ||||||
|  | const grabNewUsersTableSchema_1 = __importDefault(require("./grabNewUsersTableSchema")); | ||||||
|  | /** | ||||||
|  |  * # Add User Table to Database | ||||||
|  |  */ | ||||||
|  | function addUsersTableToDb(_a) { | ||||||
|  |     return __awaiter(this, arguments, void 0, function* ({ userId, database, useLocal, payload, }) { | ||||||
|  |         try { | ||||||
|  |             const dbFullName = database; | ||||||
|  |             const userPreset = (0, grabNewUsersTableSchema_1.default)({ payload }); | ||||||
|  |             if (!userPreset) | ||||||
|  |                 throw new Error("Couldn't Get User Preset!"); | ||||||
|  |             const userSchemaData = (0, grabUserSchemaData_1.default)({ userId }); | ||||||
|  |             if (!userSchemaData) | ||||||
|  |                 throw new Error("User schema data not found!"); | ||||||
|  |             let targetDatabase = userSchemaData.find((db) => db.dbFullName === database); | ||||||
|  |             if (!targetDatabase) { | ||||||
|  |                 throw new Error("Couldn't Find Target Database!"); | ||||||
|  |             } | ||||||
|  |             let existingTableIndex = targetDatabase === null || targetDatabase === void 0 ? void 0 : targetDatabase.tables.findIndex((table) => table.tableName === "users"); | ||||||
|  |             if (typeof existingTableIndex == "number" && existingTableIndex > 0) { | ||||||
|  |                 targetDatabase.tables[existingTableIndex] = userPreset; | ||||||
|  |             } | ||||||
|  |             else { | ||||||
|  |                 targetDatabase.tables.push(userPreset); | ||||||
|  |             } | ||||||
|  |             (0, setUserSchemaData_1.default)({ schemaData: userSchemaData, userId }); | ||||||
|  |             /** @type {any[] | null} */ | ||||||
|  |             const targetDb = useLocal | ||||||
|  |                 ? yield (0, LOCAL_DB_HANDLER_1.default)(`SELECT id FROM user_databases WHERE user_id=? AND db_slug=?`, [userId, database]) | ||||||
|  |                 : yield (0, DB_HANDLER_1.default)(`SELECT id FROM user_databases WHERE user_id=? AND db_slug=?`, [userId, database]); | ||||||
|  |             if (targetDb === null || targetDb === void 0 ? void 0 : targetDb[0]) { | ||||||
|  |                 const newTableEntry = yield (0, addDbEntry_1.default)({ | ||||||
|  |                     dbFullName: "datasquirel", | ||||||
|  |                     tableName: "user_database_tables", | ||||||
|  |                     data: { | ||||||
|  |                         user_id: userId, | ||||||
|  |                         db_id: targetDb[0].id, | ||||||
|  |                         db_slug: targetDatabase.dbSlug, | ||||||
|  |                         table_name: "Users", | ||||||
|  |                         table_slug: "users", | ||||||
|  |                     }, | ||||||
|  |                     useLocal, | ||||||
|  |                 }); | ||||||
|  |             } | ||||||
|  |             const dbShellUpdate = yield (0, createDbFromSchema_1.default)({ | ||||||
|  |                 userId, | ||||||
|  |                 targetDatabase: dbFullName, | ||||||
|  |             }); | ||||||
|  |             return `Done!`; | ||||||
|  |         } | ||||||
|  |         catch ( /** @type {any} */error) { | ||||||
|  |             console.log(`addUsersTableToDb.js ERROR: ${error.message}`); | ||||||
|  |             (0, serverError_1.default)({ | ||||||
|  |                 component: "addUsersTableToDb", | ||||||
|  |                 message: error.message, | ||||||
|  |                 user: { id: userId }, | ||||||
|  |             }); | ||||||
|  |             return error.message; | ||||||
|  |         } | ||||||
|  |     }); | ||||||
|  | } | ||||||
							
								
								
									
										6
									
								
								dist/package-shared/functions/backend/api-cred.d.ts
									
									
									
									
										vendored
									
									
										Normal file
									
								
							
							
						
						
									
										6
									
								
								dist/package-shared/functions/backend/api-cred.d.ts
									
									
									
									
										vendored
									
									
										Normal file
									
								
							| @ -0,0 +1,6 @@ | |||||||
|  | import { CheckApiCredentialsFn } from "../../types"; | ||||||
|  | /** | ||||||
|  |  * # Grap API Credentials | ||||||
|  |  */ | ||||||
|  | declare const grabApiCred: CheckApiCredentialsFn; | ||||||
|  | export default grabApiCred; | ||||||
							
								
								
									
										50
									
								
								dist/package-shared/functions/backend/api-cred.js
									
									
									
									
										vendored
									
									
										Normal file
									
								
							
							
						
						
									
										50
									
								
								dist/package-shared/functions/backend/api-cred.js
									
									
									
									
										vendored
									
									
										Normal file
									
								
							| @ -0,0 +1,50 @@ | |||||||
|  | "use strict"; | ||||||
|  | var __importDefault = (this && this.__importDefault) || function (mod) { | ||||||
|  |     return (mod && mod.__esModule) ? mod : { "default": mod }; | ||||||
|  | }; | ||||||
|  | Object.defineProperty(exports, "__esModule", { value: true }); | ||||||
|  | const fs_1 = __importDefault(require("fs")); | ||||||
|  | const decrypt_1 = __importDefault(require("../dsql/decrypt")); | ||||||
|  | /** | ||||||
|  |  * # Grap API Credentials | ||||||
|  |  */ | ||||||
|  | const grabApiCred = ({ key, database, table, user_id, media, }) => { | ||||||
|  |     var _a, _b; | ||||||
|  |     if (!key) | ||||||
|  |         return null; | ||||||
|  |     if (!user_id) | ||||||
|  |         return null; | ||||||
|  |     try { | ||||||
|  |         const allowedKeysPath = process.env.DSQL_API_KEYS_PATH; | ||||||
|  |         if (!allowedKeysPath) | ||||||
|  |             throw new Error("process.env.DSQL_API_KEYS_PATH variable not found"); | ||||||
|  |         const ApiJSON = (0, decrypt_1.default)({ encryptedString: key }); | ||||||
|  |         /** @type {import("../../types").ApiKeyObject} */ | ||||||
|  |         const ApiObject = JSON.parse(ApiJSON || ""); | ||||||
|  |         const isApiKeyValid = fs_1.default.existsSync(`${allowedKeysPath}/${ApiObject.sign}`); | ||||||
|  |         if (String(ApiObject.user_id) !== String(user_id)) | ||||||
|  |             return null; | ||||||
|  |         if (!isApiKeyValid) | ||||||
|  |             return null; | ||||||
|  |         if (!ApiObject.target_database) | ||||||
|  |             return ApiObject; | ||||||
|  |         if (media) | ||||||
|  |             return ApiObject; | ||||||
|  |         if (!database && ApiObject.target_database) | ||||||
|  |             return null; | ||||||
|  |         const isDatabaseAllowed = (_a = ApiObject.target_database) === null || _a === void 0 ? void 0 : _a.split(",").includes(String(database)); | ||||||
|  |         if (isDatabaseAllowed && !ApiObject.target_table) | ||||||
|  |             return ApiObject; | ||||||
|  |         if (isDatabaseAllowed && !table && ApiObject.target_table) | ||||||
|  |             return null; | ||||||
|  |         const isTableAllowed = (_b = ApiObject.target_table) === null || _b === void 0 ? void 0 : _b.split(",").includes(String(table)); | ||||||
|  |         if (isTableAllowed) | ||||||
|  |             return ApiObject; | ||||||
|  |         return null; | ||||||
|  |     } | ||||||
|  |     catch ( /** @type {any} */error) { | ||||||
|  |         console.log(`api-cred ERROR: ${error.message}`); | ||||||
|  |         return { error: `api-cred ERROR: ${error.message}` }; | ||||||
|  |     } | ||||||
|  | }; | ||||||
|  | exports.default = grabApiCred; | ||||||
							
								
								
									
										23
									
								
								dist/package-shared/functions/backend/auth/write-auth-files.d.ts
									
									
									
									
										vendored
									
									
										Normal file
									
								
							
							
						
						
									
										23
									
								
								dist/package-shared/functions/backend/auth/write-auth-files.d.ts
									
									
									
									
										vendored
									
									
										Normal file
									
								
							| @ -0,0 +1,23 @@ | |||||||
|  | export declare const grabAuthDirs: () => { | ||||||
|  |     root: string; | ||||||
|  |     auth: string; | ||||||
|  | }; | ||||||
|  | export declare const initAuthFiles: () => boolean; | ||||||
|  | /** | ||||||
|  |  * # Write Auth Files | ||||||
|  |  */ | ||||||
|  | export declare const writeAuthFile: (name: string, data: string) => boolean; | ||||||
|  | /** | ||||||
|  |  * # Get Auth Files | ||||||
|  |  */ | ||||||
|  | export declare const getAuthFile: (name: string) => string | null; | ||||||
|  | /** | ||||||
|  |  * # Delete Auth Files | ||||||
|  |  * @param {string} name | ||||||
|  |  */ | ||||||
|  | export declare const deleteAuthFile: (name: string) => void | null; | ||||||
|  | /** | ||||||
|  |  * # Delete Auth Files | ||||||
|  |  * @param {string} name | ||||||
|  |  */ | ||||||
|  | export declare const checkAuthFile: (name: string) => boolean; | ||||||
							
								
								
									
										90
									
								
								dist/package-shared/functions/backend/auth/write-auth-files.js
									
									
									
									
										vendored
									
									
										Normal file
									
								
							
							
						
						
									
										90
									
								
								dist/package-shared/functions/backend/auth/write-auth-files.js
									
									
									
									
										vendored
									
									
										Normal file
									
								
							| @ -0,0 +1,90 @@ | |||||||
|  | "use strict"; | ||||||
|  | var __importDefault = (this && this.__importDefault) || function (mod) { | ||||||
|  |     return (mod && mod.__esModule) ? mod : { "default": mod }; | ||||||
|  | }; | ||||||
|  | Object.defineProperty(exports, "__esModule", { value: true }); | ||||||
|  | exports.checkAuthFile = exports.deleteAuthFile = exports.getAuthFile = exports.writeAuthFile = exports.initAuthFiles = exports.grabAuthDirs = void 0; | ||||||
|  | const fs_1 = __importDefault(require("fs")); | ||||||
|  | const path_1 = __importDefault(require("path")); | ||||||
|  | const grabAuthDirs = () => { | ||||||
|  |     const DSQL_AUTH_DIR = process.env.DSQL_AUTH_DIR; | ||||||
|  |     const ROOT_DIR = (DSQL_AUTH_DIR === null || DSQL_AUTH_DIR === void 0 ? void 0 : DSQL_AUTH_DIR.match(/./)) | ||||||
|  |         ? DSQL_AUTH_DIR | ||||||
|  |         : path_1.default.resolve(process.cwd(), "./.tmp"); | ||||||
|  |     const AUTH_DIR = path_1.default.join(ROOT_DIR, "logins"); | ||||||
|  |     return { root: ROOT_DIR, auth: AUTH_DIR }; | ||||||
|  | }; | ||||||
|  | exports.grabAuthDirs = grabAuthDirs; | ||||||
|  | const initAuthFiles = () => { | ||||||
|  |     try { | ||||||
|  |         const authDirs = (0, exports.grabAuthDirs)(); | ||||||
|  |         if (!fs_1.default.existsSync(authDirs.root)) | ||||||
|  |             fs_1.default.mkdirSync(authDirs.root, { recursive: true }); | ||||||
|  |         if (!fs_1.default.existsSync(authDirs.auth)) | ||||||
|  |             fs_1.default.mkdirSync(authDirs.auth, { recursive: true }); | ||||||
|  |         return true; | ||||||
|  |     } | ||||||
|  |     catch (error) { | ||||||
|  |         console.log(`Error initializing Auth Files: ${error.message}`); | ||||||
|  |         return false; | ||||||
|  |     } | ||||||
|  | }; | ||||||
|  | exports.initAuthFiles = initAuthFiles; | ||||||
|  | /** | ||||||
|  |  * # Write Auth Files | ||||||
|  |  */ | ||||||
|  | const writeAuthFile = (name, data) => { | ||||||
|  |     (0, exports.initAuthFiles)(); | ||||||
|  |     try { | ||||||
|  |         fs_1.default.writeFileSync(path_1.default.join((0, exports.grabAuthDirs)().auth, name), data); | ||||||
|  |         return true; | ||||||
|  |     } | ||||||
|  |     catch ( /** @type {any} */error) { | ||||||
|  |         console.log(`Error writing Auth File: ${error.message}`); | ||||||
|  |         return false; | ||||||
|  |     } | ||||||
|  | }; | ||||||
|  | exports.writeAuthFile = writeAuthFile; | ||||||
|  | /** | ||||||
|  |  * # Get Auth Files | ||||||
|  |  */ | ||||||
|  | const getAuthFile = (name) => { | ||||||
|  |     try { | ||||||
|  |         const authFilePath = path_1.default.join((0, exports.grabAuthDirs)().auth, name); | ||||||
|  |         return fs_1.default.readFileSync(authFilePath, "utf-8"); | ||||||
|  |     } | ||||||
|  |     catch ( /** @type {any} */error) { | ||||||
|  |         console.log(`Error getting Auth File: ${error.message}`); | ||||||
|  |         return null; | ||||||
|  |     } | ||||||
|  | }; | ||||||
|  | exports.getAuthFile = getAuthFile; | ||||||
|  | /** | ||||||
|  |  * # Delete Auth Files | ||||||
|  |  * @param {string} name | ||||||
|  |  */ | ||||||
|  | const deleteAuthFile = (name) => { | ||||||
|  |     try { | ||||||
|  |         return fs_1.default.rmSync(path_1.default.join((0, exports.grabAuthDirs)().auth, name)); | ||||||
|  |     } | ||||||
|  |     catch ( /** @type {any} */error) { | ||||||
|  |         console.log(`Error deleting Auth File: ${error.message}`); | ||||||
|  |         return null; | ||||||
|  |     } | ||||||
|  | }; | ||||||
|  | exports.deleteAuthFile = deleteAuthFile; | ||||||
|  | /** | ||||||
|  |  * # Delete Auth Files | ||||||
|  |  * @param {string} name | ||||||
|  |  */ | ||||||
|  | const checkAuthFile = (name) => { | ||||||
|  |     try { | ||||||
|  |         return fs_1.default.existsSync(path_1.default.join((0, exports.grabAuthDirs)().auth, name)); | ||||||
|  |         return true; | ||||||
|  |     } | ||||||
|  |     catch ( /** @type {any} */error) { | ||||||
|  |         console.log(`Error checking Auth File: ${error.message}`); | ||||||
|  |         return false; | ||||||
|  |     } | ||||||
|  | }; | ||||||
|  | exports.checkAuthFile = checkAuthFile; | ||||||
							
								
								
									
										14
									
								
								dist/package-shared/functions/backend/cookies/get-auth-cookie-names.d.ts
									
									
									
									
										vendored
									
									
										Normal file
									
								
							
							
						
						
									
										14
									
								
								dist/package-shared/functions/backend/cookies/get-auth-cookie-names.d.ts
									
									
									
									
										vendored
									
									
										Normal file
									
								
							| @ -0,0 +1,14 @@ | |||||||
|  | type Param = { | ||||||
|  |     database?: string; | ||||||
|  |     userId?: string | number; | ||||||
|  | }; | ||||||
|  | type Return = { | ||||||
|  |     keyCookieName: string; | ||||||
|  |     csrfCookieName: string; | ||||||
|  |     oneTimeCodeName: string; | ||||||
|  | }; | ||||||
|  | /** | ||||||
|  |  * # Grab Auth Cookie Names | ||||||
|  |  */ | ||||||
|  | export default function getAuthCookieNames(params?: Param): Return; | ||||||
|  | export {}; | ||||||
							
								
								
									
										38
									
								
								dist/package-shared/functions/backend/cookies/get-auth-cookie-names.js
									
									
									
									
										vendored
									
									
										Normal file
									
								
							
							
						
						
									
										38
									
								
								dist/package-shared/functions/backend/cookies/get-auth-cookie-names.js
									
									
									
									
										vendored
									
									
										Normal file
									
								
							| @ -0,0 +1,38 @@ | |||||||
|  | "use strict"; | ||||||
|  | Object.defineProperty(exports, "__esModule", { value: true }); | ||||||
|  | exports.default = getAuthCookieNames; | ||||||
|  | /** | ||||||
|  |  * # Grab Auth Cookie Names | ||||||
|  |  */ | ||||||
|  | function getAuthCookieNames(params) { | ||||||
|  |     var _a, _b; | ||||||
|  |     const cookiesPrefix = process.env.DSQL_COOKIES_PREFIX || "dsql_"; | ||||||
|  |     const cookiesKeyName = process.env.DSQL_COOKIES_KEY_NAME || "key"; | ||||||
|  |     const cookiesCSRFName = process.env.DSQL_COOKIES_CSRF_NAME || "csrf"; | ||||||
|  |     const cookieOneTimeCodeName = process.env.DSQL_COOKIES_ONE_TIME_CODE_NAME || "one-time-code"; | ||||||
|  |     const targetDatabase = ((_a = params === null || params === void 0 ? void 0 : params.database) === null || _a === void 0 ? void 0 : _a.replace(/^datasquirel_user_\d+_/, "")) || | ||||||
|  |         ((_b = process.env.DSQL_DB_NAME) === null || _b === void 0 ? void 0 : _b.replace(/^datasquirel_user_\d+_/, "")); | ||||||
|  |     let keyCookieName = cookiesPrefix; | ||||||
|  |     if (params === null || params === void 0 ? void 0 : params.userId) | ||||||
|  |         keyCookieName += `user_${params.userId}_`; | ||||||
|  |     if (targetDatabase) | ||||||
|  |         keyCookieName += `${targetDatabase}_`; | ||||||
|  |     keyCookieName += cookiesKeyName; | ||||||
|  |     let csrfCookieName = cookiesPrefix; | ||||||
|  |     if (params === null || params === void 0 ? void 0 : params.userId) | ||||||
|  |         csrfCookieName += `user_${params.userId}_`; | ||||||
|  |     if (targetDatabase) | ||||||
|  |         csrfCookieName += `${targetDatabase}_`; | ||||||
|  |     csrfCookieName += cookiesCSRFName; | ||||||
|  |     let oneTimeCodeName = cookiesPrefix; | ||||||
|  |     if (params === null || params === void 0 ? void 0 : params.userId) | ||||||
|  |         oneTimeCodeName += `user_${params.userId}_`; | ||||||
|  |     if (targetDatabase) | ||||||
|  |         oneTimeCodeName += `${targetDatabase}_`; | ||||||
|  |     oneTimeCodeName += cookieOneTimeCodeName; | ||||||
|  |     return { | ||||||
|  |         keyCookieName, | ||||||
|  |         csrfCookieName, | ||||||
|  |         oneTimeCodeName, | ||||||
|  |     }; | ||||||
|  | } | ||||||
							
								
								
									
										40
									
								
								dist/package-shared/functions/backend/db/addDbEntry.d.ts
									
									
									
									
										vendored
									
									
										Normal file
									
								
							
							
						
						
									
										40
									
								
								dist/package-shared/functions/backend/db/addDbEntry.d.ts
									
									
									
									
										vendored
									
									
										Normal file
									
								
							| @ -0,0 +1,40 @@ | |||||||
|  | type Param = { | ||||||
|  |     dbContext?: "Master" | "Dsql User"; | ||||||
|  |     paradigm?: "Read Only" | "Full Access"; | ||||||
|  |     dbFullName?: string; | ||||||
|  |     tableName: string; | ||||||
|  |     data: any; | ||||||
|  |     tableSchema?: import("../../../types").DSQL_TableSchemaType; | ||||||
|  |     duplicateColumnName?: string; | ||||||
|  |     duplicateColumnValue?: string; | ||||||
|  |     update?: boolean; | ||||||
|  |     encryptionKey?: string; | ||||||
|  |     encryptionSalt?: string; | ||||||
|  |     useLocal?: boolean; | ||||||
|  | }; | ||||||
|  | /** | ||||||
|  |  * Add a db Entry Function | ||||||
|  |  * ============================================================================== | ||||||
|  |  * @description Description | ||||||
|  |  * @async | ||||||
|  |  * | ||||||
|  |  * @param {object} params - An object containing the function parameters. | ||||||
|  |  * @param {("Master" | "Dsql User")} [params.dbContext] - What is the database context? "Master" | ||||||
|  |  * or "Dsql User". Defaults to "Master" | ||||||
|  |  * @param {("Read Only" | "Full Access")} [params.paradigm] - What is the paradigm for "Dsql User"? | ||||||
|  |  * "Read only" or "Full Access"? Defaults to "Read Only" | ||||||
|  |  * @param {string} [params.dbFullName] - Database full name | ||||||
|  |  * @param {string} params.tableName - Table name | ||||||
|  |  * @param {any} params.data - Data to add | ||||||
|  |  * @param {import("../../../types").DSQL_TableSchemaType} [params.tableSchema] - Table schema | ||||||
|  |  * @param {string} [params.duplicateColumnName] - Duplicate column name | ||||||
|  |  * @param {string} [params.duplicateColumnValue] - Duplicate column value | ||||||
|  |  * @param {boolean} [params.update] - Update this row if it exists | ||||||
|  |  * @param {string} [params.encryptionKey] - Update this row if it exists | ||||||
|  |  * @param {string} [params.encryptionSalt] - Update this row if it exists | ||||||
|  |  * @param {boolean} [params.useLocal] | ||||||
|  |  * | ||||||
|  |  * @returns {Promise<any>} | ||||||
|  |  */ | ||||||
|  | export default function addDbEntry({ dbContext, paradigm, dbFullName, tableName, data, tableSchema, duplicateColumnName, duplicateColumnValue, update, encryptionKey, encryptionSalt, useLocal, }: Param): Promise<any>; | ||||||
|  | export {}; | ||||||
							
								
								
									
										209
									
								
								dist/package-shared/functions/backend/db/addDbEntry.js
									
									
									
									
										vendored
									
									
										Normal file
									
								
							
							
						
						
									
										209
									
								
								dist/package-shared/functions/backend/db/addDbEntry.js
									
									
									
									
										vendored
									
									
										Normal file
									
								
							| @ -0,0 +1,209 @@ | |||||||
|  | "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 = addDbEntry; | ||||||
|  | const sanitize_html_1 = __importDefault(require("sanitize-html")); | ||||||
|  | const sanitizeHtmlOptions_1 = __importDefault(require("../html/sanitizeHtmlOptions")); | ||||||
|  | const updateDbEntry_1 = __importDefault(require("./updateDbEntry")); | ||||||
|  | const DB_HANDLER_1 = __importDefault(require("../../../utils/backend/global-db/DB_HANDLER")); | ||||||
|  | const DSQL_USER_DB_HANDLER_1 = __importDefault(require("../../../utils/backend/global-db/DSQL_USER_DB_HANDLER")); | ||||||
|  | const encrypt_1 = __importDefault(require("../../dsql/encrypt")); | ||||||
|  | const LOCAL_DB_HANDLER_1 = __importDefault(require("../../../utils/backend/global-db/LOCAL_DB_HANDLER")); | ||||||
|  | /** | ||||||
|  |  * Add a db Entry Function | ||||||
|  |  * ============================================================================== | ||||||
|  |  * @description Description | ||||||
|  |  * @async | ||||||
|  |  * | ||||||
|  |  * @param {object} params - An object containing the function parameters. | ||||||
|  |  * @param {("Master" | "Dsql User")} [params.dbContext] - What is the database context? "Master" | ||||||
|  |  * or "Dsql User". Defaults to "Master" | ||||||
|  |  * @param {("Read Only" | "Full Access")} [params.paradigm] - What is the paradigm for "Dsql User"? | ||||||
|  |  * "Read only" or "Full Access"? Defaults to "Read Only" | ||||||
|  |  * @param {string} [params.dbFullName] - Database full name | ||||||
|  |  * @param {string} params.tableName - Table name | ||||||
|  |  * @param {any} params.data - Data to add | ||||||
|  |  * @param {import("../../../types").DSQL_TableSchemaType} [params.tableSchema] - Table schema | ||||||
|  |  * @param {string} [params.duplicateColumnName] - Duplicate column name | ||||||
|  |  * @param {string} [params.duplicateColumnValue] - Duplicate column value | ||||||
|  |  * @param {boolean} [params.update] - Update this row if it exists | ||||||
|  |  * @param {string} [params.encryptionKey] - Update this row if it exists | ||||||
|  |  * @param {string} [params.encryptionSalt] - Update this row if it exists | ||||||
|  |  * @param {boolean} [params.useLocal] | ||||||
|  |  * | ||||||
|  |  * @returns {Promise<any>} | ||||||
|  |  */ | ||||||
|  | function addDbEntry(_a) { | ||||||
|  |     return __awaiter(this, arguments, void 0, function* ({ dbContext, paradigm, dbFullName, tableName, data, tableSchema, duplicateColumnName, duplicateColumnValue, update, encryptionKey, encryptionSalt, useLocal, }) { | ||||||
|  |         var _b, _c; | ||||||
|  |         /** | ||||||
|  |          * Initialize variables | ||||||
|  |          */ | ||||||
|  |         const isMaster = useLocal | ||||||
|  |             ? true | ||||||
|  |             : (dbContext === null || dbContext === void 0 ? void 0 : dbContext.match(/dsql.user/i)) | ||||||
|  |                 ? false | ||||||
|  |                 : dbFullName && !dbFullName.match(/^datasquirel$/) | ||||||
|  |                     ? false | ||||||
|  |                     : true; | ||||||
|  |         /** @type { any } */ | ||||||
|  |         const dbHandler = useLocal | ||||||
|  |             ? LOCAL_DB_HANDLER_1.default | ||||||
|  |             : isMaster | ||||||
|  |                 ? DB_HANDLER_1.default | ||||||
|  |                 : DSQL_USER_DB_HANDLER_1.default; | ||||||
|  |         ////////////////////////////////////////
 | ||||||
|  |         ////////////////////////////////////////
 | ||||||
|  |         ////////////////////////////////////////
 | ||||||
|  |         if (data === null || data === void 0 ? void 0 : data["date_created_timestamp"]) | ||||||
|  |             delete data["date_created_timestamp"]; | ||||||
|  |         if (data === null || data === void 0 ? void 0 : data["date_updated_timestamp"]) | ||||||
|  |             delete data["date_updated_timestamp"]; | ||||||
|  |         if (data === null || data === void 0 ? void 0 : data["date_updated"]) | ||||||
|  |             delete data["date_updated"]; | ||||||
|  |         if (data === null || data === void 0 ? void 0 : data["date_updated_code"]) | ||||||
|  |             delete data["date_updated_code"]; | ||||||
|  |         if (data === null || data === void 0 ? void 0 : data["date_created"]) | ||||||
|  |             delete data["date_created"]; | ||||||
|  |         if (data === null || data === void 0 ? void 0 : data["date_created_code"]) | ||||||
|  |             delete data["date_created_code"]; | ||||||
|  |         ////////////////////////////////////////
 | ||||||
|  |         ////////////////////////////////////////
 | ||||||
|  |         ////////////////////////////////////////
 | ||||||
|  |         /** | ||||||
|  |          * Handle function logic | ||||||
|  |          */ | ||||||
|  |         if (duplicateColumnName && typeof duplicateColumnName === "string") { | ||||||
|  |             const duplicateValue = isMaster | ||||||
|  |                 ? yield dbHandler(`SELECT * FROM \`${tableName}\` WHERE \`${duplicateColumnName}\`=?`, [duplicateColumnValue]) | ||||||
|  |                 : yield dbHandler({ | ||||||
|  |                     paradigm: "Read Only", | ||||||
|  |                     database: dbFullName, | ||||||
|  |                     queryString: `SELECT * FROM \`${tableName}\` WHERE \`${duplicateColumnName}\`=?`, | ||||||
|  |                     queryValues: [duplicateColumnValue], | ||||||
|  |                 }); | ||||||
|  |             if ((duplicateValue === null || duplicateValue === void 0 ? void 0 : duplicateValue[0]) && !update) { | ||||||
|  |                 return null; | ||||||
|  |             } | ||||||
|  |             else if (duplicateValue && duplicateValue[0] && update) { | ||||||
|  |                 return yield (0, updateDbEntry_1.default)({ | ||||||
|  |                     dbContext, | ||||||
|  |                     paradigm, | ||||||
|  |                     dbFullName, | ||||||
|  |                     tableName, | ||||||
|  |                     data, | ||||||
|  |                     tableSchema, | ||||||
|  |                     encryptionKey, | ||||||
|  |                     encryptionSalt, | ||||||
|  |                     identifierColumnName: duplicateColumnName, | ||||||
|  |                     identifierValue: duplicateColumnValue || "", | ||||||
|  |                 }); | ||||||
|  |             } | ||||||
|  |         } | ||||||
|  |         /** | ||||||
|  |          * Declare variables | ||||||
|  |          * | ||||||
|  |          * @description Declare "results" variable | ||||||
|  |          */ | ||||||
|  |         const dataKeys = Object.keys(data); | ||||||
|  |         let insertKeysArray = []; | ||||||
|  |         let insertValuesArray = []; | ||||||
|  |         for (let i = 0; i < dataKeys.length; i++) { | ||||||
|  |             try { | ||||||
|  |                 const dataKey = dataKeys[i]; | ||||||
|  |                 // @ts-ignore
 | ||||||
|  |                 let value = data === null || data === void 0 ? void 0 : data[dataKey]; | ||||||
|  |                 const targetFieldSchemaArray = tableSchema | ||||||
|  |                     ? (_b = tableSchema === null || tableSchema === void 0 ? void 0 : tableSchema.fields) === null || _b === void 0 ? void 0 : _b.filter((field) => field.fieldName == dataKey) | ||||||
|  |                     : null; | ||||||
|  |                 const targetFieldSchema = targetFieldSchemaArray && targetFieldSchemaArray[0] | ||||||
|  |                     ? targetFieldSchemaArray[0] | ||||||
|  |                     : null; | ||||||
|  |                 if (value == null || value == undefined) | ||||||
|  |                     continue; | ||||||
|  |                 if (((_c = targetFieldSchema === null || targetFieldSchema === void 0 ? void 0 : targetFieldSchema.dataType) === null || _c === void 0 ? void 0 : _c.match(/int$/i)) && | ||||||
|  |                     typeof value == "string" && | ||||||
|  |                     !(value === null || value === void 0 ? void 0 : value.match(/./))) | ||||||
|  |                     continue; | ||||||
|  |                 if (targetFieldSchema === null || targetFieldSchema === void 0 ? void 0 : targetFieldSchema.encrypted) { | ||||||
|  |                     value = (0, encrypt_1.default)({ | ||||||
|  |                         data: value, | ||||||
|  |                         encryptionKey, | ||||||
|  |                         encryptionSalt, | ||||||
|  |                     }); | ||||||
|  |                     console.log("DSQL: Encrypted value =>", value); | ||||||
|  |                 } | ||||||
|  |                 const htmlRegex = /<[^>]+>/g; | ||||||
|  |                 if ((targetFieldSchema === null || targetFieldSchema === void 0 ? void 0 : targetFieldSchema.richText) || String(value).match(htmlRegex)) { | ||||||
|  |                     value = (0, sanitize_html_1.default)(value, sanitizeHtmlOptions_1.default); | ||||||
|  |                 } | ||||||
|  |                 if (targetFieldSchema === null || targetFieldSchema === void 0 ? void 0 : targetFieldSchema.pattern) { | ||||||
|  |                     const pattern = new RegExp(targetFieldSchema.pattern, targetFieldSchema.patternFlags || ""); | ||||||
|  |                     if (!pattern.test(value)) { | ||||||
|  |                         console.log("DSQL: Pattern not matched =>", value); | ||||||
|  |                         value = ""; | ||||||
|  |                     } | ||||||
|  |                 } | ||||||
|  |                 insertKeysArray.push("`" + dataKey + "`"); | ||||||
|  |                 if (typeof value === "object") { | ||||||
|  |                     value = JSON.stringify(value); | ||||||
|  |                 } | ||||||
|  |                 if (typeof value == "number") { | ||||||
|  |                     insertValuesArray.push(String(value)); | ||||||
|  |                 } | ||||||
|  |                 else { | ||||||
|  |                     insertValuesArray.push(value); | ||||||
|  |                 } | ||||||
|  |             } | ||||||
|  |             catch ( /** @type {any} */error) { | ||||||
|  |                 console.log("DSQL: Error in parsing data keys =>", error.message); | ||||||
|  |                 continue; | ||||||
|  |             } | ||||||
|  |         } | ||||||
|  |         ////////////////////////////////////////
 | ||||||
|  |         if (!(data === null || data === void 0 ? void 0 : data["date_created"])) { | ||||||
|  |             insertKeysArray.push("`date_created`"); | ||||||
|  |             insertValuesArray.push(Date()); | ||||||
|  |         } | ||||||
|  |         if (!(data === null || data === void 0 ? void 0 : data["date_created_code"])) { | ||||||
|  |             insertKeysArray.push("`date_created_code`"); | ||||||
|  |             insertValuesArray.push(Date.now()); | ||||||
|  |         } | ||||||
|  |         ////////////////////////////////////////
 | ||||||
|  |         if (!(data === null || data === void 0 ? void 0 : data["date_updated"])) { | ||||||
|  |             insertKeysArray.push("`date_updated`"); | ||||||
|  |             insertValuesArray.push(Date()); | ||||||
|  |         } | ||||||
|  |         if (!(data === null || data === void 0 ? void 0 : data["date_updated_code"])) { | ||||||
|  |             insertKeysArray.push("`date_updated_code`"); | ||||||
|  |             insertValuesArray.push(Date.now()); | ||||||
|  |         } | ||||||
|  |         ////////////////////////////////////////
 | ||||||
|  |         const query = `INSERT INTO \`${tableName}\` (${insertKeysArray.join(",")}) VALUES (${insertValuesArray.map(() => "?").join(",")})`; | ||||||
|  |         const queryValuesArray = insertValuesArray; | ||||||
|  |         const newInsert = isMaster | ||||||
|  |             ? yield dbHandler(query, queryValuesArray) | ||||||
|  |             : yield dbHandler({ | ||||||
|  |                 paradigm, | ||||||
|  |                 database: dbFullName, | ||||||
|  |                 queryString: query, | ||||||
|  |                 queryValues: queryValuesArray, | ||||||
|  |             }); | ||||||
|  |         /** | ||||||
|  |          * Return statement | ||||||
|  |          */ | ||||||
|  |         return newInsert; | ||||||
|  |     }); | ||||||
|  | } | ||||||
							
								
								
									
										16
									
								
								dist/package-shared/functions/backend/db/deleteDbEntry.d.ts
									
									
									
									
										vendored
									
									
										Normal file
									
								
							
							
						
						
									
										16
									
								
								dist/package-shared/functions/backend/db/deleteDbEntry.d.ts
									
									
									
									
										vendored
									
									
										Normal file
									
								
							| @ -0,0 +1,16 @@ | |||||||
|  | type Param = { | ||||||
|  |     dbContext?: string; | ||||||
|  |     paradigm?: "Read Only" | "Full Access"; | ||||||
|  |     dbFullName: string; | ||||||
|  |     tableName: string; | ||||||
|  |     tableSchema?: import("../../../types").DSQL_TableSchemaType; | ||||||
|  |     identifierColumnName: string; | ||||||
|  |     identifierValue: string | number; | ||||||
|  |     useLocal?: boolean; | ||||||
|  | }; | ||||||
|  | /** | ||||||
|  |  * # Delete DB Entry Function | ||||||
|  |  * @description | ||||||
|  |  */ | ||||||
|  | export default function deleteDbEntry({ dbContext, paradigm, dbFullName, tableName, identifierColumnName, identifierValue, useLocal, }: Param): Promise<object | null>; | ||||||
|  | export {}; | ||||||
							
								
								
									
										62
									
								
								dist/package-shared/functions/backend/db/deleteDbEntry.js
									
									
									
									
										vendored
									
									
										Normal file
									
								
							
							
						
						
									
										62
									
								
								dist/package-shared/functions/backend/db/deleteDbEntry.js
									
									
									
									
										vendored
									
									
										Normal file
									
								
							| @ -0,0 +1,62 @@ | |||||||
|  | "use strict"; | ||||||
|  | var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { | ||||||
|  |     function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } | ||||||
|  |     return new (P || (P = Promise))(function (resolve, reject) { | ||||||
|  |         function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } | ||||||
|  |         function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } | ||||||
|  |         function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } | ||||||
|  |         step((generator = generator.apply(thisArg, _arguments || [])).next()); | ||||||
|  |     }); | ||||||
|  | }; | ||||||
|  | var __importDefault = (this && this.__importDefault) || function (mod) { | ||||||
|  |     return (mod && mod.__esModule) ? mod : { "default": mod }; | ||||||
|  | }; | ||||||
|  | Object.defineProperty(exports, "__esModule", { value: true }); | ||||||
|  | exports.default = deleteDbEntry; | ||||||
|  | const DB_HANDLER_1 = __importDefault(require("../../../utils/backend/global-db/DB_HANDLER")); | ||||||
|  | const DSQL_USER_DB_HANDLER_1 = __importDefault(require("../../../utils/backend/global-db/DSQL_USER_DB_HANDLER")); | ||||||
|  | const LOCAL_DB_HANDLER_1 = __importDefault(require("../../../utils/backend/global-db/LOCAL_DB_HANDLER")); | ||||||
|  | /** | ||||||
|  |  * # Delete DB Entry Function | ||||||
|  |  * @description | ||||||
|  |  */ | ||||||
|  | function deleteDbEntry(_a) { | ||||||
|  |     return __awaiter(this, arguments, void 0, function* ({ dbContext, paradigm, dbFullName, tableName, identifierColumnName, identifierValue, useLocal, }) { | ||||||
|  |         try { | ||||||
|  |             const isMaster = useLocal | ||||||
|  |                 ? true | ||||||
|  |                 : (dbContext === null || dbContext === void 0 ? void 0 : dbContext.match(/dsql.user/i)) | ||||||
|  |                     ? false | ||||||
|  |                     : dbFullName && !dbFullName.match(/^datasquirel$/) | ||||||
|  |                         ? false | ||||||
|  |                         : true; | ||||||
|  |             /** @type { (a1:any, a2?:any) => any } */ | ||||||
|  |             const dbHandler = useLocal | ||||||
|  |                 ? LOCAL_DB_HANDLER_1.default | ||||||
|  |                 : isMaster | ||||||
|  |                     ? DB_HANDLER_1.default | ||||||
|  |                     : DSQL_USER_DB_HANDLER_1.default; | ||||||
|  |             /** | ||||||
|  |              * Execution | ||||||
|  |              * | ||||||
|  |              * @description | ||||||
|  |              */ | ||||||
|  |             const query = `DELETE FROM ${tableName} WHERE \`${identifierColumnName}\`=?`; | ||||||
|  |             const deletedEntry = isMaster | ||||||
|  |                 ? yield dbHandler(query, [identifierValue]) | ||||||
|  |                 : yield dbHandler({ | ||||||
|  |                     paradigm, | ||||||
|  |                     queryString: query, | ||||||
|  |                     database: dbFullName, | ||||||
|  |                     queryValues: [identifierValue], | ||||||
|  |                 }); | ||||||
|  |             /** | ||||||
|  |              * Return statement | ||||||
|  |              */ | ||||||
|  |             return deletedEntry; | ||||||
|  |         } | ||||||
|  |         catch (error) { | ||||||
|  |             return null; | ||||||
|  |         } | ||||||
|  |     }); | ||||||
|  | } | ||||||
							
								
								
									
										5
									
								
								dist/package-shared/functions/backend/db/pathTraversalCheck.d.ts
									
									
									
									
										vendored
									
									
										Normal file
									
								
							
							
						
						
									
										5
									
								
								dist/package-shared/functions/backend/db/pathTraversalCheck.d.ts
									
									
									
									
										vendored
									
									
										Normal file
									
								
							| @ -0,0 +1,5 @@ | |||||||
|  | /** | ||||||
|  |  * # Path Traversal Check | ||||||
|  |  * @returns {string} | ||||||
|  |  */ | ||||||
|  | export default function pathTraversalCheck(text: string | number): string; | ||||||
							
								
								
									
										10
									
								
								dist/package-shared/functions/backend/db/pathTraversalCheck.js
									
									
									
									
										vendored
									
									
										Normal file
									
								
							
							
						
						
									
										10
									
								
								dist/package-shared/functions/backend/db/pathTraversalCheck.js
									
									
									
									
										vendored
									
									
										Normal file
									
								
							| @ -0,0 +1,10 @@ | |||||||
|  | "use strict"; | ||||||
|  | Object.defineProperty(exports, "__esModule", { value: true }); | ||||||
|  | exports.default = pathTraversalCheck; | ||||||
|  | /** | ||||||
|  |  * # Path Traversal Check | ||||||
|  |  * @returns {string} | ||||||
|  |  */ | ||||||
|  | function pathTraversalCheck(text) { | ||||||
|  |     return text.toString().replace(/\//g, ""); | ||||||
|  | } | ||||||
							
								
								
									
										14
									
								
								dist/package-shared/functions/backend/db/runQuery.d.ts
									
									
									
									
										vendored
									
									
										Normal file
									
								
							
							
						
						
									
										14
									
								
								dist/package-shared/functions/backend/db/runQuery.d.ts
									
									
									
									
										vendored
									
									
										Normal file
									
								
							| @ -0,0 +1,14 @@ | |||||||
|  | type Param = { | ||||||
|  |     dbFullName: string; | ||||||
|  |     query: string | any; | ||||||
|  |     readOnly?: boolean; | ||||||
|  |     local?: boolean; | ||||||
|  |     dbSchema?: import("../../../types").DSQL_DatabaseSchemaType; | ||||||
|  |     queryValuesArray?: (string | number)[]; | ||||||
|  |     tableName?: string; | ||||||
|  | }; | ||||||
|  | /** | ||||||
|  |  * # Run DSQL users queries | ||||||
|  |  */ | ||||||
|  | export default function runQuery({ dbFullName, query, readOnly, dbSchema, queryValuesArray, tableName, local, }: Param): Promise<any>; | ||||||
|  | export {}; | ||||||
							
								
								
									
										155
									
								
								dist/package-shared/functions/backend/db/runQuery.js
									
									
									
									
										vendored
									
									
										Normal file
									
								
							
							
						
						
									
										155
									
								
								dist/package-shared/functions/backend/db/runQuery.js
									
									
									
									
										vendored
									
									
										Normal file
									
								
							| @ -0,0 +1,155 @@ | |||||||
|  | "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 = runQuery; | ||||||
|  | const fullAccessDbHandler_1 = __importDefault(require("../fullAccessDbHandler")); | ||||||
|  | const varReadOnlyDatabaseDbHandler_1 = __importDefault(require("../varReadOnlyDatabaseDbHandler")); | ||||||
|  | const serverError_1 = __importDefault(require("../serverError")); | ||||||
|  | const addDbEntry_1 = __importDefault(require("./addDbEntry")); | ||||||
|  | const updateDbEntry_1 = __importDefault(require("./updateDbEntry")); | ||||||
|  | const deleteDbEntry_1 = __importDefault(require("./deleteDbEntry")); | ||||||
|  | const trim_sql_1 = __importDefault(require("../../../utils/trim-sql")); | ||||||
|  | /** | ||||||
|  |  * # Run DSQL users queries | ||||||
|  |  */ | ||||||
|  | function runQuery(_a) { | ||||||
|  |     return __awaiter(this, arguments, void 0, function* ({ dbFullName, query, readOnly, dbSchema, queryValuesArray, tableName, local, }) { | ||||||
|  |         /** | ||||||
|  |          * Declare variables | ||||||
|  |          * | ||||||
|  |          * @description Declare "results" variable | ||||||
|  |          */ | ||||||
|  |         let result; | ||||||
|  |         let error; | ||||||
|  |         let tableSchema; | ||||||
|  |         if (dbSchema) { | ||||||
|  |             try { | ||||||
|  |                 const table = tableName | ||||||
|  |                     ? tableName | ||||||
|  |                     : typeof query == "string" | ||||||
|  |                         ? null | ||||||
|  |                         : query | ||||||
|  |                             ? query === null || query === void 0 ? void 0 : query.table | ||||||
|  |                             : null; | ||||||
|  |                 if (!table) | ||||||
|  |                     throw new Error("No table name provided"); | ||||||
|  |                 tableSchema = dbSchema.tables.filter((tb) => (tb === null || tb === void 0 ? void 0 : tb.tableName) === table)[0]; | ||||||
|  |             } | ||||||
|  |             catch (_err) { | ||||||
|  |                 // console.log("ERROR getting tableSchema: ", _err.message);
 | ||||||
|  |             } | ||||||
|  |         } | ||||||
|  |         /** | ||||||
|  |          * Declare variables | ||||||
|  |          * | ||||||
|  |          * @description Declare "results" variable | ||||||
|  |          */ | ||||||
|  |         try { | ||||||
|  |             if (typeof query === "string") { | ||||||
|  |                 const formattedQuery = (0, trim_sql_1.default)(query); | ||||||
|  |                 /** | ||||||
|  |                  * Input Validation | ||||||
|  |                  * | ||||||
|  |                  * @description Input Validation | ||||||
|  |                  */ | ||||||
|  |                 if (readOnly && | ||||||
|  |                     formattedQuery.match(/^alter|^delete|information_schema|^create/i)) { | ||||||
|  |                     throw new Error("Wrong Input!"); | ||||||
|  |                 } | ||||||
|  |                 if (readOnly) { | ||||||
|  |                     result = yield (0, varReadOnlyDatabaseDbHandler_1.default)({ | ||||||
|  |                         queryString: formattedQuery, | ||||||
|  |                         queryValuesArray: queryValuesArray === null || queryValuesArray === void 0 ? void 0 : queryValuesArray.map((vl) => String(vl)), | ||||||
|  |                         database: dbFullName, | ||||||
|  |                         tableSchema, | ||||||
|  |                         useLocal: local, | ||||||
|  |                     }); | ||||||
|  |                 } | ||||||
|  |                 else { | ||||||
|  |                     result = yield (0, fullAccessDbHandler_1.default)({ | ||||||
|  |                         queryString: formattedQuery, | ||||||
|  |                         queryValuesArray: queryValuesArray === null || queryValuesArray === void 0 ? void 0 : queryValuesArray.map((vl) => String(vl)), | ||||||
|  |                         database: dbFullName, | ||||||
|  |                         tableSchema, | ||||||
|  |                         local, | ||||||
|  |                     }); | ||||||
|  |                 } | ||||||
|  |             } | ||||||
|  |             else if (typeof query === "object") { | ||||||
|  |                 /** | ||||||
|  |                  * Declare variables | ||||||
|  |                  * | ||||||
|  |                  * @description Declare "results" variable | ||||||
|  |                  */ | ||||||
|  |                 const { data, action, table, identifierColumnName, identifierValue, update, duplicateColumnName, duplicateColumnValue, } = query; | ||||||
|  |                 switch (action.toLowerCase()) { | ||||||
|  |                     case "insert": | ||||||
|  |                         result = yield (0, addDbEntry_1.default)({ | ||||||
|  |                             dbContext: local ? "Master" : "Dsql User", | ||||||
|  |                             paradigm: "Full Access", | ||||||
|  |                             dbFullName: dbFullName, | ||||||
|  |                             tableName: table, | ||||||
|  |                             data: data, | ||||||
|  |                             update, | ||||||
|  |                             duplicateColumnName, | ||||||
|  |                             duplicateColumnValue, | ||||||
|  |                             tableSchema, | ||||||
|  |                             useLocal: local, | ||||||
|  |                         }); | ||||||
|  |                         if (!(result === null || result === void 0 ? void 0 : result.insertId)) { | ||||||
|  |                             error = new Error("Couldn't insert data"); | ||||||
|  |                         } | ||||||
|  |                         break; | ||||||
|  |                     case "update": | ||||||
|  |                         result = yield (0, updateDbEntry_1.default)({ | ||||||
|  |                             dbContext: local ? "Master" : "Dsql User", | ||||||
|  |                             paradigm: "Full Access", | ||||||
|  |                             dbFullName: dbFullName, | ||||||
|  |                             tableName: table, | ||||||
|  |                             data: data, | ||||||
|  |                             identifierColumnName, | ||||||
|  |                             identifierValue, | ||||||
|  |                             tableSchema, | ||||||
|  |                             useLocal: local, | ||||||
|  |                         }); | ||||||
|  |                         break; | ||||||
|  |                     case "delete": | ||||||
|  |                         result = yield (0, deleteDbEntry_1.default)({ | ||||||
|  |                             dbContext: local ? "Master" : "Dsql User", | ||||||
|  |                             paradigm: "Full Access", | ||||||
|  |                             dbFullName: dbFullName, | ||||||
|  |                             tableName: table, | ||||||
|  |                             identifierColumnName, | ||||||
|  |                             identifierValue, | ||||||
|  |                             tableSchema, | ||||||
|  |                             useLocal: local, | ||||||
|  |                         }); | ||||||
|  |                         break; | ||||||
|  |                     default: | ||||||
|  |                         result = null; | ||||||
|  |                         break; | ||||||
|  |                 } | ||||||
|  |             } | ||||||
|  |         } | ||||||
|  |         catch ( /** @type {any} */error) { | ||||||
|  |             (0, serverError_1.default)({ | ||||||
|  |                 component: "functions/backend/runQuery", | ||||||
|  |                 message: error.message, | ||||||
|  |             }); | ||||||
|  |             result = null; | ||||||
|  |             error = error.message; | ||||||
|  |         } | ||||||
|  |         return { result, error }; | ||||||
|  |     }); | ||||||
|  | } | ||||||
							
								
								
									
										8
									
								
								dist/package-shared/functions/backend/db/sanitizeSql.d.ts
									
									
									
									
										vendored
									
									
										Normal file
									
								
							
							
						
						
									
										8
									
								
								dist/package-shared/functions/backend/db/sanitizeSql.d.ts
									
									
									
									
										vendored
									
									
										Normal file
									
								
							| @ -0,0 +1,8 @@ | |||||||
|  | /** | ||||||
|  |  * Sanitize SQL function | ||||||
|  |  * ============================================================================== | ||||||
|  |  * @description this function takes in a text(or number) and returns a sanitized | ||||||
|  |  * text, usually without spaces | ||||||
|  |  */ | ||||||
|  | declare function sanitizeSql(text: any, spaces: boolean, regex?: RegExp | null): any; | ||||||
|  | export default sanitizeSql; | ||||||
							
								
								
									
										111
									
								
								dist/package-shared/functions/backend/db/sanitizeSql.js
									
									
									
									
										vendored
									
									
										Normal file
									
								
							
							
						
						
									
										111
									
								
								dist/package-shared/functions/backend/db/sanitizeSql.js
									
									
									
									
										vendored
									
									
										Normal file
									
								
							| @ -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 lodash_1 = __importDefault(require("lodash")); | ||||||
|  | /** | ||||||
|  |  * Sanitize SQL function | ||||||
|  |  * ============================================================================== | ||||||
|  |  * @description this function takes in a text(or number) and returns a sanitized | ||||||
|  |  * text, usually without spaces | ||||||
|  |  */ | ||||||
|  | function sanitizeSql(text, spaces, regex) { | ||||||
|  |     var _a; | ||||||
|  |     if (!text) | ||||||
|  |         return ""; | ||||||
|  |     if (typeof text == "number" || typeof text == "boolean") | ||||||
|  |         return text; | ||||||
|  |     if (typeof text == "string" && !((_a = text === null || text === void 0 ? void 0 : text.toString()) === null || _a === void 0 ? void 0 : _a.match(/./))) | ||||||
|  |         return ""; | ||||||
|  |     if (typeof text == "object" && !Array.isArray(text)) { | ||||||
|  |         const newObject = sanitizeObjects(text, spaces); | ||||||
|  |         return newObject; | ||||||
|  |     } | ||||||
|  |     else if (typeof text == "object" && Array.isArray(text)) { | ||||||
|  |         const newArray = sanitizeArrays(text, spaces); | ||||||
|  |         return newArray; | ||||||
|  |     } | ||||||
|  |     let finalText = text; | ||||||
|  |     if (regex) { | ||||||
|  |         finalText = text.toString().replace(regex, ""); | ||||||
|  |     } | ||||||
|  |     if (spaces) { | ||||||
|  |     } | ||||||
|  |     else { | ||||||
|  |         finalText = text | ||||||
|  |             .toString() | ||||||
|  |             .replace(/\n|\r|\n\r|\r\n/g, "") | ||||||
|  |             .replace(/ /g, ""); | ||||||
|  |     } | ||||||
|  |     const escapeRegex = /select |insert |drop |delete |alter |create |exec | union | or | like | concat|LOAD_FILE|ASCII| COLLATE | HAVING | information_schema|DECLARE |\#|WAITFOR |delay |BENCHMARK |\/\*.*\*\//gi; | ||||||
|  |     finalText = finalText | ||||||
|  |         .replace(/(?<!\\)\'/g, "\\'") | ||||||
|  |         .replace(/(?<!\\)\`/g, "\\`") | ||||||
|  |         .replace(/\/\*\*\//g, "") | ||||||
|  |         .replace(escapeRegex, "\\$&"); | ||||||
|  |     return finalText; | ||||||
|  | } | ||||||
|  | /** | ||||||
|  |  * Sanitize Objects Function | ||||||
|  |  * ============================================================================== | ||||||
|  |  * @description Sanitize objects in the form { key: "value" } | ||||||
|  |  * | ||||||
|  |  * @param {any} object - Database Full Name | ||||||
|  |  * @param {boolean} [spaces] - Allow spaces | ||||||
|  |  * | ||||||
|  |  * @returns {object} | ||||||
|  |  */ | ||||||
|  | function sanitizeObjects(object, spaces) { | ||||||
|  |     /** @type {any} */ | ||||||
|  |     let objectUpdated = Object.assign({}, object); | ||||||
|  |     const keys = Object.keys(objectUpdated); | ||||||
|  |     keys.forEach((key) => { | ||||||
|  |         const value = objectUpdated[key]; | ||||||
|  |         if (!value) { | ||||||
|  |             delete objectUpdated[key]; | ||||||
|  |             return; | ||||||
|  |         } | ||||||
|  |         if (typeof value == "string" || typeof value == "number") { | ||||||
|  |             objectUpdated[key] = sanitizeSql(value, spaces); | ||||||
|  |         } | ||||||
|  |         else if (typeof value == "object" && !Array.isArray(value)) { | ||||||
|  |             objectUpdated[key] = sanitizeObjects(value, spaces); | ||||||
|  |         } | ||||||
|  |         else if (typeof value == "object" && Array.isArray(value)) { | ||||||
|  |             objectUpdated[key] = sanitizeArrays(value, spaces); | ||||||
|  |         } | ||||||
|  |     }); | ||||||
|  |     return objectUpdated; | ||||||
|  | } | ||||||
|  | /** | ||||||
|  |  * Sanitize Objects Function | ||||||
|  |  * ============================================================================== | ||||||
|  |  * @description Sanitize objects in the form { key: "value" } | ||||||
|  |  * | ||||||
|  |  * @param {any[]} array - Database Full Name | ||||||
|  |  * @param {boolean} [spaces] - Allow spaces | ||||||
|  |  * | ||||||
|  |  * @returns {string[]|number[]|object[]} | ||||||
|  |  */ | ||||||
|  | function sanitizeArrays(array, spaces) { | ||||||
|  |     let arrayUpdated = lodash_1.default.cloneDeep(array); | ||||||
|  |     arrayUpdated.forEach((item, index) => { | ||||||
|  |         const value = item; | ||||||
|  |         if (!value) { | ||||||
|  |             arrayUpdated.splice(index, 1); | ||||||
|  |             return; | ||||||
|  |         } | ||||||
|  |         if (typeof item == "string" || typeof item == "number") { | ||||||
|  |             arrayUpdated[index] = sanitizeSql(value, spaces); | ||||||
|  |         } | ||||||
|  |         else if (typeof item == "object" && !Array.isArray(value)) { | ||||||
|  |             arrayUpdated[index] = sanitizeObjects(value, spaces); | ||||||
|  |         } | ||||||
|  |         else if (typeof item == "object" && Array.isArray(value)) { | ||||||
|  |             arrayUpdated[index] = sanitizeArrays(item, spaces); | ||||||
|  |         } | ||||||
|  |     }); | ||||||
|  |     return arrayUpdated; | ||||||
|  | } | ||||||
|  | exports.default = sanitizeSql; | ||||||
							
								
								
									
										19
									
								
								dist/package-shared/functions/backend/db/updateDbEntry.d.ts
									
									
									
									
										vendored
									
									
										Normal file
									
								
							
							
						
						
									
										19
									
								
								dist/package-shared/functions/backend/db/updateDbEntry.d.ts
									
									
									
									
										vendored
									
									
										Normal file
									
								
							| @ -0,0 +1,19 @@ | |||||||
|  | type Param = { | ||||||
|  |     dbContext?: "Master" | "Dsql User"; | ||||||
|  |     paradigm?: "Read Only" | "Full Access"; | ||||||
|  |     dbFullName?: string; | ||||||
|  |     tableName: string; | ||||||
|  |     encryptionKey?: string; | ||||||
|  |     encryptionSalt?: string; | ||||||
|  |     data: any; | ||||||
|  |     tableSchema?: import("../../../types").DSQL_TableSchemaType; | ||||||
|  |     identifierColumnName: string; | ||||||
|  |     identifierValue: string | number; | ||||||
|  |     useLocal?: boolean; | ||||||
|  | }; | ||||||
|  | /** | ||||||
|  |  * # Update DB Function | ||||||
|  |  * @description | ||||||
|  |  */ | ||||||
|  | export default function updateDbEntry({ dbContext, paradigm, dbFullName, tableName, data, tableSchema, identifierColumnName, identifierValue, encryptionKey, encryptionSalt, useLocal, }: Param): Promise<object | null>; | ||||||
|  | export {}; | ||||||
							
								
								
									
										144
									
								
								dist/package-shared/functions/backend/db/updateDbEntry.js
									
									
									
									
										vendored
									
									
										Normal file
									
								
							
							
						
						
									
										144
									
								
								dist/package-shared/functions/backend/db/updateDbEntry.js
									
									
									
									
										vendored
									
									
										Normal file
									
								
							| @ -0,0 +1,144 @@ | |||||||
|  | "use strict"; | ||||||
|  | var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { | ||||||
|  |     function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } | ||||||
|  |     return new (P || (P = Promise))(function (resolve, reject) { | ||||||
|  |         function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } | ||||||
|  |         function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } | ||||||
|  |         function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } | ||||||
|  |         step((generator = generator.apply(thisArg, _arguments || [])).next()); | ||||||
|  |     }); | ||||||
|  | }; | ||||||
|  | var __importDefault = (this && this.__importDefault) || function (mod) { | ||||||
|  |     return (mod && mod.__esModule) ? mod : { "default": mod }; | ||||||
|  | }; | ||||||
|  | Object.defineProperty(exports, "__esModule", { value: true }); | ||||||
|  | exports.default = updateDbEntry; | ||||||
|  | const sanitize_html_1 = __importDefault(require("sanitize-html")); | ||||||
|  | const sanitizeHtmlOptions_1 = __importDefault(require("../html/sanitizeHtmlOptions")); | ||||||
|  | const DB_HANDLER_1 = __importDefault(require("../../../utils/backend/global-db/DB_HANDLER")); | ||||||
|  | const DSQL_USER_DB_HANDLER_1 = __importDefault(require("../../../utils/backend/global-db/DSQL_USER_DB_HANDLER")); | ||||||
|  | const encrypt_1 = __importDefault(require("../../dsql/encrypt")); | ||||||
|  | const LOCAL_DB_HANDLER_1 = __importDefault(require("../../../utils/backend/global-db/LOCAL_DB_HANDLER")); | ||||||
|  | /** | ||||||
|  |  * # Update DB Function | ||||||
|  |  * @description | ||||||
|  |  */ | ||||||
|  | function updateDbEntry(_a) { | ||||||
|  |     return __awaiter(this, arguments, void 0, function* ({ dbContext, paradigm, dbFullName, tableName, data, tableSchema, identifierColumnName, identifierValue, encryptionKey, encryptionSalt, useLocal, }) { | ||||||
|  |         var _b; | ||||||
|  |         /** | ||||||
|  |          * Check if data is valid | ||||||
|  |          */ | ||||||
|  |         if (!data || !Object.keys(data).length) | ||||||
|  |             return null; | ||||||
|  |         const isMaster = useLocal | ||||||
|  |             ? true | ||||||
|  |             : (dbContext === null || dbContext === void 0 ? void 0 : dbContext.match(/dsql.user/i)) | ||||||
|  |                 ? false | ||||||
|  |                 : dbFullName && !dbFullName.match(/^datasquirel$/) | ||||||
|  |                     ? false | ||||||
|  |                     : true; | ||||||
|  |         /** @type {(a1:any, a2?:any)=> any } */ | ||||||
|  |         const dbHandler = useLocal | ||||||
|  |             ? LOCAL_DB_HANDLER_1.default | ||||||
|  |             : isMaster | ||||||
|  |                 ? DB_HANDLER_1.default | ||||||
|  |                 : DSQL_USER_DB_HANDLER_1.default; | ||||||
|  |         ////////////////////////////////////////
 | ||||||
|  |         ////////////////////////////////////////
 | ||||||
|  |         ////////////////////////////////////////
 | ||||||
|  |         /** | ||||||
|  |          * Declare variables | ||||||
|  |          * | ||||||
|  |          * @description Declare "results" variable | ||||||
|  |          */ | ||||||
|  |         const dataKeys = Object.keys(data); | ||||||
|  |         let updateKeyValueArray = []; | ||||||
|  |         let updateValues = []; | ||||||
|  |         for (let i = 0; i < dataKeys.length; i++) { | ||||||
|  |             try { | ||||||
|  |                 const dataKey = dataKeys[i]; | ||||||
|  |                 // @ts-ignore
 | ||||||
|  |                 let value = data[dataKey]; | ||||||
|  |                 const targetFieldSchemaArray = tableSchema | ||||||
|  |                     ? (_b = tableSchema === null || tableSchema === void 0 ? void 0 : tableSchema.fields) === null || _b === void 0 ? void 0 : _b.filter((field) => field.fieldName === dataKey) | ||||||
|  |                     : null; | ||||||
|  |                 const targetFieldSchema = targetFieldSchemaArray && targetFieldSchemaArray[0] | ||||||
|  |                     ? targetFieldSchemaArray[0] | ||||||
|  |                     : null; | ||||||
|  |                 if (value == null || value == undefined) | ||||||
|  |                     continue; | ||||||
|  |                 const htmlRegex = /<[^>]+>/g; | ||||||
|  |                 if ((targetFieldSchema === null || targetFieldSchema === void 0 ? void 0 : targetFieldSchema.richText) || String(value).match(htmlRegex)) { | ||||||
|  |                     value = (0, sanitize_html_1.default)(value, sanitizeHtmlOptions_1.default); | ||||||
|  |                 } | ||||||
|  |                 if (targetFieldSchema === null || targetFieldSchema === void 0 ? void 0 : targetFieldSchema.encrypted) { | ||||||
|  |                     value = (0, encrypt_1.default)({ | ||||||
|  |                         data: value, | ||||||
|  |                         encryptionKey, | ||||||
|  |                         encryptionSalt, | ||||||
|  |                     }); | ||||||
|  |                 } | ||||||
|  |                 if (typeof value === "object") { | ||||||
|  |                     value = JSON.stringify(value); | ||||||
|  |                 } | ||||||
|  |                 if (targetFieldSchema === null || targetFieldSchema === void 0 ? void 0 : targetFieldSchema.pattern) { | ||||||
|  |                     const pattern = new RegExp(targetFieldSchema.pattern, targetFieldSchema.patternFlags || ""); | ||||||
|  |                     if (!pattern.test(value)) { | ||||||
|  |                         console.log("DSQL: Pattern not matched =>", value); | ||||||
|  |                         value = ""; | ||||||
|  |                     } | ||||||
|  |                 } | ||||||
|  |                 if (typeof value === "string" && value.match(/^null$/i)) { | ||||||
|  |                     value = { | ||||||
|  |                         toSqlString: function () { | ||||||
|  |                             return "NULL"; | ||||||
|  |                         }, | ||||||
|  |                     }; | ||||||
|  |                 } | ||||||
|  |                 if (typeof value === "string" && !value.match(/./i)) { | ||||||
|  |                     value = { | ||||||
|  |                         toSqlString: function () { | ||||||
|  |                             return "NULL"; | ||||||
|  |                         }, | ||||||
|  |                     }; | ||||||
|  |                 } | ||||||
|  |                 updateKeyValueArray.push(`\`${dataKey}\`=?`); | ||||||
|  |                 if (typeof value == "number") { | ||||||
|  |                     updateValues.push(String(value)); | ||||||
|  |                 } | ||||||
|  |                 else { | ||||||
|  |                     updateValues.push(value); | ||||||
|  |                 } | ||||||
|  |                 ////////////////////////////////////////
 | ||||||
|  |                 ////////////////////////////////////////
 | ||||||
|  |             } | ||||||
|  |             catch ( /** @type {any} */error) { | ||||||
|  |                 ////////////////////////////////////////
 | ||||||
|  |                 ////////////////////////////////////////
 | ||||||
|  |                 console.log("DSQL: Error in parsing data keys in update function =>", error.message); | ||||||
|  |                 continue; | ||||||
|  |             } | ||||||
|  |         } | ||||||
|  |         ////////////////////////////////////////
 | ||||||
|  |         ////////////////////////////////////////
 | ||||||
|  |         updateKeyValueArray.push(`date_updated='${Date()}'`); | ||||||
|  |         updateKeyValueArray.push(`date_updated_code='${Date.now()}'`); | ||||||
|  |         ////////////////////////////////////////
 | ||||||
|  |         ////////////////////////////////////////
 | ||||||
|  |         const query = `UPDATE ${tableName} SET ${updateKeyValueArray.join(",")} WHERE \`${identifierColumnName}\`=?`; | ||||||
|  |         updateValues.push(identifierValue); | ||||||
|  |         const updatedEntry = isMaster | ||||||
|  |             ? yield dbHandler(query, updateValues) | ||||||
|  |             : yield dbHandler({ | ||||||
|  |                 paradigm, | ||||||
|  |                 database: dbFullName, | ||||||
|  |                 queryString: query, | ||||||
|  |                 queryValues: updateValues, | ||||||
|  |             }); | ||||||
|  |         /** | ||||||
|  |          * Return statement | ||||||
|  |          */ | ||||||
|  |         return updatedEntry; | ||||||
|  |     }); | ||||||
|  | } | ||||||
							
								
								
									
										4
									
								
								dist/package-shared/functions/backend/dbHandler.d.ts
									
									
									
									
										vendored
									
									
										Normal file
									
								
							
							
						
						
									
										4
									
								
								dist/package-shared/functions/backend/dbHandler.d.ts
									
									
									
									
										vendored
									
									
										Normal file
									
								
							| @ -0,0 +1,4 @@ | |||||||
|  | /** | ||||||
|  |  * # Main DB Handler Function | ||||||
|  |  */ | ||||||
|  | export default function dbHandler(...args: any[]): Promise<any>; | ||||||
							
								
								
									
										82
									
								
								dist/package-shared/functions/backend/dbHandler.js
									
									
									
									
										vendored
									
									
										Normal file
									
								
							
							
						
						
									
										82
									
								
								dist/package-shared/functions/backend/dbHandler.js
									
									
									
									
										vendored
									
									
										Normal file
									
								
							| @ -0,0 +1,82 @@ | |||||||
|  | "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 = dbHandler; | ||||||
|  | const fs_1 = __importDefault(require("fs")); | ||||||
|  | const serverError_1 = __importDefault(require("./serverError")); | ||||||
|  | const serverless_mysql_1 = __importDefault(require("serverless-mysql")); | ||||||
|  | const grabDbSSL_1 = __importDefault(require("../../utils/backend/grabDbSSL")); | ||||||
|  | const connection = (0, serverless_mysql_1.default)({ | ||||||
|  |     config: { | ||||||
|  |         host: process.env.DSQL_DB_HOST, | ||||||
|  |         user: process.env.DSQL_DB_USERNAME, | ||||||
|  |         password: process.env.DSQL_DB_PASSWORD, | ||||||
|  |         database: process.env.DSQL_DB_NAME, | ||||||
|  |         charset: "utf8mb4", | ||||||
|  |         ssl: (0, grabDbSSL_1.default)(), | ||||||
|  |     }, | ||||||
|  | }); | ||||||
|  | /** | ||||||
|  |  * # Main DB Handler Function | ||||||
|  |  */ | ||||||
|  | function dbHandler(...args) { | ||||||
|  |     return __awaiter(this, void 0, void 0, function* () { | ||||||
|  |         var _a; | ||||||
|  |         ((_a = process.env.NODE_ENV) === null || _a === void 0 ? void 0 : _a.match(/dev/)) && | ||||||
|  |             fs_1.default.appendFileSync("./.tmp/sqlQuery.sql", args[0] + "\n" + Date() + "\n\n\n", "utf8"); | ||||||
|  |         /** | ||||||
|  |          * Declare variables | ||||||
|  |          * | ||||||
|  |          * @description Declare "results" variable | ||||||
|  |          */ | ||||||
|  |         let results; | ||||||
|  |         /** | ||||||
|  |          * Fetch from db | ||||||
|  |          * | ||||||
|  |          * @description Fetch data from db if no cache | ||||||
|  |          */ | ||||||
|  |         try { | ||||||
|  |             results = yield new Promise((resolve, reject) => { | ||||||
|  |                 connection.query(...args, (error, result, fields) => { | ||||||
|  |                     if (error) { | ||||||
|  |                         resolve({ error: error.message }); | ||||||
|  |                     } | ||||||
|  |                     else { | ||||||
|  |                         resolve(result); | ||||||
|  |                     } | ||||||
|  |                 }); | ||||||
|  |             }); | ||||||
|  |             yield connection.end(); | ||||||
|  |         } | ||||||
|  |         catch (error) { | ||||||
|  |             fs_1.default.appendFileSync("./.tmp/dbErrorLogs.txt", JSON.stringify(error, null, 4) + "\n" + Date() + "\n\n\n", "utf8"); | ||||||
|  |             results = null; | ||||||
|  |             (0, serverError_1.default)({ | ||||||
|  |                 component: "dbHandler", | ||||||
|  |                 message: error.message, | ||||||
|  |             }); | ||||||
|  |         } | ||||||
|  |         /** | ||||||
|  |          * Return results | ||||||
|  |          * | ||||||
|  |          * @description Return results add to cache if "req" param is passed | ||||||
|  |          */ | ||||||
|  |         if (results) { | ||||||
|  |             return JSON.parse(JSON.stringify(results)); | ||||||
|  |         } | ||||||
|  |         else { | ||||||
|  |             return null; | ||||||
|  |         } | ||||||
|  |     }); | ||||||
|  | } | ||||||
							
								
								
									
										7
									
								
								dist/package-shared/functions/backend/defaultFieldsRegexp.d.ts
									
									
									
									
										vendored
									
									
										Normal file
									
								
							
							
						
						
									
										7
									
								
								dist/package-shared/functions/backend/defaultFieldsRegexp.d.ts
									
									
									
									
										vendored
									
									
										Normal file
									
								
							| @ -0,0 +1,7 @@ | |||||||
|  | /** | ||||||
|  |  * Regular expression to match default fields | ||||||
|  |  * | ||||||
|  |  * @description Regular expression to match default fields | ||||||
|  |  */ | ||||||
|  | declare const defaultFieldsRegexp: RegExp; | ||||||
|  | export default defaultFieldsRegexp; | ||||||
							
								
								
									
										9
									
								
								dist/package-shared/functions/backend/defaultFieldsRegexp.js
									
									
									
									
										vendored
									
									
										Normal file
									
								
							
							
						
						
									
										9
									
								
								dist/package-shared/functions/backend/defaultFieldsRegexp.js
									
									
									
									
										vendored
									
									
										Normal file
									
								
							| @ -0,0 +1,9 @@ | |||||||
|  | "use strict"; | ||||||
|  | Object.defineProperty(exports, "__esModule", { value: true }); | ||||||
|  | /** | ||||||
|  |  * Regular expression to match default fields | ||||||
|  |  * | ||||||
|  |  * @description Regular expression to match default fields | ||||||
|  |  */ | ||||||
|  | const defaultFieldsRegexp = /^id$|^uuid$|^date_created$|^date_created_code$|^date_created_timestamp$|^date_updated$|^date_updated_code$|^date_updated_timestamp$/; | ||||||
|  | exports.default = defaultFieldsRegexp; | ||||||
							
								
								
									
										12
									
								
								dist/package-shared/functions/backend/fullAccessDbHandler.d.ts
									
									
									
									
										vendored
									
									
										Normal file
									
								
							
							
						
						
									
										12
									
								
								dist/package-shared/functions/backend/fullAccessDbHandler.d.ts
									
									
									
									
										vendored
									
									
										Normal file
									
								
							| @ -0,0 +1,12 @@ | |||||||
|  | type Param = { | ||||||
|  |     queryString: string; | ||||||
|  |     database: string; | ||||||
|  |     local?: boolean; | ||||||
|  |     tableSchema?: import("../../types").DSQL_TableSchemaType | null; | ||||||
|  |     queryValuesArray?: string[]; | ||||||
|  | }; | ||||||
|  | /** | ||||||
|  |  * # Full Access Db Handler | ||||||
|  |  */ | ||||||
|  | export default function fullAccessDbHandler({ queryString, database, tableSchema, queryValuesArray, local, }: Param): Promise<any>; | ||||||
|  | export {}; | ||||||
							
								
								
									
										80
									
								
								dist/package-shared/functions/backend/fullAccessDbHandler.js
									
									
									
									
										vendored
									
									
										Normal file
									
								
							
							
						
						
									
										80
									
								
								dist/package-shared/functions/backend/fullAccessDbHandler.js
									
									
									
									
										vendored
									
									
										Normal file
									
								
							| @ -0,0 +1,80 @@ | |||||||
|  | "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 = fullAccessDbHandler; | ||||||
|  | const DSQL_USER_DB_HANDLER_1 = __importDefault(require("../../utils/backend/global-db/DSQL_USER_DB_HANDLER")); | ||||||
|  | const LOCAL_DB_HANDLER_1 = __importDefault(require("../../utils/backend/global-db/LOCAL_DB_HANDLER")); | ||||||
|  | const parseDbResults_1 = __importDefault(require("./parseDbResults")); | ||||||
|  | const serverError_1 = __importDefault(require("./serverError")); | ||||||
|  | /** | ||||||
|  |  * # Full Access Db Handler | ||||||
|  |  */ | ||||||
|  | function fullAccessDbHandler(_a) { | ||||||
|  |     return __awaiter(this, arguments, void 0, function* ({ queryString, database, tableSchema, queryValuesArray, local, }) { | ||||||
|  |         /** | ||||||
|  |          * Declare variables | ||||||
|  |          * | ||||||
|  |          * @description Declare "results" variable | ||||||
|  |          */ | ||||||
|  |         let results; | ||||||
|  |         /** | ||||||
|  |          * Fetch from db | ||||||
|  |          * | ||||||
|  |          * @description Fetch data from db if no cache | ||||||
|  |          */ | ||||||
|  |         try { | ||||||
|  |             /** ********************* Run Query */ | ||||||
|  |             results = local | ||||||
|  |                 ? yield (0, LOCAL_DB_HANDLER_1.default)(queryString, queryValuesArray) | ||||||
|  |                 : yield (0, DSQL_USER_DB_HANDLER_1.default)({ | ||||||
|  |                     paradigm: "Full Access", | ||||||
|  |                     database, | ||||||
|  |                     queryString, | ||||||
|  |                     queryValues: queryValuesArray, | ||||||
|  |                 }); | ||||||
|  |             ////////////////////////////////////////
 | ||||||
|  |         } | ||||||
|  |         catch ( /** @type {any} */error) { | ||||||
|  |             ////////////////////////////////////////
 | ||||||
|  |             (0, serverError_1.default)({ | ||||||
|  |                 component: "fullAccessDbHandler", | ||||||
|  |                 message: error.message, | ||||||
|  |             }); | ||||||
|  |             /** | ||||||
|  |              * Return error | ||||||
|  |              */ | ||||||
|  |             return error.message; | ||||||
|  |         } | ||||||
|  |         /** | ||||||
|  |          * Return results | ||||||
|  |          * | ||||||
|  |          * @description Return results add to cache if "req" param is passed | ||||||
|  |          */ | ||||||
|  |         if (results && tableSchema) { | ||||||
|  |             const unparsedResults = results; | ||||||
|  |             const parsedResults = yield (0, parseDbResults_1.default)({ | ||||||
|  |                 unparsedResults: unparsedResults, | ||||||
|  |                 tableSchema: tableSchema, | ||||||
|  |             }); | ||||||
|  |             return parsedResults; | ||||||
|  |         } | ||||||
|  |         else if (results) { | ||||||
|  |             return results; | ||||||
|  |         } | ||||||
|  |         else { | ||||||
|  |             return null; | ||||||
|  |         } | ||||||
|  |     }); | ||||||
|  | } | ||||||
							
								
								
									
										9
									
								
								dist/package-shared/functions/backend/grabNewUsersTableSchema.d.ts
									
									
									
									
										vendored
									
									
										Normal file
									
								
							
							
						
						
									
										9
									
								
								dist/package-shared/functions/backend/grabNewUsersTableSchema.d.ts
									
									
									
									
										vendored
									
									
										Normal file
									
								
							| @ -0,0 +1,9 @@ | |||||||
|  | import { DSQL_TableSchemaType } from "../../types"; | ||||||
|  | /** | ||||||
|  |  * # Add User Table to Database | ||||||
|  |  */ | ||||||
|  | export default function grabNewUsersTableSchema(params: { | ||||||
|  |     payload?: { | ||||||
|  |         [s: string]: any; | ||||||
|  |     }; | ||||||
|  | }): DSQL_TableSchemaType | null; | ||||||
							
								
								
									
										42
									
								
								dist/package-shared/functions/backend/grabNewUsersTableSchema.js
									
									
									
									
										vendored
									
									
										Normal file
									
								
							
							
						
						
									
										42
									
								
								dist/package-shared/functions/backend/grabNewUsersTableSchema.js
									
									
									
									
										vendored
									
									
										Normal file
									
								
							| @ -0,0 +1,42 @@ | |||||||
|  | "use strict"; | ||||||
|  | var __importDefault = (this && this.__importDefault) || function (mod) { | ||||||
|  |     return (mod && mod.__esModule) ? mod : { "default": mod }; | ||||||
|  | }; | ||||||
|  | Object.defineProperty(exports, "__esModule", { value: true }); | ||||||
|  | exports.default = grabNewUsersTableSchema; | ||||||
|  | const grabSchemaFieldsFromData_1 = __importDefault(require("./grabSchemaFieldsFromData")); | ||||||
|  | const serverError_1 = __importDefault(require("./serverError")); | ||||||
|  | /** | ||||||
|  |  * # Add User Table to Database | ||||||
|  |  */ | ||||||
|  | function grabNewUsersTableSchema(params) { | ||||||
|  |     try { | ||||||
|  |         const userPreset = require("../../data/presets/users.json"); | ||||||
|  |         const defaultFields = require("../../data/defaultFields.json"); | ||||||
|  |         const supplementalFields = (params === null || params === void 0 ? void 0 : params.payload) | ||||||
|  |             ? (0, grabSchemaFieldsFromData_1.default)({ | ||||||
|  |                 data: params === null || params === void 0 ? void 0 : params.payload, | ||||||
|  |                 excludeData: defaultFields, | ||||||
|  |                 excludeFields: userPreset.fields, | ||||||
|  |             }) | ||||||
|  |             : []; | ||||||
|  |         console.log("supplementalFields", supplementalFields); | ||||||
|  |         const allFields = [...userPreset.fields, ...supplementalFields]; | ||||||
|  |         console.log("allFields", allFields); | ||||||
|  |         const finalFields = [ | ||||||
|  |             ...defaultFields.slice(0, 2), | ||||||
|  |             ...allFields, | ||||||
|  |             ...defaultFields.slice(2), | ||||||
|  |         ]; | ||||||
|  |         userPreset.fields = [...finalFields]; | ||||||
|  |         return userPreset; | ||||||
|  |     } | ||||||
|  |     catch ( /** @type {any} */error) { | ||||||
|  |         console.log(`grabNewUsersTableSchema.js ERROR: ${error.message}`); | ||||||
|  |         (0, serverError_1.default)({ | ||||||
|  |             component: "grabNewUsersTableSchema", | ||||||
|  |             message: error.message, | ||||||
|  |         }); | ||||||
|  |         return null; | ||||||
|  |     } | ||||||
|  | } | ||||||
							
								
								
									
										16
									
								
								dist/package-shared/functions/backend/grabSchemaFieldsFromData.d.ts
									
									
									
									
										vendored
									
									
										Normal file
									
								
							
							
						
						
									
										16
									
								
								dist/package-shared/functions/backend/grabSchemaFieldsFromData.d.ts
									
									
									
									
										vendored
									
									
										Normal file
									
								
							| @ -0,0 +1,16 @@ | |||||||
|  | import { DSQL_FieldSchemaType } from "../../types"; | ||||||
|  | type Param = { | ||||||
|  |     data?: { | ||||||
|  |         [s: string]: any; | ||||||
|  |     }; | ||||||
|  |     fields?: string[]; | ||||||
|  |     excludeData?: { | ||||||
|  |         [s: string]: any; | ||||||
|  |     }; | ||||||
|  |     excludeFields?: DSQL_FieldSchemaType[]; | ||||||
|  | }; | ||||||
|  | /** | ||||||
|  |  * # Add User Table to Database | ||||||
|  |  */ | ||||||
|  | export default function grabSchemaFieldsFromData({ data, fields, excludeData, excludeFields, }: Param): DSQL_FieldSchemaType[]; | ||||||
|  | export {}; | ||||||
							
								
								
									
										66
									
								
								dist/package-shared/functions/backend/grabSchemaFieldsFromData.js
									
									
									
									
										vendored
									
									
										Normal file
									
								
							
							
						
						
									
										66
									
								
								dist/package-shared/functions/backend/grabSchemaFieldsFromData.js
									
									
									
									
										vendored
									
									
										Normal file
									
								
							| @ -0,0 +1,66 @@ | |||||||
|  | "use strict"; | ||||||
|  | var __importDefault = (this && this.__importDefault) || function (mod) { | ||||||
|  |     return (mod && mod.__esModule) ? mod : { "default": mod }; | ||||||
|  | }; | ||||||
|  | Object.defineProperty(exports, "__esModule", { value: true }); | ||||||
|  | exports.default = grabSchemaFieldsFromData; | ||||||
|  | const serverError_1 = __importDefault(require("./serverError")); | ||||||
|  | /** | ||||||
|  |  * # Add User Table to Database | ||||||
|  |  */ | ||||||
|  | function grabSchemaFieldsFromData({ data, fields, excludeData, excludeFields, }) { | ||||||
|  |     var _a; | ||||||
|  |     try { | ||||||
|  |         const possibleFields = require("../../data/possibleFields.json"); | ||||||
|  |         const dataTypes = require("../../data/dataTypes.json"); | ||||||
|  |         /** @type {DSQL_FieldSchemaType[]} */ | ||||||
|  |         const finalFields = []; | ||||||
|  |         /** @type {string[]} */ | ||||||
|  |         let filteredFields = []; | ||||||
|  |         if (data && ((_a = Object.keys(data)) === null || _a === void 0 ? void 0 : _a[0])) { | ||||||
|  |             filteredFields = Object.keys(data); | ||||||
|  |         } | ||||||
|  |         if (fields) { | ||||||
|  |             filteredFields = [...filteredFields, ...fields]; | ||||||
|  |             filteredFields = [...new Set(filteredFields)]; | ||||||
|  |         } | ||||||
|  |         filteredFields = filteredFields | ||||||
|  |             .filter((fld) => !excludeData || !Object.keys(excludeData).includes(fld)) | ||||||
|  |             .filter((fld) => !excludeFields || | ||||||
|  |             !excludeFields.find((exlFld) => exlFld.fieldName == fld)); | ||||||
|  |         filteredFields.forEach((fld) => { | ||||||
|  |             const value = data ? data[fld] : null; | ||||||
|  |             if (typeof value == "string") { | ||||||
|  |                 const newField = { | ||||||
|  |                     fieldName: fld, | ||||||
|  |                     dataType: value.length > 255 ? "TEXT" : "VARCHAR(255)", | ||||||
|  |                 }; | ||||||
|  |                 if (Boolean(value.match(/<[^>]+>/g))) { | ||||||
|  |                     newField.richText = true; | ||||||
|  |                 } | ||||||
|  |                 finalFields.push(newField); | ||||||
|  |             } | ||||||
|  |             else if (typeof value == "number") { | ||||||
|  |                 finalFields.push({ | ||||||
|  |                     fieldName: fld, | ||||||
|  |                     dataType: "INT", | ||||||
|  |                 }); | ||||||
|  |             } | ||||||
|  |             else { | ||||||
|  |                 finalFields.push({ | ||||||
|  |                     fieldName: fld, | ||||||
|  |                     dataType: "VARCHAR(255)", | ||||||
|  |                 }); | ||||||
|  |             } | ||||||
|  |         }); | ||||||
|  |         return finalFields; | ||||||
|  |     } | ||||||
|  |     catch ( /** @type {any} */error) { | ||||||
|  |         console.log(`grabSchemaFieldsFromData.js ERROR: ${error.message}`); | ||||||
|  |         (0, serverError_1.default)({ | ||||||
|  |             component: "grabSchemaFieldsFromData.js", | ||||||
|  |             message: error.message, | ||||||
|  |         }); | ||||||
|  |         return []; | ||||||
|  |     } | ||||||
|  | } | ||||||
							
								
								
									
										6
									
								
								dist/package-shared/functions/backend/grabUserSchemaData.d.ts
									
									
									
									
										vendored
									
									
										Normal file
									
								
							
							
						
						
									
										6
									
								
								dist/package-shared/functions/backend/grabUserSchemaData.d.ts
									
									
									
									
										vendored
									
									
										Normal file
									
								
							| @ -0,0 +1,6 @@ | |||||||
|  | /** | ||||||
|  |  * # Grab User Schema Data | ||||||
|  |  */ | ||||||
|  | export default function grabUserSchemaData({ userId, }: { | ||||||
|  |     userId: string | number; | ||||||
|  | }): import("../../types").DSQL_DatabaseSchemaType[] | null; | ||||||
							
								
								
									
										26
									
								
								dist/package-shared/functions/backend/grabUserSchemaData.js
									
									
									
									
										vendored
									
									
										Normal file
									
								
							
							
						
						
									
										26
									
								
								dist/package-shared/functions/backend/grabUserSchemaData.js
									
									
									
									
										vendored
									
									
										Normal file
									
								
							| @ -0,0 +1,26 @@ | |||||||
|  | "use strict"; | ||||||
|  | var __importDefault = (this && this.__importDefault) || function (mod) { | ||||||
|  |     return (mod && mod.__esModule) ? mod : { "default": mod }; | ||||||
|  | }; | ||||||
|  | Object.defineProperty(exports, "__esModule", { value: true }); | ||||||
|  | exports.default = grabUserSchemaData; | ||||||
|  | const serverError_1 = __importDefault(require("./serverError")); | ||||||
|  | const fs_1 = __importDefault(require("fs")); | ||||||
|  | const path_1 = __importDefault(require("path")); | ||||||
|  | /** | ||||||
|  |  * # Grab User Schema Data | ||||||
|  |  */ | ||||||
|  | function grabUserSchemaData({ userId, }) { | ||||||
|  |     try { | ||||||
|  |         const userSchemaFilePath = path_1.default.resolve(process.cwd(), `${process.env.DSQL_USER_DB_SCHEMA_PATH}/user-${userId}/main.json`); | ||||||
|  |         const userSchemaData = JSON.parse(fs_1.default.readFileSync(userSchemaFilePath, "utf-8")); | ||||||
|  |         return userSchemaData; | ||||||
|  |     } | ||||||
|  |     catch (error) { | ||||||
|  |         (0, serverError_1.default)({ | ||||||
|  |             component: "grabUserSchemaData", | ||||||
|  |             message: error.message, | ||||||
|  |         }); | ||||||
|  |         return null; | ||||||
|  |     } | ||||||
|  | } | ||||||
							
								
								
									
										13
									
								
								dist/package-shared/functions/backend/handleNodemailer.d.ts
									
									
									
									
										vendored
									
									
										Normal file
									
								
							
							
						
						
									
										13
									
								
								dist/package-shared/functions/backend/handleNodemailer.d.ts
									
									
									
									
										vendored
									
									
										Normal file
									
								
							| @ -0,0 +1,13 @@ | |||||||
|  | type Param = { | ||||||
|  |     to?: string; | ||||||
|  |     subject?: string; | ||||||
|  |     text?: string; | ||||||
|  |     html?: string; | ||||||
|  |     senderName?: string; | ||||||
|  |     alias?: string | null; | ||||||
|  | }; | ||||||
|  | /** | ||||||
|  |  * # Handle mails With Nodemailer | ||||||
|  |  */ | ||||||
|  | export default function handleNodemailer({ to, subject, text, html, alias, senderName, }: Param): Promise<any>; | ||||||
|  | export {}; | ||||||
							
								
								
									
										89
									
								
								dist/package-shared/functions/backend/handleNodemailer.js
									
									
									
									
										vendored
									
									
										Normal file
									
								
							
							
						
						
									
										89
									
								
								dist/package-shared/functions/backend/handleNodemailer.js
									
									
									
									
										vendored
									
									
										Normal file
									
								
							| @ -0,0 +1,89 @@ | |||||||
|  | "use strict"; | ||||||
|  | var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { | ||||||
|  |     function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } | ||||||
|  |     return new (P || (P = Promise))(function (resolve, reject) { | ||||||
|  |         function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } | ||||||
|  |         function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } | ||||||
|  |         function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } | ||||||
|  |         step((generator = generator.apply(thisArg, _arguments || [])).next()); | ||||||
|  |     }); | ||||||
|  | }; | ||||||
|  | var __importDefault = (this && this.__importDefault) || function (mod) { | ||||||
|  |     return (mod && mod.__esModule) ? mod : { "default": mod }; | ||||||
|  | }; | ||||||
|  | Object.defineProperty(exports, "__esModule", { value: true }); | ||||||
|  | exports.default = handleNodemailer; | ||||||
|  | const fs_1 = __importDefault(require("fs")); | ||||||
|  | const nodemailer_1 = __importDefault(require("nodemailer")); | ||||||
|  | let transporter = nodemailer_1.default.createTransport({ | ||||||
|  |     host: process.env.DSQL_MAIL_HOST, | ||||||
|  |     port: 465, | ||||||
|  |     secure: true, | ||||||
|  |     auth: { | ||||||
|  |         user: process.env.DSQL_MAIL_EMAIL, | ||||||
|  |         pass: process.env.DSQL_MAIL_PASSWORD, | ||||||
|  |     }, | ||||||
|  | }); | ||||||
|  | /** | ||||||
|  |  * # Handle mails With Nodemailer | ||||||
|  |  */ | ||||||
|  | function handleNodemailer(_a) { | ||||||
|  |     return __awaiter(this, arguments, void 0, function* ({ to, subject, text, html, alias, senderName, }) { | ||||||
|  |         ////////////////////////////////////////
 | ||||||
|  |         ////////////////////////////////////////
 | ||||||
|  |         ////////////////////////////////////////
 | ||||||
|  |         if (!process.env.DSQL_MAIL_HOST || | ||||||
|  |             !process.env.DSQL_MAIL_EMAIL || | ||||||
|  |             !process.env.DSQL_MAIL_PASSWORD) { | ||||||
|  |             return null; | ||||||
|  |         } | ||||||
|  |         const sender = (() => { | ||||||
|  |             if (alias === null || alias === void 0 ? void 0 : alias.match(/support/i)) | ||||||
|  |                 return process.env.DSQL_MAIL_EMAIL; | ||||||
|  |             return process.env.DSQL_MAIL_EMAIL; | ||||||
|  |         })(); | ||||||
|  |         ////////////////////////////////////////
 | ||||||
|  |         ////////////////////////////////////////
 | ||||||
|  |         ////////////////////////////////////////
 | ||||||
|  |         let sentMessage; | ||||||
|  |         if (!fs_1.default.existsSync("./email/index.html")) { | ||||||
|  |             return; | ||||||
|  |         } | ||||||
|  |         let mailRoot = fs_1.default.readFileSync("./email/index.html", "utf8"); | ||||||
|  |         let finalHtml = mailRoot | ||||||
|  |             .replace(/{{email_body}}/, html ? html : "") | ||||||
|  |             .replace(/{{issue_date}}/, Date().substring(0, 24)); | ||||||
|  |         ////////////////////////////////////////
 | ||||||
|  |         ////////////////////////////////////////
 | ||||||
|  |         ////////////////////////////////////////
 | ||||||
|  |         try { | ||||||
|  |             let mailObject = {}; | ||||||
|  |             mailObject["from"] = `"${senderName || "Datasquirel"}" <${sender}>`; | ||||||
|  |             mailObject["sender"] = sender; | ||||||
|  |             if (alias) | ||||||
|  |                 mailObject["replyTo"] = sender; | ||||||
|  |             mailObject["to"] = to; | ||||||
|  |             mailObject["subject"] = subject; | ||||||
|  |             mailObject["text"] = text; | ||||||
|  |             mailObject["html"] = finalHtml; | ||||||
|  |             // send mail with defined transport object
 | ||||||
|  |             let info = yield transporter.sendMail(mailObject); | ||||||
|  |             sentMessage = info; | ||||||
|  |             ////////////////////////////////////////
 | ||||||
|  |             ////////////////////////////////////////
 | ||||||
|  |             ////////////////////////////////////////
 | ||||||
|  |         } | ||||||
|  |         catch ( /** @type {any} */error) { | ||||||
|  |             ////////////////////////////////////////
 | ||||||
|  |             ////////////////////////////////////////
 | ||||||
|  |             ////////////////////////////////////////
 | ||||||
|  |             console.log("ERROR in handleNodemailer Function =>", error.message); | ||||||
|  |             // serverError({
 | ||||||
|  |             //     component: "handleNodemailer",
 | ||||||
|  |             //     message: error.message,
 | ||||||
|  |             //     user: { email: to },
 | ||||||
|  |             // });
 | ||||||
|  |         } | ||||||
|  |         return sentMessage; | ||||||
|  |     }); | ||||||
|  | } | ||||||
							
								
								
									
										9
									
								
								dist/package-shared/functions/backend/html/sanitizeHtmlOptions.d.ts
									
									
									
									
										vendored
									
									
										Normal file
									
								
							
							
						
						
									
										9
									
								
								dist/package-shared/functions/backend/html/sanitizeHtmlOptions.d.ts
									
									
									
									
										vendored
									
									
										Normal file
									
								
							| @ -0,0 +1,9 @@ | |||||||
|  | declare const sanitizeHtmlOptions: { | ||||||
|  |     allowedTags: string[]; | ||||||
|  |     allowedAttributes: { | ||||||
|  |         a: string[]; | ||||||
|  |         img: string[]; | ||||||
|  |         "*": string[]; | ||||||
|  |     }; | ||||||
|  | }; | ||||||
|  | export default sanitizeHtmlOptions; | ||||||
Some files were not shown because too many files have changed in this diff Show More
		Loading…
	
		Reference in New Issue
	
	Block a user
	 Benjamin Toby
						Benjamin Toby