datasquirel/package-shared/shell/setSQLCredentials.ts

69 lines
2.5 KiB
TypeScript
Raw Normal View History

2024-12-06 10:31:24 +00:00
require("dotenv").config({ path: "./../.env" });
2025-01-10 19:10:28 +00:00
import generator from "generate-password";
import noDatabaseDbHandler from "./utils/noDatabaseDbHandler";
import dbHandler from "./utils/dbHandler";
import encrypt from "../functions/dsql/encrypt";
2024-12-06 10:31:24 +00:00
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/**
2025-01-10 19:10:28 +00:00
* # Set SQL Credentials
2024-12-06 10:31:24 +00:00
*/
async function setSQLCredentials() {
2025-01-10 19:10:28 +00:00
const users = (await dbHandler({
2024-12-06 10:31:24 +00:00
query: `SELECT * FROM users`,
2025-01-10 19:10:28 +00:00
})) as any[] | null;
2024-12-06 10:31:24 +00:00
if (!users) {
process.exit();
}
for (let i = 0; i < users.length; i++) {
const user = users[i];
if (!user) continue;
if (user.mariadb_user && user.mariadb_pass) {
continue;
}
try {
const username = `dsql_user_${user.id}`;
const password = generator.generate({
length: 16,
numbers: true,
symbols: true,
uppercase: true,
exclude: "*#.'`\"",
});
const encryptedPassword = encrypt({ data: password });
await noDatabaseDbHandler(
2024-12-09 11:45:39 +00:00
`CREATE USER IF NOT EXISTS '${username}'@'127.0.0.1' IDENTIFIED BY '${password}'`
2024-12-06 10:31:24 +00:00
);
await noDatabaseDbHandler(
`GRANT ALL PRIVILEGES ON \`datasquirel\\_user\\_${user.id}\\_%\`.* TO '${username}'@'127.0.0.1'`
);
await noDatabaseDbHandler(`FLUSH PRIVILEGES`);
const updateUser = await dbHandler({
query: `UPDATE users SET mariadb_user = ?, mariadb_host = '127.0.0.1' mariadb_pass = ? WHERE id = ?`,
values: [username, encryptedPassword, user.id],
});
console.log(
`User ${user.id}: ${user.first_name} ${user.last_name} SQL credentials successfully added.`
);
2025-01-10 19:10:28 +00:00
} catch (error: any) {
2024-12-06 10:31:24 +00:00
console.log(`Error in adding SQL user =>`, error.message);
}
}
}
setSQLCredentials();