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
+1961 -1839

No files matched your search

+471 -470
View File
@@ -17,500 +17,501 @@ import { handleValidationError, handleError } from "./controllerUtils.js";
const SERVICE_NAME = "authController"; const SERVICE_NAME = "authController";
dotenv.config(); dotenv.config();
/** class AuthController {
* Creates and returns JWT token with an arbitrary payload constructor(db, settingsService, emailService, jobQueue) {
* @function this.db = db;
* @param {Object} payload this.settingsService = settingsService;
* @param {tokenType} typeOfToken - Whether to generate refresh token with long TTL or access token with short TTL. this.emailService = emailService;
* @param {Object} appSettings this.jobQueue = jobQueue;
* @returns {String}
* @throws {Error}
*/
const issueToken = (payload, typeOfToken, appSettings) => {
try {
const tokenTTL =
typeOfToken === tokenType.REFRESH_TOKEN
? (appSettings?.refreshTokenTTL ?? "7d")
: (appSettings?.jwtTTL ?? "2h");
const tokenSecret =
typeOfToken === tokenType.REFRESH_TOKEN
? appSettings?.refreshTokenSecret
: appSettings?.jwtSecret;
const payloadData = typeOfToken === tokenType.REFRESH_TOKEN ? {} : payload;
return jwt.sign(payloadData, tokenSecret, { expiresIn: tokenTTL });
} catch (error) {
throw handleError(error, SERVICE_NAME, "issueToken");
} }
};
/** /**
* Registers a new user. If the user is the first account, a JWT secret is created. If not, an invite token is required. * Creates and returns JWT token with an arbitrary payload
* @async * @function
* @param {Object} req - The Express request object. * @param {Object} payload
* @property {Object} req.body - The body of the request. * @param {tokenType} typeOfToken - Whether to generate refresh token with long TTL or access token with short TTL.
* @property {string} req.body.inviteToken - The invite token for registration. * @param {Object} appSettings
* @property {Object} req.file - The file object for the user's profile image. * @returns {String}
* @param {Object} res - The Express response object. * @throws {Error}
* @param {function} next - The next middleware function. */
* @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. issueToken = (payload, typeOfToken, appSettings) => {
* @throws {Error} If there is an error during the process, especially if there is a validation error (422). try {
*/ const tokenTTL =
const registerUser = async (req, res, next) => { typeOfToken === tokenType.REFRESH_TOKEN
// joi validation ? (appSettings?.refreshTokenTTL ?? "7d")
try { : (appSettings?.jwtTTL ?? "2h");
await registrationBodyValidation.validateAsync(req.body); const tokenSecret =
} catch (error) { typeOfToken === tokenType.REFRESH_TOKEN
const validationError = handleValidationError(error, SERVICE_NAME); ? appSettings?.refreshTokenSecret
next(validationError); : appSettings?.jwtSecret;
return; const payloadData = typeOfToken === tokenType.REFRESH_TOKEN ? {} : payload;
}
// Create a new user return jwt.sign(payloadData, tokenSecret, { expiresIn: tokenTTL });
try { } catch (error) {
const { inviteToken } = req.body; throw handleError(error, SERVICE_NAME, "issueToken");
// If superAdmin exists, a token should be attached to all further register requests
const superAdminExists = await req.db.checkSuperadmin(req, res);
if (superAdminExists) {
await req.db.getInviteTokenAndDelete(inviteToken);
} else {
// This is the first account, create JWT secret to use if one is not supplied by env
const jwtSecret = crypto.randomBytes(64).toString("hex");
await req.db.updateAppSettings({ jwtSecret });
} }
};
const newUser = await req.db.insertUser({ ...req.body }, req.file); /**
logger.info({ * Registers a new user. If the user is the first account, a JWT secret is created. If not, an invite token is required.
message: successMessages.AUTH_CREATE_USER, * @async
service: SERVICE_NAME, * @param {Object} req - The Express request object.
details: newUser._id, * @property {Object} req.body - The body of the request.
}); * @property {string} req.body.inviteToken - The invite token for registration.
* @property {Object} req.file - The file object for the user's profile image.
* @param {Object} res - The Express response object.
* @param {function} next - The next middleware function.
* @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).
*/
registerUser = async (req, res, next) => {
try {
await registrationBodyValidation.validateAsync(req.body);
} catch (error) {
const validationError = handleValidationError(error, SERVICE_NAME);
next(validationError);
return;
}
// Create a new user
try {
const { inviteToken } = req.body;
// If superAdmin exists, a token should be attached to all further register requests
const superAdminExists = await this.db.checkSuperadmin(req, res);
if (superAdminExists) {
await this.db.getInviteTokenAndDelete(inviteToken);
} else {
// This is the first account, create JWT secret to use if one is not supplied by env
const jwtSecret = crypto.randomBytes(64).toString("hex");
await this.db.updateAppSettings({ jwtSecret });
}
const userForToken = { ...newUser._doc }; const newUser = await this.db.insertUser({ ...req.body }, req.file);
delete userForToken.profileImage; logger.info({
delete userForToken.avatarImage; message: successMessages.AUTH_CREATE_USER,
service: SERVICE_NAME,
const appSettings = await req.settingsService.getSettings(); details: newUser._id,
const token = issueToken(userForToken, tokenType.ACCESS_TOKEN, appSettings);
const refreshToken = issueToken({}, tokenType.REFRESH_TOKEN, appSettings);
req.emailService
.buildAndSendEmail(
"welcomeEmailTemplate",
{ name: newUser.firstName },
newUser.email,
"Welcome to Uptime Monitor"
)
.catch((error) => {
logger.error({
message: error.message,
service: SERVICE_NAME,
method: "registerUser",
stack: error.stack,
});
}); });
return res.status(200).json({ const userForToken = { ...newUser._doc };
success: true, delete userForToken.profileImage;
msg: successMessages.AUTH_CREATE_USER, delete userForToken.avatarImage;
data: { user: newUser, token: token, refreshToken: refreshToken },
});
} catch (error) {
next(handleError(error, SERVICE_NAME, "registerController"));
}
};
/** const appSettings = await this.settingsService.getSettings();
* Logs in a user by validating the user's credentials and issuing a JWT token.
* @async
* @param {Object} req - The Express request object.
* @property {Object} req.body - The body of the request.
* @property {string} req.body.email - The email of the user.
* @property {string} req.body.password - The password of the user.
* @param {Object} res - The Express response object.
* @param {function} next - The next middleware function.
* @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.
*/
const loginUser = async (req, res, next) => {
try {
await loginValidation.validateAsync(req.body);
} catch (error) {
const validationError = handleValidationError(error, SERVICE_NAME);
next(validationError);
return;
}
try {
const { email, password } = req.body;
// Check if user exists const token = this.issueToken(userForToken, tokenType.ACCESS_TOKEN, appSettings);
const user = await req.db.getUserByEmail(email); const refreshToken = this.issueToken({}, tokenType.REFRESH_TOKEN, appSettings);
// Compare password this.emailService
const match = await user.comparePassword(password); .buildAndSendEmail(
if (match !== true) { "welcomeEmailTemplate",
next(new Error(errorMessages.AUTH_INCORRECT_PASSWORD)); { name: newUser.firstName },
newUser.email,
"Welcome to Uptime Monitor"
)
.catch((error) => {
logger.error({
message: error.message,
service: SERVICE_NAME,
method: "registerUser",
stack: error.stack,
});
});
return res.status(200).json({
success: true,
msg: successMessages.AUTH_CREATE_USER,
data: { user: newUser, token: token, refreshToken: refreshToken },
});
} catch (error) {
next(handleError(error, SERVICE_NAME, "registerController"));
}
};
/**
* Logs in a user by validating the user's credentials and issuing a JWT token.
* @async
* @param {Object} req - The Express request object.
* @property {Object} req.body - The body of the request.
* @property {string} req.body.email - The email of the user.
* @property {string} req.body.password - The password of the user.
* @param {Object} res - The Express response object.
* @param {function} next - The next middleware function.
* @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.
*/
loginUser = async (req, res, next) => {
try {
await loginValidation.validateAsync(req.body);
} catch (error) {
const validationError = handleValidationError(error, SERVICE_NAME);
next(validationError);
return;
}
try {
const { email, password } = req.body;
// Check if user exists
const user = await this.db.getUserByEmail(email);
// Compare password
const match = await user.comparePassword(password);
if (match !== true) {
next(new Error(errorMessages.AUTH_INCORRECT_PASSWORD));
return;
}
// Remove password from user object. Should this be abstracted to DB layer?
const userWithoutPassword = { ...user._doc };
delete userWithoutPassword.password;
delete userWithoutPassword.avatarImage;
// Happy path, return token
const appSettings = await this.settingsService.getSettings();
const token = this.issueToken(
userWithoutPassword,
tokenType.ACCESS_TOKEN,
appSettings
);
const refreshToken = this.issueToken({}, tokenType.REFRESH_TOKEN, appSettings);
// reset avatar image
userWithoutPassword.avatarImage = user.avatarImage;
return res.status(200).json({
success: true,
msg: successMessages.AUTH_LOGIN_USER,
data: { user: userWithoutPassword, token: token, refreshToken: refreshToken },
});
} catch (error) {
next(handleError(error, SERVICE_NAME, "loginUser"));
}
};
/**
* Generates new auth token if the refresh token is valid
* @async
* @param {Express.Request} req - The Express request object.
* @property {Object} req.headers - The parameter of the request.
* @param {Express.Response} res - The Express response object.
* @param {function} next - The next middleware function.
* @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
*/
refreshAuthToken = async (req, res, next) => {
try {
// check for refreshToken
const refreshToken = req.headers["x-refresh-token"];
if (!refreshToken) {
// No refresh token provided
const error = new Error(errorMessages.NO_REFRESH_TOKEN);
error.status = 401;
error.service = SERVICE_NAME;
error.method = "refreshAuthToken";
return next(error);
}
// Verify refresh token
const appSettings = await this.settingsService.getSettings();
const { refreshTokenSecret } = appSettings;
jwt.verify(refreshToken, refreshTokenSecret, async (refreshErr, refreshDecoded) => {
if (refreshErr) {
// Invalid or expired refresh token, trigger logout
const errorMessage =
refreshErr.name === "TokenExpiredError"
? errorMessages.EXPIRED_REFRESH_TOKEN
: errorMessages.INVALID_REFRESH_TOKEN;
const error = new Error(errorMessage);
error.status = 401;
error.service = SERVICE_NAME;
return next(error);
}
});
// Refresh token is valid and unexpired, generate new access token
const oldAuthToken = getTokenFromHeaders(req.headers);
const { jwtSecret } = await this.settingsService.getSettings();
const payloadData = jwt.verify(oldAuthToken, jwtSecret, { ignoreExpiration: true });
// delete old token related data
delete payloadData.iat;
delete payloadData.exp;
const newAuthToken = this.issueToken(
payloadData,
tokenType.ACCESS_TOKEN,
appSettings
);
return res.status(200).json({
success: true,
msg: successMessages.AUTH_TOKEN_REFRESHED,
data: { user: payloadData, token: newAuthToken, refreshToken: refreshToken },
});
} catch (error) {
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.
* @async
* @param {Object} req - The Express request object.
* @property {Object} req.params - The parameters of the request.
* @property {string} req.params.userId - The ID of the user to be edited.
* @property {Object} req.body - The body of the request.
* @property {string} req.body.password - The current password of the user.
* @property {string} req.body.newPassword - The new password of the user.
* @param {Object} res - The Express response object.
* @param {function} next - The next middleware function.
* @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).
*/
editUser = async (req, res, next) => {
try {
await editUserParamValidation.validateAsync(req.params);
await editUserBodyValidation.validateAsync(req.body);
} catch (error) {
const validationError = handleValidationError(error, SERVICE_NAME);
next(validationError);
return; return;
} }
// Remove password from user object. Should this be abstracted to DB layer? // TODO is this neccessary any longer? Verify ownership middleware should handle this
const userWithoutPassword = { ...user._doc }; if (req.params.userId !== req.user._id.toString()) {
delete userWithoutPassword.password; const error = new Error(errorMessages.AUTH_UNAUTHORIZED);
delete userWithoutPassword.avatarImage;
// Happy path, return token
const appSettings = await req.settingsService.getSettings();
const token = issueToken(userWithoutPassword, tokenType.ACCESS_TOKEN, appSettings);
const refreshToken = issueToken({}, tokenType.REFRESH_TOKEN, appSettings);
// reset avatar image
userWithoutPassword.avatarImage = user.avatarImage;
return res.status(200).json({
success: true,
msg: successMessages.AUTH_LOGIN_USER,
data: { user: userWithoutPassword, token: token, refreshToken: refreshToken },
});
} catch (error) {
next(handleError(error, SERVICE_NAME, "loginUser"));
}
};
/**
* Generates new auth token if the refresh token is valid
* @async
* @param {Express.Request} req - The Express request object.
* @property {Object} req.headers - The parameter of the request.
* @param {Express.Response} res - The Express response object.
* @param {function} next - The next middleware function.
* @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
*/
const refreshAuthToken = async (req, res, next) => {
try {
// check for refreshToken
const refreshToken = req.headers["x-refresh-token"];
if (!refreshToken) {
// No refresh token provided
const error = new Error(errorMessages.NO_REFRESH_TOKEN);
error.status = 401; error.status = 401;
error.service = SERVICE_NAME; error.service = SERVICE_NAME;
error.method = "refreshAuthToken"; next(error);
return next(error); return;
} }
// Verify refresh token try {
const appSettings = await req.settingsService.getSettings(); // Change Password check
const { refreshTokenSecret } = appSettings; if (req.body.password && req.body.newPassword) {
jwt.verify(refreshToken, refreshTokenSecret, async (refreshErr, refreshDecoded) => { // Get token from headers
if (refreshErr) { const token = getTokenFromHeaders(req.headers);
// Invalid or expired refresh token, trigger logout // Get email from token
const errorMessage = const { jwtSecret } = this.settingsService.getSettings();
refreshErr.name === "TokenExpiredError" const { email } = jwt.verify(token, jwtSecret);
? errorMessages.EXPIRED_REFRESH_TOKEN // Add user email to body for DB operation
: errorMessages.INVALID_REFRESH_TOKEN; req.body.email = email;
const error = new Error(errorMessage); // Get user
error.status = 401; const user = await this.db.getUserByEmail(email);
error.service = SERVICE_NAME; // Compare passwords
return next(error); const match = await user.comparePassword(req.body.password);
// If not a match, throw a 403
// 403 instead of 401 to avoid triggering axios interceptor
if (!match) {
const error = new Error(errorMessages.AUTH_INCORRECT_PASSWORD);
error.status = 403;
next(error);
return;
}
// If a match, update the password
req.body.password = req.body.newPassword;
} }
});
// Refresh token is valid and unexpired, generate new access token
const oldAuthToken = getTokenFromHeaders(req.headers);
const { jwtSecret } = await req.settingsService.getSettings();
const payloadData = jwt.verify(oldAuthToken, jwtSecret, { ignoreExpiration: true });
// delete old token related data
delete payloadData.iat;
delete payloadData.exp;
const newAuthToken = issueToken(payloadData, tokenType.ACCESS_TOKEN, appSettings);
return res.status(200).json({ const updatedUser = await this.db.updateUser(req, res);
success: true, return res.status(200).json({
msg: successMessages.AUTH_TOKEN_REFRESHED, success: true,
data: { user: payloadData, token: newAuthToken, refreshToken: refreshToken }, msg: successMessages.AUTH_UPDATE_USER,
}); data: updatedUser,
} catch (error) { });
next(handleError(error, SERVICE_NAME, "refreshAuthToken")); } catch (error) {
} next(handleError(error, SERVICE_NAME, "userEditController"));
}; }
};
/** /**
* Edits a user's information. If the user wants to change their password, the current password is checked before updating to the new password. * Checks if a superadmin account exists in the database.
* @async * @async
* @param {Object} req - The Express request object. * @param {Object} req - The Express request object.
* @property {Object} req.params - The parameters of the request. * @param {Object} res - The Express response object.
* @property {string} req.params.userId - The ID of the user to be edited. * @param {function} next - The next middleware function.
* @property {Object} req.body - The body of the request. * @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.
* @property {string} req.body.password - The current password of the user. * @throws {Error} If there is an error during the process.
* @property {string} req.body.newPassword - The new password of the user. */
* @param {Object} res - The Express response object. checkSuperadminExists = async (req, res, next) => {
* @param {function} next - The next middleware function. try {
* @returns {Object} The response object with a success status, a message indicating the update of the user, and the updated user data. const superAdminExists = await this.db.checkSuperadmin(req, res);
* @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). return res.status(200).json({
*/ success: true,
const editUser = async (req, res, next) => { msg: successMessages.AUTH_ADMIN_EXISTS,
try { data: superAdminExists,
await editUserParamValidation.validateAsync(req.params); });
await editUserBodyValidation.validateAsync(req.body); } catch (error) {
} catch (error) { next(handleError(error, SERVICE_NAME, "checkSuperadminController"));
const validationError = handleValidationError(error, SERVICE_NAME); }
next(validationError); };
return; /**
} * Requests a recovery token for a user. The user's email is validated and a recovery token is created and sent via email.
* @async
// TODO is this neccessary any longer? Verify ownership middleware should handle this * @param {Object} req - The Express request object.
if (req.params.userId !== req.user._id.toString()) { * @property {Object} req.body - The body of the request.
const error = new Error(errorMessages.AUTH_UNAUTHORIZED); * @property {string} req.body.email - The email of the user requesting recovery.
error.status = 401; * @param {Object} res - The Express response object.
error.service = SERVICE_NAME; * @param {function} next - The next middleware function.
next(error); * @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.
return; * @throws {Error} If there is an error during the process, especially if there is a validation error (422).
} */
requestRecovery = async (req, res, next) => {
try { try {
// Change Password check await recoveryValidation.validateAsync(req.body);
if (req.body.password && req.body.newPassword) { } catch (error) {
// Get token from headers const validationError = handleValidationError(error, SERVICE_NAME);
const token = getTokenFromHeaders(req.headers); next(validationError);
// Get email from token return;
const { jwtSecret } = req.settingsService.getSettings();
const { email } = jwt.verify(token, jwtSecret);
// Add user email to body for DB operation
req.body.email = email;
// Get user
const user = await req.db.getUserByEmail(email);
// Compare passwords
const match = await user.comparePassword(req.body.password);
// If not a match, throw a 403
// 403 instead of 401 to avoid triggering axios interceptor
if (!match) {
const error = new Error(errorMessages.AUTH_INCORRECT_PASSWORD);
error.status = 403;
next(error);
return;
}
// If a match, update the password
req.body.password = req.body.newPassword;
} }
const updatedUser = await req.db.updateUser(req, res); try {
return res.status(200).json({ const { email } = req.body;
success: true, const user = await this.db.getUserByEmail(email);
msg: successMessages.AUTH_UPDATE_USER, const recoveryToken = await this.db.requestRecoveryToken(req, res);
data: updatedUser, const name = user.firstName;
}); const { clientHost } = this.settingsService.getSettings();
} catch (error) { const url = `${clientHost}/set-new-password/${recoveryToken.token}`;
next(handleError(error, SERVICE_NAME, "userEditController")); const msgId = await this.emailService.buildAndSendEmail(
} "passwordResetTemplate",
}; {
name,
/** email,
* Checks if a superadmin account exists in the database. url,
* @async },
* @param {Object} req - The Express request object.
* @param {Object} res - The Express response object.
* @param {function} next - The next middleware function.
* @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.
*/
const checkSuperadminExists = async (req, res, next) => {
try {
const superAdminExists = await req.db.checkSuperadmin(req, res);
return res.status(200).json({
success: true,
msg: successMessages.AUTH_ADMIN_EXISTS,
data: superAdminExists,
});
} catch (error) {
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.
* @async
* @param {Object} req - The Express request object.
* @property {Object} req.body - The body of the request.
* @property {string} req.body.email - The email of the user requesting recovery.
* @param {Object} res - The Express response object.
* @param {function} next - The next middleware function.
* @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).
*/
const requestRecovery = async (req, res, next) => {
try {
await recoveryValidation.validateAsync(req.body);
} catch (error) {
const validationError = handleValidationError(error, SERVICE_NAME);
next(validationError);
return;
}
try {
const { email } = req.body;
const user = await req.db.getUserByEmail(email);
const recoveryToken = await req.db.requestRecoveryToken(req, res);
const name = user.firstName;
const { clientHost } = req.settingsService.getSettings();
const url = `${clientHost}/set-new-password/${recoveryToken.token}`;
const msgId = await req.emailService.buildAndSendEmail(
"passwordResetTemplate",
{
name,
email, email,
url, "Checkmate Password Reset"
}, );
email,
"Checkmate Password Reset"
);
return res.status(200).json({ return res.status(200).json({
success: true, success: true,
msg: successMessages.AUTH_CREATE_RECOVERY_TOKEN, msg: successMessages.AUTH_CREATE_RECOVERY_TOKEN,
data: msgId, data: msgId,
}); });
} catch (error) { } catch (error) {
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 * @param {Object} req - The Express request object.
* @param {Object} req - The Express request object. * @property {Object} req.body - The body of the request.
* @property {Object} req.body - The body of the request. * @property {string} req.body.token - The recovery token to be validated.
* @property {string} req.body.token - The recovery token to be validated. * @param {Object} res - The Express response object.
* @param {Object} res - The Express response object. * @param {function} next - The next middleware function.
* @param {function} next - The next middleware function. * @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). */
*/ validateRecovery = async (req, res, next) => {
const validateRecovery = async (req, res, next) => { try {
try { await recoveryTokenValidation.validateAsync(req.body);
await recoveryTokenValidation.validateAsync(req.body); } catch (error) {
} catch (error) { const validationError = handleValidationError(error, SERVICE_NAME);
const validationError = handleValidationError(error, SERVICE_NAME); next(validationError);
next(validationError); return;
return;
}
try {
await req.db.validateRecoveryToken(req, res);
return res.status(200).json({
success: true,
msg: successMessages.AUTH_VERIFY_RECOVERY_TOKEN,
});
} catch (error) {
next(handleError(error, SERVICE_NAME, "validateRecoveryTokenController"));
}
};
/**
* Resets a user's password. The new password is validated and if valid, the user's password is updated in the database and a new JWT token is issued.
* @async
* @param {Object} req - The Express request object.
* @property {Object} req.body - The body of the request.
* @property {string} req.body.token - The recovery token.
* @property {string} req.body.password - The new password of the user.
* @param {Object} res - The Express response object.
* @param {function} next - The next middleware function.
* @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).
*/
const resetPassword = async (req, res, next) => {
try {
await newPasswordValidation.validateAsync(req.body);
} catch (error) {
const validationError = handleValidationError(error, SERVICE_NAME);
next(validationError);
return;
}
try {
const user = await req.db.resetPassword(req, res);
const appSettings = await req.settingsService.getSettings();
const token = issueToken(user._doc, tokenType.ACCESS_TOKEN, appSettings);
res.status(200).json({
success: true,
msg: successMessages.AUTH_RESET_PASSWORD,
data: { user, token },
});
} catch (error) {
next(handleError(error, SERVICE_NAME, "resetPasswordController"));
}
};
/**
* Deletes a user and all associated monitors, checks, and alerts.
*
* @param {Object} req - The request object.
* @param {Object} res - The response object.
* @param {Function} next - The next middleware function.
* @returns {Object} The response object with success status and message.
* @throws {Error} If user validation fails or user is not found in the database.
*/
const deleteUser = async (req, res, next) => {
try {
const token = getTokenFromHeaders(req.headers);
const decodedToken = jwt.decode(token);
const { email } = decodedToken;
// Check if the user exists
const user = await req.db.getUserByEmail(email);
// 1. Find all the monitors associated with the team ID if superadmin
const result = await req.db.getMonitorsByTeamId({
params: { teamId: user.teamId },
});
if (user.role.includes("superadmin")) {
//2. Remove all jobs, delete checks and alerts
result?.monitors.length > 0 &&
(await Promise.all(
result.monitors.map(async (monitor) => {
await req.jobQueue.deleteJob(monitor);
await req.db.deleteChecks(monitor._id);
await req.db.deletePageSpeedChecksByMonitorId(monitor._id);
await req.db.deleteNotificationsByMonitorId(monitor._id);
})
));
// 3. Delete team
await req.db.deleteTeam(user.teamId);
// 4. Delete all other team members
await req.db.deleteAllOtherUsers();
// 5. Delete each monitor
await req.db.deleteMonitorsByUserId(user._id);
} }
// 6. Delete the user by id
await req.db.deleteUser(user._id);
return res.status(200).json({
success: true,
msg: successMessages.AUTH_DELETE_USER,
});
} catch (error) {
next(handleError(error, SERVICE_NAME, "deleteUserController"));
}
};
const getAllUsers = async (req, res, next) => { try {
try { await this.db.validateRecoveryToken(req, res);
const allUsers = await req.db.getAllUsers(req, res); return res.status(200).json({
res.status(200).json({ success: true, msg: "Got all users", data: allUsers }); success: true,
} catch (error) { msg: successMessages.AUTH_VERIFY_RECOVERY_TOKEN,
next(handleError(error, SERVICE_NAME, "getAllUsersController")); });
} } catch (error) {
}; next(handleError(error, SERVICE_NAME, "validateRecoveryTokenController"));
}
};
export { /**
issueToken, * Resets a user's password. The new password is validated and if valid, the user's password is updated in the database and a new JWT token is issued.
registerUser, * @async
loginUser, * @param {Object} req - The Express request object.
refreshAuthToken, * @property {Object} req.body - The body of the request.
editUser, * @property {string} req.body.token - The recovery token.
checkSuperadminExists, * @property {string} req.body.password - The new password of the user.
requestRecovery, * @param {Object} res - The Express response object.
validateRecovery, * @param {function} next - The next middleware function.
resetPassword, * @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.
deleteUser, * @throws {Error} If there is an error during the process, especially if there is a validation error (422).
getAllUsers, */
}; resetPassword = async (req, res, next) => {
try {
await newPasswordValidation.validateAsync(req.body);
} catch (error) {
const validationError = handleValidationError(error, SERVICE_NAME);
next(validationError);
return;
}
try {
const user = await this.db.resetPassword(req, res);
const appSettings = await this.settingsService.getSettings();
const token = this.issueToken(user._doc, tokenType.ACCESS_TOKEN, appSettings);
res.status(200).json({
success: true,
msg: successMessages.AUTH_RESET_PASSWORD,
data: { user, token },
});
} catch (error) {
next(handleError(error, SERVICE_NAME, "resetPasswordController"));
}
};
/**
* Deletes a user and all associated monitors, checks, and alerts.
*
* @param {Object} req - The request object.
* @param {Object} res - The response object.
* @param {Function} next - The next middleware function.
* @returns {Object} The response object with success status and message.
* @throws {Error} If user validation fails or user is not found in the database.
*/
deleteUser = async (req, res, next) => {
try {
const token = getTokenFromHeaders(req.headers);
const decodedToken = jwt.decode(token);
const { email } = decodedToken;
// Check if the user exists
const user = await this.db.getUserByEmail(email);
// 1. Find all the monitors associated with the team ID if superadmin
const result = await this.db.getMonitorsByTeamId({
params: { teamId: user.teamId },
});
if (user.role.includes("superadmin")) {
//2. Remove all jobs, delete checks and alerts
result?.monitors.length > 0 &&
(await Promise.all(
result.monitors.map(async (monitor) => {
await this.jobQueue.deleteJob(monitor);
await this.db.deleteChecks(monitor._id);
await this.db.deletePageSpeedChecksByMonitorId(monitor._id);
await this.db.deleteNotificationsByMonitorId(monitor._id);
})
));
// 3. Delete team
await this.db.deleteTeam(user.teamId);
// 4. Delete all other team members
await this.db.deleteAllOtherUsers();
// 5. Delete each monitor
await this.db.deleteMonitorsByUserId(user._id);
}
// 6. Delete the user by id
await this.db.deleteUser(user._id);
return res.status(200).json({
success: true,
msg: successMessages.AUTH_DELETE_USER,
});
} catch (error) {
next(handleError(error, SERVICE_NAME, "deleteUserController"));
}
};
getAllUsers = async (req, res, next) => {
try {
const allUsers = await this.db.getAllUsers(req, res);
res.status(200).json({ success: true, msg: "Got all users", data: allUsers });
} catch (error) {
next(handleError(error, SERVICE_NAME, "getAllUsersController"));
}
};
}
export default AuthController;
+122 -123
View File
@@ -16,139 +16,138 @@ import { handleValidationError, handleError } from "./controllerUtils.js";
const SERVICE_NAME = "checkController"; const SERVICE_NAME = "checkController";
const createCheck = async (req, res, next) => { class CheckController {
try { constructor(db, settingsService) {
await createCheckParamValidation.validateAsync(req.params); this.db = db;
await createCheckBodyValidation.validateAsync(req.body); this.settingsService = settingsService;
} catch (error) {
next(handleValidationError(error, SERVICE_NAME));
return;
} }
try { createCheck = async (req, res, next) => {
const checkData = { ...req.body }; try {
const check = await req.db.createCheck(checkData); await createCheckParamValidation.validateAsync(req.params);
return res await createCheckBodyValidation.validateAsync(req.body);
.status(200) } catch (error) {
.json({ success: true, msg: successMessages.CHECK_CREATE, data: check }); next(handleValidationError(error, SERVICE_NAME));
} catch (error) { return;
next(handleError(error, SERVICE_NAME, "createCheck")); }
}
};
const getChecks = async (req, res, next) => { try {
try { const checkData = { ...req.body };
await getChecksParamValidation.validateAsync(req.params); const check = await this.db.createCheck(checkData);
await getChecksQueryValidation.validateAsync(req.query); return res
} catch (error) { .status(200)
next(handleValidationError(error, SERVICE_NAME)); .json({ success: true, msg: successMessages.CHECK_CREATE, data: check });
return; } catch (error) {
} next(handleError(error, SERVICE_NAME, "createCheck"));
}
};
try { getChecks = async (req, res, next) => {
const checks = await req.db.getChecks(req); try {
const checksCount = await req.db.getChecksCount(req); await getChecksParamValidation.validateAsync(req.params);
return res.status(200).json({ await getChecksQueryValidation.validateAsync(req.query);
success: true, } catch (error) {
msg: successMessages.CHECK_GET, next(handleValidationError(error, SERVICE_NAME));
data: { checksCount, checks }, return;
}); }
} catch (error) {
next(handleError(error, SERVICE_NAME, "getChecks"));
}
};
const getTeamChecks = async (req, res, next) => { try {
try { const checks = await this.db.getChecks(req);
await getTeamChecksParamValidation.validateAsync(req.params); const checksCount = await this.db.getChecksCount(req);
await getTeamChecksQueryValidation.validateAsync(req.query); return res.status(200).json({
} catch (error) { success: true,
next(handleValidationError(error, SERVICE_NAME)); msg: successMessages.CHECK_GET,
return; data: { checksCount, checks },
} });
try { } catch (error) {
const checkData = await req.db.getTeamChecks(req); next(handleError(error, SERVICE_NAME, "getChecks"));
return res.status(200).json({ }
success: true, };
msg: successMessages.CHECK_GET,
data: checkData,
});
} catch (error) {
next(handleError(error, SERVICE_NAME, "getTeamChecks"));
}
};
const deleteChecks = async (req, res, next) => { getTeamChecks = async (req, res, next) => {
try { try {
await deleteChecksParamValidation.validateAsync(req.params); await getTeamChecksParamValidation.validateAsync(req.params);
} catch (error) { await getTeamChecksQueryValidation.validateAsync(req.query);
next(handleValidationError(error, SERVICE_NAME)); } catch (error) {
return; next(handleValidationError(error, SERVICE_NAME));
} return;
}
try {
const checkData = await this.db.getTeamChecks(req);
return res.status(200).json({
success: true,
msg: successMessages.CHECK_GET,
data: checkData,
});
} catch (error) {
next(handleError(error, SERVICE_NAME, "getTeamChecks"));
}
};
try { deleteChecks = async (req, res, next) => {
const deletedCount = await req.db.deleteChecks(req.params.monitorId); try {
return res.status(200).json({ await deleteChecksParamValidation.validateAsync(req.params);
success: true, } catch (error) {
msg: successMessages.CHECK_DELETE, next(handleValidationError(error, SERVICE_NAME));
data: { deletedCount }, return;
}); }
} catch (error) {
next(handleError(error, SERVICE_NAME, "deleteChecks"));
}
};
const deleteChecksByTeamId = async (req, res, next) => { try {
try { const deletedCount = await this.db.deleteChecks(req.params.monitorId);
await deleteChecksByTeamIdParamValidation.validateAsync(req.params); return res.status(200).json({
} catch (error) { success: true,
next(handleValidationError(error, SERVICE_NAME)); msg: successMessages.CHECK_DELETE,
return; data: { deletedCount },
} });
} catch (error) {
next(handleError(error, SERVICE_NAME, "deleteChecks"));
}
};
try { deleteChecksByTeamId = async (req, res, next) => {
const deletedCount = await req.db.deleteChecksByTeamId(req.params.teamId); try {
return res.status(200).json({ await deleteChecksByTeamIdParamValidation.validateAsync(req.params);
success: true, } catch (error) {
msg: successMessages.CHECK_DELETE, next(handleValidationError(error, SERVICE_NAME));
data: { deletedCount }, return;
}); }
} catch (error) {
next(handleError(error, SERVICE_NAME, "deleteChecksByTeamId"));
}
};
const updateChecksTTL = async (req, res, next) => { try {
const SECONDS_PER_DAY = 86400; const deletedCount = await this.db.deleteChecksByTeamId(req.params.teamId);
return res.status(200).json({
success: true,
msg: successMessages.CHECK_DELETE,
data: { deletedCount },
});
} catch (error) {
next(handleError(error, SERVICE_NAME, "deleteChecksByTeamId"));
}
};
try { updateChecksTTL = async (req, res, next) => {
await updateChecksTTLBodyValidation.validateAsync(req.body); const SECONDS_PER_DAY = 86400;
} catch (error) {
next(handleValidationError(error, SERVICE_NAME));
return;
}
try { try {
// Get user's teamId await updateChecksTTLBodyValidation.validateAsync(req.body);
const token = getTokenFromHeaders(req.headers); } catch (error) {
const { jwtSecret } = req.settingsService.getSettings(); next(handleValidationError(error, SERVICE_NAME));
const { teamId } = jwt.verify(token, jwtSecret); return;
const ttl = parseInt(req.body.ttl, 10) * SECONDS_PER_DAY; }
await req.db.updateChecksTTL(teamId, ttl);
return res.status(200).json({
success: true,
msg: successMessages.CHECK_UPDATE_TTL,
});
} catch (error) {
next(handleError(error, SERVICE_NAME, "updateTTL"));
}
};
export { try {
createCheck, // Get user's teamId
getChecks, const token = getTokenFromHeaders(req.headers);
getTeamChecks, const { jwtSecret } = this.settingsService.getSettings();
deleteChecks, const { teamId } = jwt.verify(token, jwtSecret);
deleteChecksByTeamId, const ttl = parseInt(req.body.ttl, 10) * SECONDS_PER_DAY;
updateChecksTTL, await this.db.updateChecksTTL(teamId, ttl);
}; return res.status(200).json({
success: true,
msg: successMessages.CHECK_UPDATE_TTL,
});
} catch (error) {
next(handleError(error, SERVICE_NAME, "updateTTL"));
}
};
}
export default CheckController;
+74 -67
View File
@@ -4,83 +4,90 @@ 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 {
* Issues an invitation to a new user. Only admins can invite new users. An invitation token is created and sent via email. constructor(db, settingsService, emailService) {
* @async this.db = db;
* @param {Object} req - The Express request object. this.settingsService = settingsService;
* @property {Object} req.headers - The headers of the request. this.emailService = emailService;
* @property {string} req.headers.authorization - The authorization header containing the JWT token. }
* @property {Object} req.body - The body of the request.
* @property {string} req.body.email - The email of the user to be invited. /**
* @param {Object} res - The Express response object. * Issues an invitation to a new user. Only admins can invite new users. An invitation token is created and sent via email.
* @param {function} next - The next middleware function. * @async
* @returns {Object} The response object with a success status, a message indicating the sending of the invitation, and the invitation token. * @param {Object} req - The Express request object.
* @throws {Error} If there is an error during the process, especially if there is a validation error (422). * @property {Object} req.headers - The headers of the request.
*/ * @property {string} req.headers.authorization - The authorization header containing the JWT token.
const issueInvitation = async (req, res, next) => { * @property {Object} req.body - The body of the request.
try { * @property {string} req.body.email - The email of the user to be invited.
// Only admins can invite * @param {Object} res - The Express response object.
const token = getTokenFromHeaders(req.headers); * @param {function} next - The next middleware function.
const { role, firstname, teamId } = jwt.decode(token); * @returns {Object} The response object with a success status, a message indicating the sending of the invitation, and the invitation token.
req.body.teamId = teamId; * @throws {Error} If there is an error during the process, especially if there is a validation error (422).
*/
issueInvitation = async (req, res, next) => {
try { try {
await inviteRoleValidation.validateAsync({ roles: role }); // Only admins can invite
await inviteBodyValidation.validateAsync(req.body); const token = getTokenFromHeaders(req.headers);
const { role, firstname, teamId } = jwt.decode(token);
req.body.teamId = teamId;
try {
await inviteRoleValidation.validateAsync({ roles: role });
await inviteBodyValidation.validateAsync(req.body);
} catch (error) {
next(handleValidationError(error, SERVICE_NAME));
return;
}
const inviteToken = await this.db.requestInviteToken({ ...req.body });
const { clientHost } = this.settingsService.getSettings();
this.emailService
.buildAndSendEmail(
"employeeActivationTemplate",
{
name: firstname,
link: `${clientHost}/register/${inviteToken.token}`,
},
req.body.email,
"Welcome to Uptime Monitor"
)
.catch((error) => {
logger.error({
message: error.message,
service: SERVICE_NAME,
method: "issueInvitation",
stack: error.stack,
});
});
return res
.status(200)
.json({ success: true, msg: "Invite sent", data: inviteToken });
} catch (error) {
next(handleError(error, SERVICE_NAME, "inviteController"));
}
};
inviteVerifyController = async (req, res, next) => {
try {
await inviteVerificationBodyValidation.validateAsync(req.body);
} catch (error) { } catch (error) {
next(handleValidationError(error, SERVICE_NAME)); next(handleValidationError(error, SERVICE_NAME));
return; return;
} }
const inviteToken = await req.db.requestInviteToken({ ...req.body }); try {
const { clientHost } = req.settingsService.getSettings(); const invite = await this.db.getInviteToken(req.body.token);
req.emailService res.status(200).json({ status: "success", msg: "Invite verified", data: invite });
.buildAndSendEmail( } catch (error) {
"employeeActivationTemplate", next(handleError(error, SERVICE_NAME, "inviteVerifyController"));
{ }
name: firstname, };
link: `${clientHost}/register/${inviteToken.token}`, }
},
req.body.email,
"Welcome to Uptime Monitor"
)
.catch((error) => {
logger.error({
message: error.message,
service: SERVICE_NAME,
method: "issueInvitation",
stack: error.stack,
});
});
return res.status(200).json({ success: true, msg: "Invite sent", data: inviteToken }); export default InviteController;
} catch (error) {
next(handleError(error, SERVICE_NAME, "inviteController"));
}
};
const inviteVerifyController = async (req, res, next) => {
try {
await inviteVerificationBodyValidation.validateAsync(req.body);
} catch (error) {
next(handleValidationError(error, SERVICE_NAME));
return;
}
try {
const invite = await req.db.getInviteToken(req.body.token);
res.status(200).json({ status: "success", msg: "Invite verified", data: invite });
} catch (error) {
next(handleError(error, SERVICE_NAME, "inviteVerifyController"));
}
};
export { issueInvitation, inviteVerifyController };
+139 -140
View File
@@ -11,157 +11,156 @@ 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 {
try { constructor(db, settingsService) {
await createMaintenanceWindowBodyValidation.validateAsync(req.body); this.db = db;
} catch (error) { this.settingsService = settingsService;
next(handleValidationError(error, SERVICE_NAME));
return;
} }
try {
const token = getTokenFromHeaders(req.headers); createMaintenanceWindows = async (req, res, next) => {
const { jwtSecret } = req.settingsService.getSettings(); try {
const { teamId } = jwt.verify(token, jwtSecret); await createMaintenanceWindowBodyValidation.validateAsync(req.body);
const monitorIds = req.body.monitors; } catch (error) {
const dbTransactions = monitorIds.map((monitorId) => { next(handleValidationError(error, SERVICE_NAME));
return req.db.createMaintenanceWindow({ return;
teamId, }
monitorId, try {
name: req.body.name, const token = getTokenFromHeaders(req.headers);
active: req.body.active ? req.body.active : true, const { jwtSecret } = this.settingsService.getSettings();
repeat: req.body.repeat, const { teamId } = jwt.verify(token, jwtSecret);
start: req.body.start, const monitorIds = req.body.monitors;
end: req.body.end, const dbTransactions = monitorIds.map((monitorId) => {
return this.db.createMaintenanceWindow({
teamId,
monitorId,
name: req.body.name,
active: req.body.active ? req.body.active : true,
repeat: req.body.repeat,
start: req.body.start,
end: req.body.end,
});
}); });
}); await Promise.all(dbTransactions);
await Promise.all(dbTransactions); return res.status(201).json({
return res.status(201).json({ success: true,
success: true, msg: successMessages.MAINTENANCE_WINDOW_CREATE,
msg: successMessages.MAINTENANCE_WINDOW_CREATE, });
}); } catch (error) {
} catch (error) { next(handleError(error, SERVICE_NAME, "createMaintenanceWindow"));
next(handleError(error, SERVICE_NAME, "createMaintenanceWindow")); }
} };
};
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) {
next(handleValidationError(error, SERVICE_NAME)); next(handleValidationError(error, SERVICE_NAME));
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,
data: maintenanceWindow, data: maintenanceWindow,
}); });
} catch (error) { } catch (error) {
next(handleError(error, SERVICE_NAME, "getMaintenanceWindowById")); next(handleError(error, SERVICE_NAME, "getMaintenanceWindowById"));
} }
}; };
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) {
next(handleValidationError(error, SERVICE_NAME)); next(handleValidationError(error, SERVICE_NAME));
return; return;
} }
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
); );
return res.status(200).json({ return res.status(200).json({
success: true, success: true,
msg: successMessages.MAINTENANCE_WINDOW_GET_BY_TEAM, msg: successMessages.MAINTENANCE_WINDOW_GET_BY_TEAM,
data: maintenanceWindows, data: maintenanceWindows,
}); });
} catch (error) { } catch (error) {
next(handleError(error, SERVICE_NAME, "getMaintenanceWindowsByUserId")); next(handleError(error, SERVICE_NAME, "getMaintenanceWindowsByUserId"));
} }
}; };
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) {
next(handleValidationError(error, SERVICE_NAME)); next(handleValidationError(error, SERVICE_NAME));
return; return;
} }
try { try {
const maintenanceWindows = await req.db.getMaintenanceWindowsByMonitorId( const maintenanceWindows = await this.db.getMaintenanceWindowsByMonitorId(
req.params.monitorId req.params.monitorId
); );
return res.status(200).json({ return res.status(200).json({
success: true, success: true,
msg: successMessages.MAINTENANCE_WINDOW_GET_BY_USER, msg: successMessages.MAINTENANCE_WINDOW_GET_BY_USER,
data: maintenanceWindows, data: maintenanceWindows,
}); });
} catch (error) { } catch (error) {
next(handleError(error, SERVICE_NAME, "getMaintenanceWindowsByMonitorId")); next(handleError(error, SERVICE_NAME, "getMaintenanceWindowsByMonitorId"));
} }
}; };
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) {
next(handleValidationError(error, SERVICE_NAME)); next(handleValidationError(error, SERVICE_NAME));
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,
}); });
} catch (error) { } catch (error) {
next(handleError(error, SERVICE_NAME, "deleteMaintenanceWindow")); next(handleError(error, SERVICE_NAME, "deleteMaintenanceWindow"));
} }
}; };
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);
} catch (error) { } catch (error) {
next(handleValidationError(error, SERVICE_NAME)); next(handleValidationError(error, SERVICE_NAME));
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
); );
return res.status(200).json({ return res.status(200).json({
success: true, success: true,
msg: successMessages.MAINTENANCE_WINDOW_EDIT, msg: successMessages.MAINTENANCE_WINDOW_EDIT,
data: editedMaintenanceWindow, data: editedMaintenanceWindow,
}); });
} catch (error) { } catch (error) {
next(handleError(error, SERVICE_NAME, "editMaintenanceWindow")); next(handleError(error, SERVICE_NAME, "editMaintenanceWindow"));
} }
}; };
}
export { export default MaintenanceWindowController;
createMaintenanceWindows,
getMaintenanceWindowById,
getMaintenanceWindowsByTeamId,
getMaintenanceWindowsByMonitorId,
deleteMaintenanceWindow,
editMaintenanceWindow,
};
+470 -477
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,510 +23,503 @@ import axios from "axios";
const SERVICE_NAME = "monitorController"; const SERVICE_NAME = "monitorController";
/** class MonitorController {
* Returns all monitors constructor(db, settingsService, jobQueue) {
* @async this.db = db;
* @param {Express.Request} req this.settingsService = settingsService;
* @param {Express.Response} res this.jobQueue = jobQueue;
* @param {function} next
* @returns {Promise<Express.Response>}
* @throws {Error}
*/
const getAllMonitors = async (req, res, next) => {
try {
const monitors = await req.db.getAllMonitors();
return res.status(200).json({
success: true,
msg: successMessages.MONITOR_GET_ALL,
data: monitors,
});
} catch (error) {
next(handleError(error, SERVICE_NAME, "getAllMonitors"));
}
};
/**
* Returns all monitors with uptime stats for 1,7,30, and 90 days
* @async
* @param {Express.Request} req
* @param {Express.Response} res
* @param {function} next
* @returns {Promise<Express.Response>}
* @throws {Error}
*/
const getAllMonitorsWithUptimeStats = async (req, res, next) => {
try {
const monitors = await req.db.getAllMonitorsWithUptimeStats();
return res.status(200).json({
success: true,
msg: successMessages.MONITOR_GET_ALL,
data: monitors,
});
} catch (error) {
next(handleError(error, SERVICE_NAME, "getAllMonitorsWithUptimeStats"));
}
};
/**
* Returns monitor stats for monitor with matching ID
* @async
* @param {Express.Request} req
* @param {Express.Response} res
* @param {function} next
* @returns {Promise<Express.Response>}
* @throws {Error}
*/
const getMonitorStatsById = async (req, res, next) => {
try {
await getMonitorStatsByIdParamValidation.validateAsync(req.params);
await getMonitorStatsByIdQueryValidation.validateAsync(req.query);
} catch (error) {
next(handleValidationError(error, SERVICE_NAME));
return;
} }
try { /**
const monitorStats = await req.db.getMonitorStatsById(req); * Returns all monitors
return res.status(200).json({ * @async
success: true, * @param {Express.Request} req
msg: successMessages.MONITOR_STATS_BY_ID, * @param {Express.Response} res
data: monitorStats, * @param {function} next
}); * @returns {Promise<Express.Response>}
} catch (error) { * @throws {Error}
next(handleError(error, SERVICE_NAME, "getMonitorStatsById")); */
} getAllMonitors = async (req, res, next) => {
}; try {
const monitors = await this.db.getAllMonitors();
return res.status(200).json({
success: true,
msg: successMessages.MONITOR_GET_ALL,
data: monitors,
});
} catch (error) {
next(handleError(error, SERVICE_NAME, "getAllMonitors"));
}
};
const getMonitorCertificate = async (req, res, next, fetchMonitorCertificate) => { /**
try { * Returns all monitors with uptime stats for 1,7,30, and 90 days
await getCertificateParamValidation.validateAsync(req.params); * @async
} catch (error) { * @param {Express.Request} req
next(handleValidationError(error, SERVICE_NAME)); * @param {Express.Response} res
} * @param {function} next
* @returns {Promise<Express.Response>}
* @throws {Error}
*/
getAllMonitorsWithUptimeStats = async (req, res, next) => {
try {
const monitors = await this.db.getAllMonitorsWithUptimeStats();
return res.status(200).json({
success: true,
msg: successMessages.MONITOR_GET_ALL,
data: monitors,
});
} catch (error) {
next(handleError(error, SERVICE_NAME, "getAllMonitorsWithUptimeStats"));
}
};
try { /**
const { monitorId } = req.params; * Returns monitor stats for monitor with matching ID
const monitor = await req.db.getMonitorById(monitorId); * @async
const certificate = await fetchMonitorCertificate(sslChecker, monitor); * @param {Express.Request} req
* @param {Express.Response} res
* @param {function} next
* @returns {Promise<Express.Response>}
* @throws {Error}
*/
getMonitorStatsById = async (req, res, next) => {
try {
await getMonitorStatsByIdParamValidation.validateAsync(req.params);
await getMonitorStatsByIdQueryValidation.validateAsync(req.query);
} catch (error) {
next(handleValidationError(error, SERVICE_NAME));
return;
}
return res.status(200).json({ try {
success: true, const monitorStats = await this.db.getMonitorStatsById(req);
msg: successMessages.MONITOR_CERTIFICATE, return res.status(200).json({
data: { success: true,
certificateDate: new Date(certificate.validTo), msg: successMessages.MONITOR_STATS_BY_ID,
}, data: monitorStats,
}); });
} catch (error) { } catch (error) {
next(handleError(error, SERVICE_NAME, "getMonitorCertificate")); next(handleError(error, SERVICE_NAME, "getMonitorStatsById"));
} }
}; };
/** getMonitorCertificate = async (req, res, next, fetchMonitorCertificate) => {
* Retrieves a monitor by its ID. try {
* @async await getCertificateParamValidation.validateAsync(req.params);
* @param {Object} req - The Express request object. } catch (error) {
* @property {Object} req.params - The parameters of the request. next(handleValidationError(error, SERVICE_NAME));
* @property {string} req.params.monitorId - The ID of the monitor to be retrieved. }
* @param {Object} res - The Express response object.
* @param {function} next - The next middleware function.
* @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).
*/
const getMonitorById = async (req, res, next) => {
try {
await getMonitorByIdParamValidation.validateAsync(req.params);
await getMonitorByIdQueryValidation.validateAsync(req.query);
} catch (error) {
next(handleValidationError(error, SERVICE_NAME));
return;
}
try { try {
const monitor = await req.db.getMonitorById(req.params.monitorId); const { monitorId } = req.params;
return res.status(200).json({ const monitor = await this.db.getMonitorById(monitorId);
success: true, const certificate = await fetchMonitorCertificate(sslChecker, monitor);
msg: successMessages.MONITOR_GET_BY_ID,
data: monitor,
});
} catch (error) {
next(handleError(error, SERVICE_NAME, "getMonitorById"));
}
};
/** return res.status(200).json({
* Retrieves all monitors and a summary for a team based on the team ID. success: true,
* @async msg: successMessages.MONITOR_CERTIFICATE,
* @param {Object} req - The Express request object. data: {
* @property {Object} req.params - The parameters of the request. certificateDate: new Date(certificate.validTo),
* @property {string} req.params.teamId - The ID of the team. },
* @property {Object} req.query - The query parameters of the request. });
* @property {string} req.query.type - The type of the request. } catch (error) {
* @param {Object} res - The Express response object. next(handleError(error, SERVICE_NAME, "getMonitorCertificate"));
* @param {function} next - The next middleware function. }
* @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).
*/
const getMonitorsAndSummaryByTeamId = async (req, res, next) => {
try {
await getMonitorsAndSummaryByTeamIdParamValidation.validateAsync(req.params);
await getMonitorsAndSummaryByTeamIdQueryValidation.validateAsync(req.query);
} catch (error) {
next(handleValidationError(error, SERVICE_NAME));
return;
}
try { /**
const { teamId } = req.params; * Retrieves a monitor by its ID.
const { type } = req.query; * @async
const monitorsSummary = await req.db.getMonitorsAndSummaryByTeamId(teamId, type); * @param {Object} req - The Express request object.
return res.status(200).json({ * @property {Object} req.params - The parameters of the request.
success: true, * @property {string} req.params.monitorId - The ID of the monitor to be retrieved.
msg: successMessages.MONITOR_GET_BY_USER_ID(teamId), * @param {Object} res - The Express response object.
data: monitorsSummary, * @param {function} next - The next middleware function.
}); * @returns {Object} The response object with a success status, a message, and the retrieved monitor data.
} catch (error) { * @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).
next(handleError(error, SERVICE_NAME, "getMonitorsAndSummaryByTeamId")); */
} getMonitorById = async (req, res, next) => {
}; try {
await getMonitorByIdParamValidation.validateAsync(req.params);
await getMonitorByIdQueryValidation.validateAsync(req.query);
} catch (error) {
next(handleValidationError(error, SERVICE_NAME));
return;
}
/** try {
* Retrieves all monitors associated with a team by the team's ID. const monitor = await this.db.getMonitorById(req.params.monitorId);
* @async return res.status(200).json({
* @param {Object} req - The Express request object. success: true,
* @property {Object} req.params - The parameters of the request. msg: successMessages.MONITOR_GET_BY_ID,
* @property {string} req.params.teamId - The ID of the team. data: monitor,
* @property {Object} req.query - The query parameters of the request. });
* @param {Object} res - The Express response object. } catch (error) {
* @param {function} next - The next middleware function. next(handleError(error, SERVICE_NAME, "getMonitorById"));
* @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). };
*/
const getMonitorsByTeamId = async (req, res, next) => {
try {
await getMonitorsByTeamIdValidation.validateAsync(req.params);
await getMonitorsByTeamIdQueryValidation.validateAsync(req.query);
} catch (error) {
next(handleValidationError(error, SERVICE_NAME));
return;
}
try { /**
const teamId = req.params.teamId; * Retrieves all monitors and a summary for a team based on the team ID.
const monitors = await req.db.getMonitorsByTeamId(req, res); * @async
return res.status(200).json({ * @param {Object} req - The Express request object.
success: true, * @property {Object} req.params - The parameters of the request.
msg: successMessages.MONITOR_GET_BY_USER_ID(teamId), * @property {string} req.params.teamId - The ID of the team.
data: monitors, * @property {Object} req.query - The query parameters of the request.
}); * @property {string} req.query.type - The type of the request.
} catch (error) { * @param {Object} res - The Express response object.
next(handleError(error, SERVICE_NAME, "getMonitorsByTeamId")); * @param {function} next - The next middleware function.
next(error); * @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).
}; */
getMonitorsAndSummaryByTeamId = async (req, res, next) => {
try {
await getMonitorsAndSummaryByTeamIdParamValidation.validateAsync(req.params);
await getMonitorsAndSummaryByTeamIdQueryValidation.validateAsync(req.query);
} catch (error) {
next(handleValidationError(error, SERVICE_NAME));
return;
}
/** try {
* Creates a new monitor and adds it to the job queue. const { teamId } = req.params;
* @async const { type } = req.query;
* @param {Object} req - The Express request object. const monitorsSummary = await this.db.getMonitorsAndSummaryByTeamId(teamId, type);
* @property {Object} req.body - The body of the request. return res.status(200).json({
* @property {Array} req.body.notifications - The notifications associated with the monitor. success: true,
* @param {Object} res - The Express response object. msg: successMessages.MONITOR_GET_BY_USER_ID(teamId),
* @param {function} next - The next middleware function. data: monitorsSummary,
* @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). } catch (error) {
*/ next(handleError(error, SERVICE_NAME, "getMonitorsAndSummaryByTeamId"));
const createMonitor = async (req, res, next) => { }
try { };
await createMonitorBodyValidation.validateAsync(req.body);
} catch (error) {
next(handleValidationError(error, SERVICE_NAME));
return;
}
try { /**
const notifications = req.body.notifications; * Retrieves all monitors associated with a team by the team's ID.
const monitor = await req.db.createMonitor(req, res); * @async
* @param {Object} req - The Express request object.
* @property {Object} req.params - The parameters of the request.
* @property {string} req.params.teamId - The ID of the team.
* @property {Object} req.query - The query parameters of the request.
* @param {Object} res - The Express response object.
* @param {function} next - The next middleware function.
* @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).
*/
getMonitorsByTeamId = async (req, res, next) => {
try {
await getMonitorsByTeamIdValidation.validateAsync(req.params);
await getMonitorsByTeamIdQueryValidation.validateAsync(req.query);
} catch (error) {
next(handleValidationError(error, SERVICE_NAME));
return;
}
if (notifications && notifications.length > 0) { try {
monitor.notifications = await Promise.all( const teamId = req.params.teamId;
notifications.map(async (notification) => { const monitors = await this.db.getMonitorsByTeamId(req, res);
notification.monitorId = monitor._id; return res.status(200).json({
return await req.db.createNotification(notification); success: true,
msg: successMessages.MONITOR_GET_BY_USER_ID(teamId),
data: monitors,
});
} catch (error) {
next(handleError(error, SERVICE_NAME, "getMonitorsByTeamId"));
next(error);
}
};
/**
* Creates a new monitor and adds it to the job queue.
* @async
* @param {Object} req - The Express request object.
* @property {Object} req.body - The body of the request.
* @property {Array} req.body.notifications - The notifications associated with the monitor.
* @param {Object} res - The Express response object.
* @param {function} next - The next middleware function.
* @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).
*/
createMonitor = async (req, res, next) => {
try {
await createMonitorBodyValidation.validateAsync(req.body);
} catch (error) {
next(handleValidationError(error, SERVICE_NAME));
return;
}
try {
const notifications = req.body.notifications;
const monitor = await this.db.createMonitor(req, res);
if (notifications && notifications.length > 0) {
monitor.notifications = await Promise.all(
notifications.map(async (notification) => {
notification.monitorId = monitor._id;
return await this.db.createNotification(notification);
})
);
}
await monitor.save();
// Add monitor to job queue
this.jobQueue.addJob(monitor._id, monitor);
return res.status(201).json({
success: true,
msg: successMessages.MONITOR_CREATE,
data: monitor,
});
} catch (error) {
next(handleError(error, SERVICE_NAME, "createMonitor"));
}
};
/**
* Checks if the endpoint can be resolved
* @async
* @param {Object} req - The Express request object.
* @property {Object} req.query - The query parameters of the request.
* @param {Object} res - The Express response object.
* @param {function} next - The next middleware function.
* @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).
*/
checkEndpointResolution = async (req, res, next) => {
try {
await getMonitorURLByQueryValidation.validateAsync(req.query);
} catch (error) {
next(handleValidationError(error, SERVICE_NAME));
return;
}
try {
const { monitorURL } = req.query;
const parsedUrl = new URL(monitorURL);
const response = await axios.get(parsedUrl, {
timeout: 5000,
validateStatus: () => true,
});
return res.status(200).json({
success: true,
code: response.status,
statusText: response.statusText,
msg: `URL resolved successfully`,
});
} catch (error) {
next(handleError(error, SERVICE_NAME, "checkEndpointResolution"));
}
};
/**
* Deletes a monitor by its ID and also deletes associated checks, alerts, and notifications.
* @async
* @param {Object} req - The Express request object.
* @property {Object} req.params - The parameters of the request.
* @property {string} req.params.monitorId - The ID of the monitor to be deleted.
* @param {Object} res - The Express response object.
* @param {function} next - The next middleware function.
* @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.
*/
deleteMonitor = async (req, res, next) => {
try {
await getMonitorByIdParamValidation.validateAsync(req.params);
} catch (error) {
next(handleValidationError(error, SERVICE_NAME));
return;
}
try {
const monitor = await this.db.deleteMonitor(req, res, next);
// Delete associated checks,alerts,and notifications
try {
await this.jobQueue.deleteJob(monitor);
await this.db.deleteChecks(monitor._id);
await this.db.deletePageSpeedChecksByMonitorId(monitor._id);
await this.db.deleteNotificationsByMonitorId(monitor._id);
await this.db.deleteHardwareChecksByMonitorId(monitor._id);
} catch (error) {
logger.error({
message: `Error deleting associated records for monitor ${monitor._id} with name ${monitor.name}`,
service: SERVICE_NAME,
method: "deleteMonitor",
stack: error.stack,
});
}
return res.status(200).json({ success: true, msg: successMessages.MONITOR_DELETE });
} catch (error) {
next(handleError(error, SERVICE_NAME, "deleteMonitor"));
}
};
/**
* Deletes all monitors associated with a team.
* @async
* @param {Object} req - The Express request object.
* @property {Object} req.headers - The headers of the request.
* @property {string} req.headers.authorization - The authorization header containing the JWT token.
* @param {Object} res - The Express response object.
* @param {function} next
* @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.
*/
deleteAllMonitors = async (req, res, next) => {
try {
const token = getTokenFromHeaders(req.headers);
const { jwtSecret } = this.settingsService.getSettings();
const { teamId } = jwt.verify(token, jwtSecret);
const { monitors, deletedCount } = await this.db.deleteAllMonitors(teamId);
await Promise.all(
monitors.map(async (monitor) => {
try {
await this.jobQueue.deleteJob(monitor);
await this.db.deleteChecks(monitor._id);
await this.db.deletePageSpeedChecksByMonitorId(monitor._id);
await this.db.deleteNotificationsByMonitorId(monitor._id);
} catch (error) {
logger.error({
message: `Error deleting associated records for monitor ${monitor._id} with name ${monitor.name}`,
service: SERVICE_NAME,
method: "deleteAllMonitors",
stack: error.stack,
});
}
}) })
); );
} return res
.status(200)
await monitor.save(); .json({ success: true, msg: `Deleted ${deletedCount} monitors` });
// Add monitor to job queue
req.jobQueue.addJob(monitor._id, monitor);
return res.status(201).json({
success: true,
msg: successMessages.MONITOR_CREATE,
data: monitor,
});
} catch (error) {
next(handleError(error, SERVICE_NAME, "createMonitor"));
}
};
/**
* Checks if the endpoint can be resolved
* @async
* @param {Object} req - The Express request object.
* @property {Object} req.query - The query parameters of the request.
* @param {Object} res - The Express response object.
* @param {function} next - The next middleware function.
* @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).
*/
const checkEndpointResolution = async (req, res, next) => {
try {
await getMonitorURLByQueryValidation.validateAsync(req.query);
} catch (error) {
next(handleValidationError(error, SERVICE_NAME));
return;
}
try {
const { monitorURL } = req.query;
const parsedUrl = new URL(monitorURL);
const response = await axios.get(parsedUrl, {
timeout: 5000,
validateStatus: () => true,
});
return res.status(200).json({
success: true,
code: response.status,
statusText: response.statusText,
msg: `URL resolved successfully`,
});
} catch (error) {
next(handleError(error, SERVICE_NAME, "checkEndpointResolution"));
}
};
/**
* Deletes a monitor by its ID and also deletes associated checks, alerts, and notifications.
* @async
* @param {Object} req - The Express request object.
* @property {Object} req.params - The parameters of the request.
* @property {string} req.params.monitorId - The ID of the monitor to be deleted.
* @param {Object} res - The Express response object.
* @param {function} next - The next middleware function.
* @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.
*/
const deleteMonitor = async (req, res, next) => {
try {
await getMonitorByIdParamValidation.validateAsync(req.params);
} catch (error) {
next(handleValidationError(error, SERVICE_NAME));
return;
}
try {
const monitor = await req.db.deleteMonitor(req, res, next);
// Delete associated checks,alerts,and notifications
try {
await req.jobQueue.deleteJob(monitor);
await req.db.deleteChecks(monitor._id);
await req.db.deletePageSpeedChecksByMonitorId(monitor._id);
await req.db.deleteNotificationsByMonitorId(monitor._id);
await req.db.deleteHardwareChecksByMonitorId(monitor._id);
} catch (error) { } catch (error) {
logger.error({ next(handleError(error, SERVICE_NAME, "deleteAllMonitors"));
message: `Error deleting associated records for monitor ${monitor._id} with name ${monitor.name}`,
service: SERVICE_NAME,
method: "deleteMonitor",
stack: error.stack,
});
} }
return res.status(200).json({ success: true, msg: successMessages.MONITOR_DELETE }); };
} catch (error) {
next(handleError(error, SERVICE_NAME, "deleteMonitor"));
}
};
/** /**
* Deletes all monitors associated with a team. * Edits a monitor by its ID, updates its notifications, and updates its job in the job queue.
* @async * @async
* @param {Object} req - The Express request object. * @param {Object} req - The Express request object.
* @property {Object} req.headers - The headers of the request. * @property {Object} req.params - The parameters of the request.
* @property {string} req.headers.authorization - The authorization header containing the JWT token. * @property {string} req.params.monitorId - The ID of the monitor to be edited.
* @param {Object} res - The Express response object. * @property {Object} req.body - The body of the request.
* @param {function} next * @property {Array} req.body.notifications - The notifications to be associated with the monitor.
* @returns {Object} The response object with a success status and a message indicating the number of deleted monitors. * @param {Object} res - The Express response object.
* @throws {Error} If there is an error during the deletion process. * @param {function} next - The next middleware function.
*/ * @returns {Object} The response object with a success status, a message indicating the editing of the monitor, and the edited monitor data.
const deleteAllMonitors = async (req, res, next) => { * @throws {Error} If there is an error during the process, especially if there is a validation error (422).
try { */
const token = getTokenFromHeaders(req.headers); editMonitor = async (req, res, next) => {
const { jwtSecret } = req.settingsService.getSettings(); try {
const { teamId } = jwt.verify(token, jwtSecret); await getMonitorByIdParamValidation.validateAsync(req.params);
const { monitors, deletedCount } = await req.db.deleteAllMonitors(teamId); await editMonitorBodyValidation.validateAsync(req.body);
await Promise.all( } catch (error) {
monitors.map(async (monitor) => { next(handleValidationError(error, SERVICE_NAME));
try { return;
await req.jobQueue.deleteJob(monitor); }
await req.db.deleteChecks(monitor._id);
await req.db.deletePageSpeedChecksByMonitorId(monitor._id);
await req.db.deleteNotificationsByMonitorId(monitor._id);
} catch (error) {
logger.error({
message: `Error deleting associated records for monitor ${monitor._id} with name ${monitor.name}`,
service: SERVICE_NAME,
method: "deleteAllMonitors",
stack: error.stack,
});
}
})
);
return res
.status(200)
.json({ success: true, msg: `Deleted ${deletedCount} monitors` });
} catch (error) {
next(handleError(error, SERVICE_NAME, "deleteAllMonitors"));
}
};
/** try {
* Edits a monitor by its ID, updates its notifications, and updates its job in the job queue. const { monitorId } = req.params;
* @async const monitorBeforeEdit = await this.db.getMonitorById(monitorId);
* @param {Object} req - The Express request object.
* @property {Object} req.params - The parameters of the request.
* @property {string} req.params.monitorId - The ID of the monitor to be edited.
* @property {Object} req.body - The body of the request.
* @property {Array} req.body.notifications - The notifications to be associated with the monitor.
* @param {Object} res - The Express response object.
* @param {function} next - The next middleware function.
* @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).
*/
const editMonitor = async (req, res, next) => {
try {
await getMonitorByIdParamValidation.validateAsync(req.params);
await editMonitorBodyValidation.validateAsync(req.body);
} catch (error) {
next(handleValidationError(error, SERVICE_NAME));
return;
}
try { // Get notifications from the request body
const { monitorId } = req.params; const notifications = req.body.notifications;
const monitorBeforeEdit = await req.db.getMonitorById(monitorId);
// Get notifications from the request body const editedMonitor = await this.db.editMonitor(monitorId, req.body);
const notifications = req.body.notifications;
const editedMonitor = await req.db.editMonitor(monitorId, req.body); await this.db.deleteNotificationsByMonitorId(editedMonitor._id);
await req.db.deleteNotificationsByMonitorId(editedMonitor._id); await Promise.all(
notifications &&
notifications.map(async (notification) => {
notification.monitorId = editedMonitor._id;
await this.db.createNotification(notification);
})
);
await Promise.all( // Delete the old job(editedMonitor has the same ID as the old monitor)
notifications && await this.jobQueue.deleteJob(monitorBeforeEdit);
notifications.map(async (notification) => { // Add the new job back to the queue
notification.monitorId = editedMonitor._id; await this.jobQueue.addJob(editedMonitor._id, editedMonitor);
await req.db.createNotification(notification); return res.status(200).json({
}) success: true,
); msg: successMessages.MONITOR_EDIT,
data: editedMonitor,
});
} catch (error) {
next(handleError(error, SERVICE_NAME, "editMonitor"));
}
};
// Delete the old job(editedMonitor has the same ID as the old monitor) /**
await req.jobQueue.deleteJob(monitorBeforeEdit); * Pauses or resumes a monitor based on its current state.
// Add the new job back to the queue * @async
await req.jobQueue.addJob(editedMonitor._id, editedMonitor); * @param {Object} req - The Express request object.
return res.status(200).json({ * @property {Object} req.params - The parameters of the request.
success: true, * @property {string} req.params.monitorId - The ID of the monitor to be paused or resumed.
msg: successMessages.MONITOR_EDIT, * @param {Object} res - The Express response object.
data: editedMonitor, * @param {function} next - The next middleware function.
}); * @returns {Object} The response object with a success status, a message indicating the new state of the monitor, and the updated monitor data.
} catch (error) { * @throws {Error} If there is an error during the process.
next(handleError(error, SERVICE_NAME, "editMonitor")); */
} pauseMonitor = async (req, res, next) => {
}; try {
await pauseMonitorParamValidation.validateAsync(req.params);
} catch (error) {
next(handleValidationError(error, SERVICE_NAME));
}
/** try {
* Pauses or resumes a monitor based on its current state. const monitor = await this.db.getMonitorById(req.params.monitorId);
* @async monitor.isActive === true
* @param {Object} req - The Express request object. ? await this.jobQueue.deleteJob(monitor)
* @property {Object} req.params - The parameters of the request. : await this.jobQueue.addJob(monitor._id, monitor);
* @property {string} req.params.monitorId - The ID of the monitor to be paused or resumed.
* @param {Object} res - The Express response object.
* @param {function} next - The next middleware function.
* @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.
*/
const pauseMonitor = async (req, res, next) => {
try {
await pauseMonitorParamValidation.validateAsync(req.params);
} catch (error) {
next(handleValidationError(error, SERVICE_NAME));
}
try { monitor.isActive = !monitor.isActive;
const monitor = await req.db.getMonitorById(req.params.monitorId); monitor.status = undefined;
monitor.isActive === true monitor.save();
? await req.jobQueue.deleteJob(monitor) return res.status(200).json({
: await req.jobQueue.addJob(monitor._id, monitor); success: true,
msg: monitor.isActive
? successMessages.MONITOR_RESUME
: successMessages.MONITOR_PAUSE,
data: monitor,
});
} catch (error) {
next(handleError(error, SERVICE_NAME, "pauseMonitor"));
}
};
monitor.isActive = !monitor.isActive; /**
monitor.status = undefined; * Adds demo monitors for a team.
monitor.save(); * @async
return res.status(200).json({ * @param {Object} req - The Express request object.
success: true, * @property {Object} req.headers - The headers of the request.
msg: monitor.isActive * @property {string} req.headers.authorization - The authorization header containing the JWT token.
? successMessages.MONITOR_RESUME * @param {Object} res - The Express response object.
: successMessages.MONITOR_PAUSE, * @param {function} next - The next middleware function.
data: monitor, * @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.
} catch (error) { */
next(handleError(error, SERVICE_NAME, "pauseMonitor")); addDemoMonitors = async (req, res, next) => {
} try {
}; const token = getTokenFromHeaders(req.headers);
const { jwtSecret } = this.settingsService.getSettings();
const { _id, teamId } = jwt.verify(token, jwtSecret);
const demoMonitors = await this.db.addDemoMonitors(_id, teamId);
await Promise.all(
demoMonitors.map((monitor) => this.jobQueue.addJob(monitor._id, monitor))
);
/** return res.status(200).json({
* Adds demo monitors for a team. success: true,
* @async msg: successMessages.MONITOR_DEMO_ADDED,
* @param {Object} req - The Express request object. data: demoMonitors.length,
* @property {Object} req.headers - The headers of the request. });
* @property {string} req.headers.authorization - The authorization header containing the JWT token. } catch (error) {
* @param {Object} res - The Express response object. next(handleError(error, SERVICE_NAME, "addDemoMonitors"));
* @param {function} next - The next middleware function. }
* @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. }
*/
const addDemoMonitors = async (req, res, next) => {
try {
const token = getTokenFromHeaders(req.headers);
const { jwtSecret } = req.settingsService.getSettings();
const { _id, teamId } = jwt.verify(token, jwtSecret);
const demoMonitors = await req.db.addDemoMonitors(_id, teamId);
await Promise.all(
demoMonitors.map((monitor) => req.jobQueue.addJob(monitor._id, monitor))
);
return res.status(200).json({ export default MonitorController;
success: true,
msg: successMessages.MONITOR_DEMO_ADDED,
data: demoMonitors.length,
});
} catch (error) {
next(handleError(error, SERVICE_NAME, "addDemoMonitors"));
}
};
export {
getAllMonitors,
getAllMonitorsWithUptimeStats,
getMonitorStatsById,
getMonitorCertificate,
getMonitorById,
getMonitorsAndSummaryByTeamId,
getMonitorsByTeamId,
createMonitor,
checkEndpointResolution,
deleteMonitor,
deleteAllMonitors,
editMonitor,
pauseMonitor,
addDemoMonitors,
};
+55 -48
View File
@@ -1,57 +1,64 @@
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 {
try { constructor(jobQueue) {
const metrics = await req.jobQueue.getMetrics(); this.jobQueue = jobQueue;
res.status(200).json({
success: true,
msg: successMessages.QUEUE_GET_METRICS,
data: metrics,
});
} catch (error) {
next(handleError(error, SERVICE_NAME, "getMetrics"));
return;
} }
};
const getJobs = async (req, res, next) => { getMetrics = async (req, res, next) => {
try { try {
const jobs = await req.jobQueue.getJobStats(); const metrics = await this.jobQueue.getMetrics();
return res.status(200).json({ res.status(200).json({
success: true, success: true,
msg: successMessages.QUEUE_GET_METRICS, msg: successMessages.QUEUE_GET_METRICS,
data: jobs, data: metrics,
}); });
} catch (error) { } catch (error) {
next(handleError(error, SERVICE_NAME, "getJobs")); next(handleError(error, SERVICE_NAME, "getMetrics"));
return; return;
} }
}; };
const addJob = async (req, res, next) => { getJobs = async (req, res, next) => {
try { try {
await req.jobQueue.addJob(Math.random().toString(36).substring(7)); const jobs = await this.jobQueue.getJobStats();
return res.status(200).json({ return res.status(200).json({
success: true, success: true,
msg: successMessages.QUEUE_ADD_JOB, msg: successMessages.QUEUE_GET_METRICS,
}); data: jobs,
} catch (error) { });
next(handleError(error, SERVICE_NAME, "addJob")); } catch (error) {
return; next(handleError(error, SERVICE_NAME, "getJobs"));
} return;
}; }
};
const obliterateQueue = async (req, res, next) => { addJob = async (req, res, next) => {
try { try {
await req.jobQueue.obliterate(); await this.jobQueue.addJob(Math.random().toString(36).substring(7));
return res.status(200).json({ success: true, msg: successMessages.QUEUE_OBLITERATE }); return res.status(200).json({
} catch (error) { success: true,
next(handleError(error, SERVICE_NAME, "obliterateQueue")); msg: successMessages.QUEUE_ADD_JOB,
return; });
} } catch (error) {
}; next(handleError(error, SERVICE_NAME, "addJob"));
return;
}
};
export { getMetrics, getJobs, addJob, obliterateQueue }; obliterateQueue = async (req, res, next) => {
try {
await this.jobQueue.obliterate();
return res
.status(200)
.json({ success: true, msg: successMessages.QUEUE_OBLITERATE });
} catch (error) {
next(handleError(error, SERVICE_NAME, "obliterateQueue"));
return;
}
};
}
export default JobQueueController;
+41 -34
View File
@@ -3,40 +3,47 @@ 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 {
try { constructor(db, settingsService) {
const settings = { ...(await req.settingsService.getSettings()) }; this.db = db;
delete settings.jwtSecret; this.settingsService = settingsService;
return res.status(200).json({
success: true,
msg: successMessages.GET_APP_SETTINGS,
data: settings,
});
} catch (error) {
next(handleError(error, SERVICE_NAME, "getAppSettings"));
}
};
const updateAppSettings = async (req, res, next) => {
try {
await updateAppSettingsBodyValidation.validateAsync(req.body);
} catch (error) {
next(handleValidationError(error, SERVICE_NAME));
return;
} }
try { getAppSettings = async (req, res, next) => {
await req.db.updateAppSettings(req.body); try {
const updatedSettings = { ...(await req.settingsService.reloadSettings()) }; const settings = { ...(await this.settingsService.getSettings()) };
delete updatedSettings.jwtSecret; delete settings.jwtSecret;
return res.status(200).json({ return res.status(200).json({
success: true, success: true,
msg: successMessages.UPDATE_APP_SETTINGS, msg: successMessages.GET_APP_SETTINGS,
data: updatedSettings, data: settings,
}); });
} catch (error) { } catch (error) {
next(handleError(error, SERVICE_NAME, "updateAppSettings")); next(handleError(error, SERVICE_NAME, "getAppSettings"));
} }
}; };
export { getAppSettings, updateAppSettings }; updateAppSettings = async (req, res, next) => {
try {
await updateAppSettingsBodyValidation.validateAsync(req.body);
} catch (error) {
next(handleValidationError(error, SERVICE_NAME));
return;
}
try {
await this.db.updateAppSettings(req.body);
const updatedSettings = { ...(await this.settingsService.reloadSettings()) };
delete updatedSettings.jwtSecret;
return res.status(200).json({
success: true,
msg: successMessages.UPDATE_APP_SETTINGS,
data: updatedSettings,
});
} catch (error) {
next(handleError(error, SERVICE_NAME, "updateAppSettings"));
}
};
}
export default SettingsController;
+42 -37
View File
@@ -7,45 +7,50 @@ import { successMessages } from "../utils/messages.js";
const SERVICE_NAME = "statusPageController"; const SERVICE_NAME = "statusPageController";
const createStatusPage = async (req, res, next) => { class StatusPageController {
try { constructor(db) {
await createStatusPageBodyValidation.validateAsync(req.body); this.db = db;
} catch (error) {
next(handleValidationError(error, SERVICE_NAME));
return;
} }
try { createStatusPage = async (req, res, next) => {
const statusPage = await req.db.createStatusPage(req.body); try {
return res.status(200).json({ await createStatusPageBodyValidation.validateAsync(req.body);
success: true, } catch (error) {
msg: successMessages.STATUS_PAGE_CREATE, next(handleValidationError(error, SERVICE_NAME));
data: statusPage, return;
}); }
} catch (error) {
next(handleError(error, SERVICE_NAME, "createStatusPage"));
}
};
const getStatusPageByUrl = async (req, res, next) => { try {
try { const statusPage = await this.db.createStatusPage(req.body);
await getStatusPageParamValidation.validateAsync(req.params); return res.status(200).json({
} catch (error) { success: true,
next(handleValidationError(error, SERVICE_NAME)); msg: successMessages.STATUS_PAGE_CREATE,
return; data: statusPage,
} });
} catch (error) {
next(handleError(error, SERVICE_NAME, "createStatusPage"));
}
};
getStatusPageByUrl = async (req, res, next) => {
try {
await getStatusPageParamValidation.validateAsync(req.params);
} catch (error) {
next(handleValidationError(error, SERVICE_NAME));
return;
}
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,
data: statusPage, data: statusPage,
}); });
} catch (error) { } catch (error) {
next(handleError(error, SERVICE_NAME, "getStatusPage")); next(handleError(error, SERVICE_NAME, "getStatusPage"));
} }
}; };
}
export { createStatusPage, getStatusPageByUrl }; export default StatusPageController;
+76 -181
View File
@@ -2,234 +2,129 @@ 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
//****************************************
const connect = async () => {
try {
const connectionString =
process.env.DB_CONNECTION_STRING || "mongodb://localhost:27017/uptime_db";
await mongoose.connect(connectionString);
// If there are no AppSettings, create one
let appSettings = await AppSettings.find();
if (appSettings.length === 0) {
appSettings = new AppSettings({});
await appSettings.save();
}
logger.info({ message: "Connected to MongoDB" });
} catch (error) {
logger.error({
message: error.message,
service: SERVICE_NAME,
method: "connect",
stack: error.stack,
});
throw error;
}
};
const disconnect = async () => {
try {
logger.info({ message: "Disconnecting from MongoDB" });
await mongoose.disconnect();
logger.info({ message: "Disconnected from MongoDB" });
return;
} catch (error) {
logger.error({
message: error.message,
service: SERVICE_NAME,
method: "disconnect",
stack: error.stack,
});
}
};
const checkSuperadmin = async (req, res) => {
try {
const superAdmin = await UserModel.findOne({ role: "superadmin" });
if (superAdmin !== null) {
return true;
}
return false;
} catch (error) {
throw error;
}
};
//**************************************** //****************************************
// User Operations // User Operations
//**************************************** //****************************************
import { import * as userModule from "./modules/userModule.js";
insertUser,
getUserByEmail,
updateUser,
deleteUser,
deleteTeam,
deleteAllOtherUsers,
getAllUsers,
logoutUser,
} from "./modules/userModule.js";
//**************************************** //****************************************
// Invite Token Operations // Invite Token Operations
//**************************************** //****************************************
import { import * as inviteModule from "./modules/inviteModule.js";
requestInviteToken,
getInviteToken,
getInviteTokenAndDelete,
} from "./modules/inviteModule.js";
//**************************************** //****************************************
// Recovery Operations // Recovery Operations
//**************************************** //****************************************
import { import * as recoveryModule from "./modules/recoveryModule.js";
requestRecoveryToken,
validateRecoveryToken,
resetPassword,
} from "./modules/recoveryModule.js";
//**************************************** //****************************************
// Monitors // Monitors
//**************************************** //****************************************
import { import * as monitorModule from "./modules/monitorModule.js";
getAllMonitors,
getAllMonitorsWithUptimeStats,
getMonitorStatsById,
getMonitorById,
getMonitorsAndSummaryByTeamId,
getMonitorsByTeamId,
createMonitor,
deleteMonitor,
deleteAllMonitors,
deleteMonitorsByUserId,
editMonitor,
addDemoMonitors,
} from "./modules/monitorModule.js";
//**************************************** //****************************************
// Page Speed Checks // Page Speed Checks
//**************************************** //****************************************
import { import * as pageSpeedCheckModule from "./modules/pageSpeedCheckModule.js";
createPageSpeedCheck,
deletePageSpeedChecksByMonitorId,
} from "./modules/pageSpeedCheckModule.js";
//**************************************** //****************************************
// Hardware Checks // Hardware Checks
//**************************************** //****************************************
import { import * as hardwareCheckModule from "./modules/hardwareCheckModule.js";
createHardwareCheck,
deleteHardwareChecksByMonitorId,
} from "./modules/hardwareCheckModule.js";
//**************************************** //****************************************
// Checks // Checks
//**************************************** //****************************************
import { import * as checkModule from "./modules/checkModule.js";
createCheck,
getChecksCount,
getChecks,
getTeamChecks,
deleteChecks,
deleteChecksByTeamId,
updateChecksTTL,
} from "./modules/checkModule.js";
//**************************************** //****************************************
// Maintenance Window // Maintenance Window
//**************************************** //****************************************
import { import * as maintenanceWindowModule from "./modules/maintenanceWindowModule.js";
createMaintenanceWindow,
getMaintenanceWindowById,
getMaintenanceWindowsByTeamId,
getMaintenanceWindowsByMonitorId,
deleteMaintenanceWindowById,
deleteMaintenanceWindowByMonitorId,
deleteMaintenanceWindowByUserId,
editMaintenanceWindowById,
} from "./modules/maintenanceWindowModule.js";
//**************************************** //****************************************
// Notifications // Notifications
//**************************************** //****************************************
import { import * as notificationModule from "./modules/notificationModule.js";
createNotification,
getNotificationsByMonitorId,
deleteNotificationsByMonitorId,
} from "./modules/notificationModule.js";
//**************************************** //****************************************
// AppSettings // AppSettings
//**************************************** //****************************************
import { getAppSettings, updateAppSettings } from "./modules/settingsModule.js"; import * as settingsModule from "./modules/settingsModule.js";
//**************************************** //****************************************
// Status Page // Status Page
//**************************************** //****************************************
import { createStatusPage, getStatusPageByUrl } from "./modules/statusPageModule.js"; import * as statusPageModule from "./modules/statusPageModule.js";
export default { class MongoDB {
connect, static SERVICE_NAME = "MongoDB";
disconnect,
insertUser, constructor() {
getUserByEmail, Object.assign(this, userModule);
updateUser, Object.assign(this, inviteModule);
deleteUser, Object.assign(this, recoveryModule);
deleteTeam, Object.assign(this, monitorModule);
deleteAllOtherUsers, Object.assign(this, pageSpeedCheckModule);
getAllUsers, Object.assign(this, hardwareCheckModule);
logoutUser, Object.assign(this, checkModule);
requestInviteToken, Object.assign(this, maintenanceWindowModule);
getInviteToken, Object.assign(this, notificationModule);
getInviteTokenAndDelete, Object.assign(this, settingsModule);
requestRecoveryToken, Object.assign(this, statusPageModule);
validateRecoveryToken, }
resetPassword,
checkSuperadmin, connect = async () => {
getAllMonitors, try {
getAllMonitorsWithUptimeStats, const connectionString =
getMonitorStatsById, process.env.DB_CONNECTION_STRING || "mongodb://localhost:27017/uptime_db";
getMonitorById, await mongoose.connect(connectionString);
getMonitorsAndSummaryByTeamId, // If there are no AppSettings, create one
getMonitorsByTeamId, let appSettings = await AppSettings.find();
createMonitor, if (appSettings.length === 0) {
deleteMonitor, appSettings = new AppSettings({});
deleteAllMonitors, await appSettings.save();
editMonitor, }
addDemoMonitors, logger.info({ message: "Connected to MongoDB" });
createCheck, } catch (error) {
getChecksCount, logger.error({
getChecks, message: error.message,
getTeamChecks, service: this.SERVICE_NAME,
deleteChecks, method: "connect",
deleteChecksByTeamId, stack: error.stack,
updateChecksTTL, });
deleteMonitorsByUserId, throw error;
createPageSpeedCheck, }
deletePageSpeedChecksByMonitorId, };
createHardwareCheck,
deleteHardwareChecksByMonitorId, disconnect = async () => {
createMaintenanceWindow, try {
getMaintenanceWindowsByTeamId, logger.info({ message: "Disconnecting from MongoDB" });
getMaintenanceWindowById, await mongoose.disconnect();
getMaintenanceWindowsByMonitorId, logger.info({ message: "Disconnected from MongoDB" });
deleteMaintenanceWindowById, return;
deleteMaintenanceWindowByMonitorId, } catch (error) {
deleteMaintenanceWindowByUserId, logger.error({
editMaintenanceWindowById, message: error.message,
createNotification, service: this.SERVICE_NAME,
getNotificationsByMonitorId, method: "disconnect",
deleteNotificationsByMonitorId, stack: error.stack,
getAppSettings, });
updateAppSettings, }
createStatusPage, };
getStatusPageByUrl, checkSuperadmin = async (req, res) => {
}; const superAdmin = await UserModel.findOne({ role: "superadmin" });
if (superAdmin !== null) {
return true;
}
return false;
};
}
export default MongoDB;
+149 -113
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;
const shutdown = async () => {
if (isShuttingDown) {
return;
}
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);
}, SHUTDOWN_TIMEOUT);
try {
server.close();
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) {
logger.error({
message: error.message,
service: SERVICE_NAME,
method: "shutdown",
stack: error.stack,
});
}
};
// Need to wrap server setup in a function to handle async nature of JobQueue // Need to wrap server setup in a function to handle async nature of JobQueue
const startApp = async () => { const startApp = async () => {
const app = express(); const app = express();
// middlewares // Create DB
app.use( const db = new MongoDB();
cors() await db.connect();
//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 });
}
});
//health check
app.use("/api/v1/healthy", (req, res) => {
try {
logger.info({ message: "Checking Health of the server." });
return res.status(200).json({ message: "Healthy" });
} catch (error) {
logger.error({
message: error.message,
service: SERVICE_NAME,
method: "healthCheck",
stack: error.stack,
});
return res.status(500).json({ message: error.message });
}
});
/**
* Error handler middleware
* Should be called last
*/
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) {
+48 -26
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);
//Recovery routes this.router.put(
router.post("/recovery/request", requestRecovery); "/user/:userId",
router.post("/recovery/validate", validateRecovery); upload.single("profileImage"),
router.post("/recovery/reset/", resetPassword); verifyJWT,
this.authController.editUser
);
export default router; 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
this.router.post("/recovery/request", this.authController.requestRecovery);
this.router.post("/recovery/validate", this.authController.validateRecovery);
this.router.post("/recovery/reset/", this.authController.resetPassword);
}
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;
+26 -20
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(
"/monitor/:monitorId",
verifyOwnership(Monitor, "monitorId"),
this.maintenanceWindowController.getMaintenanceWindowsByMonitorId
);
router.get( this.router.get(
"/monitor/:monitorId", "/team/",
verifyOwnership(Monitor, "monitorId"), this.maintenanceWindowController.getMaintenanceWindowsByTeamId
getMaintenanceWindowsByMonitorId );
);
router.get("/team/", getMaintenanceWindowsByTeamId); this.router.get("/:id", this.maintenanceWindowController.getMaintenanceWindowById);
router.get("/:id", getMaintenanceWindowById); this.router.put("/:id", this.maintenanceWindowController.editMaintenanceWindow);
router.put("/:id", editMaintenanceWindow); this.router.delete("/:id", this.maintenanceWindowController.deleteMaintenanceWindow);
}
router.delete("/:id", deleteMaintenanceWindow); getRouter() {
return this.router;
}
}
export default router; export default MaintenanceWindowRoutes;
+66 -38
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(
router.get("/:monitorId", getMonitorById); req,
router.get("/team/summary/:teamId", getMonitorsAndSummaryByTeamId); res,
router.get("/team/:teamId", getMonitorsByTeamId); next,
fetchMonitorCertificate
);
});
this.router.get("/:monitorId", this.monitorController.getMonitorById);
this.router.get(
"/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) => {