Update Cookie Expiry Logic
This commit is contained in:
		
							parent
							
								
									870bc7fd17
								
							
						
					
					
						commit
						e829ebd2ed
					
				| @ -21,6 +21,7 @@ const api_login_1 = __importDefault(require("../../functions/api/users/api-login | ||||
| const get_auth_cookie_names_1 = __importDefault(require("../../functions/backend/cookies/get-auth-cookie-names")); | ||||
| const write_auth_files_1 = require("../../functions/backend/auth/write-auth-files"); | ||||
| const debug_log_1 = __importDefault(require("../../utils/logging/debug-log")); | ||||
| const grab_cookie_expirt_date_1 = __importDefault(require("../../utils/grab-cookie-expirt-date")); | ||||
| /** | ||||
|  * # Login A user | ||||
|  */ | ||||
| @ -29,6 +30,7 @@ function loginUser(_a) { | ||||
|         var _b, _c, _d; | ||||
|         const grabedHostNames = (0, grab_host_names_1.default)({ userId: user_id || apiUserID }); | ||||
|         const { host, port, scheme } = grabedHostNames; | ||||
|         const COOKIE_EXPIRY_DATE = (0, grab_cookie_expirt_date_1.default)(); | ||||
|         const defaultTempLoginFieldName = "temp_login_code"; | ||||
|         const emailLoginTempCodeFieldName = email_login | ||||
|             ? temp_code_field | ||||
| @ -71,7 +73,6 @@ function loginUser(_a) { | ||||
|         /** | ||||
|          * Initialize HTTP response variable | ||||
|          */ | ||||
|         /** @type {import("../../types").APILoginFunctionReturn} */ | ||||
|         let httpResponse = { | ||||
|             success: false, | ||||
|         }; | ||||
| @ -186,8 +187,8 @@ function loginUser(_a) { | ||||
|                 debugFn(encryptedPayload, "encryptedPayload"); | ||||
|             } | ||||
|             response === null || response === void 0 ? void 0 : response.setHeader("Set-Cookie", [ | ||||
|                 `${authKeyName}=${encryptedPayload};samesite=strict;path=/;HttpOnly=true${secureCookie ? ";Secure=true" : ""}`, | ||||
|                 `${csrfName}=${(_d = httpResponse.payload) === null || _d === void 0 ? void 0 : _d.csrf_k};samesite=strict;path=/;HttpOnly=true`, | ||||
|                 `${authKeyName}=${encryptedPayload};samesite=strict;path=/;HttpOnly=true;Expires=${COOKIE_EXPIRY_DATE}${secureCookie ? ";Secure=true" : ""}`, | ||||
|                 `${csrfName}=${(_d = httpResponse.payload) === null || _d === void 0 ? void 0 : _d.csrf_k};samesite=strict;path=/;HttpOnly=true;Expires=${COOKIE_EXPIRY_DATE}`, | ||||
|             ]); | ||||
|             if (debug) { | ||||
|                 debugFn("Response Sent!"); | ||||
|  | ||||
| @ -21,6 +21,7 @@ const grab_host_names_1 = __importDefault(require("../../utils/grab-host-names") | ||||
| const api_reauth_user_1 = __importDefault(require("../../functions/api/users/api-reauth-user")); | ||||
| const write_auth_files_1 = require("../../functions/backend/auth/write-auth-files"); | ||||
| const get_auth_cookie_names_1 = __importDefault(require("../../functions/backend/cookies/get-auth-cookie-names")); | ||||
| const grab_cookie_expirt_date_1 = __importDefault(require("../../utils/grab-cookie-expirt-date")); | ||||
| /** | ||||
|  * # Reauthorize User | ||||
|  */ | ||||
| @ -34,6 +35,7 @@ function reauthUser(_a) { | ||||
|          */ | ||||
|         const grabedHostNames = (0, grab_host_names_1.default)(); | ||||
|         const { host, port, scheme } = grabedHostNames; | ||||
|         const COOKIE_EXPIRY_DATE = (0, grab_cookie_expirt_date_1.default)(); | ||||
|         const finalEncryptionKey = encryptionKey || process.env.DSQL_ENCRYPTION_PASSWORD; | ||||
|         const finalEncryptionSalt = encryptionSalt || process.env.DSQL_ENCRYPTION_SALT; | ||||
|         const existingUser = (0, user_auth_1.default)({ | ||||
| @ -143,8 +145,8 @@ function reauthUser(_a) { | ||||
|             const authKeyName = cookieNames.keyCookieName; | ||||
|             const csrfName = cookieNames.csrfCookieName; | ||||
|             response === null || response === void 0 ? void 0 : response.setHeader("Set-Cookie", [ | ||||
|                 `${authKeyName}=${encryptedPayload};samesite=strict;path=/;HttpOnly=true${secureCookie ? ";Secure=true" : ""}`, | ||||
|                 `${csrfName}=${(_c = httpResponse.payload) === null || _c === void 0 ? void 0 : _c.csrf_k};samesite=strict;path=/;HttpOnly=true`, | ||||
|                 `${authKeyName}=${encryptedPayload};samesite=strict;path=/;HttpOnly=true;Expires=${COOKIE_EXPIRY_DATE}${secureCookie ? ";Secure=true" : ""}`, | ||||
|                 `${csrfName}=${(_c = httpResponse.payload) === null || _c === void 0 ? void 0 : _c.csrf_k};samesite=strict;path=/;HttpOnly=true;Expires=${COOKIE_EXPIRY_DATE}`, | ||||
|             ]); | ||||
|             if (httpResponse.csrf) { | ||||
|                 (0, write_auth_files_1.deleteAuthFile)(String(existingUser.payload.csrf_k)); | ||||
|  | ||||
| @ -18,6 +18,7 @@ const path_1 = __importDefault(require("path")); | ||||
| const encrypt_1 = __importDefault(require("../../../functions/dsql/encrypt")); | ||||
| const grab_host_names_1 = __importDefault(require("../../../utils/grab-host-names")); | ||||
| const api_github_login_1 = __importDefault(require("../../../functions/api/users/social/api-github-login")); | ||||
| const grab_cookie_expirt_date_1 = __importDefault(require("../../../utils/grab-cookie-expirt-date")); | ||||
| /** | ||||
|  * # SERVER FUNCTION: Login with google Function | ||||
|  */ | ||||
| @ -30,6 +31,7 @@ function githubAuth(_a) { | ||||
|          */ | ||||
|         const grabedHostNames = (0, grab_host_names_1.default)(); | ||||
|         const { host, port, scheme } = grabedHostNames; | ||||
|         const COOKIE_EXPIRY_DATE = (0, grab_cookie_expirt_date_1.default)(); | ||||
|         if (!code || (code === null || code === void 0 ? void 0 : code.match(/ /))) { | ||||
|             return { | ||||
|                 success: false, | ||||
| @ -162,8 +164,8 @@ function githubAuth(_a) { | ||||
|             const authKeyName = `datasquirel_${dsqlUserId}_${database}_auth_key`; | ||||
|             const csrfName = `datasquirel_${dsqlUserId}_${database}_csrf`; | ||||
|             response.setHeader("Set-Cookie", [ | ||||
|                 `${authKeyName}=${encryptedPayload};samesite=strict;path=/;HttpOnly=true${secureCookie ? ";Secure=true" : ""}`, | ||||
|                 `${csrfName}=${user.csrf_k};samesite=strict;path=/;HttpOnly=true`, | ||||
|                 `${authKeyName}=${encryptedPayload};samesite=strict;path=/;HttpOnly=true;Expires=${COOKIE_EXPIRY_DATE}${secureCookie ? ";Secure=true" : ""}`, | ||||
|                 `${csrfName}=${user.csrf_k};samesite=strict;path=/;HttpOnly=true;Expires=${COOKIE_EXPIRY_DATE}`, | ||||
|             ]); | ||||
|         } | ||||
|         return httpResponse; | ||||
|  | ||||
| @ -18,6 +18,7 @@ const grab_host_names_1 = __importDefault(require("../../../utils/grab-host-name | ||||
| const api_google_login_1 = __importDefault(require("../../../functions/api/users/social/api-google-login")); | ||||
| const get_auth_cookie_names_1 = __importDefault(require("../../../functions/backend/cookies/get-auth-cookie-names")); | ||||
| const write_auth_files_1 = require("../../../functions/backend/auth/write-auth-files"); | ||||
| const grab_cookie_expirt_date_1 = __importDefault(require("../../../utils/grab-cookie-expirt-date")); | ||||
| /** | ||||
|  * # SERVER FUNCTION: Login with google Function | ||||
|  */ | ||||
| @ -28,6 +29,7 @@ function googleAuth(_a) { | ||||
|             userId: apiUserID || process.env.DSQL_API_USER_ID, | ||||
|         }); | ||||
|         const { host, port, scheme, user_id } = grabedHostNames; | ||||
|         const COOKIE_EXPIRY_DATE = (0, grab_cookie_expirt_date_1.default)(); | ||||
|         const finalEncryptionKey = encryptionKey || process.env.DSQL_ENCRYPTION_PASSWORD; | ||||
|         const finalEncryptionSalt = encryptionSalt || process.env.DSQL_ENCRYPTION_SALT; | ||||
|         if (!(finalEncryptionKey === null || finalEncryptionKey === void 0 ? void 0 : finalEncryptionKey.match(/.{8,}/))) { | ||||
| @ -150,8 +152,8 @@ function googleAuth(_a) { | ||||
|             const authKeyName = cookieNames.keyCookieName; | ||||
|             const csrfName = cookieNames.csrfCookieName; | ||||
|             response === null || response === void 0 ? void 0 : response.setHeader("Set-Cookie", [ | ||||
|                 `${authKeyName}=${encryptedPayload};samesite=strict;path=/;HttpOnly=true${secureCookie ? ";Secure=true" : ""}`, | ||||
|                 `${csrfName}=${(_b = httpResponse.payload) === null || _b === void 0 ? void 0 : _b.csrf_k};samesite=strict;path=/;HttpOnly=true`, | ||||
|                 `${authKeyName}=${encryptedPayload};samesite=strict;path=/;HttpOnly=true;;Expires=${COOKIE_EXPIRY_DATE}${secureCookie ? ";Secure=true" : ""}`, | ||||
|                 `${csrfName}=${(_b = httpResponse.payload) === null || _b === void 0 ? void 0 : _b.csrf_k};samesite=strict;path=/;HttpOnly=true;;Expires=${COOKIE_EXPIRY_DATE}`, | ||||
|             ]); | ||||
|         } | ||||
|         return httpResponse; | ||||
|  | ||||
| @ -49,9 +49,6 @@ function handleGrants(_a) { | ||||
|                         const revokePrivilege = yield (0, noDatabaseDbHandler_1.default)(revokeGrantText); | ||||
|                     } | ||||
|                 } | ||||
|                 /** | ||||
|                  * @type {GrantType[]} | ||||
|                  */ | ||||
|                 const grantsArray = grants; | ||||
|                 for (let i = 0; i < grantsArray.length; i++) { | ||||
|                     const grantObject = grantsArray[i]; | ||||
|  | ||||
| @ -13,21 +13,18 @@ var __importDefault = (this && this.__importDefault) || function (mod) { | ||||
| }; | ||||
| Object.defineProperty(exports, "__esModule", { value: true }); | ||||
| exports.default = refreshUsersAndGrants; | ||||
| const path_1 = __importDefault(require("path")); | ||||
| require("dotenv").config({ path: path_1.default.resolve(__dirname, "../../../.env") }); | ||||
| const generate_password_1 = __importDefault(require("generate-password")); | ||||
| const noDatabaseDbHandler_1 = __importDefault(require("../utils/noDatabaseDbHandler")); | ||||
| const dbHandler_1 = __importDefault(require("../utils/dbHandler")); | ||||
| const handleGrants_1 = __importDefault(require("./handleGrants")); | ||||
| const encrypt_1 = __importDefault(require("../../functions/dsql/encrypt")); | ||||
| const decrypt_1 = __importDefault(require("../../functions/dsql/decrypt")); | ||||
| const defaultMariadbUserHost = process.env.DSQL_DB_HOST || "127.0.0.1"; | ||||
| /** | ||||
|  * # Refresh Mariadb User Grants | ||||
|  */ | ||||
| function refreshUsersAndGrants(_a) { | ||||
|     return __awaiter(this, arguments, void 0, function* ({ userId, mariadbUserHost, mariadbUsername, sqlUserID, }) { | ||||
|         var _b, _c, _d, _e, _f; | ||||
|         var _b, _c, _d; | ||||
|         const mariadbUsers = (yield (0, dbHandler_1.default)({ | ||||
|             query: `SELECT * FROM mariadb_users`, | ||||
|         })); | ||||
| @ -37,38 +34,29 @@ function refreshUsersAndGrants(_a) { | ||||
|         const isRootUser = userId | ||||
|             ? userId == Number(process.env.DSQL_SU_USER_ID) | ||||
|             : false; | ||||
|         const isWildcardHost = mariadbUserHost == "%"; | ||||
|         if (isWildcardHost && !isRootUser) { | ||||
|             return; | ||||
|         } | ||||
|         for (let i = 0; i < mariadbUsers.length; i++) { | ||||
|             const mariadbUser = mariadbUsers[i]; | ||||
|             if (!mariadbUser) | ||||
|                 continue; | ||||
|             if (userId && mariadbUser.user_id != userId) | ||||
|                 continue; | ||||
|             if (sqlUserID && mariadbUser.id != sqlUserID) | ||||
|                 continue; | ||||
|             try { | ||||
|                 const { mariadb_user, mariadb_host, mariadb_pass, user_id } = mariadbUser; | ||||
|                 const existingUser = yield (0, noDatabaseDbHandler_1.default)(`SELECT * FROM mysql.user WHERE User = '${mariadb_user}' AND Host = '${mariadb_host}'`); | ||||
|                 const existingMariaDBUserArray = userId && sqlUserID | ||||
|                     ? yield (0, dbHandler_1.default)({ | ||||
|                         query: `SELECT * FROM mariadb_users WHERE id = ? AND user_id = ?`, | ||||
|                         values: [sqlUserID, userId], | ||||
|                     }) | ||||
|                     : null; | ||||
|                 const activeMariadbUserObject = Array.isArray(existingMariaDBUserArray) | ||||
|                     ? existingMariaDBUserArray === null || existingMariaDBUserArray === void 0 ? void 0 : existingMariaDBUserArray[0] | ||||
|                     : undefined; | ||||
|                 const isPrimary = activeMariadbUserObject | ||||
|                     ? ((_b = String(activeMariadbUserObject.primary)) === null || _b === void 0 ? void 0 : _b.match(/1/)) | ||||
|                 const { username, password, host, user_id } = mariadbUser; | ||||
|                 const existingUser = yield (0, noDatabaseDbHandler_1.default)(`SELECT * FROM mysql.user WHERE User = '${username}' AND Host = '${host}'`); | ||||
|                 const isUserExisting = Boolean((_b = existingUser === null || existingUser === void 0 ? void 0 : existingUser[0]) === null || _b === void 0 ? void 0 : _b.User); | ||||
|                 const isPrimary = ((_c = String(mariadbUser.primary)) === null || _c === void 0 ? void 0 : _c.match(/1/)) | ||||
|                     ? true | ||||
|                         : false | ||||
|                     : false; | ||||
|                 const isUserExisting = Boolean((_c = existingUser === null || existingUser === void 0 ? void 0 : existingUser[0]) === null || _c === void 0 ? void 0 : _c.User); | ||||
|                 const isThisPrimaryHost = Boolean(mariadbUserHost == defaultMariadbUserHost); | ||||
|                 const dslUsername = isRootUser | ||||
|                     ? mariadbUsername | ||||
|                     : `dsql_user_${user_id}`; | ||||
|                 const dsqlPassword = (activeMariadbUserObject === null || activeMariadbUserObject === void 0 ? void 0 : activeMariadbUserObject.password) | ||||
|                     ? activeMariadbUserObject.password | ||||
|                     : isUserExisting | ||||
|                         ? mariadb_pass | ||||
|                 const dsqlPassword = (mariadbUser === null || mariadbUser === void 0 ? void 0 : mariadbUser.password) | ||||
|                     ? (0, decrypt_1.default)({ encryptedString: mariadbUser.password }) | ||||
|                     : isUserExisting && password | ||||
|                         ? (0, decrypt_1.default)({ encryptedString: password }) | ||||
|                         : generate_password_1.default.generate({ | ||||
|                             length: 16, | ||||
|                             numbers: true, | ||||
| @ -76,121 +64,46 @@ function refreshUsersAndGrants(_a) { | ||||
|                             uppercase: true, | ||||
|                             exclude: "*#.'`\"", | ||||
|                         }); | ||||
|                 const encryptedPassword = (activeMariadbUserObject === null || activeMariadbUserObject === void 0 ? void 0 : activeMariadbUserObject.password) | ||||
|                     ? activeMariadbUserObject.password | ||||
|                 const encryptedPassword = (mariadbUser === null || mariadbUser === void 0 ? void 0 : mariadbUser.password) | ||||
|                     ? mariadbUser.password | ||||
|                     : isUserExisting | ||||
|                         ? mariadb_pass | ||||
|                         : (0, encrypt_1.default)({ | ||||
|                             data: dsqlPassword, | ||||
|                             encryptionKey: process.env.DSQL_ENCRYPTION_PASSWORD, | ||||
|                             encryptionSalt: process.env.DSQL_ENCRYPTION_SALT, | ||||
|                         }); | ||||
|                 if (!isUserExisting && | ||||
|                     !sqlUserID && | ||||
|                     !isPrimary && | ||||
|                     !mariadbUserHost && | ||||
|                     !mariadbUsername) { | ||||
|                     const createNewUser = yield (0, noDatabaseDbHandler_1.default)(`CREATE USER IF NOT EXISTS '${dslUsername}'@'${defaultMariadbUserHost}' IDENTIFIED BY '${dsqlPassword}'`); | ||||
|                     console.log("createNewUser", createNewUser); | ||||
|                     console.log(`User ${mariadbUser.id}: ${mariadbUser.first_name} ${mariadbUser.last_name} SQL credentials successfully updated.`); | ||||
|                     const updateUser = yield (0, dbHandler_1.default)({ | ||||
|                         query: `UPDATE users SET mariadb_user = ?, mariadb_host = ?, mariadb_pass = ? WHERE id = ?`, | ||||
|                         values: [ | ||||
|                             dslUsername, | ||||
|                             defaultMariadbUserHost, | ||||
|                             encryptedPassword, | ||||
|                             mariadbUser.id, | ||||
|                         ], | ||||
|                     }); | ||||
|                         ? password | ||||
|                         : (0, encrypt_1.default)({ data: dsqlPassword }); | ||||
|                 if (!isUserExisting) { | ||||
|                     if (isWildcardHost) { | ||||
|                         const _existingUsers = (yield (0, noDatabaseDbHandler_1.default)(`SELECT * FROM mysql.user WHERE user='${mariadbUsername}'`)); | ||||
|                         for (let i = 0; i < _existingUsers.length; i++) { | ||||
|                             const exUsr = _existingUsers[i]; | ||||
|                             yield (0, noDatabaseDbHandler_1.default)(`DROP USER '${exUsr.User}'@'${exUsr.Host}'`); | ||||
|                         } | ||||
|                 else if (!isUserExisting && mariadbUserHost) { | ||||
|                     const createNewUser = yield (0, noDatabaseDbHandler_1.default)(`CREATE USER IF NOT EXISTS '${dslUsername}'@'${mariadbUserHost}' IDENTIFIED BY '${dsqlPassword}'`); | ||||
|                     } | ||||
|                     const createNewUser = yield (0, noDatabaseDbHandler_1.default)(`CREATE USER IF NOT EXISTS '${mariadbUsername}'@'${mariadbUserHost}' IDENTIFIED BY '${dsqlPassword}'`); | ||||
|                 } | ||||
|                 if (isPrimary) { | ||||
|                     const finalHost = mariadbUserHost | ||||
|                         ? mariadbUserHost | ||||
|                         : mariadb_host; | ||||
|                     const updateUser = yield (0, dbHandler_1.default)({ | ||||
|                         query: `UPDATE users SET mariadb_user = ?, mariadb_host = ?, mariadb_pass = ? WHERE id = ?`, | ||||
|                         values: [ | ||||
|                             dslUsername, | ||||
|                             finalHost, | ||||
|                             mariadbUsername, | ||||
|                             mariadbUserHost, | ||||
|                             encryptedPassword, | ||||
|                             mariadbUser.id, | ||||
|                         ], | ||||
|                     }); | ||||
|                 } | ||||
|                 //////////////////////////////////////////////
 | ||||
|                 //////////////////////////////////////////////
 | ||||
|                 //////////////////////////////////////////////
 | ||||
|                 /** | ||||
|                  * @description Handle mariadb_users table | ||||
|                  */ | ||||
|                 const existingMariadbPrimaryUser = yield (0, dbHandler_1.default)({ | ||||
|                     query: `SELECT * FROM mariadb_users WHERE user_id = ? AND \`primary\` = 1`, | ||||
|                     values: [user_id], | ||||
|                 }); | ||||
|                 const isPrimaryUserExisting = Boolean(Array.isArray(existingMariadbPrimaryUser) && | ||||
|                     ((_d = existingMariadbPrimaryUser === null || existingMariadbPrimaryUser === void 0 ? void 0 : existingMariadbPrimaryUser[0]) === null || _d === void 0 ? void 0 : _d.user_id)); | ||||
|                 const primaryUserGrants = [ | ||||
|                     { | ||||
|                         database: "*", | ||||
|                         table: "*", | ||||
|                         privileges: ["ALL"], | ||||
|                     }, | ||||
|                 ]; | ||||
|                 if (!isPrimaryUserExisting) { | ||||
|                     const insertPrimaryMariadbUser = yield (0, dbHandler_1.default)({ | ||||
|                         query: `INSERT INTO mariadb_users (user_id, username, password, \`primary\`, grants) VALUES (?, ?, ?, ?, ?)`, | ||||
|                         values: [ | ||||
|                             user_id, | ||||
|                             dslUsername, | ||||
|                             encryptedPassword, | ||||
|                             "1", | ||||
|                             JSON.stringify(primaryUserGrants), | ||||
|                         ], | ||||
|                     }); | ||||
|                 } | ||||
|                 //////////////////////////////////////////////
 | ||||
|                 const existingExtraMariadbUsers = yield (0, dbHandler_1.default)({ | ||||
|                     query: `SELECT * FROM mariadb_users WHERE user_id = ? AND \`primary\` != '1'`, | ||||
|                     values: [user_id], | ||||
|                 }); | ||||
|                 if (Array.isArray(existingExtraMariadbUsers)) { | ||||
|                     for (let i = 0; i < existingExtraMariadbUsers.length; i++) { | ||||
|                         const _mariadbUser = existingExtraMariadbUsers[i]; | ||||
|                         if (_mariadbUser && | ||||
|                             _mariadbUser.username != mariadbUsername) | ||||
|                             continue; | ||||
|                         if (mariadbUserHost && _mariadbUser.host != mariadbUserHost) | ||||
|                             continue; | ||||
|                         const decrptedPassword = (0, decrypt_1.default)({ | ||||
|                             encryptedString: _mariadbUser.password || "", | ||||
|                             encryptionKey: process.env.DSQL_ENCRYPTION_PASSWORD, | ||||
|                             encryptionSalt: process.env.DSQL_ENCRYPTION_SALT, | ||||
|                         }); | ||||
|                         const existingExtraMariadbUser = yield (0, noDatabaseDbHandler_1.default)(`SELECT * FROM mysql.user WHERE User='${_mariadbUser.username}' AND Host='${_mariadbUser.host}'`); | ||||
|                         const isExtraMariadbUserExisting = Boolean((_e = existingExtraMariadbUser === null || existingExtraMariadbUser === void 0 ? void 0 : existingExtraMariadbUser[0]) === null || _e === void 0 ? void 0 : _e.User); | ||||
|                         if (!isExtraMariadbUserExisting) { | ||||
|                             yield (0, noDatabaseDbHandler_1.default)(`CREATE USER IF NOT EXISTS '${_mariadbUser.username}'@'${_mariadbUser.host}' IDENTIFIED BY '${decrptedPassword}'`); | ||||
|                         } | ||||
|                 const isGrantHandled = yield (0, handleGrants_1.default)({ | ||||
|                             username: _mariadbUser.username, | ||||
|                             host: _mariadbUser.host, | ||||
|                             grants: _mariadbUser.grants && | ||||
|                                 typeof _mariadbUser.grants == "string" | ||||
|                                 ? JSON.parse(_mariadbUser.grants) | ||||
|                     username: mariadbUser.username, | ||||
|                     host: mariadbUser.host, | ||||
|                     grants: mariadbUser.grants && typeof mariadbUser.grants == "string" | ||||
|                         ? JSON.parse(mariadbUser.grants) | ||||
|                         : [], | ||||
|                             userId: String(userId), | ||||
|                     userId: String(user_id), | ||||
|                 }); | ||||
|                 if (!isGrantHandled) { | ||||
|                             console.log(`Error in handling grants for user ${_mariadbUser.username}@${_mariadbUser.host}`); | ||||
|                         } | ||||
|                     } | ||||
|                     console.log(`Error in handling grants for user ${mariadbUser.username}@${mariadbUser.host}`); | ||||
|                 } | ||||
|             } | ||||
|             catch (error) { | ||||
|                 (_f = global.ERROR_CALLBACK) === null || _f === void 0 ? void 0 : _f.call(global, `Error Refreshing MariaDB Users and Grants`, error); | ||||
|                 (_d = global.ERROR_CALLBACK) === null || _d === void 0 ? void 0 : _d.call(global, `Error Refreshing MariaDB Users and Grants`, error); | ||||
|             } | ||||
|         } | ||||
|     }); | ||||
|  | ||||
							
								
								
									
										49
									
								
								dist/package-shared/types/index.d.ts
									
									
									
									
										vendored
									
									
								
							
							
						
						
									
										49
									
								
								dist/package-shared/types/index.d.ts
									
									
									
									
										vendored
									
									
								
							| @ -1352,4 +1352,53 @@ export type DsqlCrudParam<T extends { | ||||
|     debug?: boolean; | ||||
| }; | ||||
| export type ErrorCallback = (title: string, error: Error, data?: any) => void; | ||||
| export interface MariaDBUser { | ||||
|     Host: string; | ||||
|     User: string; | ||||
|     Password: string; | ||||
|     Select_priv: string; | ||||
|     Insert_priv: string; | ||||
|     Update_priv: string; | ||||
|     Delete_priv: string; | ||||
|     Create_priv: string; | ||||
|     Drop_priv: string; | ||||
|     Reload_priv: string; | ||||
|     Shutdown_priv: string; | ||||
|     Process_priv: string; | ||||
|     File_priv: string; | ||||
|     Grant_priv: string; | ||||
|     References_priv: string; | ||||
|     Index_priv: string; | ||||
|     Alter_priv: string; | ||||
|     Show_db_priv: string; | ||||
|     Super_priv: string; | ||||
|     Create_tmp_table_priv: string; | ||||
|     Lock_tables_priv: string; | ||||
|     Execute_priv: string; | ||||
|     Repl_slave_priv: string; | ||||
|     Repl_client_priv: string; | ||||
|     Create_view_priv: string; | ||||
|     Show_view_priv: string; | ||||
|     Create_routine_priv: string; | ||||
|     Alter_routine_priv: string; | ||||
|     Create_user_priv: string; | ||||
|     Event_priv: string; | ||||
|     Trigger_priv: string; | ||||
|     Create_tablespace_priv: string; | ||||
|     Delete_history_priv: string; | ||||
|     ssl_type: string; | ||||
|     ssl_cipher: string; | ||||
|     x509_issuer: string; | ||||
|     x509_subject: string; | ||||
|     max_questions: number; | ||||
|     max_updates: number; | ||||
|     max_connections: number; | ||||
|     max_user_connections: number; | ||||
|     plugin: string; | ||||
|     authentication_string: string; | ||||
|     password_expired: string; | ||||
|     is_role: string; | ||||
|     default_role: string; | ||||
|     max_statement_time: number; | ||||
| } | ||||
| export {}; | ||||
|  | ||||
| @ -15,7 +15,7 @@ function exportMariadbDatabase({ dbFullName, targetFilePath, mariadbHost, mariad | ||||
|     const finalMariadbUser = mariadbUser || process.env.DSQL_DB_USERNAME; | ||||
|     const finalMariadbHost = mariadbHost || process.env.DSQL_DB_HOST; | ||||
|     const finalMariadbPass = mariadbPass || process.env.DSQL_DB_PASSWORD; | ||||
|     const cmd = `${mysqlDumpPath} -u ${finalMariadbUser} -h ${finalMariadbHost} -p${finalMariadbPass} ${dbFullName} > ${targetFilePath}`; | ||||
|     const cmd = `${mysqlDumpPath} -u ${finalMariadbUser} -h ${finalMariadbHost} -p"${finalMariadbPass}" ${dbFullName} > ${targetFilePath}`; | ||||
|     let execSyncOptions = { | ||||
|         encoding: "utf-8", | ||||
|     }; | ||||
|  | ||||
| @ -27,7 +27,7 @@ function importMariadbDatabase(_a) { | ||||
|         const finalMariadbHost = mariadbHost || process.env.DSQL_DB_HOST; | ||||
|         const finalMariadbPass = mariadbPass || process.env.DSQL_DB_PASSWORD; | ||||
|         yield (0, conn_db_handler_1.default)(global.DSQL_DB_CONN, `CREATE DATABASE IF NOT EXISTS ${dbFullName}`); | ||||
|         const cmd = `${mysqlPath} -u ${finalMariadbUser} -h ${finalMariadbHost} -p${finalMariadbPass} ${dbFullName} < ${targetFilePath}`; | ||||
|         const cmd = `${mysqlPath} -u ${finalMariadbUser} -h ${finalMariadbHost} -p"${finalMariadbPass}" ${dbFullName} < ${targetFilePath}`; | ||||
|         let execSyncOptions = { | ||||
|             encoding: "utf-8", | ||||
|         }; | ||||
|  | ||||
| @ -26,6 +26,7 @@ export default function grabDirNames(param?: Param): { | ||||
|     dbNginxLoadBalancerConfigFile: string; | ||||
|     dockerComposeFile: string; | ||||
|     testDockerComposeFile: string; | ||||
|     extraDockerComposeFile: string; | ||||
|     siteSetupFile: string; | ||||
|     envFile: string; | ||||
|     testEnvFile: string; | ||||
|  | ||||
| @ -54,6 +54,7 @@ function grabDirNames(param) { | ||||
|     const dbNginxLoadBalancerConfigFile = path_1.default.join(appDir, "docker/mariadb/load-balancer/config/template/nginx.conf"); | ||||
|     const dockerComposeFile = path_1.default.join(appDir, "docker-compose.yml"); | ||||
|     const testDockerComposeFile = path_1.default.join(appDir, "test.docker-compose.yml"); | ||||
|     const extraDockerComposeFile = path_1.default.join(appDir, "extra.docker-compose.yml"); | ||||
|     const siteSetupFile = path_1.default.join(appDir, "site-setup.json"); | ||||
|     const envFile = path_1.default.join(appDir, ".env"); | ||||
|     const testEnvFile = path_1.default.join(appDir, "test.env"); | ||||
| @ -79,6 +80,7 @@ function grabDirNames(param) { | ||||
|         dbNginxLoadBalancerConfigFile, | ||||
|         dockerComposeFile, | ||||
|         testDockerComposeFile, | ||||
|         extraDockerComposeFile, | ||||
|         siteSetupFile, | ||||
|         envFile, | ||||
|         testEnvFile, | ||||
|  | ||||
							
								
								
									
										1
									
								
								dist/package-shared/utils/grab-cookie-expirt-date.d.ts
									
									
									
									
										vendored
									
									
										Normal file
									
								
							
							
						
						
									
										1
									
								
								dist/package-shared/utils/grab-cookie-expirt-date.d.ts
									
									
									
									
										vendored
									
									
										Normal file
									
								
							| @ -0,0 +1 @@ | ||||
| export default function grabCookieExpiryDate(): string; | ||||
							
								
								
									
										17
									
								
								dist/package-shared/utils/grab-cookie-expirt-date.js
									
									
									
									
										vendored
									
									
										Normal file
									
								
							
							
						
						
									
										17
									
								
								dist/package-shared/utils/grab-cookie-expirt-date.js
									
									
									
									
										vendored
									
									
										Normal file
									
								
							| @ -0,0 +1,17 @@ | ||||
| "use strict"; | ||||
| var __importDefault = (this && this.__importDefault) || function (mod) { | ||||
|     return (mod && mod.__esModule) ? mod : { "default": mod }; | ||||
| }; | ||||
| Object.defineProperty(exports, "__esModule", { value: true }); | ||||
| exports.default = grabCookieExpiryDate; | ||||
| const numberfy_1 = __importDefault(require("./numberfy")); | ||||
| function grabCookieExpiryDate() { | ||||
|     const ONE_DAY_IN_SECONDS = 60 * 60 * 24; | ||||
|     const ONE_WEEK_IN_SECONDS = ONE_DAY_IN_SECONDS * 7; | ||||
|     const COOKIE_EXPIRY_TIME_IN_SECONDS = process.env.DSQL_SESSION_EXPIRY_TIME | ||||
|         ? (0, numberfy_1.default)(process.env.DSQL_SESSION_EXPIRY_TIME) | ||||
|         : ONE_WEEK_IN_SECONDS; | ||||
|     const COOKIE_EXPIRY_IN_MILLISECONDS = COOKIE_EXPIRY_TIME_IN_SECONDS * 1000; | ||||
|     const COOKIE_EXPIRY_DATE = new Date(Date.now() + COOKIE_EXPIRY_IN_MILLISECONDS).toUTCString(); | ||||
|     return COOKIE_EXPIRY_DATE; | ||||
| } | ||||
| @ -12,6 +12,8 @@ import { | ||||
|     PackageUserLoginRequestBody, | ||||
| } from "../../types"; | ||||
| import debugLog from "../../utils/logging/debug-log"; | ||||
| import numberfy from "../../utils/numberfy"; | ||||
| import grabCookieExpiryDate from "../../utils/grab-cookie-expirt-date"; | ||||
| 
 | ||||
| type Param = { | ||||
|     key?: string; | ||||
| @ -65,6 +67,7 @@ export default async function loginUser({ | ||||
| }: Param): Promise<APILoginFunctionReturn> { | ||||
|     const grabedHostNames = grabHostNames({ userId: user_id || apiUserID }); | ||||
|     const { host, port, scheme } = grabedHostNames; | ||||
|     const COOKIE_EXPIRY_DATE = grabCookieExpiryDate(); | ||||
| 
 | ||||
|     const defaultTempLoginFieldName = "temp_login_code"; | ||||
|     const emailLoginTempCodeFieldName = email_login | ||||
| @ -117,7 +120,6 @@ export default async function loginUser({ | ||||
|      * Initialize HTTP response variable | ||||
|      */ | ||||
| 
 | ||||
|     /** @type {import("../../types").APILoginFunctionReturn} */ | ||||
|     let httpResponse: import("../../types").APILoginFunctionReturn = { | ||||
|         success: false, | ||||
|     }; | ||||
| @ -268,10 +270,10 @@ export default async function loginUser({ | ||||
|         } | ||||
| 
 | ||||
|         response?.setHeader("Set-Cookie", [ | ||||
|             `${authKeyName}=${encryptedPayload};samesite=strict;path=/;HttpOnly=true${ | ||||
|             `${authKeyName}=${encryptedPayload};samesite=strict;path=/;HttpOnly=true;Expires=${COOKIE_EXPIRY_DATE}${ | ||||
|                 secureCookie ? ";Secure=true" : "" | ||||
|             }`,
 | ||||
|             `${csrfName}=${httpResponse.payload?.csrf_k};samesite=strict;path=/;HttpOnly=true`, | ||||
|             `${csrfName}=${httpResponse.payload?.csrf_k};samesite=strict;path=/;HttpOnly=true;Expires=${COOKIE_EXPIRY_DATE}`, | ||||
|         ]); | ||||
| 
 | ||||
|         if (debug) { | ||||
|  | ||||
| @ -1,5 +1,4 @@ | ||||
| import http from "http"; | ||||
| import https from "https"; | ||||
| import fs from "fs"; | ||||
| import path from "path"; | ||||
| import encrypt from "../../functions/dsql/encrypt"; | ||||
| @ -13,6 +12,7 @@ import { | ||||
| } from "../../functions/backend/auth/write-auth-files"; | ||||
| import getAuthCookieNames from "../../functions/backend/cookies/get-auth-cookie-names"; | ||||
| import { APILoginFunctionReturn } from "../../types"; | ||||
| import grabCookieExpiryDate from "../../utils/grab-cookie-expirt-date"; | ||||
| 
 | ||||
| type Param = { | ||||
|     key?: string; | ||||
| @ -51,6 +51,7 @@ export default async function reauthUser({ | ||||
|      */ | ||||
|     const grabedHostNames = grabHostNames(); | ||||
|     const { host, port, scheme } = grabedHostNames; | ||||
|     const COOKIE_EXPIRY_DATE = grabCookieExpiryDate(); | ||||
| 
 | ||||
|     const finalEncryptionKey = | ||||
|         encryptionKey || process.env.DSQL_ENCRYPTION_PASSWORD; | ||||
| @ -190,10 +191,10 @@ export default async function reauthUser({ | ||||
|         const csrfName = cookieNames.csrfCookieName; | ||||
| 
 | ||||
|         response?.setHeader("Set-Cookie", [ | ||||
|             `${authKeyName}=${encryptedPayload};samesite=strict;path=/;HttpOnly=true${ | ||||
|             `${authKeyName}=${encryptedPayload};samesite=strict;path=/;HttpOnly=true;Expires=${COOKIE_EXPIRY_DATE}${ | ||||
|                 secureCookie ? ";Secure=true" : "" | ||||
|             }`,
 | ||||
|             `${csrfName}=${httpResponse.payload?.csrf_k};samesite=strict;path=/;HttpOnly=true`, | ||||
|             `${csrfName}=${httpResponse.payload?.csrf_k};samesite=strict;path=/;HttpOnly=true;Expires=${COOKIE_EXPIRY_DATE}`, | ||||
|         ]); | ||||
| 
 | ||||
|         if (httpResponse.csrf) { | ||||
|  | ||||
| @ -4,6 +4,7 @@ import path from "path"; | ||||
| import encrypt from "../../../functions/dsql/encrypt"; | ||||
| import grabHostNames from "../../../utils/grab-host-names"; | ||||
| import apiGithubLogin from "../../../functions/api/users/social/api-github-login"; | ||||
| import grabCookieExpiryDate from "../../../utils/grab-cookie-expirt-date"; | ||||
| 
 | ||||
| interface FunctionReturn { | ||||
|     success: boolean; | ||||
| @ -59,6 +60,7 @@ export default async function githubAuth({ | ||||
|      */ | ||||
|     const grabedHostNames = grabHostNames(); | ||||
|     const { host, port, scheme } = grabedHostNames; | ||||
|     const COOKIE_EXPIRY_DATE = grabCookieExpiryDate(); | ||||
| 
 | ||||
|     if (!code || code?.match(/ /)) { | ||||
|         return { | ||||
| @ -230,10 +232,10 @@ export default async function githubAuth({ | ||||
|         const csrfName = `datasquirel_${dsqlUserId}_${database}_csrf`; | ||||
| 
 | ||||
|         response.setHeader("Set-Cookie", [ | ||||
|             `${authKeyName}=${encryptedPayload};samesite=strict;path=/;HttpOnly=true${ | ||||
|             `${authKeyName}=${encryptedPayload};samesite=strict;path=/;HttpOnly=true;Expires=${COOKIE_EXPIRY_DATE}${ | ||||
|                 secureCookie ? ";Secure=true" : "" | ||||
|             }`,
 | ||||
|             `${csrfName}=${user.csrf_k};samesite=strict;path=/;HttpOnly=true`, | ||||
|             `${csrfName}=${user.csrf_k};samesite=strict;path=/;HttpOnly=true;Expires=${COOKIE_EXPIRY_DATE}`, | ||||
|         ]); | ||||
|     } | ||||
| 
 | ||||
|  | ||||
| @ -5,6 +5,7 @@ import apiGoogleLogin from "../../../functions/api/users/social/api-google-login | ||||
| import getAuthCookieNames from "../../../functions/backend/cookies/get-auth-cookie-names"; | ||||
| import { writeAuthFile } from "../../../functions/backend/auth/write-auth-files"; | ||||
| import { APILoginFunctionReturn } from "../../../types"; | ||||
| import grabCookieExpiryDate from "../../../utils/grab-cookie-expirt-date"; | ||||
| 
 | ||||
| type Param = { | ||||
|     key?: string; | ||||
| @ -40,6 +41,7 @@ export default async function googleAuth({ | ||||
|         userId: apiUserID || process.env.DSQL_API_USER_ID, | ||||
|     }); | ||||
|     const { host, port, scheme, user_id } = grabedHostNames; | ||||
|     const COOKIE_EXPIRY_DATE = grabCookieExpiryDate(); | ||||
| 
 | ||||
|     const finalEncryptionKey = | ||||
|         encryptionKey || process.env.DSQL_ENCRYPTION_PASSWORD; | ||||
| @ -194,10 +196,10 @@ export default async function googleAuth({ | ||||
|         const csrfName = cookieNames.csrfCookieName; | ||||
| 
 | ||||
|         response?.setHeader("Set-Cookie", [ | ||||
|             `${authKeyName}=${encryptedPayload};samesite=strict;path=/;HttpOnly=true${ | ||||
|             `${authKeyName}=${encryptedPayload};samesite=strict;path=/;HttpOnly=true;;Expires=${COOKIE_EXPIRY_DATE}${ | ||||
|                 secureCookie ? ";Secure=true" : "" | ||||
|             }`,
 | ||||
|             `${csrfName}=${httpResponse.payload?.csrf_k};samesite=strict;path=/;HttpOnly=true`, | ||||
|             `${csrfName}=${httpResponse.payload?.csrf_k};samesite=strict;path=/;HttpOnly=true;;Expires=${COOKIE_EXPIRY_DATE}`, | ||||
|         ]); | ||||
|     } | ||||
| 
 | ||||
|  | ||||
| @ -70,9 +70,6 @@ export default async function handleGrants({ | ||||
|                 } | ||||
|             } | ||||
| 
 | ||||
|             /** | ||||
|              * @type {GrantType[]} | ||||
|              */ | ||||
|             const grantsArray: GrantType[] = grants; | ||||
| 
 | ||||
|             for (let i = 0; i < grantsArray.length; i++) { | ||||
|  | ||||
| @ -1,15 +1,11 @@ | ||||
| import path from "path"; | ||||
| require("dotenv").config({ path: path.resolve(__dirname, "../../../.env") }); | ||||
| 
 | ||||
| import generator from "generate-password"; | ||||
| import noDatabaseDbHandler from "../utils/noDatabaseDbHandler"; | ||||
| import dbHandler from "../utils/dbHandler"; | ||||
| import handleGrants, { GrantType } from "./handleGrants"; | ||||
| import handleGrants from "./handleGrants"; | ||||
| import encrypt from "../../functions/dsql/encrypt"; | ||||
| import decrypt from "../../functions/dsql/decrypt"; | ||||
| import { MYSQL_mariadb_users_table_def } from "../../types"; | ||||
| 
 | ||||
| const defaultMariadbUserHost = process.env.DSQL_DB_HOST || "127.0.0.1"; | ||||
| import { DSQL_DATASQUIREL_MARIADB_USERS } from "@/package-shared/types/dsql"; | ||||
| import { MariaDBUser } from "@/package-shared/types"; | ||||
| 
 | ||||
| type Param = { | ||||
|     userId?: number | string; | ||||
| @ -39,53 +35,38 @@ export default async function refreshUsersAndGrants({ | ||||
|         ? userId == Number(process.env.DSQL_SU_USER_ID) | ||||
|         : false; | ||||
| 
 | ||||
|     const isWildcardHost = mariadbUserHost == "%"; | ||||
| 
 | ||||
|     if (isWildcardHost && !isRootUser) { | ||||
|         return; | ||||
|     } | ||||
| 
 | ||||
|     for (let i = 0; i < mariadbUsers.length; i++) { | ||||
|         const mariadbUser = mariadbUsers[i]; | ||||
|         const mariadbUser = mariadbUsers[i] as | ||||
|             | DSQL_DATASQUIREL_MARIADB_USERS | ||||
|             | undefined; | ||||
| 
 | ||||
|         if (!mariadbUser) continue; | ||||
|         if (userId && mariadbUser.user_id != userId) continue; | ||||
|         if (sqlUserID && mariadbUser.id != sqlUserID) continue; | ||||
| 
 | ||||
|         try { | ||||
|             const { mariadb_user, mariadb_host, mariadb_pass, user_id } = | ||||
|                 mariadbUser; | ||||
|             const { username, password, host, user_id } = mariadbUser; | ||||
| 
 | ||||
|             const existingUser = await noDatabaseDbHandler( | ||||
|                 `SELECT * FROM mysql.user WHERE User = '${mariadb_user}' AND Host = '${mariadb_host}'` | ||||
|                 `SELECT * FROM mysql.user WHERE User = '${username}' AND Host = '${host}'` | ||||
|             ); | ||||
| 
 | ||||
|             const existingMariaDBUserArray = | ||||
|                 userId && sqlUserID | ||||
|                     ? await dbHandler({ | ||||
|                           query: `SELECT * FROM mariadb_users WHERE id = ? AND user_id = ?`, | ||||
|                           values: [sqlUserID, userId], | ||||
|                       }) | ||||
|                     : null; | ||||
| 
 | ||||
|             const activeMariadbUserObject: | ||||
|                 | import("../../types").MYSQL_mariadb_users_table_def | ||||
|                 | undefined = Array.isArray(existingMariaDBUserArray) | ||||
|                 ? existingMariaDBUserArray?.[0] | ||||
|                 : undefined; | ||||
| 
 | ||||
|             const isPrimary = activeMariadbUserObject | ||||
|                 ? String(activeMariadbUserObject.primary)?.match(/1/) | ||||
|                     ? true | ||||
|                     : false | ||||
|                 : false; | ||||
| 
 | ||||
|             const isUserExisting = Boolean(existingUser?.[0]?.User); | ||||
| 
 | ||||
|             const isThisPrimaryHost = Boolean( | ||||
|                 mariadbUserHost == defaultMariadbUserHost | ||||
|             ); | ||||
|             const isPrimary = String(mariadbUser.primary)?.match(/1/) | ||||
|                 ? true | ||||
|                 : false; | ||||
| 
 | ||||
|             const dslUsername = isRootUser | ||||
|                 ? mariadbUsername | ||||
|                 : `dsql_user_${user_id}`; | ||||
| 
 | ||||
|             const dsqlPassword = activeMariadbUserObject?.password | ||||
|                 ? activeMariadbUserObject.password | ||||
|                 : isUserExisting | ||||
|                 ? mariadb_pass | ||||
|             const dsqlPassword = mariadbUser?.password | ||||
|                 ? decrypt({ encryptedString: mariadbUser.password }) | ||||
|                 : isUserExisting && password | ||||
|                 ? decrypt({ encryptedString: password }) | ||||
|                 : generator.generate({ | ||||
|                       length: 16, | ||||
|                       numbers: true, | ||||
| @ -94,161 +75,58 @@ export default async function refreshUsersAndGrants({ | ||||
|                       exclude: "*#.'`\"", | ||||
|                   }); | ||||
| 
 | ||||
|             const encryptedPassword = activeMariadbUserObject?.password | ||||
|                 ? activeMariadbUserObject.password | ||||
|             const encryptedPassword = mariadbUser?.password | ||||
|                 ? mariadbUser.password | ||||
|                 : isUserExisting | ||||
|                 ? mariadb_pass | ||||
|                 : encrypt({ | ||||
|                       data: dsqlPassword, | ||||
|                       encryptionKey: process.env.DSQL_ENCRYPTION_PASSWORD, | ||||
|                       encryptionSalt: process.env.DSQL_ENCRYPTION_SALT, | ||||
|                   }); | ||||
|                 ? password | ||||
|                 : encrypt({ data: dsqlPassword }); | ||||
| 
 | ||||
|             if ( | ||||
|                 !isUserExisting && | ||||
|                 !sqlUserID && | ||||
|                 !isPrimary && | ||||
|                 !mariadbUserHost && | ||||
|                 !mariadbUsername | ||||
|             ) { | ||||
|                 const createNewUser = await noDatabaseDbHandler( | ||||
|                     `CREATE USER IF NOT EXISTS '${dslUsername}'@'${defaultMariadbUserHost}' IDENTIFIED BY '${dsqlPassword}'` | ||||
|             if (!isUserExisting) { | ||||
|                 if (isWildcardHost) { | ||||
|                     const _existingUsers = (await noDatabaseDbHandler( | ||||
|                         `SELECT * FROM mysql.user WHERE user='${mariadbUsername}'` | ||||
|                     )) as MariaDBUser[]; | ||||
| 
 | ||||
|                     for (let i = 0; i < _existingUsers.length; i++) { | ||||
|                         const exUsr = _existingUsers[i]; | ||||
|                         await noDatabaseDbHandler( | ||||
|                             `DROP USER '${exUsr.User}'@'${exUsr.Host}'` | ||||
|                         ); | ||||
|                     } | ||||
|                 } | ||||
| 
 | ||||
|                 console.log("createNewUser", createNewUser); | ||||
| 
 | ||||
|                 console.log( | ||||
|                     `User ${mariadbUser.id}: ${mariadbUser.first_name} ${mariadbUser.last_name} SQL credentials successfully updated.` | ||||
|                 ); | ||||
| 
 | ||||
|                 const updateUser = await dbHandler({ | ||||
|                     query: `UPDATE users SET mariadb_user = ?, mariadb_host = ?, mariadb_pass = ? WHERE id = ?`, | ||||
|                     values: [ | ||||
|                         dslUsername, | ||||
|                         defaultMariadbUserHost, | ||||
|                         encryptedPassword, | ||||
|                         mariadbUser.id, | ||||
|                     ], | ||||
|                 }); | ||||
|             } else if (!isUserExisting && mariadbUserHost) { | ||||
|                 const createNewUser = await noDatabaseDbHandler( | ||||
|                     `CREATE USER IF NOT EXISTS '${dslUsername}'@'${mariadbUserHost}' IDENTIFIED BY '${dsqlPassword}'` | ||||
|                     `CREATE USER IF NOT EXISTS '${mariadbUsername}'@'${mariadbUserHost}' IDENTIFIED BY '${dsqlPassword}'` | ||||
|                 ); | ||||
|             } | ||||
| 
 | ||||
|             if (isPrimary) { | ||||
|                 const finalHost = mariadbUserHost | ||||
|                     ? mariadbUserHost | ||||
|                     : mariadb_host; | ||||
| 
 | ||||
|                 const updateUser = await dbHandler({ | ||||
|                     query: `UPDATE users SET mariadb_user = ?, mariadb_host = ?, mariadb_pass = ? WHERE id = ?`, | ||||
|                     values: [ | ||||
|                         dslUsername, | ||||
|                         finalHost, | ||||
|                         mariadbUsername, | ||||
|                         mariadbUserHost, | ||||
|                         encryptedPassword, | ||||
|                         mariadbUser.id, | ||||
|                     ], | ||||
|                 }); | ||||
|             } | ||||
| 
 | ||||
|             //////////////////////////////////////////////
 | ||||
|             //////////////////////////////////////////////
 | ||||
|             //////////////////////////////////////////////
 | ||||
| 
 | ||||
|             /** | ||||
|              * @description Handle mariadb_users table | ||||
|              */ | ||||
|             const existingMariadbPrimaryUser = await dbHandler({ | ||||
|                 query: `SELECT * FROM mariadb_users WHERE user_id = ? AND \`primary\` = 1`, | ||||
|                 values: [user_id], | ||||
|             }); | ||||
| 
 | ||||
|             const isPrimaryUserExisting = Boolean( | ||||
|                 Array.isArray(existingMariadbPrimaryUser) && | ||||
|                     existingMariadbPrimaryUser?.[0]?.user_id | ||||
|             ); | ||||
| 
 | ||||
|             const primaryUserGrants: GrantType[] = [ | ||||
|                 { | ||||
|                     database: "*", | ||||
|                     table: "*", | ||||
|                     privileges: ["ALL"], | ||||
|                 }, | ||||
|             ]; | ||||
| 
 | ||||
|             if (!isPrimaryUserExisting) { | ||||
|                 const insertPrimaryMariadbUser = await dbHandler({ | ||||
|                     query: `INSERT INTO mariadb_users (user_id, username, password, \`primary\`, grants) VALUES (?, ?, ?, ?, ?)`, | ||||
|                     values: [ | ||||
|                         user_id, | ||||
|                         dslUsername, | ||||
|                         encryptedPassword, | ||||
|                         "1", | ||||
|                         JSON.stringify(primaryUserGrants), | ||||
|                     ], | ||||
|                 }); | ||||
|             } | ||||
| 
 | ||||
|             //////////////////////////////////////////////
 | ||||
| 
 | ||||
|             const existingExtraMariadbUsers = await dbHandler({ | ||||
|                 query: `SELECT * FROM mariadb_users WHERE user_id = ? AND \`primary\` != '1'`, | ||||
|                 values: [user_id], | ||||
|             }); | ||||
| 
 | ||||
|             if (Array.isArray(existingExtraMariadbUsers)) { | ||||
|                 for (let i = 0; i < existingExtraMariadbUsers.length; i++) { | ||||
|                     const _mariadbUser = existingExtraMariadbUsers[ | ||||
|                         i | ||||
|                     ] as MYSQL_mariadb_users_table_def; | ||||
| 
 | ||||
|                     if ( | ||||
|                         _mariadbUser && | ||||
|                         _mariadbUser.username != mariadbUsername | ||||
|                     ) | ||||
|                         continue; | ||||
|                     if (mariadbUserHost && _mariadbUser.host != mariadbUserHost) | ||||
|                         continue; | ||||
| 
 | ||||
|                     const decrptedPassword = decrypt({ | ||||
|                         encryptedString: _mariadbUser.password || "", | ||||
|                         encryptionKey: process.env.DSQL_ENCRYPTION_PASSWORD, | ||||
|                         encryptionSalt: process.env.DSQL_ENCRYPTION_SALT, | ||||
|                     }); | ||||
| 
 | ||||
|                     const existingExtraMariadbUser = await noDatabaseDbHandler( | ||||
|                         `SELECT * FROM mysql.user WHERE User='${_mariadbUser.username}' AND Host='${_mariadbUser.host}'` | ||||
|                     ); | ||||
| 
 | ||||
|                     const isExtraMariadbUserExisting = Boolean( | ||||
|                         existingExtraMariadbUser?.[0]?.User | ||||
|                     ); | ||||
| 
 | ||||
|                     if (!isExtraMariadbUserExisting) { | ||||
|                         await noDatabaseDbHandler( | ||||
|                             `CREATE USER IF NOT EXISTS '${_mariadbUser.username}'@'${_mariadbUser.host}' IDENTIFIED BY '${decrptedPassword}'` | ||||
|                         ); | ||||
|                     } | ||||
| 
 | ||||
|             const isGrantHandled = await handleGrants({ | ||||
|                         username: _mariadbUser.username, | ||||
|                         host: _mariadbUser.host, | ||||
|                 username: mariadbUser.username, | ||||
|                 host: mariadbUser.host, | ||||
|                 grants: | ||||
|                             _mariadbUser.grants && | ||||
|                             typeof _mariadbUser.grants == "string" | ||||
|                                 ? JSON.parse(_mariadbUser.grants) | ||||
|                     mariadbUser.grants && typeof mariadbUser.grants == "string" | ||||
|                         ? JSON.parse(mariadbUser.grants) | ||||
|                         : [], | ||||
|                         userId: String(userId), | ||||
|                 userId: String(user_id), | ||||
|             }); | ||||
| 
 | ||||
|             if (!isGrantHandled) { | ||||
|                 console.log( | ||||
|                             `Error in handling grants for user ${_mariadbUser.username}@${_mariadbUser.host}` | ||||
|                     `Error in handling grants for user ${mariadbUser.username}@${mariadbUser.host}` | ||||
|                 ); | ||||
|             } | ||||
|                 } | ||||
|             } | ||||
|         } catch (error: any) { | ||||
|             global.ERROR_CALLBACK?.( | ||||
|                 `Error Refreshing MariaDB Users and Grants`, | ||||
|  | ||||
| @ -1525,3 +1525,53 @@ export type DsqlCrudParam< | ||||
| }; | ||||
| 
 | ||||
| export type ErrorCallback = (title: string, error: Error, data?: any) => void; | ||||
| 
 | ||||
| export interface MariaDBUser { | ||||
|     Host: string; | ||||
|     User: string; | ||||
|     Password: string; | ||||
|     Select_priv: string; | ||||
|     Insert_priv: string; | ||||
|     Update_priv: string; | ||||
|     Delete_priv: string; | ||||
|     Create_priv: string; | ||||
|     Drop_priv: string; | ||||
|     Reload_priv: string; | ||||
|     Shutdown_priv: string; | ||||
|     Process_priv: string; | ||||
|     File_priv: string; | ||||
|     Grant_priv: string; | ||||
|     References_priv: string; | ||||
|     Index_priv: string; | ||||
|     Alter_priv: string; | ||||
|     Show_db_priv: string; | ||||
|     Super_priv: string; | ||||
|     Create_tmp_table_priv: string; | ||||
|     Lock_tables_priv: string; | ||||
|     Execute_priv: string; | ||||
|     Repl_slave_priv: string; | ||||
|     Repl_client_priv: string; | ||||
|     Create_view_priv: string; | ||||
|     Show_view_priv: string; | ||||
|     Create_routine_priv: string; | ||||
|     Alter_routine_priv: string; | ||||
|     Create_user_priv: string; | ||||
|     Event_priv: string; | ||||
|     Trigger_priv: string; | ||||
|     Create_tablespace_priv: string; | ||||
|     Delete_history_priv: string; | ||||
|     ssl_type: string; | ||||
|     ssl_cipher: string; | ||||
|     x509_issuer: string; | ||||
|     x509_subject: string; | ||||
|     max_questions: number; | ||||
|     max_updates: number; | ||||
|     max_connections: number; | ||||
|     max_user_connections: number; | ||||
|     plugin: string; | ||||
|     authentication_string: string; | ||||
|     password_expired: string; | ||||
|     is_role: string; | ||||
|     default_role: string; | ||||
|     max_statement_time: number; | ||||
| } | ||||
|  | ||||
| @ -26,7 +26,7 @@ export default function exportMariadbDatabase({ | ||||
|     const finalMariadbHost = mariadbHost || process.env.DSQL_DB_HOST; | ||||
|     const finalMariadbPass = mariadbPass || process.env.DSQL_DB_PASSWORD; | ||||
| 
 | ||||
|     const cmd = `${mysqlDumpPath} -u ${finalMariadbUser} -h ${finalMariadbHost} -p${finalMariadbPass} ${dbFullName} > ${targetFilePath}`; | ||||
|     const cmd = `${mysqlDumpPath} -u ${finalMariadbUser} -h ${finalMariadbHost} -p"${finalMariadbPass}" ${dbFullName} > ${targetFilePath}`; | ||||
| 
 | ||||
|     let execSyncOptions: ExecSyncOptions = { | ||||
|         encoding: "utf-8", | ||||
|  | ||||
| @ -32,7 +32,7 @@ export default async function importMariadbDatabase({ | ||||
|         `CREATE DATABASE IF NOT EXISTS ${dbFullName}` | ||||
|     ); | ||||
| 
 | ||||
|     const cmd = `${mysqlPath} -u ${finalMariadbUser} -h ${finalMariadbHost} -p${finalMariadbPass} ${dbFullName} < ${targetFilePath}`; | ||||
|     const cmd = `${mysqlPath} -u ${finalMariadbUser} -h ${finalMariadbHost} -p"${finalMariadbPass}" ${dbFullName} < ${targetFilePath}`; | ||||
| 
 | ||||
|     let execSyncOptions: ExecSyncOptions = { | ||||
|         encoding: "utf-8", | ||||
|  | ||||
| @ -73,7 +73,13 @@ export default function grabDirNames(param?: Param) { | ||||
| 
 | ||||
|     const dockerComposeFile = path.join(appDir, "docker-compose.yml"); | ||||
|     const testDockerComposeFile = path.join(appDir, "test.docker-compose.yml"); | ||||
|     const extraDockerComposeFile = path.join( | ||||
|         appDir, | ||||
|         "extra.docker-compose.yml" | ||||
|     ); | ||||
| 
 | ||||
|     const siteSetupFile = path.join(appDir, "site-setup.json"); | ||||
| 
 | ||||
|     const envFile = path.join(appDir, ".env"); | ||||
|     const testEnvFile = path.join(appDir, "test.env"); | ||||
| 
 | ||||
| @ -99,6 +105,7 @@ export default function grabDirNames(param?: Param) { | ||||
|         dbNginxLoadBalancerConfigFile, | ||||
|         dockerComposeFile, | ||||
|         testDockerComposeFile, | ||||
|         extraDockerComposeFile, | ||||
|         siteSetupFile, | ||||
|         envFile, | ||||
|         testEnvFile, | ||||
|  | ||||
							
								
								
									
										18
									
								
								package-shared/utils/grab-cookie-expirt-date.ts
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										18
									
								
								package-shared/utils/grab-cookie-expirt-date.ts
									
									
									
									
									
										Normal file
									
								
							| @ -0,0 +1,18 @@ | ||||
| import numberfy from "./numberfy"; | ||||
| 
 | ||||
| export default function grabCookieExpiryDate() { | ||||
|     const ONE_DAY_IN_SECONDS = 60 * 60 * 24; | ||||
|     const ONE_WEEK_IN_SECONDS = ONE_DAY_IN_SECONDS * 7; | ||||
| 
 | ||||
|     const COOKIE_EXPIRY_TIME_IN_SECONDS = process.env.DSQL_SESSION_EXPIRY_TIME | ||||
|         ? numberfy(process.env.DSQL_SESSION_EXPIRY_TIME) | ||||
|         : ONE_WEEK_IN_SECONDS; | ||||
| 
 | ||||
|     const COOKIE_EXPIRY_IN_MILLISECONDS = COOKIE_EXPIRY_TIME_IN_SECONDS * 1000; | ||||
| 
 | ||||
|     const COOKIE_EXPIRY_DATE = new Date( | ||||
|         Date.now() + COOKIE_EXPIRY_IN_MILLISECONDS | ||||
|     ).toUTCString(); | ||||
| 
 | ||||
|     return COOKIE_EXPIRY_DATE; | ||||
| } | ||||
| @ -1,6 +1,6 @@ | ||||
| { | ||||
|     "name": "@moduletrace/datasquirel", | ||||
|     "version": "4.2.1", | ||||
|     "version": "4.2.2", | ||||
|     "description": "Cloud-based SQL data management tool", | ||||
|     "main": "dist/index.js", | ||||
|     "bin": { | ||||
|  | ||||
		Loading…
	
		Reference in New Issue
	
	Block a user
	 Benjamin Toby
						Benjamin Toby