datasquirel/package-shared/functions/backend/auth/write-auth-files.ts

82 lines
2.1 KiB
TypeScript
Raw Normal View History

2025-01-10 19:10:28 +00:00
import fs from "fs";
import path from "path";
2024-12-08 08:58:57 +00:00
2025-01-10 19:10:28 +00:00
export const grabAuthDirs = () => {
2024-12-13 13:14:38 +00:00
const DSQL_AUTH_DIR = process.env.DSQL_AUTH_DIR;
const ROOT_DIR = DSQL_AUTH_DIR?.match(/./)
? DSQL_AUTH_DIR
: path.resolve(process.cwd(), "./.tmp");
2024-12-08 08:58:57 +00:00
const AUTH_DIR = path.join(ROOT_DIR, "logins");
return { root: ROOT_DIR, auth: AUTH_DIR };
};
2025-01-10 19:10:28 +00:00
export const initAuthFiles = () => {
2024-12-08 08:58:57 +00:00
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;
2025-01-10 19:10:28 +00:00
} catch (error: any) {
2024-12-08 08:58:57 +00:00
console.log(`Error initializing Auth Files: ${error.message}`);
return false;
}
};
/**
* # Write Auth Files
*/
2025-01-10 19:10:28 +00:00
export const writeAuthFile = (name: string, data: string) => {
2024-12-08 08:58:57 +00:00
initAuthFiles();
try {
fs.writeFileSync(path.join(grabAuthDirs().auth, name), data);
return true;
2025-01-10 19:10:28 +00:00
} catch (/** @type {any} */ error: any) {
2024-12-08 08:58:57 +00:00
console.log(`Error writing Auth File: ${error.message}`);
return false;
}
};
/**
* # Get Auth Files
*/
2025-01-10 19:10:28 +00:00
export const getAuthFile = (name: string) => {
2024-12-08 08:58:57 +00:00
try {
const authFilePath = path.join(grabAuthDirs().auth, name);
return fs.readFileSync(authFilePath, "utf-8");
2025-01-10 19:10:28 +00:00
} catch (/** @type {any} */ error: any) {
2024-12-08 08:58:57 +00:00
console.log(`Error getting Auth File: ${error.message}`);
return null;
}
};
/**
* # Delete Auth Files
* @param {string} name
*/
2025-01-10 19:10:28 +00:00
export const deleteAuthFile = (name: string) => {
2024-12-08 08:58:57 +00:00
try {
return fs.rmSync(path.join(grabAuthDirs().auth, name));
2025-01-10 19:10:28 +00:00
} catch (/** @type {any} */ error: any) {
2024-12-08 08:58:57 +00:00
console.log(`Error deleting Auth File: ${error.message}`);
return null;
}
};
/**
* # Delete Auth Files
* @param {string} name
*/
2025-01-10 19:10:28 +00:00
export const checkAuthFile = (name: string) => {
2024-12-08 08:58:57 +00:00
try {
return fs.existsSync(path.join(grabAuthDirs().auth, name));
return true;
2025-01-10 19:10:28 +00:00
} catch (/** @type {any} */ error: any) {
2024-12-08 08:58:57 +00:00
console.log(`Error checking Auth File: ${error.message}`);
return false;
}
};