Merge pull request #1470 from bluewave-labs/feat/be/migrate-to-class

feat: be/migrate to class
This commit is contained in:
Alexander Holliday authored and GitHub committed 2024-12-27 09:54:20 -08:00
commit 955d3c6298
28 files changed
+767 -645

No files matched your search

+67 -66
View File
@@ -17,6 +17,14 @@ import { handleValidationError, handleError } from "./controllerUtils.js";
const SERVICE_NAME = "authController"; const SERVICE_NAME = "authController";
dotenv.config(); dotenv.config();
class AuthController {
constructor(db, settingsService, emailService, jobQueue) {
this.db = db;
this.settingsService = settingsService;
this.emailService = emailService;
this.jobQueue = jobQueue;
}
/** /**
* Creates and returns JWT token with an arbitrary payload * Creates and returns JWT token with an arbitrary payload
* @function * @function
@@ -26,7 +34,7 @@ dotenv.config();
* @returns {String} * @returns {String}
* @throws {Error} * @throws {Error}
*/ */
const issueToken = (payload, typeOfToken, appSettings) => { issueToken = (payload, typeOfToken, appSettings) => {
try { try {
const tokenTTL = const tokenTTL =
typeOfToken === tokenType.REFRESH_TOKEN typeOfToken === tokenType.REFRESH_TOKEN
@@ -56,8 +64,7 @@ const issueToken = (payload, typeOfToken, appSettings) => {
* @returns {Object} The response object with a success status, a message indicating the creation of the user, the created user data, and a JWT token. * @returns {Object} The response object with a success status, a message indicating the creation of the user, the created user data, and a JWT token.
* @throws {Error} If there is an error during the process, especially if there is a validation error (422). * @throws {Error} If there is an error during the process, especially if there is a validation error (422).
*/ */
const registerUser = async (req, res, next) => { registerUser = async (req, res, next) => {
// joi validation
try { try {
await registrationBodyValidation.validateAsync(req.body); await registrationBodyValidation.validateAsync(req.body);
} catch (error) { } catch (error) {
@@ -69,16 +76,16 @@ const registerUser = async (req, res, next) => {
try { try {
const { inviteToken } = req.body; const { inviteToken } = req.body;
// If superAdmin exists, a token should be attached to all further register requests // If superAdmin exists, a token should be attached to all further register requests
const superAdminExists = await req.db.checkSuperadmin(req, res); const superAdminExists = await this.db.checkSuperadmin(req, res);
if (superAdminExists) { if (superAdminExists) {
await req.db.getInviteTokenAndDelete(inviteToken); await this.db.getInviteTokenAndDelete(inviteToken);
} else { } else {
// This is the first account, create JWT secret to use if one is not supplied by env // This is the first account, create JWT secret to use if one is not supplied by env
const jwtSecret = crypto.randomBytes(64).toString("hex"); const jwtSecret = crypto.randomBytes(64).toString("hex");
await req.db.updateAppSettings({ jwtSecret }); await this.db.updateAppSettings({ jwtSecret });
} }
const newUser = await req.db.insertUser({ ...req.body }, req.file); const newUser = await this.db.insertUser({ ...req.body }, req.file);
logger.info({ logger.info({
message: successMessages.AUTH_CREATE_USER, message: successMessages.AUTH_CREATE_USER,
service: SERVICE_NAME, service: SERVICE_NAME,
@@ -89,12 +96,12 @@ const registerUser = async (req, res, next) => {
delete userForToken.profileImage; delete userForToken.profileImage;
delete userForToken.avatarImage; delete userForToken.avatarImage;
const appSettings = await req.settingsService.getSettings(); const appSettings = await this.settingsService.getSettings();
const token = issueToken(userForToken, tokenType.ACCESS_TOKEN, appSettings); const token = this.issueToken(userForToken, tokenType.ACCESS_TOKEN, appSettings);
const refreshToken = issueToken({}, tokenType.REFRESH_TOKEN, appSettings); const refreshToken = this.issueToken({}, tokenType.REFRESH_TOKEN, appSettings);
req.emailService this.emailService
.buildAndSendEmail( .buildAndSendEmail(
"welcomeEmailTemplate", "welcomeEmailTemplate",
{ name: newUser.firstName }, { name: newUser.firstName },
@@ -132,7 +139,7 @@ const registerUser = async (req, res, next) => {
* @returns {Object} The response object with a success status, a message indicating the login of the user, the user data (without password and avatar image), and a JWT token. * @returns {Object} The response object with a success status, a message indicating the login of the user, the user data (without password and avatar image), and a JWT token.
* @throws {Error} If there is an error during the process, especially if there is a validation error (422) or the password is incorrect. * @throws {Error} If there is an error during the process, especially if there is a validation error (422) or the password is incorrect.
*/ */
const loginUser = async (req, res, next) => { loginUser = async (req, res, next) => {
try { try {
await loginValidation.validateAsync(req.body); await loginValidation.validateAsync(req.body);
} catch (error) { } catch (error) {
@@ -144,7 +151,7 @@ const loginUser = async (req, res, next) => {
const { email, password } = req.body; const { email, password } = req.body;
// Check if user exists // Check if user exists
const user = await req.db.getUserByEmail(email); const user = await this.db.getUserByEmail(email);
// Compare password // Compare password
const match = await user.comparePassword(password); const match = await user.comparePassword(password);
@@ -159,9 +166,13 @@ const loginUser = async (req, res, next) => {
delete userWithoutPassword.avatarImage; delete userWithoutPassword.avatarImage;
// Happy path, return token // Happy path, return token
const appSettings = await req.settingsService.getSettings(); const appSettings = await this.settingsService.getSettings();
const token = issueToken(userWithoutPassword, tokenType.ACCESS_TOKEN, appSettings); const token = this.issueToken(
const refreshToken = issueToken({}, tokenType.REFRESH_TOKEN, appSettings); userWithoutPassword,
tokenType.ACCESS_TOKEN,
appSettings
);
const refreshToken = this.issueToken({}, tokenType.REFRESH_TOKEN, appSettings);
// reset avatar image // reset avatar image
userWithoutPassword.avatarImage = user.avatarImage; userWithoutPassword.avatarImage = user.avatarImage;
@@ -185,7 +196,7 @@ const loginUser = async (req, res, next) => {
* @returns {Object} The response object with a success status, a message indicating new auth token is generated. * @returns {Object} The response object with a success status, a message indicating new auth token is generated.
* @throws {Error} If there is an error during the process such as any of the token is not received * @throws {Error} If there is an error during the process such as any of the token is not received
*/ */
const refreshAuthToken = async (req, res, next) => { refreshAuthToken = async (req, res, next) => {
try { try {
// check for refreshToken // check for refreshToken
const refreshToken = req.headers["x-refresh-token"]; const refreshToken = req.headers["x-refresh-token"];
@@ -200,7 +211,7 @@ const refreshAuthToken = async (req, res, next) => {
} }
// Verify refresh token // Verify refresh token
const appSettings = await req.settingsService.getSettings(); const appSettings = await this.settingsService.getSettings();
const { refreshTokenSecret } = appSettings; const { refreshTokenSecret } = appSettings;
jwt.verify(refreshToken, refreshTokenSecret, async (refreshErr, refreshDecoded) => { jwt.verify(refreshToken, refreshTokenSecret, async (refreshErr, refreshDecoded) => {
if (refreshErr) { if (refreshErr) {
@@ -217,12 +228,16 @@ const refreshAuthToken = async (req, res, next) => {
}); });
// Refresh token is valid and unexpired, generate new access token // Refresh token is valid and unexpired, generate new access token
const oldAuthToken = getTokenFromHeaders(req.headers); const oldAuthToken = getTokenFromHeaders(req.headers);
const { jwtSecret } = await req.settingsService.getSettings(); const { jwtSecret } = await this.settingsService.getSettings();
const payloadData = jwt.verify(oldAuthToken, jwtSecret, { ignoreExpiration: true }); const payloadData = jwt.verify(oldAuthToken, jwtSecret, { ignoreExpiration: true });
// delete old token related data // delete old token related data
delete payloadData.iat; delete payloadData.iat;
delete payloadData.exp; delete payloadData.exp;
const newAuthToken = issueToken(payloadData, tokenType.ACCESS_TOKEN, appSettings); const newAuthToken = this.issueToken(
payloadData,
tokenType.ACCESS_TOKEN,
appSettings
);
return res.status(200).json({ return res.status(200).json({
success: true, success: true,
@@ -233,7 +248,6 @@ const refreshAuthToken = async (req, res, next) => {
next(handleError(error, SERVICE_NAME, "refreshAuthToken")); next(handleError(error, SERVICE_NAME, "refreshAuthToken"));
} }
}; };
/** /**
* Edits a user's information. If the user wants to change their password, the current password is checked before updating to the new password. * Edits a user's information. If the user wants to change their password, the current password is checked before updating to the new password.
* @async * @async
@@ -248,7 +262,7 @@ const refreshAuthToken = async (req, res, next) => {
* @returns {Object} The response object with a success status, a message indicating the update of the user, and the updated user data. * @returns {Object} The response object with a success status, a message indicating the update of the user, and the updated user data.
* @throws {Error} If there is an error during the process, especially if there is a validation error (422), the user is unauthorized (401), or the password is incorrect (403). * @throws {Error} If there is an error during the process, especially if there is a validation error (422), the user is unauthorized (401), or the password is incorrect (403).
*/ */
const editUser = async (req, res, next) => { editUser = async (req, res, next) => {
try { try {
await editUserParamValidation.validateAsync(req.params); await editUserParamValidation.validateAsync(req.params);
await editUserBodyValidation.validateAsync(req.body); await editUserBodyValidation.validateAsync(req.body);
@@ -273,12 +287,12 @@ const editUser = async (req, res, next) => {
// Get token from headers // Get token from headers
const token = getTokenFromHeaders(req.headers); const token = getTokenFromHeaders(req.headers);
// Get email from token // Get email from token
const { jwtSecret } = req.settingsService.getSettings(); const { jwtSecret } = this.settingsService.getSettings();
const { email } = jwt.verify(token, jwtSecret); const { email } = jwt.verify(token, jwtSecret);
// Add user email to body for DB operation // Add user email to body for DB operation
req.body.email = email; req.body.email = email;
// Get user // Get user
const user = await req.db.getUserByEmail(email); const user = await this.db.getUserByEmail(email);
// Compare passwords // Compare passwords
const match = await user.comparePassword(req.body.password); const match = await user.comparePassword(req.body.password);
// If not a match, throw a 403 // If not a match, throw a 403
@@ -293,7 +307,7 @@ const editUser = async (req, res, next) => {
req.body.password = req.body.newPassword; req.body.password = req.body.newPassword;
} }
const updatedUser = await req.db.updateUser(req, res); const updatedUser = await this.db.updateUser(req, res);
return res.status(200).json({ return res.status(200).json({
success: true, success: true,
msg: successMessages.AUTH_UPDATE_USER, msg: successMessages.AUTH_UPDATE_USER,
@@ -313,9 +327,9 @@ const editUser = async (req, res, next) => {
* @returns {Object} The response object with a success status, a message indicating the existence of a superadmin, and a boolean indicating the existence of a superadmin. * @returns {Object} The response object with a success status, a message indicating the existence of a superadmin, and a boolean indicating the existence of a superadmin.
* @throws {Error} If there is an error during the process. * @throws {Error} If there is an error during the process.
*/ */
const checkSuperadminExists = async (req, res, next) => { checkSuperadminExists = async (req, res, next) => {
try { try {
const superAdminExists = await req.db.checkSuperadmin(req, res); const superAdminExists = await this.db.checkSuperadmin(req, res);
return res.status(200).json({ return res.status(200).json({
success: true, success: true,
msg: successMessages.AUTH_ADMIN_EXISTS, msg: successMessages.AUTH_ADMIN_EXISTS,
@@ -325,7 +339,6 @@ const checkSuperadminExists = async (req, res, next) => {
next(handleError(error, SERVICE_NAME, "checkSuperadminController")); next(handleError(error, SERVICE_NAME, "checkSuperadminController"));
} }
}; };
/** /**
* Requests a recovery token for a user. The user's email is validated and a recovery token is created and sent via email. * Requests a recovery token for a user. The user's email is validated and a recovery token is created and sent via email.
* @async * @async
@@ -337,7 +350,7 @@ const checkSuperadminExists = async (req, res, next) => {
* @returns {Object} The response object with a success status, a message indicating the creation of the recovery token, and the message ID of the sent email. * @returns {Object} The response object with a success status, a message indicating the creation of the recovery token, and the message ID of the sent email.
* @throws {Error} If there is an error during the process, especially if there is a validation error (422). * @throws {Error} If there is an error during the process, especially if there is a validation error (422).
*/ */
const requestRecovery = async (req, res, next) => { requestRecovery = async (req, res, next) => {
try { try {
await recoveryValidation.validateAsync(req.body); await recoveryValidation.validateAsync(req.body);
} catch (error) { } catch (error) {
@@ -348,12 +361,12 @@ const requestRecovery = async (req, res, next) => {
try { try {
const { email } = req.body; const { email } = req.body;
const user = await req.db.getUserByEmail(email); const user = await this.db.getUserByEmail(email);
const recoveryToken = await req.db.requestRecoveryToken(req, res); const recoveryToken = await this.db.requestRecoveryToken(req, res);
const name = user.firstName; const name = user.firstName;
const { clientHost } = req.settingsService.getSettings(); const { clientHost } = this.settingsService.getSettings();
const url = `${clientHost}/set-new-password/${recoveryToken.token}`; const url = `${clientHost}/set-new-password/${recoveryToken.token}`;
const msgId = await req.emailService.buildAndSendEmail( const msgId = await this.emailService.buildAndSendEmail(
"passwordResetTemplate", "passwordResetTemplate",
{ {
name, name,
@@ -373,7 +386,6 @@ const requestRecovery = async (req, res, next) => {
next(handleError(error, SERVICE_NAME, "recoveryRequestController")); next(handleError(error, SERVICE_NAME, "recoveryRequestController"));
} }
}; };
/** /**
* Validates a recovery token. The recovery token is validated and if valid, a success message is returned. * Validates a recovery token. The recovery token is validated and if valid, a success message is returned.
* @async * @async
@@ -385,7 +397,7 @@ const requestRecovery = async (req, res, next) => {
* @returns {Object} The response object with a success status and a message indicating the validation of the recovery token. * @returns {Object} The response object with a success status and a message indicating the validation of the recovery token.
* @throws {Error} If there is an error during the process, especially if there is a validation error (422). * @throws {Error} If there is an error during the process, especially if there is a validation error (422).
*/ */
const validateRecovery = async (req, res, next) => { validateRecovery = async (req, res, next) => {
try { try {
await recoveryTokenValidation.validateAsync(req.body); await recoveryTokenValidation.validateAsync(req.body);
} catch (error) { } catch (error) {
@@ -395,7 +407,7 @@ const validateRecovery = async (req, res, next) => {
} }
try { try {
await req.db.validateRecoveryToken(req, res); await this.db.validateRecoveryToken(req, res);
return res.status(200).json({ return res.status(200).json({
success: true, success: true,
msg: successMessages.AUTH_VERIFY_RECOVERY_TOKEN, msg: successMessages.AUTH_VERIFY_RECOVERY_TOKEN,
@@ -417,7 +429,7 @@ const validateRecovery = async (req, res, next) => {
* @returns {Object} The response object with a success status, a message indicating the reset of the password, the updated user data (without password and avatar image), and a new JWT token. * @returns {Object} The response object with a success status, a message indicating the reset of the password, the updated user data (without password and avatar image), and a new JWT token.
* @throws {Error} If there is an error during the process, especially if there is a validation error (422). * @throws {Error} If there is an error during the process, especially if there is a validation error (422).
*/ */
const resetPassword = async (req, res, next) => { resetPassword = async (req, res, next) => {
try { try {
await newPasswordValidation.validateAsync(req.body); await newPasswordValidation.validateAsync(req.body);
} catch (error) { } catch (error) {
@@ -426,9 +438,9 @@ const resetPassword = async (req, res, next) => {
return; return;
} }
try { try {
const user = await req.db.resetPassword(req, res); const user = await this.db.resetPassword(req, res);
const appSettings = await req.settingsService.getSettings(); const appSettings = await this.settingsService.getSettings();
const token = issueToken(user._doc, tokenType.ACCESS_TOKEN, appSettings); const token = this.issueToken(user._doc, tokenType.ACCESS_TOKEN, appSettings);
res.status(200).json({ res.status(200).json({
success: true, success: true,
msg: successMessages.AUTH_RESET_PASSWORD, msg: successMessages.AUTH_RESET_PASSWORD,
@@ -448,17 +460,17 @@ const resetPassword = async (req, res, next) => {
* @returns {Object} The response object with success status and message. * @returns {Object} The response object with success status and message.
* @throws {Error} If user validation fails or user is not found in the database. * @throws {Error} If user validation fails or user is not found in the database.
*/ */
const deleteUser = async (req, res, next) => { deleteUser = async (req, res, next) => {
try { try {
const token = getTokenFromHeaders(req.headers); const token = getTokenFromHeaders(req.headers);
const decodedToken = jwt.decode(token); const decodedToken = jwt.decode(token);
const { email } = decodedToken; const { email } = decodedToken;
// Check if the user exists // Check if the user exists
const user = await req.db.getUserByEmail(email); const user = await this.db.getUserByEmail(email);
// 1. Find all the monitors associated with the team ID if superadmin // 1. Find all the monitors associated with the team ID if superadmin
const result = await req.db.getMonitorsByTeamId({ const result = await this.db.getMonitorsByTeamId({
params: { teamId: user.teamId }, params: { teamId: user.teamId },
}); });
@@ -467,22 +479,22 @@ const deleteUser = async (req, res, next) => {
result?.monitors.length > 0 && result?.monitors.length > 0 &&
(await Promise.all( (await Promise.all(
result.monitors.map(async (monitor) => { result.monitors.map(async (monitor) => {
await req.jobQueue.deleteJob(monitor); await this.jobQueue.deleteJob(monitor);
await req.db.deleteChecks(monitor._id); await this.db.deleteChecks(monitor._id);
await req.db.deletePageSpeedChecksByMonitorId(monitor._id); await this.db.deletePageSpeedChecksByMonitorId(monitor._id);
await req.db.deleteNotificationsByMonitorId(monitor._id); await this.db.deleteNotificationsByMonitorId(monitor._id);
}) })
)); ));
// 3. Delete team // 3. Delete team
await req.db.deleteTeam(user.teamId); await this.db.deleteTeam(user.teamId);
// 4. Delete all other team members // 4. Delete all other team members
await req.db.deleteAllOtherUsers(); await this.db.deleteAllOtherUsers();
// 5. Delete each monitor // 5. Delete each monitor
await req.db.deleteMonitorsByUserId(user._id); await this.db.deleteMonitorsByUserId(user._id);
} }
// 6. Delete the user by id // 6. Delete the user by id
await req.db.deleteUser(user._id); await this.db.deleteUser(user._id);
return res.status(200).json({ return res.status(200).json({
success: true, success: true,
msg: successMessages.AUTH_DELETE_USER, msg: successMessages.AUTH_DELETE_USER,
@@ -492,25 +504,14 @@ const deleteUser = async (req, res, next) => {
} }
}; };
const getAllUsers = async (req, res, next) => { getAllUsers = async (req, res, next) => {
try { try {
const allUsers = await req.db.getAllUsers(req, res); const allUsers = await this.db.getAllUsers(req, res);
res.status(200).json({ success: true, msg: "Got all users", data: allUsers }); res.status(200).json({ success: true, msg: "Got all users", data: allUsers });
} catch (error) { } catch (error) {
next(handleError(error, SERVICE_NAME, "getAllUsersController")); next(handleError(error, SERVICE_NAME, "getAllUsersController"));
} }
}; };
}
export { export default AuthController;
issueToken,
registerUser,
loginUser,
refreshAuthToken,
editUser,
checkSuperadminExists,
requestRecovery,
validateRecovery,
resetPassword,
deleteUser,
getAllUsers,
};
+22 -23
View File
@@ -16,7 +16,13 @@ import { handleValidationError, handleError } from "./controllerUtils.js";
const SERVICE_NAME = "checkController"; const SERVICE_NAME = "checkController";
const createCheck = async (req, res, next) => { class CheckController {
constructor(db, settingsService) {
this.db = db;
this.settingsService = settingsService;
}
createCheck = async (req, res, next) => {
try { try {
await createCheckParamValidation.validateAsync(req.params); await createCheckParamValidation.validateAsync(req.params);
await createCheckBodyValidation.validateAsync(req.body); await createCheckBodyValidation.validateAsync(req.body);
@@ -27,7 +33,7 @@ const createCheck = async (req, res, next) => {
try { try {
const checkData = { ...req.body }; const checkData = { ...req.body };
const check = await req.db.createCheck(checkData); const check = await this.db.createCheck(checkData);
return res return res
.status(200) .status(200)
.json({ success: true, msg: successMessages.CHECK_CREATE, data: check }); .json({ success: true, msg: successMessages.CHECK_CREATE, data: check });
@@ -36,7 +42,7 @@ const createCheck = async (req, res, next) => {
} }
}; };
const getChecks = async (req, res, next) => { getChecks = async (req, res, next) => {
try { try {
await getChecksParamValidation.validateAsync(req.params); await getChecksParamValidation.validateAsync(req.params);
await getChecksQueryValidation.validateAsync(req.query); await getChecksQueryValidation.validateAsync(req.query);
@@ -46,8 +52,8 @@ const getChecks = async (req, res, next) => {
} }
try { try {
const checks = await req.db.getChecks(req); const checks = await this.db.getChecks(req);
const checksCount = await req.db.getChecksCount(req); const checksCount = await this.db.getChecksCount(req);
return res.status(200).json({ return res.status(200).json({
success: true, success: true,
msg: successMessages.CHECK_GET, msg: successMessages.CHECK_GET,
@@ -58,7 +64,7 @@ const getChecks = async (req, res, next) => {
} }
}; };
const getTeamChecks = async (req, res, next) => { getTeamChecks = async (req, res, next) => {
try { try {
await getTeamChecksParamValidation.validateAsync(req.params); await getTeamChecksParamValidation.validateAsync(req.params);
await getTeamChecksQueryValidation.validateAsync(req.query); await getTeamChecksQueryValidation.validateAsync(req.query);
@@ -67,7 +73,7 @@ const getTeamChecks = async (req, res, next) => {
return; return;
} }
try { try {
const checkData = await req.db.getTeamChecks(req); const checkData = await this.db.getTeamChecks(req);
return res.status(200).json({ return res.status(200).json({
success: true, success: true,
msg: successMessages.CHECK_GET, msg: successMessages.CHECK_GET,
@@ -78,7 +84,7 @@ const getTeamChecks = async (req, res, next) => {
} }
}; };
const deleteChecks = async (req, res, next) => { deleteChecks = async (req, res, next) => {
try { try {
await deleteChecksParamValidation.validateAsync(req.params); await deleteChecksParamValidation.validateAsync(req.params);
} catch (error) { } catch (error) {
@@ -87,7 +93,7 @@ const deleteChecks = async (req, res, next) => {
} }
try { try {
const deletedCount = await req.db.deleteChecks(req.params.monitorId); const deletedCount = await this.db.deleteChecks(req.params.monitorId);
return res.status(200).json({ return res.status(200).json({
success: true, success: true,
msg: successMessages.CHECK_DELETE, msg: successMessages.CHECK_DELETE,
@@ -98,7 +104,7 @@ const deleteChecks = async (req, res, next) => {
} }
}; };
const deleteChecksByTeamId = async (req, res, next) => { deleteChecksByTeamId = async (req, res, next) => {
try { try {
await deleteChecksByTeamIdParamValidation.validateAsync(req.params); await deleteChecksByTeamIdParamValidation.validateAsync(req.params);
} catch (error) { } catch (error) {
@@ -107,7 +113,7 @@ const deleteChecksByTeamId = async (req, res, next) => {
} }
try { try {
const deletedCount = await req.db.deleteChecksByTeamId(req.params.teamId); const deletedCount = await this.db.deleteChecksByTeamId(req.params.teamId);
return res.status(200).json({ return res.status(200).json({
success: true, success: true,
msg: successMessages.CHECK_DELETE, msg: successMessages.CHECK_DELETE,
@@ -118,7 +124,7 @@ const deleteChecksByTeamId = async (req, res, next) => {
} }
}; };
const updateChecksTTL = async (req, res, next) => { updateChecksTTL = async (req, res, next) => {
const SECONDS_PER_DAY = 86400; const SECONDS_PER_DAY = 86400;
try { try {
@@ -131,10 +137,10 @@ const updateChecksTTL = async (req, res, next) => {
try { try {
// Get user's teamId // Get user's teamId
const token = getTokenFromHeaders(req.headers); const token = getTokenFromHeaders(req.headers);
const { jwtSecret } = req.settingsService.getSettings(); const { jwtSecret } = this.settingsService.getSettings();
const { teamId } = jwt.verify(token, jwtSecret); const { teamId } = jwt.verify(token, jwtSecret);
const ttl = parseInt(req.body.ttl, 10) * SECONDS_PER_DAY; const ttl = parseInt(req.body.ttl, 10) * SECONDS_PER_DAY;
await req.db.updateChecksTTL(teamId, ttl); await this.db.updateChecksTTL(teamId, ttl);
return res.status(200).json({ return res.status(200).json({
success: true, success: true,
msg: successMessages.CHECK_UPDATE_TTL, msg: successMessages.CHECK_UPDATE_TTL,
@@ -143,12 +149,5 @@ const updateChecksTTL = async (req, res, next) => {
next(handleError(error, SERVICE_NAME, "updateTTL")); next(handleError(error, SERVICE_NAME, "updateTTL"));
} }
}; };
}
export { export default CheckController;
createCheck,
getChecks,
getTeamChecks,
deleteChecks,
deleteChecksByTeamId,
updateChecksTTL,
};
+18 -11
View File
@@ -4,15 +4,19 @@ import {
inviteVerificationBodyValidation, inviteVerificationBodyValidation,
} from "../validation/joi.js"; } from "../validation/joi.js";
import logger from "../utils/logger.js"; import logger from "../utils/logger.js";
import dotenv from "dotenv";
import jwt from "jsonwebtoken"; import jwt from "jsonwebtoken";
import { handleError, handleValidationError } from "./controllerUtils.js"; import { handleError, handleValidationError } from "./controllerUtils.js";
import { getTokenFromHeaders } from "../utils/utils.js"; import { getTokenFromHeaders } from "../utils/utils.js";
dotenv.config();
const SERVICE_NAME = "inviteController"; const SERVICE_NAME = "inviteController";
class InviteController {
constructor(db, settingsService, emailService) {
this.db = db;
this.settingsService = settingsService;
this.emailService = emailService;
}
/** /**
* Issues an invitation to a new user. Only admins can invite new users. An invitation token is created and sent via email. * Issues an invitation to a new user. Only admins can invite new users. An invitation token is created and sent via email.
* @async * @async
@@ -26,7 +30,7 @@ const SERVICE_NAME = "inviteController";
* @returns {Object} The response object with a success status, a message indicating the sending of the invitation, and the invitation token. * @returns {Object} The response object with a success status, a message indicating the sending of the invitation, and the invitation token.
* @throws {Error} If there is an error during the process, especially if there is a validation error (422). * @throws {Error} If there is an error during the process, especially if there is a validation error (422).
*/ */
const issueInvitation = async (req, res, next) => { issueInvitation = async (req, res, next) => {
try { try {
// Only admins can invite // Only admins can invite
const token = getTokenFromHeaders(req.headers); const token = getTokenFromHeaders(req.headers);
@@ -40,9 +44,9 @@ const issueInvitation = async (req, res, next) => {
return; return;
} }
const inviteToken = await req.db.requestInviteToken({ ...req.body }); const inviteToken = await this.db.requestInviteToken({ ...req.body });
const { clientHost } = req.settingsService.getSettings(); const { clientHost } = this.settingsService.getSettings();
req.emailService this.emailService
.buildAndSendEmail( .buildAndSendEmail(
"employeeActivationTemplate", "employeeActivationTemplate",
{ {
@@ -61,13 +65,15 @@ const issueInvitation = async (req, res, next) => {
}); });
}); });
return res.status(200).json({ success: true, msg: "Invite sent", data: inviteToken }); return res
.status(200)
.json({ success: true, msg: "Invite sent", data: inviteToken });
} catch (error) { } catch (error) {
next(handleError(error, SERVICE_NAME, "inviteController")); next(handleError(error, SERVICE_NAME, "inviteController"));
} }
}; };
const inviteVerifyController = async (req, res, next) => { inviteVerifyController = async (req, res, next) => {
try { try {
await inviteVerificationBodyValidation.validateAsync(req.body); await inviteVerificationBodyValidation.validateAsync(req.body);
} catch (error) { } catch (error) {
@@ -76,11 +82,12 @@ const inviteVerifyController = async (req, res, next) => {
} }
try { try {
const invite = await req.db.getInviteToken(req.body.token); const invite = await this.db.getInviteToken(req.body.token);
res.status(200).json({ status: "success", msg: "Invite verified", data: invite }); res.status(200).json({ status: "success", msg: "Invite verified", data: invite });
} catch (error) { } catch (error) {
next(handleError(error, SERVICE_NAME, "inviteVerifyController")); next(handleError(error, SERVICE_NAME, "inviteVerifyController"));
} }
}; };
}
export { issueInvitation, inviteVerifyController }; export default InviteController;
@@ -11,10 +11,15 @@ import jwt from "jsonwebtoken";
import { getTokenFromHeaders } from "../utils/utils.js"; import { getTokenFromHeaders } from "../utils/utils.js";
import { successMessages } from "../utils/messages.js"; import { successMessages } from "../utils/messages.js";
import { handleValidationError, handleError } from "./controllerUtils.js"; import { handleValidationError, handleError } from "./controllerUtils.js";
const SERVICE_NAME = "maintenanceWindowController"; const SERVICE_NAME = "maintenanceWindowController";
const createMaintenanceWindows = async (req, res, next) => { class MaintenanceWindowController {
constructor(db, settingsService) {
this.db = db;
this.settingsService = settingsService;
}
createMaintenanceWindows = async (req, res, next) => {
try { try {
await createMaintenanceWindowBodyValidation.validateAsync(req.body); await createMaintenanceWindowBodyValidation.validateAsync(req.body);
} catch (error) { } catch (error) {
@@ -23,11 +28,11 @@ const createMaintenanceWindows = async (req, res, next) => {
} }
try { try {
const token = getTokenFromHeaders(req.headers); const token = getTokenFromHeaders(req.headers);
const { jwtSecret } = req.settingsService.getSettings(); const { jwtSecret } = this.settingsService.getSettings();
const { teamId } = jwt.verify(token, jwtSecret); const { teamId } = jwt.verify(token, jwtSecret);
const monitorIds = req.body.monitors; const monitorIds = req.body.monitors;
const dbTransactions = monitorIds.map((monitorId) => { const dbTransactions = monitorIds.map((monitorId) => {
return req.db.createMaintenanceWindow({ return this.db.createMaintenanceWindow({
teamId, teamId,
monitorId, monitorId,
name: req.body.name, name: req.body.name,
@@ -47,7 +52,7 @@ const createMaintenanceWindows = async (req, res, next) => {
} }
}; };
const getMaintenanceWindowById = async (req, res, next) => { getMaintenanceWindowById = async (req, res, next) => {
try { try {
await getMaintenanceWindowByIdParamValidation.validateAsync(req.params); await getMaintenanceWindowByIdParamValidation.validateAsync(req.params);
} catch (error) { } catch (error) {
@@ -55,7 +60,7 @@ const getMaintenanceWindowById = async (req, res, next) => {
return; return;
} }
try { try {
const maintenanceWindow = await req.db.getMaintenanceWindowById(req.params.id); const maintenanceWindow = await this.db.getMaintenanceWindowById(req.params.id);
return res.status(200).json({ return res.status(200).json({
success: true, success: true,
msg: successMessages.MAINTENANCE_WINDOW_GET_BY_ID, msg: successMessages.MAINTENANCE_WINDOW_GET_BY_ID,
@@ -66,7 +71,7 @@ const getMaintenanceWindowById = async (req, res, next) => {
} }
}; };
const getMaintenanceWindowsByTeamId = async (req, res, next) => { getMaintenanceWindowsByTeamId = async (req, res, next) => {
try { try {
await getMaintenanceWindowsByTeamIdQueryValidation.validateAsync(req.query); await getMaintenanceWindowsByTeamIdQueryValidation.validateAsync(req.query);
} catch (error) { } catch (error) {
@@ -76,9 +81,9 @@ const getMaintenanceWindowsByTeamId = async (req, res, next) => {
try { try {
const token = getTokenFromHeaders(req.headers); const token = getTokenFromHeaders(req.headers);
const { jwtSecret } = req.settingsService.getSettings(); const { jwtSecret } = this.settingsService.getSettings();
const { teamId } = jwt.verify(token, jwtSecret); const { teamId } = jwt.verify(token, jwtSecret);
const maintenanceWindows = await req.db.getMaintenanceWindowsByTeamId( const maintenanceWindows = await this.db.getMaintenanceWindowsByTeamId(
teamId, teamId,
req.query req.query
); );
@@ -93,7 +98,7 @@ const getMaintenanceWindowsByTeamId = async (req, res, next) => {
} }
}; };
const getMaintenanceWindowsByMonitorId = async (req, res, next) => { getMaintenanceWindowsByMonitorId = async (req, res, next) => {
try { try {
await getMaintenanceWindowsByMonitorIdParamValidation.validateAsync(req.params); await getMaintenanceWindowsByMonitorIdParamValidation.validateAsync(req.params);
} catch (error) { } catch (error) {
@@ -102,7 +107,7 @@ const getMaintenanceWindowsByMonitorId = async (req, res, next) => {
} }
try { try {
const maintenanceWindows = await req.db.getMaintenanceWindowsByMonitorId( const maintenanceWindows = await this.db.getMaintenanceWindowsByMonitorId(
req.params.monitorId req.params.monitorId
); );
@@ -116,7 +121,7 @@ const getMaintenanceWindowsByMonitorId = async (req, res, next) => {
} }
}; };
const deleteMaintenanceWindow = async (req, res, next) => { deleteMaintenanceWindow = async (req, res, next) => {
try { try {
await deleteMaintenanceWindowByIdParamValidation.validateAsync(req.params); await deleteMaintenanceWindowByIdParamValidation.validateAsync(req.params);
} catch (error) { } catch (error) {
@@ -124,7 +129,7 @@ const deleteMaintenanceWindow = async (req, res, next) => {
return; return;
} }
try { try {
await req.db.deleteMaintenanceWindowById(req.params.id); await this.db.deleteMaintenanceWindowById(req.params.id);
return res.status(200).json({ return res.status(200).json({
success: true, success: true,
msg: successMessages.MAINTENANCE_WINDOW_DELETE, msg: successMessages.MAINTENANCE_WINDOW_DELETE,
@@ -134,7 +139,7 @@ const deleteMaintenanceWindow = async (req, res, next) => {
} }
}; };
const editMaintenanceWindow = async (req, res, next) => { editMaintenanceWindow = async (req, res, next) => {
try { try {
await editMaintenanceWindowByIdParamValidation.validateAsync(req.params); await editMaintenanceWindowByIdParamValidation.validateAsync(req.params);
await editMaintenanceByIdWindowBodyValidation.validateAsync(req.body); await editMaintenanceByIdWindowBodyValidation.validateAsync(req.body);
@@ -143,7 +148,7 @@ const editMaintenanceWindow = async (req, res, next) => {
return; return;
} }
try { try {
const editedMaintenanceWindow = await req.db.editMaintenanceWindowById( const editedMaintenanceWindow = await this.db.editMaintenanceWindowById(
req.params.id, req.params.id,
req.body req.body
); );
@@ -156,12 +161,6 @@ const editMaintenanceWindow = async (req, res, next) => {
next(handleError(error, SERVICE_NAME, "editMaintenanceWindow")); next(handleError(error, SERVICE_NAME, "editMaintenanceWindow"));
} }
}; };
}
export { export default MaintenanceWindowController;
createMaintenanceWindows,
getMaintenanceWindowById,
getMaintenanceWindowsByTeamId,
getMaintenanceWindowsByMonitorId,
deleteMaintenanceWindow,
editMaintenanceWindow,
};
+58 -65
View File
@@ -14,7 +14,7 @@ import {
getCertificateParamValidation, getCertificateParamValidation,
} from "../validation/joi.js"; } from "../validation/joi.js";
import sslChecker from "ssl-checker"; import sslChecker from "ssl-checker";
import { errorMessages, successMessages } from "../utils/messages.js"; import { successMessages } from "../utils/messages.js";
import jwt from "jsonwebtoken"; import jwt from "jsonwebtoken";
import { getTokenFromHeaders } from "../utils/utils.js"; import { getTokenFromHeaders } from "../utils/utils.js";
import logger from "../utils/logger.js"; import logger from "../utils/logger.js";
@@ -23,6 +23,13 @@ import axios from "axios";
const SERVICE_NAME = "monitorController"; const SERVICE_NAME = "monitorController";
class MonitorController {
constructor(db, settingsService, jobQueue) {
this.db = db;
this.settingsService = settingsService;
this.jobQueue = jobQueue;
}
/** /**
* Returns all monitors * Returns all monitors
* @async * @async
@@ -32,9 +39,9 @@ const SERVICE_NAME = "monitorController";
* @returns {Promise<Express.Response>} * @returns {Promise<Express.Response>}
* @throws {Error} * @throws {Error}
*/ */
const getAllMonitors = async (req, res, next) => { getAllMonitors = async (req, res, next) => {
try { try {
const monitors = await req.db.getAllMonitors(); const monitors = await this.db.getAllMonitors();
return res.status(200).json({ return res.status(200).json({
success: true, success: true,
msg: successMessages.MONITOR_GET_ALL, msg: successMessages.MONITOR_GET_ALL,
@@ -54,9 +61,9 @@ const getAllMonitors = async (req, res, next) => {
* @returns {Promise<Express.Response>} * @returns {Promise<Express.Response>}
* @throws {Error} * @throws {Error}
*/ */
const getAllMonitorsWithUptimeStats = async (req, res, next) => { getAllMonitorsWithUptimeStats = async (req, res, next) => {
try { try {
const monitors = await req.db.getAllMonitorsWithUptimeStats(); const monitors = await this.db.getAllMonitorsWithUptimeStats();
return res.status(200).json({ return res.status(200).json({
success: true, success: true,
msg: successMessages.MONITOR_GET_ALL, msg: successMessages.MONITOR_GET_ALL,
@@ -76,7 +83,7 @@ const getAllMonitorsWithUptimeStats = async (req, res, next) => {
* @returns {Promise<Express.Response>} * @returns {Promise<Express.Response>}
* @throws {Error} * @throws {Error}
*/ */
const getMonitorStatsById = async (req, res, next) => { getMonitorStatsById = async (req, res, next) => {
try { try {
await getMonitorStatsByIdParamValidation.validateAsync(req.params); await getMonitorStatsByIdParamValidation.validateAsync(req.params);
await getMonitorStatsByIdQueryValidation.validateAsync(req.query); await getMonitorStatsByIdQueryValidation.validateAsync(req.query);
@@ -86,7 +93,7 @@ const getMonitorStatsById = async (req, res, next) => {
} }
try { try {
const monitorStats = await req.db.getMonitorStatsById(req); const monitorStats = await this.db.getMonitorStatsById(req);
return res.status(200).json({ return res.status(200).json({
success: true, success: true,
msg: successMessages.MONITOR_STATS_BY_ID, msg: successMessages.MONITOR_STATS_BY_ID,
@@ -97,7 +104,7 @@ const getMonitorStatsById = async (req, res, next) => {
} }
}; };
const getMonitorCertificate = async (req, res, next, fetchMonitorCertificate) => { getMonitorCertificate = async (req, res, next, fetchMonitorCertificate) => {
try { try {
await getCertificateParamValidation.validateAsync(req.params); await getCertificateParamValidation.validateAsync(req.params);
} catch (error) { } catch (error) {
@@ -106,7 +113,7 @@ const getMonitorCertificate = async (req, res, next, fetchMonitorCertificate) =>
try { try {
const { monitorId } = req.params; const { monitorId } = req.params;
const monitor = await req.db.getMonitorById(monitorId); const monitor = await this.db.getMonitorById(monitorId);
const certificate = await fetchMonitorCertificate(sslChecker, monitor); const certificate = await fetchMonitorCertificate(sslChecker, monitor);
return res.status(200).json({ return res.status(200).json({
@@ -132,7 +139,7 @@ const getMonitorCertificate = async (req, res, next, fetchMonitorCertificate) =>
* @returns {Object} The response object with a success status, a message, and the retrieved monitor data. * @returns {Object} The response object with a success status, a message, and the retrieved monitor data.
* @throws {Error} If there is an error during the process, especially if the monitor is not found (404) or if there is a validation error (422). * @throws {Error} If there is an error during the process, especially if the monitor is not found (404) or if there is a validation error (422).
*/ */
const getMonitorById = async (req, res, next) => { getMonitorById = async (req, res, next) => {
try { try {
await getMonitorByIdParamValidation.validateAsync(req.params); await getMonitorByIdParamValidation.validateAsync(req.params);
await getMonitorByIdQueryValidation.validateAsync(req.query); await getMonitorByIdQueryValidation.validateAsync(req.query);
@@ -142,7 +149,7 @@ const getMonitorById = async (req, res, next) => {
} }
try { try {
const monitor = await req.db.getMonitorById(req.params.monitorId); const monitor = await this.db.getMonitorById(req.params.monitorId);
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,
@@ -166,7 +173,7 @@ const getMonitorById = async (req, res, next) => {
* @returns {Object} The response object with a success status, a message, and the data containing the monitors and summary for the team. * @returns {Object} The response object with a success status, a message, and the data containing the monitors and summary for the team.
* @throws {Error} If there is an error during the process, especially if there is a validation error (422). * @throws {Error} If there is an error during the process, especially if there is a validation error (422).
*/ */
const getMonitorsAndSummaryByTeamId = async (req, res, next) => { getMonitorsAndSummaryByTeamId = async (req, res, next) => {
try { try {
await getMonitorsAndSummaryByTeamIdParamValidation.validateAsync(req.params); await getMonitorsAndSummaryByTeamIdParamValidation.validateAsync(req.params);
await getMonitorsAndSummaryByTeamIdQueryValidation.validateAsync(req.query); await getMonitorsAndSummaryByTeamIdQueryValidation.validateAsync(req.query);
@@ -178,7 +185,7 @@ const getMonitorsAndSummaryByTeamId = async (req, res, next) => {
try { try {
const { teamId } = req.params; const { teamId } = req.params;
const { type } = req.query; const { type } = req.query;
const monitorsSummary = await req.db.getMonitorsAndSummaryByTeamId(teamId, type); const monitorsSummary = await this.db.getMonitorsAndSummaryByTeamId(teamId, type);
return res.status(200).json({ return res.status(200).json({
success: true, success: true,
msg: successMessages.MONITOR_GET_BY_USER_ID(teamId), msg: successMessages.MONITOR_GET_BY_USER_ID(teamId),
@@ -201,7 +208,7 @@ const getMonitorsAndSummaryByTeamId = async (req, res, next) => {
* @returns {Object} The response object with a success status, a message, and the data containing the monitors for the team. * @returns {Object} The response object with a success status, a message, and the data containing the monitors for the team.
* @throws {Error} If there is an error during the process, especially if there is a validation error (422). * @throws {Error} If there is an error during the process, especially if there is a validation error (422).
*/ */
const getMonitorsByTeamId = async (req, res, next) => { getMonitorsByTeamId = async (req, res, next) => {
try { try {
await getMonitorsByTeamIdValidation.validateAsync(req.params); await getMonitorsByTeamIdValidation.validateAsync(req.params);
await getMonitorsByTeamIdQueryValidation.validateAsync(req.query); await getMonitorsByTeamIdQueryValidation.validateAsync(req.query);
@@ -212,7 +219,7 @@ const getMonitorsByTeamId = async (req, res, next) => {
try { try {
const teamId = req.params.teamId; const teamId = req.params.teamId;
const monitors = await req.db.getMonitorsByTeamId(req, res); const monitors = await this.db.getMonitorsByTeamId(req, res);
return res.status(200).json({ return res.status(200).json({
success: true, success: true,
msg: successMessages.MONITOR_GET_BY_USER_ID(teamId), msg: successMessages.MONITOR_GET_BY_USER_ID(teamId),
@@ -235,7 +242,7 @@ const getMonitorsByTeamId = async (req, res, next) => {
* @returns {Object} The response object with a success status, a message indicating the creation of the monitor, and the created monitor data. * @returns {Object} The response object with a success status, a message indicating the creation of the monitor, and the created monitor data.
* @throws {Error} If there is an error during the process, especially if there is a validation error (422). * @throws {Error} If there is an error during the process, especially if there is a validation error (422).
*/ */
const createMonitor = async (req, res, next) => { createMonitor = async (req, res, next) => {
try { try {
await createMonitorBodyValidation.validateAsync(req.body); await createMonitorBodyValidation.validateAsync(req.body);
} catch (error) { } catch (error) {
@@ -245,20 +252,20 @@ const createMonitor = async (req, res, next) => {
try { try {
const notifications = req.body.notifications; const notifications = req.body.notifications;
const monitor = await req.db.createMonitor(req, res); const monitor = await this.db.createMonitor(req, res);
if (notifications && notifications.length > 0) { if (notifications && notifications.length > 0) {
monitor.notifications = await Promise.all( monitor.notifications = await Promise.all(
notifications.map(async (notification) => { notifications.map(async (notification) => {
notification.monitorId = monitor._id; notification.monitorId = monitor._id;
return await req.db.createNotification(notification); return await this.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); this.jobQueue.addJob(monitor._id, monitor);
return res.status(201).json({ return res.status(201).json({
success: true, success: true,
msg: successMessages.MONITOR_CREATE, msg: successMessages.MONITOR_CREATE,
@@ -279,7 +286,7 @@ const createMonitor = async (req, res, next) => {
* @returns {Object} The response object with a success status, a message, and the resolution result. * @returns {Object} The response object with a success status, a message, and the resolution result.
* @throws {Error} If there is an error during the process, especially if there is a validation error (422). * @throws {Error} If there is an error during the process, especially if there is a validation error (422).
*/ */
const checkEndpointResolution = async (req, res, next) => { checkEndpointResolution = async (req, res, next) => {
try { try {
await getMonitorURLByQueryValidation.validateAsync(req.query); await getMonitorURLByQueryValidation.validateAsync(req.query);
} catch (error) { } catch (error) {
@@ -316,7 +323,7 @@ const checkEndpointResolution = async (req, res, next) => {
* @returns {Object} The response object with a success status and a message indicating the deletion of the monitor. * @returns {Object} The response object with a success status and a message indicating the deletion of the monitor.
* @throws {Error} If there is an error during the process, especially if there is a validation error (422) or an error in deleting associated records. * @throws {Error} If there is an error during the process, especially if there is a validation error (422) or an error in deleting associated records.
*/ */
const deleteMonitor = async (req, res, next) => { deleteMonitor = async (req, res, next) => {
try { try {
await getMonitorByIdParamValidation.validateAsync(req.params); await getMonitorByIdParamValidation.validateAsync(req.params);
} catch (error) { } catch (error) {
@@ -325,14 +332,14 @@ const deleteMonitor = async (req, res, next) => {
} }
try { try {
const monitor = await req.db.deleteMonitor(req, res, next); const monitor = await this.db.deleteMonitor(req, res, next);
// Delete associated checks,alerts,and notifications // Delete associated checks,alerts,and notifications
try { try {
await req.jobQueue.deleteJob(monitor); await this.jobQueue.deleteJob(monitor);
await req.db.deleteChecks(monitor._id); await this.db.deleteChecks(monitor._id);
await req.db.deletePageSpeedChecksByMonitorId(monitor._id); await this.db.deletePageSpeedChecksByMonitorId(monitor._id);
await req.db.deleteNotificationsByMonitorId(monitor._id); await this.db.deleteNotificationsByMonitorId(monitor._id);
await req.db.deleteHardwareChecksByMonitorId(monitor._id); await this.db.deleteHardwareChecksByMonitorId(monitor._id);
} catch (error) { } catch (error) {
logger.error({ logger.error({
message: `Error deleting associated records for monitor ${monitor._id} with name ${monitor.name}`, message: `Error deleting associated records for monitor ${monitor._id} with name ${monitor.name}`,
@@ -358,19 +365,19 @@ const deleteMonitor = async (req, res, next) => {
* @returns {Object} The response object with a success status and a message indicating the number of deleted monitors. * @returns {Object} The response object with a success status and a message indicating the number of deleted monitors.
* @throws {Error} If there is an error during the deletion process. * @throws {Error} If there is an error during the deletion process.
*/ */
const deleteAllMonitors = async (req, res, next) => { deleteAllMonitors = async (req, res, next) => {
try { try {
const token = getTokenFromHeaders(req.headers); const token = getTokenFromHeaders(req.headers);
const { jwtSecret } = req.settingsService.getSettings(); const { jwtSecret } = this.settingsService.getSettings();
const { teamId } = jwt.verify(token, jwtSecret); const { teamId } = jwt.verify(token, jwtSecret);
const { monitors, deletedCount } = await req.db.deleteAllMonitors(teamId); const { monitors, deletedCount } = await this.db.deleteAllMonitors(teamId);
await Promise.all( await Promise.all(
monitors.map(async (monitor) => { monitors.map(async (monitor) => {
try { try {
await req.jobQueue.deleteJob(monitor); await this.jobQueue.deleteJob(monitor);
await req.db.deleteChecks(monitor._id); await this.db.deleteChecks(monitor._id);
await req.db.deletePageSpeedChecksByMonitorId(monitor._id); await this.db.deletePageSpeedChecksByMonitorId(monitor._id);
await req.db.deleteNotificationsByMonitorId(monitor._id); await this.db.deleteNotificationsByMonitorId(monitor._id);
} catch (error) { } catch (error) {
logger.error({ logger.error({
message: `Error deleting associated records for monitor ${monitor._id} with name ${monitor.name}`, message: `Error deleting associated records for monitor ${monitor._id} with name ${monitor.name}`,
@@ -402,7 +409,7 @@ const deleteAllMonitors = async (req, res, next) => {
* @returns {Object} The response object with a success status, a message indicating the editing of the monitor, and the edited monitor data. * @returns {Object} The response object with a success status, a message indicating the editing of the monitor, and the edited monitor data.
* @throws {Error} If there is an error during the process, especially if there is a validation error (422). * @throws {Error} If there is an error during the process, especially if there is a validation error (422).
*/ */
const editMonitor = async (req, res, next) => { editMonitor = async (req, res, next) => {
try { try {
await getMonitorByIdParamValidation.validateAsync(req.params); await getMonitorByIdParamValidation.validateAsync(req.params);
await editMonitorBodyValidation.validateAsync(req.body); await editMonitorBodyValidation.validateAsync(req.body);
@@ -413,27 +420,27 @@ const editMonitor = async (req, res, next) => {
try { try {
const { monitorId } = req.params; const { monitorId } = req.params;
const monitorBeforeEdit = await req.db.getMonitorById(monitorId); const monitorBeforeEdit = await this.db.getMonitorById(monitorId);
// Get notifications from the request body // Get notifications from the request body
const notifications = req.body.notifications; const notifications = req.body.notifications;
const editedMonitor = await req.db.editMonitor(monitorId, req.body); const editedMonitor = await this.db.editMonitor(monitorId, req.body);
await req.db.deleteNotificationsByMonitorId(editedMonitor._id); await this.db.deleteNotificationsByMonitorId(editedMonitor._id);
await Promise.all( await Promise.all(
notifications && notifications &&
notifications.map(async (notification) => { notifications.map(async (notification) => {
notification.monitorId = editedMonitor._id; notification.monitorId = editedMonitor._id;
await req.db.createNotification(notification); await this.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 this.jobQueue.deleteJob(monitorBeforeEdit);
// Add the new job back to the queue // Add the new job back to the queue
await req.jobQueue.addJob(editedMonitor._id, editedMonitor); await this.jobQueue.addJob(editedMonitor._id, editedMonitor);
return res.status(200).json({ return res.status(200).json({
success: true, success: true,
msg: successMessages.MONITOR_EDIT, msg: successMessages.MONITOR_EDIT,
@@ -455,7 +462,7 @@ const editMonitor = async (req, res, next) => {
* @returns {Object} The response object with a success status, a message indicating the new state of the monitor, and the updated monitor data. * @returns {Object} The response object with a success status, a message indicating the new state of the monitor, and the updated monitor data.
* @throws {Error} If there is an error during the process. * @throws {Error} If there is an error during the process.
*/ */
const pauseMonitor = async (req, res, next) => { pauseMonitor = async (req, res, next) => {
try { try {
await pauseMonitorParamValidation.validateAsync(req.params); await pauseMonitorParamValidation.validateAsync(req.params);
} catch (error) { } catch (error) {
@@ -463,10 +470,10 @@ const pauseMonitor = async (req, res, next) => {
} }
try { try {
const monitor = await req.db.getMonitorById(req.params.monitorId); const monitor = await this.db.getMonitorById(req.params.monitorId);
monitor.isActive === true monitor.isActive === true
? await req.jobQueue.deleteJob(monitor) ? await this.jobQueue.deleteJob(monitor)
: await req.jobQueue.addJob(monitor._id, monitor); : await this.jobQueue.addJob(monitor._id, monitor);
monitor.isActive = !monitor.isActive; monitor.isActive = !monitor.isActive;
monitor.status = undefined; monitor.status = undefined;
@@ -494,14 +501,14 @@ const pauseMonitor = async (req, res, next) => {
* @returns {Object} The response object with a success status, a message indicating the addition of demo monitors, and the number of demo monitors added. * @returns {Object} The response object with a success status, a message indicating the addition of demo monitors, and the number of demo monitors added.
* @throws {Error} If there is an error during the process. * @throws {Error} If there is an error during the process.
*/ */
const addDemoMonitors = async (req, res, next) => { addDemoMonitors = async (req, res, next) => {
try { try {
const token = getTokenFromHeaders(req.headers); const token = getTokenFromHeaders(req.headers);
const { jwtSecret } = req.settingsService.getSettings(); const { jwtSecret } = this.settingsService.getSettings();
const { _id, teamId } = jwt.verify(token, jwtSecret); const { _id, teamId } = jwt.verify(token, jwtSecret);
const demoMonitors = await req.db.addDemoMonitors(_id, teamId); const demoMonitors = await this.db.addDemoMonitors(_id, teamId);
await Promise.all( await Promise.all(
demoMonitors.map((monitor) => req.jobQueue.addJob(monitor._id, monitor)) demoMonitors.map((monitor) => this.jobQueue.addJob(monitor._id, monitor))
); );
return res.status(200).json({ return res.status(200).json({
@@ -513,20 +520,6 @@ const addDemoMonitors = async (req, res, next) => {
next(handleError(error, SERVICE_NAME, "addDemoMonitors")); next(handleError(error, SERVICE_NAME, "addDemoMonitors"));
} }
}; };
}
export { export default MonitorController;
getAllMonitors,
getAllMonitorsWithUptimeStats,
getMonitorStatsById,
getMonitorCertificate,
getMonitorById,
getMonitorsAndSummaryByTeamId,
getMonitorsByTeamId,
createMonitor,
checkEndpointResolution,
deleteMonitor,
deleteAllMonitors,
editMonitor,
pauseMonitor,
addDemoMonitors,
};
+19 -12
View File
@@ -1,11 +1,16 @@
import { handleError } from "./controllerUtils.js"; import { handleError } from "./controllerUtils.js";
import { errorMessages, successMessages } from "../utils/messages.js"; import { successMessages } from "../utils/messages.js";
const SERVICE_NAME = "JobQueueController"; const SERVICE_NAME = "JobQueueController";
const getMetrics = async (req, res, next) => { class JobQueueController {
constructor(jobQueue) {
this.jobQueue = jobQueue;
}
getMetrics = async (req, res, next) => {
try { try {
const metrics = await req.jobQueue.getMetrics(); const metrics = await this.jobQueue.getMetrics();
res.status(200).json({ res.status(200).json({
success: true, success: true,
msg: successMessages.QUEUE_GET_METRICS, msg: successMessages.QUEUE_GET_METRICS,
@@ -17,9 +22,9 @@ const getMetrics = async (req, res, next) => {
} }
}; };
const getJobs = async (req, res, next) => { getJobs = async (req, res, next) => {
try { try {
const jobs = await req.jobQueue.getJobStats(); const jobs = await this.jobQueue.getJobStats();
return res.status(200).json({ return res.status(200).json({
success: true, success: true,
msg: successMessages.QUEUE_GET_METRICS, msg: successMessages.QUEUE_GET_METRICS,
@@ -31,9 +36,9 @@ const getJobs = async (req, res, next) => {
} }
}; };
const addJob = async (req, res, next) => { addJob = async (req, res, next) => {
try { try {
await req.jobQueue.addJob(Math.random().toString(36).substring(7)); await this.jobQueue.addJob(Math.random().toString(36).substring(7));
return res.status(200).json({ return res.status(200).json({
success: true, success: true,
msg: successMessages.QUEUE_ADD_JOB, msg: successMessages.QUEUE_ADD_JOB,
@@ -44,14 +49,16 @@ const addJob = async (req, res, next) => {
} }
}; };
const obliterateQueue = async (req, res, next) => { obliterateQueue = async (req, res, next) => {
try { try {
await req.jobQueue.obliterate(); await this.jobQueue.obliterate();
return res.status(200).json({ success: true, msg: successMessages.QUEUE_OBLITERATE }); return res
.status(200)
.json({ success: true, msg: successMessages.QUEUE_OBLITERATE });
} catch (error) { } catch (error) {
next(handleError(error, SERVICE_NAME, "obliterateQueue")); next(handleError(error, SERVICE_NAME, "obliterateQueue"));
return; return;
} }
}; };
}
export { getMetrics, getJobs, addJob, obliterateQueue }; export default JobQueueController;
+13 -6
View File
@@ -3,9 +3,15 @@ import { updateAppSettingsBodyValidation } from "../validation/joi.js";
import { handleValidationError, handleError } from "./controllerUtils.js"; import { handleValidationError, handleError } from "./controllerUtils.js";
const SERVICE_NAME = "SettingsController"; const SERVICE_NAME = "SettingsController";
const getAppSettings = async (req, res, next) => { class SettingsController {
constructor(db, settingsService) {
this.db = db;
this.settingsService = settingsService;
}
getAppSettings = async (req, res, next) => {
try { try {
const settings = { ...(await req.settingsService.getSettings()) }; const settings = { ...(await this.settingsService.getSettings()) };
delete settings.jwtSecret; delete settings.jwtSecret;
return res.status(200).json({ return res.status(200).json({
success: true, success: true,
@@ -17,7 +23,7 @@ const getAppSettings = async (req, res, next) => {
} }
}; };
const updateAppSettings = async (req, res, next) => { updateAppSettings = async (req, res, next) => {
try { try {
await updateAppSettingsBodyValidation.validateAsync(req.body); await updateAppSettingsBodyValidation.validateAsync(req.body);
} catch (error) { } catch (error) {
@@ -26,8 +32,8 @@ const updateAppSettings = async (req, res, next) => {
} }
try { try {
await req.db.updateAppSettings(req.body); await this.db.updateAppSettings(req.body);
const updatedSettings = { ...(await req.settingsService.reloadSettings()) }; const updatedSettings = { ...(await this.settingsService.reloadSettings()) };
delete updatedSettings.jwtSecret; delete updatedSettings.jwtSecret;
return res.status(200).json({ return res.status(200).json({
success: true, success: true,
@@ -38,5 +44,6 @@ const updateAppSettings = async (req, res, next) => {
next(handleError(error, SERVICE_NAME, "updateAppSettings")); next(handleError(error, SERVICE_NAME, "updateAppSettings"));
} }
}; };
}
export { getAppSettings, updateAppSettings }; export default SettingsController;
+11 -6
View File
@@ -7,7 +7,12 @@ import { successMessages } from "../utils/messages.js";
const SERVICE_NAME = "statusPageController"; const SERVICE_NAME = "statusPageController";
const createStatusPage = async (req, res, next) => { class StatusPageController {
constructor(db) {
this.db = db;
}
createStatusPage = async (req, res, next) => {
try { try {
await createStatusPageBodyValidation.validateAsync(req.body); await createStatusPageBodyValidation.validateAsync(req.body);
} catch (error) { } catch (error) {
@@ -16,7 +21,7 @@ const createStatusPage = async (req, res, next) => {
} }
try { try {
const statusPage = await req.db.createStatusPage(req.body); const statusPage = await this.db.createStatusPage(req.body);
return res.status(200).json({ return res.status(200).json({
success: true, success: true,
msg: successMessages.STATUS_PAGE_CREATE, msg: successMessages.STATUS_PAGE_CREATE,
@@ -26,8 +31,7 @@ const createStatusPage = async (req, res, next) => {
next(handleError(error, SERVICE_NAME, "createStatusPage")); next(handleError(error, SERVICE_NAME, "createStatusPage"));
} }
}; };
getStatusPageByUrl = async (req, res, next) => {
const getStatusPageByUrl = async (req, res, next) => {
try { try {
await getStatusPageParamValidation.validateAsync(req.params); await getStatusPageParamValidation.validateAsync(req.params);
} catch (error) { } catch (error) {
@@ -37,7 +41,7 @@ const getStatusPageByUrl = async (req, res, next) => {
try { try {
const { url } = req.params; const { url } = req.params;
const statusPage = await req.db.getStatusPageByUrl(url); const statusPage = await this.db.getStatusPageByUrl(url);
return res.status(200).json({ return res.status(200).json({
success: true, success: true,
msg: successMessages.STATUS_PAGE_BY_URL, msg: successMessages.STATUS_PAGE_BY_URL,
@@ -47,5 +51,6 @@ const getStatusPageByUrl = async (req, res, next) => {
next(handleError(error, SERVICE_NAME, "getStatusPage")); next(handleError(error, SERVICE_NAME, "getStatusPage"));
} }
}; };
}
export { createStatusPage, getStatusPageByUrl }; export default StatusPageController;
+81 -186
View File
@@ -2,13 +2,85 @@ import mongoose from "mongoose";
import UserModel from "../models/User.js"; import UserModel from "../models/User.js";
import AppSettings from "../models/AppSettings.js"; import AppSettings from "../models/AppSettings.js";
import logger from "../../utils/logger.js"; import logger from "../../utils/logger.js";
const SERVICE_NAME = "MongoDB";
//**************************************** //****************************************
// DB Connection // User Operations
//**************************************** //****************************************
const connect = async () => { import * as userModule from "./modules/userModule.js";
//****************************************
// Invite Token Operations
//****************************************
import * as inviteModule from "./modules/inviteModule.js";
//****************************************
// Recovery Operations
//****************************************
import * as recoveryModule from "./modules/recoveryModule.js";
//****************************************
// Monitors
//****************************************
import * as monitorModule from "./modules/monitorModule.js";
//****************************************
// Page Speed Checks
//****************************************
import * as pageSpeedCheckModule from "./modules/pageSpeedCheckModule.js";
//****************************************
// Hardware Checks
//****************************************
import * as hardwareCheckModule from "./modules/hardwareCheckModule.js";
//****************************************
// Checks
//****************************************
import * as checkModule from "./modules/checkModule.js";
//****************************************
// Maintenance Window
//****************************************
import * as maintenanceWindowModule from "./modules/maintenanceWindowModule.js";
//****************************************
// Notifications
//****************************************
import * as notificationModule from "./modules/notificationModule.js";
//****************************************
// AppSettings
//****************************************
import * as settingsModule from "./modules/settingsModule.js";
//****************************************
// Status Page
//****************************************
import * as statusPageModule from "./modules/statusPageModule.js";
class MongoDB {
static SERVICE_NAME = "MongoDB";
constructor() {
Object.assign(this, userModule);
Object.assign(this, inviteModule);
Object.assign(this, recoveryModule);
Object.assign(this, monitorModule);
Object.assign(this, pageSpeedCheckModule);
Object.assign(this, hardwareCheckModule);
Object.assign(this, checkModule);
Object.assign(this, maintenanceWindowModule);
Object.assign(this, notificationModule);
Object.assign(this, settingsModule);
Object.assign(this, statusPageModule);
}
connect = async () => {
try { try {
const connectionString = const connectionString =
process.env.DB_CONNECTION_STRING || "mongodb://localhost:27017/uptime_db"; process.env.DB_CONNECTION_STRING || "mongodb://localhost:27017/uptime_db";
@@ -23,7 +95,7 @@ const connect = async () => {
} catch (error) { } catch (error) {
logger.error({ logger.error({
message: error.message, message: error.message,
service: SERVICE_NAME, service: this.SERVICE_NAME,
method: "connect", method: "connect",
stack: error.stack, stack: error.stack,
}); });
@@ -31,7 +103,7 @@ const connect = async () => {
} }
}; };
const disconnect = async () => { disconnect = async () => {
try { try {
logger.info({ message: "Disconnecting from MongoDB" }); logger.info({ message: "Disconnecting from MongoDB" });
await mongoose.disconnect(); await mongoose.disconnect();
@@ -40,196 +112,19 @@ const disconnect = async () => {
} catch (error) { } catch (error) {
logger.error({ logger.error({
message: error.message, message: error.message,
service: SERVICE_NAME, service: this.SERVICE_NAME,
method: "disconnect", method: "disconnect",
stack: error.stack, stack: error.stack,
}); });
} }
}; };
checkSuperadmin = async (req, res) => {
const checkSuperadmin = async (req, res) => {
try {
const superAdmin = await UserModel.findOne({ role: "superadmin" }); const superAdmin = await UserModel.findOne({ role: "superadmin" });
if (superAdmin !== null) { if (superAdmin !== null) {
return true; return true;
} }
return false; return false;
} catch (error) { };
throw error;
} }
};
//**************************************** export default MongoDB;
// User Operations
//****************************************
import {
insertUser,
getUserByEmail,
updateUser,
deleteUser,
deleteTeam,
deleteAllOtherUsers,
getAllUsers,
logoutUser,
} from "./modules/userModule.js";
//****************************************
// Invite Token Operations
//****************************************
import {
requestInviteToken,
getInviteToken,
getInviteTokenAndDelete,
} from "./modules/inviteModule.js";
//****************************************
// Recovery Operations
//****************************************
import {
requestRecoveryToken,
validateRecoveryToken,
resetPassword,
} from "./modules/recoveryModule.js";
//****************************************
// Monitors
//****************************************
import {
getAllMonitors,
getAllMonitorsWithUptimeStats,
getMonitorStatsById,
getMonitorById,
getMonitorsAndSummaryByTeamId,
getMonitorsByTeamId,
createMonitor,
deleteMonitor,
deleteAllMonitors,
deleteMonitorsByUserId,
editMonitor,
addDemoMonitors,
} from "./modules/monitorModule.js";
//****************************************
// Page Speed Checks
//****************************************
import {
createPageSpeedCheck,
deletePageSpeedChecksByMonitorId,
} from "./modules/pageSpeedCheckModule.js";
//****************************************
// Hardware Checks
//****************************************
import {
createHardwareCheck,
deleteHardwareChecksByMonitorId,
} from "./modules/hardwareCheckModule.js";
//****************************************
// Checks
//****************************************
import {
createCheck,
getChecksCount,
getChecks,
getTeamChecks,
deleteChecks,
deleteChecksByTeamId,
updateChecksTTL,
} from "./modules/checkModule.js";
//****************************************
// Maintenance Window
//****************************************
import {
createMaintenanceWindow,
getMaintenanceWindowById,
getMaintenanceWindowsByTeamId,
getMaintenanceWindowsByMonitorId,
deleteMaintenanceWindowById,
deleteMaintenanceWindowByMonitorId,
deleteMaintenanceWindowByUserId,
editMaintenanceWindowById,
} from "./modules/maintenanceWindowModule.js";
//****************************************
// Notifications
//****************************************
import {
createNotification,
getNotificationsByMonitorId,
deleteNotificationsByMonitorId,
} from "./modules/notificationModule.js";
//****************************************
// AppSettings
//****************************************
import { getAppSettings, updateAppSettings } from "./modules/settingsModule.js";
//****************************************
// Status Page
//****************************************
import { createStatusPage, getStatusPageByUrl } from "./modules/statusPageModule.js";
export default {
connect,
disconnect,
insertUser,
getUserByEmail,
updateUser,
deleteUser,
deleteTeam,
deleteAllOtherUsers,
getAllUsers,
logoutUser,
requestInviteToken,
getInviteToken,
getInviteTokenAndDelete,
requestRecoveryToken,
validateRecoveryToken,
resetPassword,
checkSuperadmin,
getAllMonitors,
getAllMonitorsWithUptimeStats,
getMonitorStatsById,
getMonitorById,
getMonitorsAndSummaryByTeamId,
getMonitorsByTeamId,
createMonitor,
deleteMonitor,
deleteAllMonitors,
editMonitor,
addDemoMonitors,
createCheck,
getChecksCount,
getChecks,
getTeamChecks,
deleteChecks,
deleteChecksByTeamId,
updateChecksTTL,
deleteMonitorsByUserId,
createPageSpeedCheck,
deletePageSpeedChecksByMonitorId,
createHardwareCheck,
deleteHardwareChecksByMonitorId,
createMaintenanceWindow,
getMaintenanceWindowsByTeamId,
getMaintenanceWindowById,
getMaintenanceWindowsByMonitorId,
deleteMaintenanceWindowById,
deleteMaintenanceWindowByMonitorId,
deleteMaintenanceWindowByUserId,
editMaintenanceWindowById,
createNotification,
getNotificationsByMonitorId,
deleteNotificationsByMonitorId,
getAppSettings,
updateAppSettings,
createStatusPage,
getStatusPageByUrl,
};
+141 -105
View File
@@ -8,16 +8,31 @@ import cors from "cors";
import logger from "./utils/logger.js"; import logger from "./utils/logger.js";
import { verifyJWT } from "./middleware/verifyJWT.js"; import { verifyJWT } from "./middleware/verifyJWT.js";
import { handleErrors } from "./middleware/handleErrors.js"; import { handleErrors } from "./middleware/handleErrors.js";
import authRouter from "./routes/authRoute.js";
import inviteRouter from "./routes/inviteRoute.js";
import monitorRouter from "./routes/monitorRoute.js";
import checkRouter from "./routes/checkRoute.js";
import maintenanceWindowRouter from "./routes/maintenanceWindowRoute.js";
import settingsRouter from "./routes/settingsRoute.js";
import statusPageRouter from "./routes/statusPageRoute.js";
import { fileURLToPath } from "url"; import { fileURLToPath } from "url";
import queueRouter from "./routes/queueRoute.js"; import AuthRoutes from "./routes/authRoute.js";
import AuthController from "./controllers/authController.js";
import InviteRoutes from "./routes/inviteRoute.js";
import InviteController from "./controllers/inviteController.js";
import MonitorRoutes from "./routes/monitorRoute.js";
import MonitorController from "./controllers/monitorController.js";
import CheckRoutes from "./routes/checkRoute.js";
import CheckController from "./controllers/checkController.js";
import MaintenanceWindowRoutes from "./routes/maintenanceWindowRoute.js";
import MaintenanceWindowController from "./controllers/maintenanceWindowController.js";
import SettingsRoutes from "./routes/settingsRoute.js";
import SettingsController from "./controllers/settingsController.js";
import StatusPageRoutes from "./routes/statusPageRoute.js";
import StatusPageController from "./controllers/statusPageController.js";
import QueueRoutes from "./routes/queueRoute.js";
import QueueController from "./controllers/queueController.js";
//JobQueue service and dependencies //JobQueue service and dependencies
import JobQueue from "./service/jobQueue.js"; import JobQueue from "./service/jobQueue.js";
@@ -41,102 +56,68 @@ import mjml2html from "mjml";
import SettingsService from "./service/settingsService.js"; import SettingsService from "./service/settingsService.js";
import AppSettings from "./db/models/AppSettings.js"; import AppSettings from "./db/models/AppSettings.js";
// Status Service and dependencies
import StatusService from "./service/statusService.js"; import StatusService from "./service/statusService.js";
// Notification Service and dependencies
import NotificationService from "./service/notificationService.js"; import NotificationService from "./service/notificationService.js";
import db from "./db/mongo/MongoDB.js"; // Service Registry
import ServiceRegistry from "./service/serviceRegistry.js";
import MongoDB from "./db/mongo/MongoDB.js";
const SERVICE_NAME = "Server"; const SERVICE_NAME = "Server";
const SHUTDOWN_TIMEOUT = 1000; const SHUTDOWN_TIMEOUT = 1000;
let isShuttingDown = false; let isShuttingDown = false;
const __filename = fileURLToPath(import.meta.url); const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename); const __dirname = path.dirname(__filename);
const openApiSpec = JSON.parse( const openApiSpec = JSON.parse(
fs.readFileSync(path.join(__dirname, "openapi.json"), "utf8") fs.readFileSync(path.join(__dirname, "openapi.json"), "utf8")
); );
let server;
const PORT = 5000; const PORT = 5000;
// Need to wrap server setup in a function to handle async nature of JobQueue const shutdown = async () => {
const startApp = async () => { if (isShuttingDown) {
const app = express(); return;
// middlewares
app.use(
cors()
//We will add configuration later
);
app.use(express.json());
app.use(helmet());
// Add db, jobQueue, emailService, and settingsService to request object for easy access
app.use((req, res, next) => {
req.db = db;
req.jobQueue = jobQueue;
req.emailService = emailService;
req.settingsService = settingsService;
next();
});
// Swagger UI
app.use("/api-docs", swaggerUi.serve, swaggerUi.setup(openApiSpec));
//routes
app.use("/api/v1/auth", authRouter);
app.use("/api/v1/settings", verifyJWT, settingsRouter);
app.use("/api/v1/invite", inviteRouter);
app.use("/api/v1/monitors", verifyJWT, monitorRouter);
app.use("/api/v1/checks", verifyJWT, checkRouter);
app.use("/api/v1/maintenance-window", verifyJWT, maintenanceWindowRouter);
app.use("/api/v1/queue", verifyJWT, queueRouter);
app.use("/api/v1/status-page", statusPageRouter);
app.use("/api/v1/dummy-data", async (req, res) => {
try {
const response = await axios.get(
"https://gist.githubusercontent.com/ajhollid/9afa39410c7bbf52cc905f285a2225bf/raw/429a231a3559ebc95f6f488ed2c766bd7d6f46e5/dummyData.json",
{
headers: {
"Content-Type": "application/json",
"Cache-Control": "no-cache",
},
}
);
return res.status(200).json(response.data);
} catch (error) {
return res.status(500).json({ message: error.message });
} }
isShuttingDown = true;
logger.info({ message: "Attempting graceful shutdown" });
setTimeout(() => {
logger.error({
message: "Could not shut down in time, forcing shutdown",
service: SERVICE_NAME,
method: "shutdown",
}); });
process.exit(1);
//health check }, SHUTDOWN_TIMEOUT);
app.use("/api/v1/healthy", (req, res) => {
try { try {
logger.info({ message: "Checking Health of the server." }); server.close();
return res.status(200).json({ message: "Healthy" }); await ServiceRegistry.get(JobQueue.SERVICE_NAME).obliterate();
await ServiceRegistry.get(MongoDB.SERVICE_NAME).disconnect();
logger.info({ message: "Graceful shutdown complete" });
process.exit(0);
} catch (error) { } catch (error) {
logger.error({ logger.error({
message: error.message, message: error.message,
service: SERVICE_NAME, service: SERVICE_NAME,
method: "healthCheck", method: "shutdown",
stack: error.stack, stack: error.stack,
}); });
return res.status(500).json({ message: error.message });
} }
}); };
// Need to wrap server setup in a function to handle async nature of JobQueue
const startApp = async () => {
const app = express();
/** // Create DB
* Error handler middleware const db = new MongoDB();
* Should be called last await db.connect();
*/
app.use(handleErrors);
// Create services // Create services
await db.connect();
const server = app.listen(PORT, () => {
logger.info({ message: `server started on port:${PORT}` });
});
const settingsService = new SettingsService(AppSettings); const settingsService = new SettingsService(AppSettings);
await settingsService.loadSettings(); await settingsService.loadSettings();
const emailService = new EmailService( const emailService = new EmailService(
@@ -162,39 +143,94 @@ const startApp = async () => {
Worker Worker
); );
const shutdown = async () => { // Register services
if (isShuttingDown) { ServiceRegistry.register(JobQueue.SERVICE_NAME, jobQueue);
return; ServiceRegistry.register(MongoDB.SERVICE_NAME, db);
} ServiceRegistry.register(SettingsService.SERVICE_NAME, settingsService);
isShuttingDown = true; ServiceRegistry.register(EmailService.SERVICE_NAME, emailService);
logger.info({ message: "Attempting graceful shutdown" }); ServiceRegistry.register(NetworkService.SERVICE_NAME, networkService);
setTimeout(() => { ServiceRegistry.register(StatusService.SERVICE_NAME, statusService);
logger.error({ ServiceRegistry.register(NotificationService.SERVICE_NAME, notificationService);
message: "Could not shut down in time, forcing shutdown", server = app.listen(PORT, () => {
service: SERVICE_NAME, logger.info({ message: `server started on port:${PORT}` });
method: "shutdown",
}); });
process.exit(1);
}, SHUTDOWN_TIMEOUT);
try {
server.close();
await jobQueue.obliterate();
await db.disconnect();
logger.info({ message: "Graceful shutdown complete" });
process.exit(0);
} catch (error) {
logger.error({
message: error.message,
service: SERVICE_NAME,
method: "shutdown",
stack: error.stack,
});
}
};
process.on("SIGUSR2", shutdown); process.on("SIGUSR2", shutdown);
process.on("SIGINT", shutdown); process.on("SIGINT", shutdown);
process.on("SIGTERM", shutdown); process.on("SIGTERM", shutdown);
//Create controllers
const authController = new AuthController(
ServiceRegistry.get(MongoDB.SERVICE_NAME),
ServiceRegistry.get(SettingsService.SERVICE_NAME),
ServiceRegistry.get(EmailService.SERVICE_NAME),
ServiceRegistry.get(JobQueue.SERVICE_NAME)
);
const monitorController = new MonitorController(
ServiceRegistry.get(MongoDB.SERVICE_NAME),
ServiceRegistry.get(SettingsService.SERVICE_NAME),
ServiceRegistry.get(JobQueue.SERVICE_NAME)
);
const settingsController = new SettingsController(
ServiceRegistry.get(MongoDB.SERVICE_NAME),
ServiceRegistry.get(SettingsService.SERVICE_NAME)
);
const checkController = new CheckController(
ServiceRegistry.get(MongoDB.SERVICE_NAME),
ServiceRegistry.get(SettingsService.SERVICE_NAME)
);
const inviteController = new InviteController(
ServiceRegistry.get(MongoDB.SERVICE_NAME),
ServiceRegistry.get(SettingsService.SERVICE_NAME),
ServiceRegistry.get(EmailService.SERVICE_NAME)
);
const maintenanceWindowController = new MaintenanceWindowController(
ServiceRegistry.get(MongoDB.SERVICE_NAME),
ServiceRegistry.get(SettingsService.SERVICE_NAME)
);
const queueController = new QueueController(ServiceRegistry.get(JobQueue.SERVICE_NAME));
const statusPageController = new StatusPageController(
ServiceRegistry.get(MongoDB.SERVICE_NAME)
);
//Create routes
const authRoutes = new AuthRoutes(authController);
const monitorRoutes = new MonitorRoutes(monitorController);
const settingsRoutes = new SettingsRoutes(settingsController);
const checkRoutes = new CheckRoutes(checkController);
const inviteRoutes = new InviteRoutes(inviteController);
const maintenanceWindowRoutes = new MaintenanceWindowRoutes(
maintenanceWindowController
);
const queueRoutes = new QueueRoutes(queueController);
const statusPageRoutes = new StatusPageRoutes(statusPageController);
// Middleware
app.use(
cors()
//We will add configuration later
);
app.use(express.json());
app.use(helmet());
// Swagger UI
app.use("/api-docs", swaggerUi.serve, swaggerUi.setup(openApiSpec));
//routes
app.use("/api/v1/auth", authRoutes.getRouter());
app.use("/api/v1/settings", verifyJWT, settingsRoutes.getRouter());
app.use("/api/v1/invite", inviteRoutes.getRouter());
app.use("/api/v1/monitors", verifyJWT, monitorRoutes.getRouter());
app.use("/api/v1/checks", verifyJWT, checkRoutes.getRouter());
app.use("/api/v1/maintenance-window", verifyJWT, maintenanceWindowRoutes.getRouter());
app.use("/api/v1/queue", verifyJWT, queueRoutes.getRouter());
app.use("/api/v1/status-page", statusPageRoutes.getRouter());
app.use(handleErrors);
}; };
startApp().catch((error) => { startApp().catch((error) => {
+6 -1
View File
@@ -1,6 +1,9 @@
import jwt from "jsonwebtoken"; import jwt from "jsonwebtoken";
const TOKEN_PREFIX = "Bearer "; const TOKEN_PREFIX = "Bearer ";
const SERVICE_NAME = "allowedRoles"; const SERVICE_NAME = "allowedRoles";
import ServiceRegistry from "../service/serviceRegistry.js";
import SettingsService from "../service/settingsService.js";
import { errorMessages } from "../utils/messages.js"; import { errorMessages } from "../utils/messages.js";
const isAllowed = (allowedRoles) => { const isAllowed = (allowedRoles) => {
@@ -27,7 +30,9 @@ const isAllowed = (allowedRoles) => {
// Parse the token // Parse the token
try { try {
const parsedToken = token.slice(TOKEN_PREFIX.length, token.length); const parsedToken = token.slice(TOKEN_PREFIX.length, token.length);
const { jwtSecret } = req.settingsService.getSettings(); const { jwtSecret } = ServiceRegistry.get(
SettingsService.SERVICE_NAME
).getSettings();
var decoded = jwt.verify(parsedToken, jwtSecret); var decoded = jwt.verify(parsedToken, jwtSecret);
const userRoles = decoded.role; const userRoles = decoded.role;
+6 -3
View File
@@ -1,6 +1,7 @@
import jwt from "jsonwebtoken"; import jwt from "jsonwebtoken";
import { errorMessages } from "../utils/messages.js"; import { errorMessages } from "../utils/messages.js";
import ServiceRegistry from "../service/serviceRegistry.js";
import SettingsService from "../service/settingsService.js";
const SERVICE_NAME = "verifyJWT"; const SERVICE_NAME = "verifyJWT";
const TOKEN_PREFIX = "Bearer "; const TOKEN_PREFIX = "Bearer ";
@@ -34,7 +35,7 @@ const verifyJWT = (req, res, next) => {
const parsedToken = token.slice(TOKEN_PREFIX.length, token.length); const parsedToken = token.slice(TOKEN_PREFIX.length, token.length);
// Verify the token's authenticity // Verify the token's authenticity
const { jwtSecret } = req.settingsService.getSettings(); const { jwtSecret } = ServiceRegistry.get(SettingsService.SERVICE_NAME).getSettings();
jwt.verify(parsedToken, jwtSecret, (err, decoded) => { jwt.verify(parsedToken, jwtSecret, (err, decoded) => {
if (err) { if (err) {
if (err.name === "TokenExpiredError") { if (err.name === "TokenExpiredError") {
@@ -67,7 +68,9 @@ function handleExpiredJwtToken(req, res, next) {
} }
// Verify refresh token // Verify refresh token
const { refreshTokenSecret } = req.settingsService.getSettings(); const { refreshTokenSecret } = ServiceRegistry.get(
SettingsService.SERVICE_NAME
).getSettings();
jwt.verify(refreshToken, refreshTokenSecret, (refreshErr, refreshDecoded) => { jwt.verify(refreshToken, refreshTokenSecret, (refreshErr, refreshDecoded) => {
if (refreshErr) { if (refreshErr) {
// Invalid or expired refresh token, trigger logout // Invalid or expired refresh token, trigger logout
+3 -1
View File
@@ -3,6 +3,8 @@ const logger = require("../utils/logger");
const SERVICE_NAME = "verifyAdmin"; const SERVICE_NAME = "verifyAdmin";
const TOKEN_PREFIX = "Bearer "; const TOKEN_PREFIX = "Bearer ";
const { errorMessages } = require("../utils/messages"); const { errorMessages } = require("../utils/messages");
import ServiceRegistry from "../service/serviceRegistry.js";
import SettingsService from "../service/settingsService.js";
/** /**
* Verifies the JWT token * Verifies the JWT token
* @function * @function
@@ -33,7 +35,7 @@ const verifySuperAdmin = (req, res, next) => {
const parsedToken = token.slice(TOKEN_PREFIX.length, token.length); const parsedToken = token.slice(TOKEN_PREFIX.length, token.length);
// verify admin role is present // verify admin role is present
const { jwtSecret } = req.settingsService.getSettings(); const { jwtSecret } = ServiceRegistry.get(SettingsService.SERVICE_NAME).getSettings();
jwt.verify(parsedToken, jwtSecret, (err, decoded) => { jwt.verify(parsedToken, jwtSecret, (err, decoded) => {
if (err) { if (err) {
+47 -25
View File
@@ -5,34 +5,56 @@ import { isAllowed } from "../middleware/isAllowed.js";
import multer from "multer"; import multer from "multer";
import User from "../db/models/User.js"; import User from "../db/models/User.js";
const router = Router();
const upload = multer(); const upload = multer();
import { class AuthRoutes {
registerUser, constructor(authController) {
loginUser, this.router = Router();
refreshAuthToken, this.authController = authController;
editUser, this.initRoutes();
requestRecovery, }
validateRecovery,
resetPassword,
checkSuperadminExists,
getAllUsers,
deleteUser,
} from "../controllers/authController.js";
//Auth routes initRoutes() {
router.post("/register", upload.single("profileImage"), registerUser); this.router.post(
router.post("/login", loginUser); "/register",
router.post("/refresh", refreshAuthToken); upload.single("profileImage"),
router.put("/user/:userId", upload.single("profileImage"), verifyJWT, editUser); this.authController.registerUser
router.get("/users/superadmin", checkSuperadminExists); );
router.get("/users", verifyJWT, isAllowed(["admin", "superadmin"]), getAllUsers); this.router.post("/login", this.authController.loginUser);
router.delete("/user/:userId", verifyJWT, verifyOwnership(User, "userId"), deleteUser); this.router.post("/refresh", this.authController.refreshAuthToken);
this.router.put(
"/user/:userId",
upload.single("profileImage"),
verifyJWT,
this.authController.editUser
);
this.router.get("/users/superadmin", this.authController.checkSuperadminExists);
this.router.get(
"/users",
verifyJWT,
isAllowed(["admin", "superadmin"]),
this.authController.getAllUsers
);
this.router.delete(
"/user/:userId",
verifyJWT,
verifyOwnership(User, "userId"),
this.authController.deleteUser
);
// Recovery routes // Recovery routes
router.post("/recovery/request", requestRecovery); this.router.post("/recovery/request", this.authController.requestRecovery);
router.post("/recovery/validate", validateRecovery); this.router.post("/recovery/validate", this.authController.validateRecovery);
router.post("/recovery/reset/", resetPassword); this.router.post("/recovery/reset/", this.authController.resetPassword);
}
export default router; getRouter() {
return this.router;
}
}
export default AuthRoutes;
+36 -16
View File
@@ -1,26 +1,46 @@
import { Router } from "express"; import { Router } from "express";
import {
createCheck,
getChecks,
deleteChecks,
getTeamChecks,
deleteChecksByTeamId,
updateChecksTTL,
} from "../controllers/checkController.js";
import { verifyOwnership } from "../middleware/verifyOwnership.js"; import { verifyOwnership } from "../middleware/verifyOwnership.js";
import { isAllowed } from "../middleware/isAllowed.js"; import { isAllowed } from "../middleware/isAllowed.js";
import Monitor from "../db/models/Monitor.js"; import Monitor from "../db/models/Monitor.js";
const router = Router(); class CheckRoutes {
constructor(checkController) {
this.router = Router();
this.checkController = checkController;
this.initRoutes();
}
router.get("/:monitorId", getChecks); initRoutes() {
router.post("/:monitorId", verifyOwnership(Monitor, "monitorId"), createCheck); this.router.get("/:monitorId", this.checkController.getChecks);
router.delete("/:monitorId", verifyOwnership(Monitor, "monitorId"), deleteChecks); this.router.post(
"/:monitorId",
verifyOwnership(Monitor, "monitorId"),
this.checkController.createCheck
);
this.router.delete(
"/:monitorId",
verifyOwnership(Monitor, "monitorId"),
this.checkController.deleteChecks
);
router.get("/team/:teamId", getTeamChecks); this.router.get("/team/:teamId", this.checkController.getTeamChecks);
router.delete("/team/:teamId", isAllowed(["admin", "superadmin"]), deleteChecksByTeamId); this.router.delete(
"/team/:teamId",
isAllowed(["admin", "superadmin"]),
this.checkController.deleteChecksByTeamId
);
router.put("/team/ttl", isAllowed(["admin", "superadmin"]), updateChecksTTL); this.router.put(
"/team/ttl",
isAllowed(["admin", "superadmin"]),
this.checkController.updateChecksTTL
);
}
export default router; getRouter() {
return this.router;
}
}
export default CheckRoutes;
+21 -8
View File
@@ -1,14 +1,27 @@
import { Router } from "express"; import { Router } from "express";
import { verifyJWT } from "../middleware/verifyJWT.js"; import { verifyJWT } from "../middleware/verifyJWT.js";
import { isAllowed } from "../middleware/isAllowed.js"; import { isAllowed } from "../middleware/isAllowed.js";
import {
issueInvitation,
inviteVerifyController,
} from "../controllers/inviteController.js";
const router = Router(); class InviteRoutes {
constructor(inviteController) {
this.router = Router();
this.inviteController = inviteController;
this.initRoutes();
}
router.post("/", isAllowed(["admin", "superadmin"]), verifyJWT, issueInvitation); initRoutes() {
router.post("/verify", inviteVerifyController); this.router.post(
"/",
isAllowed(["admin", "superadmin"]),
verifyJWT,
this.inviteController.issueInvitation
);
this.router.post("/verify", this.inviteController.inviteVerifyController);
}
export default router; getRouter() {
return this.router;
}
}
export default InviteRoutes;
+24 -18
View File
@@ -1,31 +1,37 @@
import { Router } from "express"; import { Router } from "express";
import {
createMaintenanceWindows,
getMaintenanceWindowById,
getMaintenanceWindowsByTeamId,
getMaintenanceWindowsByMonitorId,
deleteMaintenanceWindow,
editMaintenanceWindow,
} from "../controllers/maintenanceWindowController.js";
import { verifyOwnership } from "../middleware/verifyOwnership.js"; import { verifyOwnership } from "../middleware/verifyOwnership.js";
import Monitor from "../db/models/Monitor.js"; import Monitor from "../db/models/Monitor.js";
const router = Router(); class MaintenanceWindowRoutes {
constructor(maintenanceWindowController) {
this.router = Router();
this.maintenanceWindowController = maintenanceWindowController;
this.initRoutes();
}
initRoutes() {
this.router.post("/", this.maintenanceWindowController.createMaintenanceWindows);
router.post("/", createMaintenanceWindows); this.router.get(
router.get(
"/monitor/:monitorId", "/monitor/:monitorId",
verifyOwnership(Monitor, "monitorId"), verifyOwnership(Monitor, "monitorId"),
getMaintenanceWindowsByMonitorId this.maintenanceWindowController.getMaintenanceWindowsByMonitorId
); );
router.get("/team/", getMaintenanceWindowsByTeamId); this.router.get(
"/team/",
this.maintenanceWindowController.getMaintenanceWindowsByTeamId
);
router.get("/:id", getMaintenanceWindowById); this.router.get("/:id", this.maintenanceWindowController.getMaintenanceWindowById);
router.put("/:id", editMaintenanceWindow); this.router.put("/:id", this.maintenanceWindowController.editMaintenanceWindow);
router.delete("/:id", deleteMaintenanceWindow); this.router.delete("/:id", this.maintenanceWindowController.deleteMaintenanceWindow);
}
export default router; getRouter() {
return this.router;
}
}
export default MaintenanceWindowRoutes;
+62 -34
View File
@@ -1,51 +1,79 @@
import { Router } from "express"; import { Router } from "express";
import {
getAllMonitors,
getAllMonitorsWithUptimeStats,
getMonitorStatsById,
getMonitorCertificate,
getMonitorById,
getMonitorsAndSummaryByTeamId,
getMonitorsByTeamId,
createMonitor,
checkEndpointResolution,
deleteMonitor,
deleteAllMonitors,
editMonitor,
pauseMonitor,
addDemoMonitors,
} from "../controllers/monitorController.js";
import { isAllowed } from "../middleware/isAllowed.js"; import { isAllowed } from "../middleware/isAllowed.js";
import { fetchMonitorCertificate } from "../controllers/controllerUtils.js"; import { fetchMonitorCertificate } from "../controllers/controllerUtils.js";
const router = Router(); class MonitorRoutes {
constructor(monitorController) {
this.router = Router();
this.monitorController = monitorController;
this.initRoutes();
}
router.get("/", getAllMonitors); initRoutes() {
router.get("/uptime", getAllMonitorsWithUptimeStats); this.router.get("/", this.monitorController.getAllMonitors);
router.get("/stats/:monitorId", getMonitorStatsById); this.router.get("/uptime", this.monitorController.getAllMonitorsWithUptimeStats);
router.get("/certificate/:monitorId", (req, res, next) => { this.router.get("/stats/:monitorId", this.monitorController.getMonitorStatsById);
getMonitorCertificate(req, res, next, fetchMonitorCertificate); this.router.get("/certificate/:monitorId", (req, res, next) => {
this.monitorController.getMonitorCertificate(
req,
res,
next,
fetchMonitorCertificate
);
}); });
router.get("/:monitorId", getMonitorById); this.router.get("/:monitorId", this.monitorController.getMonitorById);
router.get("/team/summary/:teamId", getMonitorsAndSummaryByTeamId); this.router.get(
router.get("/team/:teamId", getMonitorsByTeamId); "/team/summary/:teamId",
this.monitorController.getMonitorsAndSummaryByTeamId
);
this.router.get("/team/:teamId", this.monitorController.getMonitorsByTeamId);
router.get( this.router.get(
"/resolution/url", "/resolution/url",
isAllowed(["admin", "superadmin"]), isAllowed(["admin", "superadmin"]),
checkEndpointResolution this.monitorController.checkEndpointResolution
); );
router.delete("/:monitorId", isAllowed(["admin", "superadmin"]), deleteMonitor); this.router.delete(
"/:monitorId",
isAllowed(["admin", "superadmin"]),
this.monitorController.deleteMonitor
);
router.post("/", isAllowed(["admin", "superadmin"]), createMonitor); this.router.post(
"/",
isAllowed(["admin", "superadmin"]),
this.monitorController.createMonitor
);
router.put("/:monitorId", isAllowed(["admin", "superadmin"]), editMonitor); this.router.put(
"/:monitorId",
isAllowed(["admin", "superadmin"]),
this.monitorController.editMonitor
);
router.delete("/", isAllowed(["superadmin"]), deleteAllMonitors); this.router.delete(
"/",
isAllowed(["superadmin"]),
this.monitorController.deleteAllMonitors
);
router.post("/pause/:monitorId", isAllowed(["admin", "superadmin"]), pauseMonitor); this.router.post(
"/pause/:monitorId",
isAllowed(["admin", "superadmin"]),
this.monitorController.pauseMonitor
);
router.post("/demo", isAllowed(["admin", "superadmin"]), addDemoMonitors); this.router.post(
"/demo",
isAllowed(["admin", "superadmin"]),
this.monitorController.addDemoMonitors
);
}
export default router; getRouter() {
return this.router;
}
}
export default MonitorRoutes;
+17 -17
View File
@@ -1,21 +1,21 @@
import { Router } from "express"; import { Router } from "express";
import {
getMetrics,
getJobs,
addJob,
obliterateQueue,
} from "../controllers/queueController.js";
const router = Router(); class QueueRoutes {
router.get("/metrics", getMetrics); constructor(queueController) {
this.router = Router();
this.queueController = queueController;
this.initRoutes();
}
initRoutes() {
this.router.get("/metrics", this.queueController.getMetrics);
this.router.get("/jobs", this.queueController.getJobs);
this.router.post("/jobs", this.queueController.addJob);
this.router.post("/obliterate", this.queueController.obliterateQueue);
}
// Get Jobs getRouter() {
router.get("/jobs", getJobs); return this.router;
}
}
// Add Job export default QueueRoutes;
router.post("/jobs", addJob);
// Obliterate Queue
router.post("/obliterate", obliterateQueue);
export default router;
+20 -5
View File
@@ -1,10 +1,25 @@
import { Router } from "express"; import { Router } from "express";
import { getAppSettings, updateAppSettings } from "../controllers/settingsController.js";
import { isAllowed } from "../middleware/isAllowed.js"; import { isAllowed } from "../middleware/isAllowed.js";
const router = Router(); class SettingsRoutes {
constructor(settingsController) {
this.router = Router();
this.settingsController = settingsController;
this.initRoutes();
}
router.get("/", getAppSettings); initRoutes() {
router.put("/", isAllowed(["superadmin"]), updateAppSettings); this.router.get("/", this.settingsController.getAppSettings);
this.router.put(
"/",
isAllowed(["superadmin"]),
this.settingsController.updateAppSettings
);
}
export default router; getRouter() {
return this.router;
}
}
export default SettingsRoutes;
+21 -10
View File
@@ -1,11 +1,22 @@
import express from "express"; import { Router } from "express";
import { verifyJWT } from "../middleware/verifyJWT.js";
import {
createStatusPage,
getStatusPageByUrl,
} from "../controllers/statusPageController.js";
const router = express.Router();
router.get("/:url", getStatusPageByUrl); import { verifyJWT } from "../middleware/verifyJWT.js";
router.post("/:url", verifyJWT, createStatusPage);
export default router; class StatusPageRoutes {
constructor(statusPageController) {
this.router = Router();
this.statusPageController = statusPageController;
this.initRoutes();
}
initRoutes() {
this.router.get("/:url", this.statusPageController.getStatusPageByUrl);
this.router.post("/:url", verifyJWT, this.statusPageController.createStatusPage);
}
getRouter() {
return this.router;
}
}
export default StatusPageRoutes;
+1
View File
@@ -10,6 +10,7 @@ const SERVICE_NAME = "EmailService";
* Represents an email service that can load templates, build, and send emails. * Represents an email service that can load templates, build, and send emails.
*/ */
class EmailService { class EmailService {
static SERVICE_NAME = SERVICE_NAME;
/** /**
* Constructs an instance of the EmailService, initializing template loaders and the email transporter. * Constructs an instance of the EmailService, initializing template loaders and the email transporter.
* @param {Object} settingsService - The settings service to get email configuration. * @param {Object} settingsService - The settings service to get email configuration.
+3 -1
View File
@@ -1,7 +1,8 @@
const QUEUE_NAME = "monitors"; const QUEUE_NAME = "monitors";
const JOBS_PER_WORKER = 5; const JOBS_PER_WORKER = 5;
import { errorMessages, successMessages } from "../utils/messages.js";
const SERVICE_NAME = "JobQueue"; const SERVICE_NAME = "JobQueue";
import { errorMessages, successMessages } from "../utils/messages.js";
/** /**
* JobQueue * JobQueue
* *
@@ -10,6 +11,7 @@ const SERVICE_NAME = "JobQueue";
* It scales the number of workers based on the number of jobs/worker * It scales the number of workers based on the number of jobs/worker
*/ */
class JobQueue { class JobQueue {
static SERVICE_NAME = SERVICE_NAME;
/** /**
* @class JobQueue * @class JobQueue
* @classdesc Manages job queue and workers. * @classdesc Manages job queue and workers.
+4 -1
View File
@@ -1,4 +1,6 @@
import { errorMessages, successMessages } from "../utils/messages.js"; import { errorMessages, successMessages } from "../utils/messages.js";
const SERVICE_NAME = "NetworkService";
/** /**
* Constructs a new NetworkService instance. * Constructs a new NetworkService instance.
* *
@@ -8,13 +10,14 @@ import { errorMessages, successMessages } from "../utils/messages.js";
* @param {Object} http - The HTTP utility for network operations. * @param {Object} http - The HTTP utility for network operations.
*/ */
class NetworkService { class NetworkService {
static SERVICE_NAME = SERVICE_NAME;
constructor(axios, ping, logger, http, Docker) { constructor(axios, ping, logger, http, Docker) {
this.TYPE_PING = "ping"; this.TYPE_PING = "ping";
this.TYPE_HTTP = "http"; this.TYPE_HTTP = "http";
this.TYPE_PAGESPEED = "pagespeed"; this.TYPE_PAGESPEED = "pagespeed";
this.TYPE_HARDWARE = "hardware"; this.TYPE_HARDWARE = "hardware";
this.TYPE_DOCKER = "docker"; this.TYPE_DOCKER = "docker";
this.SERVICE_NAME = "NetworkService"; this.SERVICE_NAME = SERVICE_NAME;
this.NETWORK_ERROR = 5000; this.NETWORK_ERROR = 5000;
this.PING_ERROR = 5001; this.PING_ERROR = 5001;
this.axios = axios; this.axios = axios;
+4 -1
View File
@@ -1,4 +1,7 @@
const SERVICE_NAME = "NotificationService";
class NotificationService { class NotificationService {
static SERVICE_NAME = SERVICE_NAME;
/** /**
* Creates an instance of NotificationService. * Creates an instance of NotificationService.
* *
@@ -7,7 +10,7 @@ class NotificationService {
* @param {Object} logger - The logger instance for logging activities. * @param {Object} logger - The logger instance for logging activities.
*/ */
constructor(emailService, db, logger) { constructor(emailService, db, logger) {
this.SERVICE_NAME = "NotificationService"; this.SERVICE_NAME = SERVICE_NAME;
this.emailService = emailService; this.emailService = emailService;
this.db = db; this.db = db;
this.logger = logger; this.logger = logger;
+35
View File
@@ -0,0 +1,35 @@
const SERVICE_NAME = "ServiceRegistry";
import logger from "../utils/logger.js";
class ServiceRegistry {
static SERVICE_NAME = SERVICE_NAME;
constructor() {
this.services = {};
}
register(name, service) {
logger.info({
message: `Registering service ${name}`,
service: SERVICE_NAME,
method: "register",
});
this.services[name] = service;
}
get(name) {
if (!this.services[name]) {
logger.error({
message: `Service ${name} is not registered`,
service: SERVICE_NAME,
method: "get",
});
throw new Error(`Service ${name} is not registered`);
}
return this.services[name];
}
listServices() {
return Object.keys(this.services);
}
}
export default new ServiceRegistry();
+1
View File
@@ -25,6 +25,7 @@ const envConfig = {
* from the database if they are not set in the environment. * from the database if they are not set in the environment.
*/ */
class SettingsService { class SettingsService {
static SERVICE_NAME = SERVICE_NAME;
/** /**
* Constructs a new SettingsService * Constructs a new SettingsService
* @constructor * @constructor
+4 -1
View File
@@ -1,4 +1,7 @@
const SERVICE_NAME = "StatusService";
class StatusService { class StatusService {
static SERVICE_NAME = SERVICE_NAME;
/** /**
* Creates an instance of StatusService. * Creates an instance of StatusService.
* *
@@ -8,7 +11,7 @@ class StatusService {
constructor(db, logger) { constructor(db, logger) {
this.db = db; this.db = db;
this.logger = logger; this.logger = logger;
this.SERVICE_NAME = "StatusService"; this.SERVICE_NAME = SERVICE_NAME;
} }
getStatusString = (status) => { getStatusString = (status) => {