107 lines
3.0 KiB
TypeScript
107 lines
3.0 KiB
TypeScript
import {
|
|
AddUpdateMariadbUserAPIReqBody,
|
|
UserSQLPermissions,
|
|
UserType,
|
|
} from "../../../types";
|
|
import {
|
|
DSQL_DATASQUIREL_MARIADB_USER_PRIVILEGES,
|
|
DSQL_DATASQUIREL_MARIADB_USERS,
|
|
DsqlTables,
|
|
} from "../../../types/dsql";
|
|
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";
|
|
|
|
type Params = AddUpdateMariadbUserAPIReqBody & {
|
|
user: UserType;
|
|
updatedRecord: DSQL_DATASQUIREL_MARIADB_USERS;
|
|
};
|
|
|
|
type Return = {
|
|
msg?: string;
|
|
success?: boolean;
|
|
};
|
|
|
|
export default async function handleMariadbUserGrants({
|
|
accessedDatabases,
|
|
grants,
|
|
isAllDbsAccess,
|
|
isAllGrants,
|
|
user,
|
|
updatedRecord,
|
|
}: Params): Promise<Return> {
|
|
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<
|
|
DSQL_DATASQUIREL_MARIADB_USER_PRIVILEGES,
|
|
(typeof DsqlTables)[number]
|
|
>({
|
|
action: "insert",
|
|
table: "mariadb_user_privileges",
|
|
data: {
|
|
user_id: user.id,
|
|
mariadb_user_id: updatedRecord.id,
|
|
privilege: grant,
|
|
},
|
|
});
|
|
}
|
|
|
|
return { success: true };
|
|
}
|
|
|
|
if (accessedDatabases?.[0]) {
|
|
const res = await handleMariadbUserGrantsForDatabases({
|
|
accessedDatabases,
|
|
updatedRecord,
|
|
user,
|
|
});
|
|
|
|
return res;
|
|
}
|
|
|
|
return {};
|
|
}
|