This commit is contained in:
Benjamin Toby
2025-03-12 07:22:04 +01:00
parent c192d9cd13
commit ec4d0428bb
7 changed files with 98 additions and 13 deletions
+6 -1
View File
@@ -35,6 +35,7 @@ type Param = {
skipWriteAuthFile?: boolean;
apiUserID?: string | number;
dbUserId?: string | number;
cleanupTokens?: boolean;
};
/**
@@ -58,6 +59,7 @@ export default async function loginUser({
skipWriteAuthFile,
dbUserId,
debug,
cleanupTokens,
}: Param): Promise<APILoginFunctionReturn> {
const grabedHostNames = grabHostNames({ userId: user_id || apiUserID });
const { host, port, scheme } = grabedHostNames;
@@ -244,7 +246,10 @@ export default async function loginUser({
if (httpResponse.csrf && !skipWriteAuthFile) {
writeAuthFile(
httpResponse.csrf,
JSON.stringify(httpResponse.payload)
JSON.stringify(httpResponse.payload),
cleanupTokens && httpResponse.payload?.id
? { userId: httpResponse.payload.id }
: undefined
);
}
@@ -1,5 +1,7 @@
import fs from "fs";
import path from "path";
import EJSON from "../../../utils/ejson";
import { DATASQUIREL_LoggedInUser } from "../../../types";
export const grabAuthDirs = () => {
const DSQL_AUTH_DIR = process.env.DSQL_AUTH_DIR;
@@ -33,10 +35,20 @@ export const initAuthFiles = () => {
/**
* # Write Auth Files
*/
export const writeAuthFile = (name: string, data: string) => {
export const writeAuthFile = (
name: string,
data: string,
cleanup?: {
userId: string | number;
}
) => {
initAuthFiles();
try {
fs.writeFileSync(path.join(grabAuthDirs().auth, name), data);
const { auth, root } = grabAuthDirs();
if (cleanup) {
cleanupUserAuthFiles(cleanup.userId);
}
fs.writeFileSync(path.join(auth, name), data);
return true;
} catch (/** @type {any} */ error: any) {
console.log(`Error writing Auth File: ${error.message}`);
@@ -44,6 +56,33 @@ export const writeAuthFile = (name: string, data: string) => {
}
};
/**
* # Clean up User Auth Files
*/
export const cleanupUserAuthFiles = (userId: string | number) => {
initAuthFiles();
try {
const { auth } = grabAuthDirs();
const loginFiles = fs.readdirSync(auth);
for (let i = 0; i < loginFiles.length; i++) {
const loginFile = loginFiles[i];
const loginFilePath = path.join(auth, loginFile);
try {
const authPayload = EJSON.parse(
fs.readFileSync(loginFilePath, "utf-8")
) as DATASQUIREL_LoggedInUser;
if (authPayload.id == userId) {
fs.unlinkSync(loginFilePath);
}
} catch (error) {}
}
return true;
} catch (error: any) {
console.log(`Error Cleaning up User Auth Files: ${error.message}`);
return false;
}
};
/**
* # Get Auth Files
*/