63 lines
2.4 KiB
JavaScript
63 lines
2.4 KiB
JavaScript
import { UserSQLPermissions, } from "../../../types";
|
|
import dsqlCrud from "../../../utils/data-fetching/crud";
|
|
import grabDbNames from "../../../utils/grab-db-names";
|
|
import normalizeText from "../../../utils/normalize-text";
|
|
import dbHandler from "../../backend/dbHandler";
|
|
import handleMariadbUserGrantsForDatabases from "./handle-mariadb-user-grants-for-databases";
|
|
import revokeAllExistingGrants from "./revoke-all-existing-grants";
|
|
export default async function handleMariadbUserGrants({ accessedDatabases, grants, isAllDbsAccess, isAllGrants, user, updatedRecord, }) {
|
|
const { userDbPrefix } = grabDbNames({ user });
|
|
/**
|
|
* # Revoke All Existing Grants
|
|
*/
|
|
await revokeAllExistingGrants({ updatedRecord, user });
|
|
/**
|
|
* # Recreate Grants
|
|
*/
|
|
if (isAllGrants && isAllDbsAccess) {
|
|
const grantAllPrivileges = await dbHandler({
|
|
query: normalizeText(`
|
|
GRANT ALL PRIVILEGES ON \
|
|
\`${userDbPrefix.replace(/\_/g, "\\_")}%\`.* TO \
|
|
'${updatedRecord.username}'@'${updatedRecord.host}'
|
|
`),
|
|
});
|
|
return { success: true };
|
|
}
|
|
if (isAllDbsAccess && grants) {
|
|
const isGrantsInalid = grants.find((g) => !UserSQLPermissions.includes(g));
|
|
if (isGrantsInalid) {
|
|
return { msg: `grants is/are invalid!` };
|
|
}
|
|
const grantQuery = normalizeText(`
|
|
GRANT ${grants.join(",")} ON \`${userDbPrefix}%\`.* TO \
|
|
'${updatedRecord.username}'@'${updatedRecord.host}'
|
|
`);
|
|
const grantSpecificPrivilegesToAllDbs = await dbHandler({
|
|
query: grantQuery,
|
|
});
|
|
for (let t = 0; t < grants.length; t++) {
|
|
const grant = grants[t];
|
|
const addGrant = await dsqlCrud({
|
|
action: "insert",
|
|
table: "mariadb_user_privileges",
|
|
data: {
|
|
user_id: user.id,
|
|
mariadb_user_id: updatedRecord.id,
|
|
privilege: grant,
|
|
},
|
|
});
|
|
}
|
|
return { success: true };
|
|
}
|
|
if (accessedDatabases === null || accessedDatabases === void 0 ? void 0 : accessedDatabases[0]) {
|
|
const res = await handleMariadbUserGrantsForDatabases({
|
|
accessedDatabases,
|
|
updatedRecord,
|
|
user,
|
|
});
|
|
return res;
|
|
}
|
|
return {};
|
|
}
|