datasquirel/package-shared/shell/testSQLEscape.ts

86 lines
2.9 KiB
TypeScript
Raw Normal View History

2024-12-06 10:31:24 +00:00
// @ts-check
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
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
* # Test SQL Escape
2024-12-06 10:31:24 +00:00
*/
2025-01-10 19:10:28 +00:00
export default async function testSQLEscape() {
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[];
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;
const defaultMariadbUserHost = process.env.DSQL_DB_HOST || "127.0.0.1";
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(
`DROP USER '${username}'@'${defaultMariadbUserHost}'`
);
await noDatabaseDbHandler(
2024-12-09 11:45:39 +00:00
`CREATE USER IF NOT EXISTS '${username}'@'${defaultMariadbUserHost}' IDENTIFIED BY '${password}'`
2024-12-06 10:31:24 +00:00
);
await noDatabaseDbHandler(
`GRANT ALL PRIVILEGES ON \`datasquirel\\_user\\_${user.id}\\_%\`.* TO '${username}'@'${defaultMariadbUserHost}'`
);
await noDatabaseDbHandler(`FLUSH PRIVILEGES`);
const updateUser = await dbHandler({
query: `UPDATE users SET mariadb_user = ?, mariadb_host = ? mariadb_pass = ? WHERE id = ?`,
values: [
username,
defaultMariadbUserHost,
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);
}
}
process.exit();
}
testSQLEscape();