Merge pull request #1075 from bluewave-labs/fix/be/refactor-auth-controller

Fix/be/refactor auth controller
This commit is contained in:
Alexander Holliday authored and GitHub committed 2024-10-26 09:39:21 +08:00
commit d8480b2548
7 files changed
+46 -75

No files matched your search

@@ -95,6 +95,7 @@ const DetailsPage = ({ isAdmin }) => {
setCertificateExpiry(formatDateWithTz(date, dateFormat, uiTimezone) ?? "N/A"); setCertificateExpiry(formatDateWithTz(date, dateFormat, uiTimezone) ?? "N/A");
} }
} catch (error) { } catch (error) {
setCertificateExpiry("N/A");
console.error(error); console.error(error);
} }
}; };
+4
View File
@@ -17,6 +17,10 @@ const fetchMonitorCertificate = async (sslChecker, monitor) => {
const monitorUrl = new URL(monitor.url); const monitorUrl = new URL(monitor.url);
const hostname = monitorUrl.hostname; const hostname = monitorUrl.hostname;
const cert = await sslChecker(hostname); const cert = await sslChecker(hostname);
// Throw an error if no cert or if cert.validTo is not present
if (cert?.validTo === null || cert?.validTo === undefined) {
throw new Error("Certificate not found");
}
return cert; return cert;
} catch (error) { } catch (error) {
throw error; throw error;
+20 -35
View File
@@ -86,21 +86,14 @@ const getMonitorCertificate = async (req, res, next, fetchMonitorCertificate) =>
const { monitorId } = req.params; const { monitorId } = req.params;
const monitor = await req.db.getMonitorById(monitorId); const monitor = await req.db.getMonitorById(monitorId);
const certificate = await fetchMonitorCertificate(sslChecker, monitor); const certificate = await fetchMonitorCertificate(sslChecker, monitor);
if (certificate && certificate.validTo) {
return res.status(200).json({ return res.status(200).json({
success: true, success: true,
msg: successMessages.MONITOR_CERTIFICATE, msg: successMessages.MONITOR_CERTIFICATE,
data: { data: {
certificateDate: new Date(certificate.validTo), certificateDate: new Date(certificate.validTo),
}, },
}); });
} else {
return res.status(200).json({
success: true,
msg: successMessages.MONITOR_CERTIFICATE,
data: { certificateDate: "N/A" },
});
}
} catch (error) { } catch (error) {
next(handleError(error, SERVICE_NAME, "getMonitorCertificate")); next(handleError(error, SERVICE_NAME, "getMonitorCertificate"));
} }
@@ -128,12 +121,6 @@ const getMonitorById = async (req, res, next) => {
try { try {
const monitor = await req.db.getMonitorById(req.params.monitorId); const monitor = await req.db.getMonitorById(req.params.monitorId);
if (!monitor) {
const error = new Error(errorMessages.MONITOR_GET_BY_ID);
error.status = 404;
throw error;
}
return res.status(200).json({ return res.status(200).json({
success: true, success: true,
msg: successMessages.MONITOR_GET_BY_ID, msg: successMessages.MONITOR_GET_BY_ID,
@@ -238,15 +225,15 @@ const createMonitor = async (req, res, next) => {
const notifications = req.body.notifications; const notifications = req.body.notifications;
const monitor = await req.db.createMonitor(req, res); const monitor = await req.db.createMonitor(req, res);
if (notifications && notifications.length !== 0) { monitor.notifications =
monitor.notifications = await Promise.all( notifications &&
(await Promise.all(
notifications.map(async (notification) => { notifications.map(async (notification) => {
notification.monitorId = monitor._id; notification.monitorId = monitor._id;
await req.db.createNotification(notification); await req.db.createNotification(notification);
}) })
); ));
await monitor.save(); await monitor.save();
}
// Add monitor to job queue // Add monitor to job queue
req.jobQueue.addJob(monitor._id, monitor); req.jobQueue.addJob(monitor._id, monitor);
return res.status(201).json({ return res.status(201).json({
@@ -413,14 +400,13 @@ const editMonitor = async (req, res, next) => {
await req.db.deleteNotificationsByMonitorId(editedMonitor._id); await req.db.deleteNotificationsByMonitorId(editedMonitor._id);
if (notifications && notifications.length !== 0) { await Promise.all(
await Promise.all( notifications &&
notifications.map(async (notification) => { notifications.map(async (notification) => {
notification.monitorId = editedMonitor._id; notification.monitorId = editedMonitor._id;
await req.db.createNotification(notification); await req.db.createNotification(notification);
}) })
); );
}
// Delete the old job(editedMonitor has the same ID as the old monitor) // Delete the old job(editedMonitor has the same ID as the old monitor)
await req.jobQueue.deleteJob(monitorBeforeEdit); await req.jobQueue.deleteJob(monitorBeforeEdit);
@@ -456,11 +442,10 @@ const pauseMonitor = async (req, res, next) => {
try { try {
const monitor = await req.db.getMonitorById(req.params.monitorId); const monitor = await req.db.getMonitorById(req.params.monitorId);
if (monitor.isActive) { monitor.isActive === true
await req.jobQueue.deleteJob(monitor); ? await req.jobQueue.deleteJob(monitor)
} else { : await req.jobQueue.addJob(monitor._id, monitor);
await req.jobQueue.addJob(monitor._id, monitor);
}
monitor.isActive = !monitor.isActive; monitor.isActive = !monitor.isActive;
monitor.status = undefined; monitor.status = undefined;
monitor.save(); monitor.save();
+3 -1
View File
@@ -288,7 +288,9 @@ const getMonitorById = async (monitorId) => {
try { try {
const monitor = await Monitor.findById(monitorId); const monitor = await Monitor.findById(monitorId);
if (monitor === null || monitor === undefined) { if (monitor === null || monitor === undefined) {
throw new Error(errorMessages.DB_FIND_MONITOR_BY_ID(monitorId)); const error = new Error(errorMessages.DB_FIND_MONITOR_BY_ID(monitorId));
error.status = 404;
throw error;
} }
// Get notifications // Get notifications
const notifications = await Notification.find({ const notifications = await Notification.find({
@@ -148,4 +148,11 @@ describe("controllerUtils - fetchMonitorCertificate", () => {
const result = await fetchMonitorCertificate(sslChecker, monitor); const result = await fetchMonitorCertificate(sslChecker, monitor);
expect(result).to.deep.equal({ validTo: "2022-01-01" }); expect(result).to.deep.equal({ validTo: "2022-01-01" });
}); });
it("should throw an error if a ssl-checker returns null", async () => {
sslChecker.returns(null);
await fetchMonitorCertificate(sslChecker, monitor).catch((error) => {
expect(error).to.be.an("error");
expect(error.message).to.equal("Certificate not found");
});
});
}); });
@@ -169,19 +169,6 @@ describe("Monitor Controller - getMonitorCertificate", () => {
}) })
).to.be.true; ).to.be.true;
}); });
it("should return success message and data if all operations succeed with an invalid cert", async () => {
req.db.getMonitorById.returns({ url: "https://www.google.com" });
fetchMonitorCertificate.returns({});
await getMonitorCertificate(req, res, next, fetchMonitorCertificate);
expect(res.status.firstCall.args[0]).to.equal(200);
expect(
res.json.calledOnceWith({
success: true,
msg: successMessages.MONITOR_CERTIFICATE,
data: { certificateDate: "N/A" },
})
).to.be.true;
});
it("should return an error if fetchMonitorCertificate fails", async () => { it("should return an error if fetchMonitorCertificate fails", async () => {
req.db.getMonitorById.returns({ url: "https://www.google.com" }); req.db.getMonitorById.returns({ url: "https://www.google.com" });
fetchMonitorCertificate.throws(new Error("Certificate error")); fetchMonitorCertificate.throws(new Error("Certificate error"));
@@ -232,7 +219,9 @@ describe("Monitor Controller - getMonitorById", () => {
expect(next.firstCall.args[0].message).to.equal("DB error"); expect(next.firstCall.args[0].message).to.equal("DB error");
}); });
it("should return 404 if a monitor is not found", async () => { it("should return 404 if a monitor is not found", async () => {
req.db.getMonitorById.returns(null); const error = new Error("Monitor not found");
error.status = 404;
req.db.getMonitorById.throws(error);
await getMonitorById(req, res, next); await getMonitorById(req, res, next);
expect(next.firstCall.args[0]).to.be.an("error"); expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].status).to.equal(404); expect(next.firstCall.args[0].status).to.equal(404);
@@ -430,19 +419,11 @@ describe("Monitor Controller - createMonitor", () => {
expect(next.firstCall.args[0]).to.be.an("error"); expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].message).to.equal("Job error"); expect(next.firstCall.args[0].message).to.equal("Job error");
}); });
it("should return success message and data if all operations succeed with empty notifications", async () => { it("should fail validation with empty notifications", async () => {
req.body.notifications = []; req.body.notifications = [];
const monitor = { _id: "123", save: sinon.stub() };
req.db.createMonitor.returns(monitor);
await createMonitor(req, res, next); await createMonitor(req, res, next);
expect(res.status.firstCall.args[0]).to.equal(201); expect(next.firstCall.args[0]).to.be.an("error");
expect( expect(next.firstCall.args[0].status).to.equal(422);
res.json.calledOnceWith({
success: true,
msg: successMessages.MONITOR_CREATE,
data: monitor,
})
).to.be.true;
}); });
it("should return success message and data if all operations succeed", async () => { it("should return success message and data if all operations succeed", async () => {
const monitor = { _id: "123", save: sinon.stub() }; const monitor = { _id: "123", save: sinon.stub() };
@@ -809,20 +790,11 @@ describe("Monitor Controller - editMonitor", () => {
expect(next.firstCall.args[0]).to.be.an("error"); expect(next.firstCall.args[0]).to.be.an("error");
expect(next.firstCall.args[0].message).to.equal("Add Job error"); expect(next.firstCall.args[0].message).to.equal("Add Job error");
}); });
it("should return success message with data if all operations succeed and empty notifications", async () => { it("should fail validation with empty notifications", async () => {
req.body.notifications = []; req.body.notifications = [];
const monitor = { _id: "123" };
req.db.getMonitorById.returns({ teamId: "123" });
req.db.editMonitor.returns(monitor);
await editMonitor(req, res, next); await editMonitor(req, res, next);
expect(res.status.firstCall.args[0]).to.equal(200); expect(next.firstCall.args[0]).to.be.an("error");
expect( expect(next.firstCall.args[0].status).to.equal(422);
res.json.calledOnceWith({
success: true,
msg: successMessages.MONITOR_EDIT,
data: monitor,
})
).to.be.true;
}); });
it("should return success message with data if all operations succeed", async () => { it("should return success message with data if all operations succeed", async () => {
const monitor = { _id: "123" }; const monitor = { _id: "123" };
+2 -2
View File
@@ -227,14 +227,14 @@ const createMonitorBodyValidation = joi.object({
usage_memory: joi.number(), usage_memory: joi.number(),
usage_disk: joi.number(), usage_disk: joi.number(),
}), }),
notifications: joi.array().items(joi.object()), notifications: joi.array().items(joi.object()).min(1),
}); });
const editMonitorBodyValidation = joi.object({ const editMonitorBodyValidation = joi.object({
name: joi.string(), name: joi.string(),
description: joi.string(), description: joi.string(),
interval: joi.number(), interval: joi.number(),
notifications: joi.array().items(joi.object()), notifications: joi.array().items(joi.object()).min(1),
}); });
const pauseMonitorParamValidation = joi.object({ const pauseMonitorParamValidation = joi.object({