dsql-admin/dsql-app/shell/updateSSLUsers.js
2024-11-05 12:12:42 +01:00

97 lines
2.9 KiB
JavaScript
Executable File

// @ts-check
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
require("dotenv").config({ path: "./../.env" });
const fs = require("fs");
const path = require("path");
// const mysql = require("mysql");
// const connection = mysql.createConnection({
// host: process.env.DSQL_DB_HOST,
// user: process.env.DSQL_DB_USERNAME,
// password: process.env.DSQL_DB_PASSWORD,
// database: process.env.DSQL_DB_NAME,
// charset: "utf8mb4",
// });
const mysql = require("serverless-mysql");
const SSL_DIR = "/app/ssl";
const connection = mysql({
config: {
host: process.env.DSQL_DB_HOST,
user: process.env.DSQL_DB_USERNAME,
password: process.env.DSQL_DB_PASSWORD,
database: process.env.DSQL_DB_NAME,
charset: "utf8mb4",
ssl: {
ca: fs.readFileSync(`${SSL_DIR}/ca-cert.pem`),
},
},
});
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
/**
* # Main DB Handler Function
* @async
*
* @param {object} params
* @param {string} params.query
* @param {string[] | object} [params.values]
* @param {string} [params.database]
*
* @returns {Promise<object|null>}
*/
(async () => {
/**
* Switch Database
*
* @description If a database is provided, switch to it
*/
try {
const result = await connection.query(
"SELECT user,host,ssl_type FROM mysql.user"
);
const parsedResults = JSON.parse(JSON.stringify(result));
for (let i = 0; i < parsedResults.length; i++) {
const user = parsedResults[i];
if (
user.User !== process.env.DSQL_DB_READ_ONLY_USERNAME ||
user.User !== process.env.DSQL_DB_FULL_ACCESS_USERNAME ||
!user.User?.match(/dsql_user_.*/i)
) {
continue;
}
const { User, Host, ssl_type } = user;
if (ssl_type === "ANY") {
continue;
}
const addUserSSL = await connection.query(
`ALTER USER '${User}'@'${Host}' REQUIRE SSL`
);
console.log(`addUserSSL => ${User}@${Host}`, addUserSSL);
}
} catch (/** @type {any} */ error) {
console.log("Connection query ERROR =>", error.message);
} finally {
connection.end();
process.exit();
}
})();