datasquirel/package-shared/shell/mariadb-users/users/update-user.js

75 lines
2.2 KiB
JavaScript
Raw Permalink Normal View History

2024-12-06 10:31:24 +00:00
// @ts-check
const path = require("path");
require("dotenv").config({ path: "../../../.env" });
const fs = require("fs");
const EJSON = require("../../../utils/ejson");
const hashPassword = require("../../../functions/dsql/hashPassword");
const updateDbEntry = require("../../../functions/backend/db/updateDbEntry");
const tmpDir = process.argv[process.argv.length - 1];
/**
* # Create New User
*/
async function createUser() {
/**
* Validate Form
*
* @description Check if request body is valid
*/
try {
const isTmpDir = Boolean(tmpDir?.match(/\.json$/));
const targetPath = isTmpDir
? path.resolve(process.cwd(), tmpDir)
: path.resolve(__dirname, "./update-user.json");
const updateUserObj = EJSON.parse(fs.readFileSync(targetPath, "utf-8"));
if (typeof updateUserObj !== "object" || Array.isArray(updateUserObj))
throw new Error("Update User Object Invalid!");
let hashedPassword = updateUserObj.password
? hashPassword({
encryptionKey: process.env.DSQL_ENCRYPTION_PASSWORD || "",
password: updateUserObj.password,
})
: undefined;
let updatePayload = { ...updateUserObj };
if (hashedPassword) {
updatePayload["password"] = hashedPassword;
}
/** @type {any} */
const newUser = await updateDbEntry({
dbFullName: "datasquirel",
tableName: "users",
data: { ...updatePayload, id: undefined },
identifierColumnName: "id",
identifierValue: updatePayload.id,
});
if (!newUser?.affectedRows) return false;
if (isTmpDir) {
try {
fs.unlinkSync(path.resolve(process.cwd(), tmpDir));
} catch (error) {}
}
return true;
} catch (/** @type {any} */ error) {
console.log(`Error in creating user => ${error.message}`);
return false;
}
}
createUser().then((res) => {
if (res) {
console.log("User Update Success!!!");
} else {
console.log("User Update Failed!");
}
process.exit();
});