datasquirel/package-shared/functions/backend/auth/write-auth-files.js
Benjamin Toby 901492f5e2 Updates
2024-12-13 14:14:38 +01:00

94 lines
2.4 KiB
JavaScript

// @ts-check
const fs = require("fs");
const path = require("path");
const grabAuthDirs = () => {
const DSQL_AUTH_DIR = process.env.DSQL_AUTH_DIR;
const ROOT_DIR = 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 };
};
const initAuthFiles = () => {
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 (/** @type {any} */ error) {
console.log(`Error initializing Auth Files: ${error.message}`);
return false;
}
};
/**
* # Write Auth Files
* @param {string} name
* @param {string} data
*/
const writeAuthFile = (name, data) => {
initAuthFiles();
try {
fs.writeFileSync(path.join(grabAuthDirs().auth, name), data);
return true;
} catch (/** @type {any} */ error) {
console.log(`Error writing Auth File: ${error.message}`);
return false;
}
};
/**
* # Get Auth Files
* @param {string} name
*/
const getAuthFile = (name) => {
try {
const authFilePath = path.join(grabAuthDirs().auth, name);
return fs.readFileSync(authFilePath, "utf-8");
} catch (/** @type {any} */ error) {
console.log(`Error getting Auth File: ${error.message}`);
return null;
}
};
/**
* # Delete Auth Files
* @param {string} name
*/
const deleteAuthFile = (name) => {
try {
return fs.rmSync(path.join(grabAuthDirs().auth, name));
} catch (/** @type {any} */ error) {
console.log(`Error deleting Auth File: ${error.message}`);
return null;
}
};
/**
* # Delete Auth Files
* @param {string} name
*/
const checkAuthFile = (name) => {
try {
return fs.existsSync(path.join(grabAuthDirs().auth, name));
return true;
} catch (/** @type {any} */ error) {
console.log(`Error checking Auth File: ${error.message}`);
return false;
}
};
exports.grabAuthDirs = grabAuthDirs;
exports.initAuthFiles = initAuthFiles;
exports.writeAuthFile = writeAuthFile;
exports.getAuthFile = getAuthFile;
exports.deleteAuthFile = deleteAuthFile;
exports.checkAuthFile = checkAuthFile;