88 lines
2.6 KiB
TypeScript
88 lines
2.6 KiB
TypeScript
import { DSQL_DATASQUIREL_MARIADB_USERS } from "../../../types/dsql";
|
|
import { UserType } from "../../../types";
|
|
import dbHandler from "../../backend/dbHandler";
|
|
import normalizeText from "../../../utils/normalize-text";
|
|
import decrypt from "../../dsql/decrypt";
|
|
|
|
type Params = {
|
|
user: UserType;
|
|
existingRecord?: DSQL_DATASQUIREL_MARIADB_USERS | null;
|
|
updatedRecord: DSQL_DATASQUIREL_MARIADB_USERS;
|
|
};
|
|
|
|
type Return = {
|
|
msg?: string;
|
|
success?: boolean;
|
|
};
|
|
|
|
export default async function handleMariadbUserCreation({
|
|
user,
|
|
existingRecord,
|
|
updatedRecord,
|
|
}: Params): Promise<Return> {
|
|
const parsedPassword = decrypt({
|
|
encryptedString: updatedRecord?.password || "",
|
|
});
|
|
|
|
if (existingRecord?.id && updatedRecord?.id) {
|
|
if (
|
|
existingRecord.username !== updatedRecord.username ||
|
|
existingRecord.host !== updatedRecord.host
|
|
) {
|
|
const renameSQLUser = await dbHandler({
|
|
query: normalizeText(`
|
|
RENAME USER '${existingRecord.username}'@'${existingRecord.host}' \
|
|
TO '${updatedRecord.username}'@'${updatedRecord.host}'
|
|
`),
|
|
});
|
|
|
|
if (!renameSQLUser) {
|
|
await createNewSQLUser({
|
|
host: updatedRecord.host,
|
|
password: parsedPassword,
|
|
username: updatedRecord.username,
|
|
});
|
|
}
|
|
}
|
|
|
|
const updateSQLUser = await dbHandler({
|
|
query: normalizeText(`
|
|
ALTER USER '${updatedRecord.username}'@'${updatedRecord.host}' \
|
|
IDENTIFIED BY '${parsedPassword}'
|
|
`),
|
|
});
|
|
|
|
if (!updateSQLUser) {
|
|
await createNewSQLUser({
|
|
host: updatedRecord.host,
|
|
password: parsedPassword,
|
|
username: updatedRecord.username,
|
|
});
|
|
}
|
|
} else if (!existingRecord?.id && updatedRecord?.id) {
|
|
await createNewSQLUser({
|
|
host: updatedRecord.host,
|
|
password: parsedPassword,
|
|
username: updatedRecord.username,
|
|
});
|
|
}
|
|
|
|
return { success: true };
|
|
}
|
|
|
|
type CreateNewUserParams = {
|
|
username?: string;
|
|
host?: string;
|
|
password?: string;
|
|
};
|
|
|
|
export async function createNewSQLUser({
|
|
host,
|
|
password,
|
|
username,
|
|
}: CreateNewUserParams) {
|
|
return await dbHandler({
|
|
query: `CREATE USER IF NOT EXISTS '${username}'@'${host}' IDENTIFIED BY '${password}'`,
|
|
});
|
|
}
|