dsql-admin/dsql-app/package-shared/functions/backend/auth/write-auth-files.js

91 lines
2.3 KiB
JavaScript
Raw Normal View History

2024-12-08 08:57:48 +00:00
// @ts-check
const fs = require("fs");
const path = require("path");
const grabAuthDirs = () => {
const ROOT_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;