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
@@ -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
*/