const fs = require("fs"); const path = require("path"); const crypto = require("crypto"); /** * Validate if a directory name is valid (alphanumeric and non-empty). * @param {string} dirName - Directory name to validate. * @returns {boolean} True if valid, false otherwise. */ function isValidDirectoryName(dirName) { const regex = /^[a-zA-Z0-9_-]+$/; return regex.test(dirName); } /** * Hash a password using SHA-256 for secure storage. * @param {string} password - Password to hash. * @returns {string} The hashed password. */ function hashPassword(password) { return crypto.createHash("sha256").update(password).digest("hex"); } /** * Verify a password against a stored hash. * @param {string} password - Password to verify. * @param {string} hash - Hash to compare against. * @returns {boolean} True if the password matches the hash, false otherwise. */ function verifyPassword(password, hash) { return hashPassword(password) === hash; } /** * Create a new user directory. * @param {string} baseDir - Base directory where user directories are stored. * @param {string} dirName - Name of the new directory. * @param {string} password - Password to save for the directory. */ function createUserDirectory(baseDir, dirName, password) { const dirPath = path.join(baseDir, dirName); if (fs.existsSync(dirPath)) { throw new Error("Directory already exists"); } // Create the directory fs.mkdirSync(dirPath, { recursive: true }); // Save hashed password const hashedPassword = hashPassword(password); fs.writeFileSync(path.join(dirPath, "password.txt"), hashedPassword, "utf8"); console.log(`Directory ${dirName} created successfully`); } /** * Delete a user directory. * @param {string} baseDir - Base directory where user directories are stored. * @param {string} dirName - Name of the directory to delete. * @param {string} password - Password to verify before deletion. */ function deleteUserDirectory(baseDir, dirName, password) { const dirPath = path.join(baseDir, dirName); if (!fs.existsSync(dirPath)) { throw new Error("Directory does not exist"); } // Verify password const passwordFile = path.join(dirPath, "password.txt"); if (!fs.existsSync(passwordFile)) { throw new Error("Password file is missing"); } const storedHash = fs.readFileSync(passwordFile, "utf8"); if (!verifyPassword(password, storedHash)) { throw new Error("Invalid password"); } // Delete the directory fs.rmSync(dirPath, { recursive: true, force: true }); console.log(`Directory ${dirName} deleted successfully`); } /** * Log messages to the console with a timestamp. * @param {string} message - Message to log. */ function logMessage(message) { const timestamp = new Date().toISOString(); console.log(`[${timestamp}] ${message}`); } module.exports = { isValidDirectoryName, hashPassword, verifyPassword, createUserDirectory, deleteUserDirectory, logMessage, };