datasquirel/dist/package-shared/shell/mariadb-users/handleGrants.js
Benjamin Toby 7e8bb37c09 Updates
2025-07-05 14:59:30 +01:00

58 lines
2.6 KiB
JavaScript

import noDatabaseDbHandler from "../utils/noDatabaseDbHandler";
/**
* # Handle Grants for Users
*/
export default async function handleGrants({ username, host, grants, userId, }) {
var _a;
let success = false;
console.log(`Handling Grants for User =>`, username, host);
if (!username) {
console.log(`No username provided.`);
return success;
}
if (!host) {
console.log(`No Host provided. \x1b[35m\`--host\`\x1b[0m flag is required`);
return success;
}
if (!grants) {
console.log(`No grants Array provided.`);
return success;
}
try {
const existingUser = await noDatabaseDbHandler(`SELECT * FROM mysql.user WHERE User = '${username}' AND Host = '${host}'`);
const isUserExisting = Boolean((_a = existingUser === null || existingUser === void 0 ? void 0 : existingUser[0]) === null || _a === void 0 ? void 0 : _a.User);
if (isUserExisting) {
const userGrants = await noDatabaseDbHandler(`SHOW GRANTS FOR '${username}'@'${host}'`);
for (let i = 0; i < userGrants.length; i++) {
const grantObject = userGrants[i];
const grant = grantObject === null || grantObject === void 0 ? void 0 : grantObject[Object.keys(grantObject)[0]];
if (grant === null || grant === void 0 ? void 0 : grant.match(/GRANT .* PRIVILEGES ON .* TO/)) {
const revokeGrantText = grant
.replace(/GRANT/, "REVOKE")
.replace(/ TO /, " FROM ");
const revokePrivilege = await noDatabaseDbHandler(revokeGrantText);
}
}
const grantsArray = grants;
for (let i = 0; i < grantsArray.length; i++) {
const grantObject = grantsArray[i];
const { database, table, privileges } = grantObject;
const tableText = table == "*" ? "*" : `\`${table}\``;
const databaseText = database == "*"
? `\`${process.env.DSQL_USER_DB_PREFIX}${userId}_%\``
: `\`${database}\``;
const privilegesText = privileges.includes("ALL")
? "ALL PRIVILEGES"
: privileges.join(", ");
const grantText = `GRANT ${privilegesText} ON ${databaseText}.${tableText} TO '${username}'@'${host}'`;
const grantPriviledge = await noDatabaseDbHandler(grantText);
}
}
success = true;
}
catch ( /** @type {any} */error) {
console.log(`Error in adding SQL user =>`, error.message);
}
return success;
}