datasquirel/dist/package-shared/functions/backend/auth/write-auth-files.js
Benjamin Toby 7e8bb37c09 Updates
2025-07-05 14:59:30 +01:00

116 lines
3.3 KiB
JavaScript

import fs from "fs";
import path from "path";
import EJSON from "../../../utils/ejson";
import debugLog from "../../../utils/logging/debug-log";
function debugFn(log, label) {
debugLog({ log, addTime: true, title: "write-auth-files", label });
}
export const grabAuthDirs = () => {
const DSQL_AUTH_DIR = process.env.DSQL_AUTH_DIR;
const ROOT_DIR = (DSQL_AUTH_DIR === null || DSQL_AUTH_DIR === void 0 ? void 0 : DSQL_AUTH_DIR.match(/./))
? DSQL_AUTH_DIR
: path.resolve(process.cwd(), "./.tmp");
const AUTH_DIR = path.join(ROOT_DIR, "logins");
return { root: ROOT_DIR, auth: AUTH_DIR };
};
export const initAuthFiles = () => {
var _a;
try {
const authDirs = grabAuthDirs();
if (!fs.existsSync(authDirs.root))
fs.mkdirSync(authDirs.root, { recursive: true });
if (!fs.existsSync(authDirs.auth))
fs.mkdirSync(authDirs.auth, { recursive: true });
return true;
}
catch (error) {
console.log(`Error initializing Auth Files: ${error.message}`);
(_a = global.ERROR_CALLBACK) === null || _a === void 0 ? void 0 : _a.call(global, `Error Initializing Auth Files`, error);
return false;
}
};
/**
* # Write Auth Files
*/
export const writeAuthFile = (name, data, cleanup) => {
initAuthFiles();
try {
const { auth } = grabAuthDirs();
if (cleanup) {
cleanupUserAuthFiles(cleanup.userId);
}
fs.writeFileSync(path.join(auth, name), data);
return true;
}
catch (error) {
console.log(`Error writing Auth File: ${error.message}`);
return false;
}
};
/**
* # Clean up User Auth Files
*/
export const cleanupUserAuthFiles = (userId) => {
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"));
if (authPayload.id == userId) {
fs.unlinkSync(loginFilePath);
}
}
catch (error) { }
}
return true;
}
catch (error) {
console.log(`Error Cleaning up User Auth Files: ${error.message}`);
return false;
}
};
/**
* # Get Auth Files
*/
export const getAuthFile = (name) => {
try {
const authFilePath = path.join(grabAuthDirs().auth, name);
return fs.readFileSync(authFilePath, "utf-8");
}
catch (error) {
console.log(`Error getting Auth File: ${error.message}`);
return null;
}
};
/**
* # Delete Auth Files
* @param {string} name
*/
export const deleteAuthFile = (name) => {
try {
return fs.rmSync(path.join(grabAuthDirs().auth, name));
}
catch (error) {
console.log(`Error deleting Auth File: ${error.message}`);
return null;
}
};
/**
* # Delete Auth Files
* @param {string} name
*/
export const checkAuthFile = (name) => {
try {
return fs.existsSync(path.join(grabAuthDirs().auth, name));
return true;
}
catch (error) {
console.log(`Error checking Auth File: ${error.message}`);
return false;
}
};