datasquirel/package-shared/functions/backend/addMariadbUser.ts
2025-01-10 20:10:28 +01:00

74 lines
2.5 KiB
TypeScript

import generator from "generate-password";
import DB_HANDLER from "../../utils/backend/global-db/DB_HANDLER";
import NO_DB_HANDLER from "../../utils/backend/global-db/NO_DB_HANDLER";
import addDbEntry from "./db/addDbEntry";
import encrypt from "../dsql/encrypt";
import LOCAL_DB_HANDLER from "../../utils/backend/global-db/LOCAL_DB_HANDLER";
type Param = {
userId: number | string;
useLocal?: boolean;
};
/**
* # Add Mariadb User
*/
export default async function addMariadbUser({
userId,
useLocal,
}: Param): Promise<any> {
try {
const defaultMariadbUserHost = process.env.DSQL_DB_HOST || "127.0.0.1";
const username = `dsql_user_${userId}`;
const password = generator.generate({
length: 16,
numbers: true,
symbols: true,
uppercase: true,
exclude: "*#.'`\"",
});
const encryptedPassword = encrypt({ data: password });
const createMariadbUsersQuery = `CREATE USER IF NOT EXISTS '${username}'@'127.0.0.1' IDENTIFIED BY '${password}'`;
if (useLocal) {
await LOCAL_DB_HANDLER(createMariadbUsersQuery);
} else {
await NO_DB_HANDLER(createMariadbUsersQuery);
}
const updateUserQuery = `UPDATE users SET mariadb_user = ?, mariadb_host = '127.0.0.1', mariadb_pass = ? WHERE id = ?`;
const updateUserValues = [username, encryptedPassword, userId];
const updateUser = useLocal
? await LOCAL_DB_HANDLER(updateUserQuery, updateUserValues)
: await DB_HANDLER(updateUserQuery, updateUserValues);
const addMariadbUser = await addDbEntry({
tableName: "mariadb_users",
data: {
user_id: userId,
username,
host: defaultMariadbUserHost,
password: encryptedPassword,
primary: "1",
grants: '[{"database":"*","table":"*","privileges":["ALL"]}]',
},
dbContext: "Master",
useLocal,
});
console.log(`User ${userId} SQL credentials successfully added.`);
} catch (/** @type {any} */ error: any) {
console.log(
`Error in adding SQL user in 'addMariadbUser' function =>`,
error.message
);
}
}
////////////////////////////////////////////////
////////////////////////////////////////////////
////////////////////////////////////////////////