Skip to content

Commit

Permalink
No building errors!
Browse files Browse the repository at this point in the history
  • Loading branch information
Its4Nik committed Dec 6, 2024
1 parent 3f35671 commit a532101
Show file tree
Hide file tree
Showing 7 changed files with 158 additions and 134 deletions.
20 changes: 14 additions & 6 deletions src/controllers/fetchData.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
// src/controllers/fetchData.ts
import db from "../config/db";
import fetchAllContainers from "../utils/containerService";
import logger from "../utils/logger";
Expand All @@ -14,7 +15,7 @@ interface Container {
}

interface AllContainerData {
[host: object]: Container[];
[host: string]: Container[] | { error: string };
}

const fetchData = async (): Promise<void> => {
Expand All @@ -41,21 +42,28 @@ const fetchData = async (): Promise<void> => {
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)) {
const fileData = fs.readFileSync(filePath, "utf8");
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}`);
Expand Down
7 changes: 4 additions & 3 deletions src/controllers/highAvailability.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,11 +26,12 @@ async function writeConfig(data: HighAvailabilityConfig): Promise<void> {
}
}

async function readConfig() {
async function readConfig(): Promise<HighAvailabilityConfig | null> {
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}`);
Expand Down
113 changes: 52 additions & 61 deletions src/routes/auth/routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<void> => {
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" });
}
});

/**
Expand All @@ -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<void> => {
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;
8 changes: 6 additions & 2 deletions src/routes/data/routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,11 @@ const router = express.Router();
import db from "../../config/db";
import logger from "../../utils/logger";

function formatRows(rows: { info: string }[]): Record<number, any> {
interface DataRow {
info: string;
}

function formatRows(rows: DataRow[]): Record<number, any> {
return rows.reduce(
(acc: Record<number, any>, row, index: number): Record<number, any> => {
acc[index] = JSON.parse(row.info);
Expand Down Expand Up @@ -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" });
Expand Down
4 changes: 2 additions & 2 deletions src/routes/highavailability/routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
29 changes: 14 additions & 15 deletions src/routes/notifications/routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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}` });
});
});

/**
Expand Down
Loading

0 comments on commit a532101

Please sign in to comment.