From a532101d24870d3dd0167a09b01d734b3cbc10df Mon Sep 17 00:00:00 2001 From: ItsNik Date: Fri, 6 Dec 2024 10:03:23 +0100 Subject: [PATCH] No building errors! --- src/controllers/fetchData.ts | 20 +++-- src/controllers/highAvailability.ts | 7 +- src/routes/auth/routes.ts | 113 ++++++++++++-------------- src/routes/data/routes.ts | 8 +- src/routes/highavailability/routes.ts | 4 +- src/routes/notifications/routes.ts | 29 ++++--- src/routes/setter/routes.ts | 111 +++++++++++++++---------- 7 files changed, 158 insertions(+), 134 deletions(-) diff --git a/src/controllers/fetchData.ts b/src/controllers/fetchData.ts index 256cbfc..67b8ec7 100644 --- a/src/controllers/fetchData.ts +++ b/src/controllers/fetchData.ts @@ -1,3 +1,4 @@ +// src/controllers/fetchData.ts import db from "../config/db"; import fetchAllContainers from "../utils/containerService"; import logger from "../utils/logger"; @@ -14,7 +15,7 @@ interface Container { } interface AllContainerData { - [host: object]: Container[]; + [host: string]: Container[] | { error: string }; } const fetchData = async (): Promise => { @@ -41,14 +42,20 @@ const fetchData = async (): Promise => { const containerStatus: AllContainerData = {}; Object.keys(allContainerData).forEach((host) => { - containerStatus[host] = (allContainerData[host] || []).map( - (container: Container) => ({ + const containers = allContainerData[host]; + + // Handle if the containers are an array, otherwise handle the error + if (Array.isArray(containers)) { + containerStatus[host] = containers.map((container: Container) => ({ name: container.name, id: container.id, state: container.state, - host: container.hostName, - }), - ); + hostName: container.hostName, + })); + } else { + // If there's an error, handle it separately + containerStatus[host] = { error: "Error fetching containers" }; + } }); if (fs.existsSync(filePath)) { @@ -56,6 +63,7 @@ const fetchData = async (): Promise => { previousState = fileData ? JSON.parse(fileData) : {}; } + // Compare previous and current state if (JSON.stringify(previousState) !== JSON.stringify(containerStatus)) { fs.writeFileSync(filePath, JSON.stringify(containerStatus, null, 2)); logger.info(`Container states saved to ${filePath}`); diff --git a/src/controllers/highAvailability.ts b/src/controllers/highAvailability.ts index 3e86706..e46a392 100644 --- a/src/controllers/highAvailability.ts +++ b/src/controllers/highAvailability.ts @@ -26,11 +26,12 @@ async function writeConfig(data: HighAvailabilityConfig): Promise { } } -async function readConfig() { +async function readConfig(): Promise { try { logger.debug("Reading HA-Config"); - const data = await fs.promises.readFile(dataPath); - console.log(data); + const data: HighAvailabilityConfig = JSON.parse( + fs.readFileSync(dataPath, "utf-8"), + ); return data; } catch (error: any) { logger.error(`Error reading HA-Config: ${(error as Error).message}`); diff --git a/src/routes/auth/routes.ts b/src/routes/auth/routes.ts index 189e645..1e40a3a 100644 --- a/src/routes/auth/routes.ts +++ b/src/routes/auth/routes.ts @@ -88,39 +88,40 @@ async function setFalse() { * 500: * description: Error saving password. */ -router.post("/enable", async (req: Request, res: Response) => { - const password = req.query.password as string; - if (await authEnabled()) { - logger.error( - "Password Authentication is already enabled, please deactivate it first", - ); - return res.status(401).json({ - message: - "Password Authentication is already enabled, please deactivate it first", - }); - } +router.post("/enable", async (req: Request, res: Response): Promise => { + try { + const password = req.query.password as string; - if (!password) { - logger.error("Password is required"); - return res.status(400).json({ message: "Password is required" }); - } + if (await authEnabled()) { + logger.error( + "Password Authentication is already enabled, please deactivate it first", + ); + res.status(401).json({ + message: + "Password Authentication is already enabled, please deactivate it first", + }); + return; + } - bcrypt.genSalt(saltRounds, (err, salt) => { - if (err) { - logger.error("Error generating salt"); - return res.status(500).json({ message: "Error generating salt" }); + if (!password) { + logger.error("Password is required"); + res.status(400).json({ message: "Password is required" }); + return; } - bcrypt.hash(password, salt, (err, hash) => { - if (err) { - logger.error("Error hashing password"); - return res.status(500).json({ message: "Error hashing password" }); - } + const salt = await bcrypt.genSalt(saltRounds); + const hash = await bcrypt.hash(password, salt); - passwordData = { hash, salt }; - writePasswordFile(JSON.stringify(passwordData)); - }); - }); + const passwordData = { hash, salt }; + writePasswordFile(JSON.stringify(passwordData)); + + res + .status(200) + .json({ message: "Password Authentication enabled successfully" }); + } catch (error) { + logger.error(`Error enabling password authentication: ${error}`); + res.status(500).json({ message: "An error occurred" }); + } }); /** @@ -143,41 +144,31 @@ router.post("/enable", async (req: Request, res: Response) => { * 500: * description: Error disabling authentication. */ -router.post("/disable", async (req: Request, res: Response) => { - const password = req.query.password as string; - if (!password) { - logger.error("Password is required!"); - return res.status(400).json({ message: "Password is required" }); - } +router.post("/disable", async (req: Request, res: Response): Promise => { + try { + const password = req.query.password as string; - await new Promise(async (resolve, reject) => { - try { - const storedData = JSON.parse(await readPasswordFile()); - bcrypt.compare( - password, - storedData.hash, - (compareErr: any, result: boolean) => { - if (compareErr) { - logger.error("Error validating password"); - return res - .status(500) - .json({ message: "Error validating password" }); - } - if (!result) { - logger.error("Invalid password"); - return res.status(401).json({ message: "Invalid password" }); - } - - setFalse(); - res.json({ message: "Authentication disabled" }); - resolve(storedData); - return res.status(200).json({ message: "Authentication enabled" }); - }, - ); - } catch (error: any) { - reject(error); + if (!password) { + logger.error("Password is required!"); + res.status(400).json({ message: "Password is required" }); + return; + } + + const storedData = JSON.parse(await readPasswordFile()); + + const isPasswordValid = await bcrypt.compare(password, storedData.hash); + if (!isPasswordValid) { + logger.error("Invalid password"); + res.status(401).json({ message: "Invalid password" }); + return; } - }); + + await setFalse(); // Assuming this is an async function + res.status(200).json({ message: "Authentication disabled" }); + } catch (error) { + logger.error(`Error disabling authentication: ${error}`); + res.status(500).json({ message: "An error occurred" }); + } }); export default router; diff --git a/src/routes/data/routes.ts b/src/routes/data/routes.ts index 546de08..39d498e 100644 --- a/src/routes/data/routes.ts +++ b/src/routes/data/routes.ts @@ -3,7 +3,11 @@ const router = express.Router(); import db from "../../config/db"; import logger from "../../utils/logger"; -function formatRows(rows: { info: string }[]): Record { +interface DataRow { + info: string; +} + +function formatRows(rows: DataRow[]): Record { return rows.reduce( (acc: Record, row, index: number): Record => { acc[index] = JSON.parse(row.info); @@ -153,7 +157,7 @@ router.get("/time/24h", (req, res) => { db.all( "SELECT info FROM data WHERE timestamp >= ?", [oneDayAgo], - (error, rows) => { + (error, rows: DataRow[]) => { if (error) { logger.error("Error fetching data from last 24 hours:", error.message); return res.status(500).json({ error: "Internal server error" }); diff --git a/src/routes/highavailability/routes.ts b/src/routes/highavailability/routes.ts index ead3bbe..11ace0a 100644 --- a/src/routes/highavailability/routes.ts +++ b/src/routes/highavailability/routes.ts @@ -16,8 +16,8 @@ const router = Router(); */ router.get("/config", async (req: Request, res: Response) => { logger.info("Getting the HA-Config"); - var data = await readConfig(); - res.status(200).json({ data }); + let data = await readConfig(); + res.status(200).json(data); }); export default router; diff --git a/src/routes/notifications/routes.ts b/src/routes/notifications/routes.ts index 0b26278..003454d 100644 --- a/src/routes/notifications/routes.ts +++ b/src/routes/notifications/routes.ts @@ -97,29 +97,28 @@ router.get("/get-template", (req: Request, res: Response) => { * type: string * description: Error message */ -router.post("/set-template", (req: Request, res: Response) => { +router.post("/set-template", (req: Request, res: Response): void => { const newData: TemplateData = req.body; if (!isTemplateData(newData)) { - return res.status(400).json({ + res.status(400).json({ message: "Invalid input format. Expected JSON with a 'text' field.", }); + return; } - fs.writeFile( - dataTemplate, - JSON.stringify(newData, null, 2), - "utf-8", - (error) => { - if (error) { - logger.error("Errored writing to file:", error); - return res - .status(500) - .json({ message: `Error writing to file: ${error}` }); - } + fs.promises + .writeFile(dataTemplate, JSON.stringify(newData, null, 2), "utf-8") + .then(() => { + logger.info("Template updated successfully."); res.json({ message: "Template updated successfully." }); - }, - ); + }) + .catch((error) => { + logger.error("Error writing to file: " + error.message); + res + .status(500) + .json({ message: `Error writing to file: ${error.message}` }); + }); }); /** diff --git a/src/routes/setter/routes.ts b/src/routes/setter/routes.ts index 8483601..e027992 100644 --- a/src/routes/setter/routes.ts +++ b/src/routes/setter/routes.ts @@ -43,34 +43,46 @@ interface DockerConfig { * 500: * description: An error occurred while adding the host. */ -router.put("/addHost", async (req: Request, res: Response) => { - const name = req.query.name as string; - const url = req.query.url as string; - const port = req.query.port as string; - if (!name || !url || !port) { - return res.status(400).json({ error: "Name, Port, and URL are required." }); - } - - try { - const config: DockerConfig = JSON.parse( - fs.readFileSync(configPath, "utf-8"), - ); - - if (config.hosts.some((host) => host.name === name)) { - return res.status(400).json({ error: "Host already exists." }); +router.put( + "/addHost", + async ( + req: Request< + unknown, + unknown, + unknown, + { name: string; url: string; port: string } + >, + res: Response, + ): Promise => { + const { name, url, port } = req.query; + + if (!name || !url || !port) { + res.status(400).json({ error: "Name, Port, and URL are required." }); + return; } - config.hosts.push({ name, url, port }); - fs.writeFileSync(configPath, JSON.stringify(config, null, 2)); - logger.info(`Added new host: ${name}`); - res.status(200).json({ message: "Host added successfully." }); - } catch (error: unknown) { - const err = error as Error; - logger.error("Error adding host: " + err.message); - res.status(500).json({ error: "Failed to add host." }); - } -}); + try { + const config: DockerConfig = JSON.parse( + fs.readFileSync(configPath, "utf-8"), + ); + + if (config.hosts.some((host) => host.name === name)) { + res.status(400).json({ error: "Host already exists." }); + return; + } + + config.hosts.push({ name, url, port }); + fs.writeFileSync(configPath, JSON.stringify(config, null, 2)); + logger.info(`Added new host: ${name}`); + res.status(200).json({ message: "Host added successfully." }); + } catch (error: unknown) { + const err = error as Error; + logger.error("Error adding host: " + err.message); + res.status(500).json({ error: "Failed to add host." }); + } + }, +); /** * @swagger @@ -129,31 +141,40 @@ router.put("/scheduler", (req: any, res: any) => { * 500: * description: An error occurred while removing the host. */ -router.delete("/removeHost", async (req: Request, res: Response) => { +router.delete("/removeHost", (req: Request, res: Response): void => { const hostName = req.query.hostName as string; if (!hostName) { - return res.status(400).json({ error: "Host name is required." }); + res.status(400).json({ error: "Host name is required." }); + return; } - try { - const rawData = fs.readFileSync(configPath, "utf-8"); - const config: DockerConfig = JSON.parse(rawData); - - const hostIndex = config.hosts.findIndex((host) => host.name === hostName); - if (hostIndex === -1) { - return res.status(404).json({ error: "Host not found." }); - } - - config.hosts.splice(hostIndex, 1); - fs.writeFileSync(configPath, JSON.stringify(config, null, 2)); - logger.info(`Removed host: ${hostName}`); - res.status(200).json({ message: "Host removed successfully." }); - } catch (error: unknown) { - const err = error as Error; - logger.error("Error removing host: " + err.message); - res.status(500).json({ error: "Failed to remove host." }); - } + fs.promises + .readFile(configPath, "utf-8") + .then((rawData) => { + const config: DockerConfig = JSON.parse(rawData); + const hostIndex = config.hosts.findIndex( + (host) => host.name === hostName, + ); + + if (hostIndex === -1) { + res.status(404).json({ error: "Host not found." }); + return; + } + + config.hosts.splice(hostIndex, 1); + + return fs.promises + .writeFile(configPath, JSON.stringify(config, null, 2)) + .then(() => { + logger.info(`Removed host: ${hostName}`); + res.status(200).json({ message: "Host removed successfully." }); + }); + }) + .catch((error) => { + logger.error("Error removing host: " + (error as Error).message); + res.status(500).json({ error: "Failed to remove host." }); + }); }); export default router;