This commit is contained in:
Benjamin Toby 2025-03-17 08:48:58 +01:00
parent ec4d0428bb
commit 34f843bc84
20 changed files with 113 additions and 46 deletions

View File

@ -25,9 +25,10 @@ type Param = {
apiUserID?: string | number; apiUserID?: string | number;
dbUserId?: string | number; dbUserId?: string | number;
cleanupTokens?: boolean; cleanupTokens?: boolean;
secureCookie?: boolean;
}; };
/** /**
* # Login A user * # Login A user
*/ */
export default function loginUser({ key, payload, database, additionalFields, response, encryptionKey, encryptionSalt, email_login, email_login_code, temp_code_field, token, user_id, skipPassword, apiUserID, skipWriteAuthFile, dbUserId, debug, cleanupTokens, }: Param): Promise<APILoginFunctionReturn>; export default function loginUser({ key, payload, database, additionalFields, response, encryptionKey, encryptionSalt, email_login, email_login_code, temp_code_field, token, user_id, skipPassword, apiUserID, skipWriteAuthFile, dbUserId, debug, cleanupTokens, secureCookie, }: Param): Promise<APILoginFunctionReturn>;
export {}; export {};

View File

@ -25,7 +25,7 @@ const debug_log_1 = __importDefault(require("../../utils/logging/debug-log"));
* # Login A user * # Login A user
*/ */
function loginUser(_a) { function loginUser(_a) {
return __awaiter(this, arguments, void 0, function* ({ key, payload, database, additionalFields, response, encryptionKey, encryptionSalt, email_login, email_login_code, temp_code_field, token, user_id, skipPassword, apiUserID, skipWriteAuthFile, dbUserId, debug, cleanupTokens, }) { return __awaiter(this, arguments, void 0, function* ({ key, payload, database, additionalFields, response, encryptionKey, encryptionSalt, email_login, email_login_code, temp_code_field, token, user_id, skipPassword, apiUserID, skipWriteAuthFile, dbUserId, debug, cleanupTokens, secureCookie, }) {
var _b, _c, _d; var _b, _c, _d;
const grabedHostNames = (0, grab_host_names_1.default)({ userId: user_id || apiUserID }); const grabedHostNames = (0, grab_host_names_1.default)({ userId: user_id || apiUserID });
const { host, port, scheme } = grabedHostNames; const { host, port, scheme } = grabedHostNames;
@ -186,7 +186,7 @@ function loginUser(_a) {
debugFn(encryptedPayload, "encryptedPayload"); debugFn(encryptedPayload, "encryptedPayload");
} }
response === null || response === void 0 ? void 0 : response.setHeader("Set-Cookie", [ response === null || response === void 0 ? void 0 : response.setHeader("Set-Cookie", [
`${authKeyName}=${encryptedPayload};samesite=strict;path=/;HttpOnly=true;Secure=true`, `${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`, `${csrfName}=${(_d = httpResponse.payload) === null || _d === void 0 ? void 0 : _d.csrf_k};samesite=strict;path=/;HttpOnly=true`,
]); ]);
if (debug) { if (debug) {

View File

@ -11,9 +11,10 @@ type Param = {
additionalFields?: string[]; additionalFields?: string[];
encryptedUserString?: string; encryptedUserString?: string;
user_id?: string | number; user_id?: string | number;
secureCookie?: boolean;
}; };
/** /**
* # Reauthorize User * # Reauthorize User
*/ */
export default function reauthUser({ key, database, response, request, level, encryptionKey, encryptionSalt, additionalFields, encryptedUserString, user_id, }: Param): Promise<APILoginFunctionReturn>; export default function reauthUser({ key, database, response, request, level, encryptionKey, encryptionSalt, additionalFields, encryptedUserString, user_id, secureCookie, }: Param): Promise<APILoginFunctionReturn>;
export {}; export {};

View File

@ -25,7 +25,7 @@ const get_auth_cookie_names_1 = __importDefault(require("../../functions/backend
* # Reauthorize User * # Reauthorize User
*/ */
function reauthUser(_a) { function reauthUser(_a) {
return __awaiter(this, arguments, void 0, function* ({ key, database, response, request, level, encryptionKey, encryptionSalt, additionalFields, encryptedUserString, user_id, }) { return __awaiter(this, arguments, void 0, function* ({ key, database, response, request, level, encryptionKey, encryptionSalt, additionalFields, encryptedUserString, user_id, secureCookie, }) {
var _b, _c; var _b, _c;
/** /**
* Check Encryption Keys * Check Encryption Keys
@ -143,7 +143,7 @@ function reauthUser(_a) {
const authKeyName = cookieNames.keyCookieName; const authKeyName = cookieNames.keyCookieName;
const csrfName = cookieNames.csrfCookieName; const csrfName = cookieNames.csrfCookieName;
response === null || response === void 0 ? void 0 : response.setHeader("Set-Cookie", [ response === null || response === void 0 ? void 0 : response.setHeader("Set-Cookie", [
`${authKeyName}=${encryptedPayload};samesite=strict;path=/;HttpOnly=true;Secure=true`, `${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`, `${csrfName}=${(_c = httpResponse.payload) === null || _c === void 0 ? void 0 : _c.csrf_k};samesite=strict;path=/;HttpOnly=true`,
]); ]);
if (httpResponse.csrf) { if (httpResponse.csrf) {

View File

@ -26,9 +26,10 @@ type Param = {
[s: string]: string | number; [s: string]: string | number;
}; };
user_id?: boolean; user_id?: boolean;
secureCookie?: boolean;
}; };
/** /**
* # SERVER FUNCTION: Login with google Function * # SERVER FUNCTION: Login with google Function
*/ */
export default function githubAuth({ key, code, email, database, clientId, clientSecret, response, encryptionKey, encryptionSalt, additionalFields, user_id, additionalData, }: Param): Promise<FunctionReturn | undefined>; export default function githubAuth({ key, code, email, database, clientId, clientSecret, response, encryptionKey, encryptionSalt, additionalFields, user_id, additionalData, secureCookie, }: Param): Promise<FunctionReturn | undefined>;
export {}; export {};

View File

@ -22,7 +22,7 @@ const api_github_login_1 = __importDefault(require("../../../functions/api/users
* # SERVER FUNCTION: Login with google Function * # SERVER FUNCTION: Login with google Function
*/ */
function githubAuth(_a) { function githubAuth(_a) {
return __awaiter(this, arguments, void 0, function* ({ key, code, email, database, clientId, clientSecret, response, encryptionKey, encryptionSalt, additionalFields, user_id, additionalData, }) { return __awaiter(this, arguments, void 0, function* ({ key, code, email, database, clientId, clientSecret, response, encryptionKey, encryptionSalt, additionalFields, user_id, additionalData, secureCookie, }) {
/** /**
* Check inputs * Check inputs
* *
@ -162,10 +162,8 @@ function githubAuth(_a) {
const authKeyName = `datasquirel_${dsqlUserId}_${database}_auth_key`; const authKeyName = `datasquirel_${dsqlUserId}_${database}_auth_key`;
const csrfName = `datasquirel_${dsqlUserId}_${database}_csrf`; const csrfName = `datasquirel_${dsqlUserId}_${database}_csrf`;
response.setHeader("Set-Cookie", [ response.setHeader("Set-Cookie", [
`${authKeyName}=${encryptedPayload};samesite=strict;path=/;HttpOnly=true;Secure=true`, `${authKeyName}=${encryptedPayload};samesite=strict;path=/;HttpOnly=true${secureCookie ? ";Secure=true" : ""}`,
`${csrfName}=${user.csrf_k};samesite=strict;path=/;HttpOnly=true`, `${csrfName}=${user.csrf_k};samesite=strict;path=/;HttpOnly=true`,
`dsqluid=${dsqlUserId};samesite=strict;path=/;HttpOnly=true`,
`datasquirel_social_id=${user.social_id};samesite=strict;path=/`,
]); ]);
} }
return httpResponse; return httpResponse;

View File

@ -13,9 +13,10 @@ type Param = {
}; };
apiUserID?: string | number; apiUserID?: string | number;
debug?: boolean; debug?: boolean;
secureCookie?: boolean;
}; };
/** /**
* # SERVER FUNCTION: Login with google Function * # SERVER FUNCTION: Login with google Function
*/ */
export default function googleAuth({ key, token, database, response, encryptionKey, encryptionSalt, additionalFields, additionalData, apiUserID, debug, }: Param): Promise<APILoginFunctionReturn>; export default function googleAuth({ key, token, database, response, encryptionKey, encryptionSalt, additionalFields, additionalData, apiUserID, debug, secureCookie, }: Param): Promise<APILoginFunctionReturn>;
export {}; export {};

View File

@ -22,7 +22,7 @@ const write_auth_files_1 = require("../../../functions/backend/auth/write-auth-f
* # SERVER FUNCTION: Login with google Function * # SERVER FUNCTION: Login with google Function
*/ */
function googleAuth(_a) { function googleAuth(_a) {
return __awaiter(this, arguments, void 0, function* ({ key, token, database, response, encryptionKey, encryptionSalt, additionalFields, additionalData, apiUserID, debug, }) { return __awaiter(this, arguments, void 0, function* ({ key, token, database, response, encryptionKey, encryptionSalt, additionalFields, additionalData, apiUserID, debug, secureCookie, }) {
var _b; var _b;
const grabedHostNames = (0, grab_host_names_1.default)({ const grabedHostNames = (0, grab_host_names_1.default)({
userId: apiUserID || process.env.DSQL_API_USER_ID, userId: apiUserID || process.env.DSQL_API_USER_ID,
@ -150,7 +150,7 @@ function googleAuth(_a) {
const authKeyName = cookieNames.keyCookieName; const authKeyName = cookieNames.keyCookieName;
const csrfName = cookieNames.csrfCookieName; const csrfName = cookieNames.csrfCookieName;
response === null || response === void 0 ? void 0 : response.setHeader("Set-Cookie", [ response === null || response === void 0 ? void 0 : response.setHeader("Set-Cookie", [
`${authKeyName}=${encryptedPayload};samesite=strict;path=/;HttpOnly=true;Secure=true`, `${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`, `${csrfName}=${(_b = httpResponse.payload) === null || _b === void 0 ? void 0 : _b.csrf_k};samesite=strict;path=/;HttpOnly=true`,
]); ]);
} }

View File

@ -7,6 +7,10 @@ exports.checkAuthFile = exports.deleteAuthFile = exports.getAuthFile = exports.c
const fs_1 = __importDefault(require("fs")); const fs_1 = __importDefault(require("fs"));
const path_1 = __importDefault(require("path")); const path_1 = __importDefault(require("path"));
const ejson_1 = __importDefault(require("../../../utils/ejson")); const ejson_1 = __importDefault(require("../../../utils/ejson"));
const debug_log_1 = __importDefault(require("../../../utils/logging/debug-log"));
function debugFn(log, label) {
(0, debug_log_1.default)({ log, addTime: true, title: "write-auth-files", label });
}
const grabAuthDirs = () => { const grabAuthDirs = () => {
const DSQL_AUTH_DIR = process.env.DSQL_AUTH_DIR; const DSQL_AUTH_DIR = process.env.DSQL_AUTH_DIR;
const ROOT_DIR = (DSQL_AUTH_DIR === null || DSQL_AUTH_DIR === void 0 ? void 0 : DSQL_AUTH_DIR.match(/./)) const ROOT_DIR = (DSQL_AUTH_DIR === null || DSQL_AUTH_DIR === void 0 ? void 0 : DSQL_AUTH_DIR.match(/./))
@ -39,14 +43,14 @@ exports.initAuthFiles = initAuthFiles;
const writeAuthFile = (name, data, cleanup) => { const writeAuthFile = (name, data, cleanup) => {
(0, exports.initAuthFiles)(); (0, exports.initAuthFiles)();
try { try {
const { auth, root } = (0, exports.grabAuthDirs)(); const { auth } = (0, exports.grabAuthDirs)();
if (cleanup) { if (cleanup) {
(0, exports.cleanupUserAuthFiles)(cleanup.userId); (0, exports.cleanupUserAuthFiles)(cleanup.userId);
} }
fs_1.default.writeFileSync(path_1.default.join(auth, name), data); fs_1.default.writeFileSync(path_1.default.join(auth, name), data);
return true; return true;
} }
catch ( /** @type {any} */error) { catch (error) {
console.log(`Error writing Auth File: ${error.message}`); console.log(`Error writing Auth File: ${error.message}`);
return false; return false;
} }
@ -87,7 +91,7 @@ const getAuthFile = (name) => {
const authFilePath = path_1.default.join((0, exports.grabAuthDirs)().auth, name); const authFilePath = path_1.default.join((0, exports.grabAuthDirs)().auth, name);
return fs_1.default.readFileSync(authFilePath, "utf-8"); return fs_1.default.readFileSync(authFilePath, "utf-8");
} }
catch ( /** @type {any} */error) { catch (error) {
console.log(`Error getting Auth File: ${error.message}`); console.log(`Error getting Auth File: ${error.message}`);
return null; return null;
} }
@ -101,7 +105,7 @@ const deleteAuthFile = (name) => {
try { try {
return fs_1.default.rmSync(path_1.default.join((0, exports.grabAuthDirs)().auth, name)); return fs_1.default.rmSync(path_1.default.join((0, exports.grabAuthDirs)().auth, name));
} }
catch ( /** @type {any} */error) { catch (error) {
console.log(`Error deleting Auth File: ${error.message}`); console.log(`Error deleting Auth File: ${error.message}`);
return null; return null;
} }
@ -116,7 +120,7 @@ const checkAuthFile = (name) => {
return fs_1.default.existsSync(path_1.default.join((0, exports.grabAuthDirs)().auth, name)); return fs_1.default.existsSync(path_1.default.join((0, exports.grabAuthDirs)().auth, name));
return true; return true;
} }
catch ( /** @type {any} */error) { catch (error) {
console.log(`Error checking Auth File: ${error.message}`); console.log(`Error checking Auth File: ${error.message}`);
return false; return false;
} }

View File

@ -32,8 +32,12 @@ function grantFullPrivileges(_a) {
for (let i = 0; i < datasquirelUserDatabases.length; i++) { for (let i = 0; i < datasquirelUserDatabases.length; i++) {
const datasquirelUserDatabase = datasquirelUserDatabases[i]; const datasquirelUserDatabase = datasquirelUserDatabases[i];
const { Database } = datasquirelUserDatabase; const { Database } = datasquirelUserDatabase;
const grantDbPriviledges = yield (0, noDatabaseDbHandler_1.default)(`GRANT ALL PRIVILEGES ON ${Database}.* TO '${process.env.DSQL_DB_FULL_ACCESS_USERNAME}'@'%' WITH GRANT OPTION`); // const grantDbPriviledges = await noDatabaseDbHandler(
const grantRead = yield (0, noDatabaseDbHandler_1.default)(`GRANT SELECT ON ${Database}.* TO '${process.env.DSQL_DB_READ_ONLY_USERNAME}'@'%'`); // `GRANT ALL PRIVILEGES ON ${Database}.* TO '${process.env.DSQL_DB_FULL_ACCESS_USERNAME}'@'%' WITH GRANT OPTION`
// );
// const grantRead = await noDatabaseDbHandler(
// `GRANT SELECT ON ${Database}.* TO '${process.env.DSQL_DB_READ_ONLY_USERNAME}'@'%'`
// );
} }
const flushPriviledged = yield (0, noDatabaseDbHandler_1.default)(`FLUSH PRIVILEGES`); const flushPriviledged = yield (0, noDatabaseDbHandler_1.default)(`FLUSH PRIVILEGES`);
} }

View File

@ -2,8 +2,10 @@ import { DATASQUIREL_LoggedInUser, UserType } from "../../../types";
type Param = { type Param = {
user?: DATASQUIREL_LoggedInUser | UserType; user?: DATASQUIREL_LoggedInUser | UserType;
userId?: string | number | null; userId?: string | number | null;
appDir?: string;
}; };
export default function grabDirNames(param?: Param): { export default function grabDirNames(param?: Param): {
appDir: string;
schemasDir: string; schemasDir: string;
userDirPath: string | undefined; userDirPath: string | undefined;
mainShemaJSONFilePath: string; mainShemaJSONFilePath: string;
@ -22,5 +24,10 @@ export default function grabDirNames(param?: Param): {
userPrivateDbImportZipFileName: string; userPrivateDbImportZipFileName: string;
userPrivateDbImportZipFilePath: string | undefined; userPrivateDbImportZipFilePath: string | undefined;
dbNginxLoadBalancerConfigFile: string; dbNginxLoadBalancerConfigFile: string;
dockerComposeFile: string;
testDockerComposeFile: string;
siteSetupFile: string;
envFile: string;
testEnvFile: string;
}; };
export {}; export {};

View File

@ -7,11 +7,12 @@ exports.default = grabDirNames;
const path_1 = __importDefault(require("path")); const path_1 = __importDefault(require("path"));
function grabDirNames(param) { function grabDirNames(param) {
var _a; var _a;
const appDir = process.env.DSQL_APP_DIR; const appDir = (param === null || param === void 0 ? void 0 : param.appDir) || process.env.DSQL_APP_DIR;
const schemasDir = process.env.DSQL_DB_SCHEMA_DIR;
const tempDirName = ".tmp";
if (!appDir) if (!appDir)
throw new Error("Please provide the `DSQL_APP_DIR` env variable."); throw new Error("Please provide the `DSQL_APP_DIR` env variable.");
const schemasDir = process.env.DSQL_DB_SCHEMA_DIR ||
path_1.default.join(appDir, "jsonData", "dbSchemas");
const tempDirName = ".tmp";
if (!schemasDir) if (!schemasDir)
throw new Error("Please provide the `DSQL_DB_SCHEMA_DIR` env variable."); throw new Error("Please provide the `DSQL_DB_SCHEMA_DIR` env variable.");
const pakageSharedDir = path_1.default.join(appDir, `package-shared`); const pakageSharedDir = path_1.default.join(appDir, `package-shared`);
@ -51,7 +52,13 @@ function grabDirNames(param) {
? path_1.default.join(userPrivateSQLExportsDir, userPrivateDbImportZipFileName) ? path_1.default.join(userPrivateSQLExportsDir, userPrivateDbImportZipFileName)
: undefined; : undefined;
const dbNginxLoadBalancerConfigFile = path_1.default.join(appDir, "docker/mariadb/load-balancer/config/template/nginx.conf"); 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 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");
return { return {
appDir,
schemasDir, schemasDir,
userDirPath, userDirPath,
mainShemaJSONFilePath, mainShemaJSONFilePath,
@ -70,5 +77,10 @@ function grabDirNames(param) {
userPrivateDbImportZipFileName, userPrivateDbImportZipFileName,
userPrivateDbImportZipFilePath, userPrivateDbImportZipFilePath,
dbNginxLoadBalancerConfigFile, dbNginxLoadBalancerConfigFile,
dockerComposeFile,
testDockerComposeFile,
siteSetupFile,
envFile,
testEnvFile,
}; };
} }

View File

@ -36,6 +36,7 @@ type Param = {
apiUserID?: string | number; apiUserID?: string | number;
dbUserId?: string | number; dbUserId?: string | number;
cleanupTokens?: boolean; cleanupTokens?: boolean;
secureCookie?: boolean;
}; };
/** /**
@ -60,6 +61,7 @@ export default async function loginUser({
dbUserId, dbUserId,
debug, debug,
cleanupTokens, cleanupTokens,
secureCookie,
}: Param): Promise<APILoginFunctionReturn> { }: Param): Promise<APILoginFunctionReturn> {
const grabedHostNames = grabHostNames({ userId: user_id || apiUserID }); const grabedHostNames = grabHostNames({ userId: user_id || apiUserID });
const { host, port, scheme } = grabedHostNames; const { host, port, scheme } = grabedHostNames;
@ -266,7 +268,9 @@ export default async function loginUser({
} }
response?.setHeader("Set-Cookie", [ response?.setHeader("Set-Cookie", [
`${authKeyName}=${encryptedPayload};samesite=strict;path=/;HttpOnly=true;Secure=true`, `${authKeyName}=${encryptedPayload};samesite=strict;path=/;HttpOnly=true${
secureCookie ? ";Secure=true" : ""
}`,
`${csrfName}=${httpResponse.payload?.csrf_k};samesite=strict;path=/;HttpOnly=true`, `${csrfName}=${httpResponse.payload?.csrf_k};samesite=strict;path=/;HttpOnly=true`,
]); ]);

View File

@ -25,6 +25,7 @@ type Param = {
additionalFields?: string[]; additionalFields?: string[];
encryptedUserString?: string; encryptedUserString?: string;
user_id?: string | number; user_id?: string | number;
secureCookie?: boolean;
}; };
/** /**
@ -41,6 +42,7 @@ export default async function reauthUser({
additionalFields, additionalFields,
encryptedUserString, encryptedUserString,
user_id, user_id,
secureCookie,
}: Param): Promise<APILoginFunctionReturn> { }: Param): Promise<APILoginFunctionReturn> {
/** /**
* Check Encryption Keys * Check Encryption Keys
@ -188,7 +190,9 @@ export default async function reauthUser({
const csrfName = cookieNames.csrfCookieName; const csrfName = cookieNames.csrfCookieName;
response?.setHeader("Set-Cookie", [ response?.setHeader("Set-Cookie", [
`${authKeyName}=${encryptedPayload};samesite=strict;path=/;HttpOnly=true;Secure=true`, `${authKeyName}=${encryptedPayload};samesite=strict;path=/;HttpOnly=true${
secureCookie ? ";Secure=true" : ""
}`,
`${csrfName}=${httpResponse.payload?.csrf_k};samesite=strict;path=/;HttpOnly=true`, `${csrfName}=${httpResponse.payload?.csrf_k};samesite=strict;path=/;HttpOnly=true`,
]); ]);

View File

@ -31,6 +31,7 @@ type Param = {
additionalFields?: string[]; additionalFields?: string[];
additionalData?: { [s: string]: string | number }; additionalData?: { [s: string]: string | number };
user_id?: boolean; user_id?: boolean;
secureCookie?: boolean;
}; };
/** /**
@ -49,6 +50,7 @@ export default async function githubAuth({
additionalFields, additionalFields,
user_id, user_id,
additionalData, additionalData,
secureCookie,
}: Param): Promise<FunctionReturn | undefined> { }: Param): Promise<FunctionReturn | undefined> {
/** /**
* Check inputs * Check inputs
@ -228,10 +230,10 @@ export default async function githubAuth({
const csrfName = `datasquirel_${dsqlUserId}_${database}_csrf`; const csrfName = `datasquirel_${dsqlUserId}_${database}_csrf`;
response.setHeader("Set-Cookie", [ response.setHeader("Set-Cookie", [
`${authKeyName}=${encryptedPayload};samesite=strict;path=/;HttpOnly=true;Secure=true`, `${authKeyName}=${encryptedPayload};samesite=strict;path=/;HttpOnly=true${
secureCookie ? ";Secure=true" : ""
}`,
`${csrfName}=${user.csrf_k};samesite=strict;path=/;HttpOnly=true`, `${csrfName}=${user.csrf_k};samesite=strict;path=/;HttpOnly=true`,
`dsqluid=${dsqlUserId};samesite=strict;path=/;HttpOnly=true`,
`datasquirel_social_id=${user.social_id};samesite=strict;path=/`,
]); ]);
} }

View File

@ -17,6 +17,7 @@ type Param = {
additionalData?: { [s: string]: string | number }; additionalData?: { [s: string]: string | number };
apiUserID?: string | number; apiUserID?: string | number;
debug?: boolean; debug?: boolean;
secureCookie?: boolean;
}; };
/** /**
@ -33,6 +34,7 @@ export default async function googleAuth({
additionalData, additionalData,
apiUserID, apiUserID,
debug, debug,
secureCookie,
}: Param): Promise<APILoginFunctionReturn> { }: Param): Promise<APILoginFunctionReturn> {
const grabedHostNames = grabHostNames({ const grabedHostNames = grabHostNames({
userId: apiUserID || process.env.DSQL_API_USER_ID, userId: apiUserID || process.env.DSQL_API_USER_ID,
@ -192,7 +194,9 @@ export default async function googleAuth({
const csrfName = cookieNames.csrfCookieName; const csrfName = cookieNames.csrfCookieName;
response?.setHeader("Set-Cookie", [ response?.setHeader("Set-Cookie", [
`${authKeyName}=${encryptedPayload};samesite=strict;path=/;HttpOnly=true;Secure=true`, `${authKeyName}=${encryptedPayload};samesite=strict;path=/;HttpOnly=true${
secureCookie ? ";Secure=true" : ""
}`,
`${csrfName}=${httpResponse.payload?.csrf_k};samesite=strict;path=/;HttpOnly=true`, `${csrfName}=${httpResponse.payload?.csrf_k};samesite=strict;path=/;HttpOnly=true`,
]); ]);
} }

View File

@ -2,6 +2,11 @@ import fs from "fs";
import path from "path"; import path from "path";
import EJSON from "../../../utils/ejson"; import EJSON from "../../../utils/ejson";
import { DATASQUIREL_LoggedInUser } from "../../../types"; import { DATASQUIREL_LoggedInUser } from "../../../types";
import debugLog from "../../../utils/logging/debug-log";
function debugFn(log: any, label?: string) {
debugLog({ log, addTime: true, title: "write-auth-files", label });
}
export const grabAuthDirs = () => { export const grabAuthDirs = () => {
const DSQL_AUTH_DIR = process.env.DSQL_AUTH_DIR; const DSQL_AUTH_DIR = process.env.DSQL_AUTH_DIR;
@ -43,14 +48,15 @@ export const writeAuthFile = (
} }
) => { ) => {
initAuthFiles(); initAuthFiles();
try { try {
const { auth, root } = grabAuthDirs(); const { auth } = grabAuthDirs();
if (cleanup) { if (cleanup) {
cleanupUserAuthFiles(cleanup.userId); cleanupUserAuthFiles(cleanup.userId);
} }
fs.writeFileSync(path.join(auth, name), data); fs.writeFileSync(path.join(auth, name), data);
return true; return true;
} catch (/** @type {any} */ error: any) { } catch (error: any) {
console.log(`Error writing Auth File: ${error.message}`); console.log(`Error writing Auth File: ${error.message}`);
return false; return false;
} }
@ -67,14 +73,16 @@ export const cleanupUserAuthFiles = (userId: string | number) => {
for (let i = 0; i < loginFiles.length; i++) { for (let i = 0; i < loginFiles.length; i++) {
const loginFile = loginFiles[i]; const loginFile = loginFiles[i];
const loginFilePath = path.join(auth, loginFile); const loginFilePath = path.join(auth, loginFile);
try { try {
const authPayload = EJSON.parse( const authPayload = EJSON.parse(
fs.readFileSync(loginFilePath, "utf-8") fs.readFileSync(loginFilePath, "utf-8")
) as DATASQUIREL_LoggedInUser; ) as DATASQUIREL_LoggedInUser;
if (authPayload.id == userId) { if (authPayload.id == userId) {
fs.unlinkSync(loginFilePath); fs.unlinkSync(loginFilePath);
} }
} catch (error) {} } catch (error: any) {}
} }
return true; return true;
} catch (error: any) { } catch (error: any) {
@ -90,7 +98,7 @@ export const getAuthFile = (name: string) => {
try { try {
const authFilePath = path.join(grabAuthDirs().auth, name); const authFilePath = path.join(grabAuthDirs().auth, name);
return fs.readFileSync(authFilePath, "utf-8"); return fs.readFileSync(authFilePath, "utf-8");
} catch (/** @type {any} */ error: any) { } catch (error: any) {
console.log(`Error getting Auth File: ${error.message}`); console.log(`Error getting Auth File: ${error.message}`);
return null; return null;
} }
@ -103,7 +111,7 @@ export const getAuthFile = (name: string) => {
export const deleteAuthFile = (name: string) => { export const deleteAuthFile = (name: string) => {
try { try {
return fs.rmSync(path.join(grabAuthDirs().auth, name)); return fs.rmSync(path.join(grabAuthDirs().auth, name));
} catch (/** @type {any} */ error: any) { } catch (error: any) {
console.log(`Error deleting Auth File: ${error.message}`); console.log(`Error deleting Auth File: ${error.message}`);
return null; return null;
} }
@ -117,7 +125,7 @@ export const checkAuthFile = (name: string) => {
try { try {
return fs.existsSync(path.join(grabAuthDirs().auth, name)); return fs.existsSync(path.join(grabAuthDirs().auth, name));
return true; return true;
} catch (/** @type {any} */ error: any) { } catch (error: any) {
console.log(`Error checking Auth File: ${error.message}`); console.log(`Error checking Auth File: ${error.message}`);
return false; return false;
} }

View File

@ -25,13 +25,13 @@ async function grantFullPrivileges({ userId }: { userId: string | null }) {
const datasquirelUserDatabase = datasquirelUserDatabases[i]; const datasquirelUserDatabase = datasquirelUserDatabases[i];
const { Database } = datasquirelUserDatabase; const { Database } = datasquirelUserDatabase;
const grantDbPriviledges = await noDatabaseDbHandler( // const grantDbPriviledges = await noDatabaseDbHandler(
`GRANT ALL PRIVILEGES ON ${Database}.* TO '${process.env.DSQL_DB_FULL_ACCESS_USERNAME}'@'%' WITH GRANT OPTION` // `GRANT ALL PRIVILEGES ON ${Database}.* TO '${process.env.DSQL_DB_FULL_ACCESS_USERNAME}'@'%' WITH GRANT OPTION`
); // );
const grantRead = await noDatabaseDbHandler( // const grantRead = await noDatabaseDbHandler(
`GRANT SELECT ON ${Database}.* TO '${process.env.DSQL_DB_READ_ONLY_USERNAME}'@'%'` // `GRANT SELECT ON ${Database}.* TO '${process.env.DSQL_DB_READ_ONLY_USERNAME}'@'%'`
); // );
} }
const flushPriviledged = await noDatabaseDbHandler(`FLUSH PRIVILEGES`); const flushPriviledged = await noDatabaseDbHandler(`FLUSH PRIVILEGES`);

View File

@ -4,15 +4,19 @@ import path from "path";
type Param = { type Param = {
user?: DATASQUIREL_LoggedInUser | UserType; user?: DATASQUIREL_LoggedInUser | UserType;
userId?: string | number | null; userId?: string | number | null;
appDir?: string;
}; };
export default function grabDirNames(param?: Param) { export default function grabDirNames(param?: Param) {
const appDir = process.env.DSQL_APP_DIR; const appDir = param?.appDir || process.env.DSQL_APP_DIR;
const schemasDir = process.env.DSQL_DB_SCHEMA_DIR;
const tempDirName = ".tmp";
if (!appDir) if (!appDir)
throw new Error("Please provide the `DSQL_APP_DIR` env variable."); throw new Error("Please provide the `DSQL_APP_DIR` env variable.");
const schemasDir =
process.env.DSQL_DB_SCHEMA_DIR ||
path.join(appDir, "jsonData", "dbSchemas");
const tempDirName = ".tmp";
if (!schemasDir) if (!schemasDir)
throw new Error( throw new Error(
"Please provide the `DSQL_DB_SCHEMA_DIR` env variable." "Please provide the `DSQL_DB_SCHEMA_DIR` env variable."
@ -67,7 +71,14 @@ export default function grabDirNames(param?: Param) {
"docker/mariadb/load-balancer/config/template/nginx.conf" "docker/mariadb/load-balancer/config/template/nginx.conf"
); );
const dockerComposeFile = path.join(appDir, "docker-compose.yml");
const testDockerComposeFile = path.join(appDir, "test.docker-compose.yml");
const siteSetupFile = path.join(appDir, "site-setup.json");
const envFile = path.join(appDir, ".env");
const testEnvFile = path.join(appDir, "test.env");
return { return {
appDir,
schemasDir, schemasDir,
userDirPath, userDirPath,
mainShemaJSONFilePath, mainShemaJSONFilePath,
@ -86,5 +97,10 @@ export default function grabDirNames(param?: Param) {
userPrivateDbImportZipFileName, userPrivateDbImportZipFileName,
userPrivateDbImportZipFilePath, userPrivateDbImportZipFilePath,
dbNginxLoadBalancerConfigFile, dbNginxLoadBalancerConfigFile,
dockerComposeFile,
testDockerComposeFile,
siteSetupFile,
envFile,
testEnvFile,
}; };
} }

View File

@ -1,6 +1,6 @@
{ {
"name": "@moduletrace/datasquirel", "name": "@moduletrace/datasquirel",
"version": "4.1.9", "version": "4.2.0",
"description": "Cloud-based SQL data management tool", "description": "Cloud-based SQL data management tool",
"main": "dist/index.js", "main": "dist/index.js",
"bin": { "bin": {