Refactor method names, add improve JSdocs for monitorController

This commit is contained in:
Alex Holliday committed 2024-10-01 10:29:32 +08:00
1 parent 6c598b976f
commit e0e80dc9c7
5 files changed
+200 -199

No files matched your search

+88 -136
View File
@@ -7,29 +7,31 @@ const {
recoveryValidation, recoveryValidation,
recoveryTokenValidation, recoveryTokenValidation,
newPasswordValidation, newPasswordValidation,
deleteUserParamValidation,
inviteRoleValidation, inviteRoleValidation,
inviteBodyValidation, inviteBodyValidation,
inviteVerifciationBodyValidation, inviteVerificationBodyValidation,
} = require("../validation/joi"); } = require("../validation/joi");
const logger = require("../utils/logger"); const logger = require("../utils/logger");
require("dotenv").config(); require("dotenv").config();
const { errorMessages, successMessages } = require("../utils/messages"); const {errorMessages, successMessages} = require("../utils/messages");
var jwt = require("jsonwebtoken"); const jwt = require("jsonwebtoken");
const SERVICE_NAME = "AuthController"; const SERVICE_NAME = "AuthController";
const { getTokenFromHeaders } = require("../utils/utils"); const {getTokenFromHeaders} = require("../utils/utils");
const crypto = require("crypto"); const crypto = require("crypto");
/** /**
* Creates and returns JWT token with an arbitrary payload * Creates and returns JWT token with an arbitrary payload
* @function * @function
* @param {Object} payload * @param {Object} payload
* @param {Object} appSettings
* @param {function} next
* @returns {String} * @returns {String}
* @throws {Error}
*/ */
const issueToken = (payload, appSettings) => { const issueToken = (payload, appSettings, next) => {
try { try {
const tokenTTL = appSettings.jwtTTL ? appSettings.jwtTTL : "2h"; const tokenTTL = appSettings.jwtTTL ? appSettings.jwtTTL : "2h";
return jwt.sign(payload, appSettings.jwtSecret, { expiresIn: tokenTTL }); return jwt.sign(payload, appSettings.jwtSecret, {expiresIn: tokenTTL});
} catch (error) { } catch (error) {
error.service === undefined ? (error.service = SERVICE_NAME) : null; error.service === undefined ? (error.service = SERVICE_NAME) : null;
error.method === undefined ? (error.method = "issueToken") : null; error.method === undefined ? (error.method = "issueToken") : null;
@@ -41,23 +43,24 @@ const issueToken = (payload, appSettings) => {
* @function * @function
* @param {express.Request} req * @param {express.Request} req
* @param {express.Response} res * @param {express.Response} res
* @param {function} next
* @returns {{success: Boolean, msg: String}} * @returns {{success: Boolean, msg: String}}
* @throws {Error}
*/ */
const registerController = async (req, res, next) => { const registerUser = async (req, res, next) => {
// joi validation // joi validation
try { try {
await registrationBodyValidation.validateAsync(req.body); await registrationBodyValidation.validateAsync(req.body);
} catch (error) { } catch (error) {
error.status = 422; error.status = 422;
error.service = SERVICE_NAME; error.service = SERVICE_NAME;
error.message = error.message = error.details?.[0]?.message || error.message || "Validation Error";
error.details?.[0]?.message || error.message || "Validation Error";
next(error); next(error);
return; return;
} }
// Create a new user // Create a new user
try { try {
const { inviteToken } = req.body; const {inviteToken} = req.body;
// If superAdmin exists, a token should be attached to all further register requests // If superAdmin exists, a token should be attached to all further register requests
const superAdminExists = await req.db.checkSuperadmin(req, res); const superAdminExists = await req.db.checkSuperadmin(req, res);
if (superAdminExists) { if (superAdminExists) {
@@ -65,39 +68,30 @@ const registerController = async (req, res, next) => {
} else { } else {
// This is the first account, create JWT secret to use if one is not supplied by env // This is the first account, create JWT secret to use if one is not supplied by env
const jwtSecret = crypto.randomBytes(64).toString("hex"); const jwtSecret = crypto.randomBytes(64).toString("hex");
await req.db.updateAppSettings({ jwtSecret }); await req.db.updateAppSettings({jwtSecret});
} }
const newUser = await req.db.insertUser({ ...req.body }, req.file); const newUser = await req.db.insertUser({...req.body}, req.file);
logger.info(successMessages.AUTH_CREATE_USER, { logger.info(successMessages.AUTH_CREATE_USER, {
service: SERVICE_NAME, service: SERVICE_NAME, userId: newUser._id,
userId: newUser._id,
}); });
const userForToken = { ...newUser._doc }; const userForToken = {...newUser._doc};
delete userForToken.profileImage; delete userForToken.profileImage;
delete userForToken.avatarImage; delete userForToken.avatarImage;
const appSettings = await req.settingsService.getSettings(); const appSettings = await req.settingsService.getSettings();
const token = issueToken(userForToken, appSettings); const token = issueToken(userForToken, appSettings);
req.emailService req.emailService
.buildAndSendEmail( .buildAndSendEmail("welcomeEmailTemplate", {name: newUser.firstName}, newUser.email, "Welcome to Uptime Monitor")
"welcomeEmailTemplate",
{ name: newUser.firstName },
newUser.email,
"Welcome to Uptime Monitor"
)
.catch((error) => { .catch((error) => {
logger.error("Error sending welcome email", { logger.error("Error sending welcome email", {
service: SERVICE_NAME, service: SERVICE_NAME, error: error.message,
error: error.message,
}); });
}); });
return res.status(200).json({ return res.status(200).json({
success: true, success: true, msg: successMessages.AUTH_CREATE_USER, data: {user: newUser, token: token},
msg: successMessages.AUTH_CREATE_USER,
data: { user: newUser, token: token },
}); });
} catch (error) { } catch (error) {
error.service === undefined ? (error.service = SERVICE_NAME) : null; error.service === undefined ? (error.service = SERVICE_NAME) : null;
@@ -111,21 +105,21 @@ const registerController = async (req, res, next) => {
* @async * @async
* @param {Express.Request} req * @param {Express.Request} req
* @param {Express.Response} res * @param {Express.Response} res
* @param {function} next
* @returns {Promise<Express.Response>} * @returns {Promise<Express.Response>}
*/ */
const loginController = async (req, res, next) => { const loginUser = async (req, res, next) => {
try { try {
await loginValidation.validateAsync(req.body); await loginValidation.validateAsync(req.body);
} catch (error) { } catch (error) {
error.status = 422; error.status = 422;
error.service = SERVICE_NAME; error.service = SERVICE_NAME;
error.message = error.message = error.details?.[0]?.message || error.message || "Validation Error";
error.details?.[0]?.message || error.message || "Validation Error";
next(error); next(error);
return; return;
} }
try { try {
const { email, password } = req.body; const {email, password} = req.body;
// Check if user exists // Check if user exists
const user = await req.db.getUserByEmail(email); const user = await req.db.getUserByEmail(email);
@@ -136,7 +130,7 @@ const loginController = async (req, res, next) => {
} }
// Remove password from user object. Should this be abstracted to DB layer? // Remove password from user object. Should this be abstracted to DB layer?
const userWithoutPassword = { ...user._doc }; const userWithoutPassword = {...user._doc};
delete userWithoutPassword.password; delete userWithoutPassword.password;
delete userWithoutPassword.avatarImage; delete userWithoutPassword.avatarImage;
@@ -147,9 +141,7 @@ const loginController = async (req, res, next) => {
userWithoutPassword.avatarImage = user.avatarImage; userWithoutPassword.avatarImage = user.avatarImage;
return res.status(200).json({ return res.status(200).json({
success: true, success: true, msg: successMessages.AUTH_LOGIN_USER, data: {user: userWithoutPassword, token: token},
msg: successMessages.AUTH_LOGIN_USER,
data: { user: userWithoutPassword, token: token },
}); });
} catch (error) { } catch (error) {
error.status = 500; error.status = 500;
@@ -159,15 +151,14 @@ const loginController = async (req, res, next) => {
} }
}; };
const userEditController = async (req, res, next) => { const editUser = async (req, res, next) => {
try { try {
await editUserParamValidation.validateAsync(req.params); await editUserParamValidation.validateAsync(req.params);
await editUserBodyValidation.validateAsync(req.body); await editUserBodyValidation.validateAsync(req.body);
} catch (error) { } catch (error) {
error.status = 422; error.status = 422;
error.service = SERVICE_NAME; error.service = SERVICE_NAME;
error.message = error.message = error.details?.[0]?.message || error.message || "Validation Error";
error.details?.[0]?.message || error.message || "Validation Error";
next(error); next(error);
return; return;
} }
@@ -191,8 +182,8 @@ const userEditController = async (req, res, next) => {
// Get token from headers // Get token from headers
const token = getTokenFromHeaders(req.headers); const token = getTokenFromHeaders(req.headers);
// Get email from token // Get email from token
const { jwtSecret } = req.settingsService.getSettings(); const {jwtSecret} = req.settingsService.getSettings();
const { email } = jwt.verify(token, jwtSecret); const {email} = jwt.verify(token, jwtSecret);
// Add user email to body for DB operation // Add user email to body for DB operation
req.body.email = email; req.body.email = email;
// Get user // Get user
@@ -211,9 +202,7 @@ const userEditController = async (req, res, next) => {
const updatedUser = await req.db.updateUser(req, res); const updatedUser = await req.db.updateUser(req, res);
return res.status(200).json({ return res.status(200).json({
success: true, success: true, msg: successMessages.AUTH_UPDATE_USER, data: updatedUser,
msg: successMessages.AUTH_UPDATE_USER,
data: updatedUser,
}); });
} catch (error) { } catch (error) {
error.service === undefined ? (error.service = SERVICE_NAME) : null; error.service === undefined ? (error.service = SERVICE_NAME) : null;
@@ -223,46 +212,38 @@ const userEditController = async (req, res, next) => {
} }
}; };
const inviteController = async (req, res, next) => { const createInvitation = async (req, res, next) => {
try { try {
// Only admins can invite // Only admins can invite
const token = getTokenFromHeaders(req.headers); const token = getTokenFromHeaders(req.headers);
const { role, firstname, teamId } = jwt.decode(token); const {role, firstname, teamId} = jwt.decode(token);
req.body.teamId = teamId; req.body.teamId = teamId;
try { try {
await inviteRoleValidation.validateAsync({ roles: role }); await inviteRoleValidation.validateAsync({roles: role});
await inviteBodyValidation.validateAsync(req.body); await inviteBodyValidation.validateAsync(req.body);
} catch (error) { } catch (error) {
error.status = 422; error.status = 422;
error.service = SERVICE_NAME; error.service = SERVICE_NAME;
error.message = error.message = error.details?.[0]?.message || error.message || "Validation Error";
error.details?.[0]?.message || error.message || "Validation Error";
next(error); next(error);
return; return;
} }
const inviteToken = await req.db.requestInviteToken(req, res); const inviteToken = await req.db.requestInviteToken(req, res);
const { clientHost } = req.settingsService.getSettings(); const {clientHost} = req.settingsService.getSettings();
req.emailService req.emailService
.buildAndSendEmail( .buildAndSendEmail("employeeActivationTemplate", {
"employeeActivationTemplate", name: firstname, link: `${clientHost}/register/${inviteToken.token}`,
{ }, req.body.email, "Welcome to Uptime Monitor")
name: firstname,
link: `${clientHost}/register/${inviteToken.token}`,
},
req.body.email,
"Welcome to Uptime Monitor"
)
.catch((error) => { .catch((error) => {
logger.error("Error sending invite email", { logger.error("Error sending invite email", {
service: SERVICE_NAME, service: SERVICE_NAME, error: error.message,
error: error.message,
}); });
}); });
return res return res
.status(200) .status(200)
.json({ success: true, msg: "Invite sent", data: inviteToken }); .json({success: true, msg: "Invite sent", data: inviteToken});
} catch (error) { } catch (error) {
error.service === undefined ? (error.service = SERVICE_NAME) : null; error.service === undefined ? (error.service = SERVICE_NAME) : null;
error.method === undefined ? (error.method = "inviteController") : null; error.method === undefined ? (error.method = "inviteController") : null;
@@ -271,14 +252,13 @@ const inviteController = async (req, res, next) => {
} }
}; };
const inviteVerifyController = async (req, res, next) => { const verifyInvitation = async (req, res, next) => {
try { try {
await inviteVerifciationBodyValidation.validateAsync(req.body); await inviteVerificationBodyValidation.validateAsync(req.body);
} catch (error) { } catch (error) {
error.status = 422; error.status = 422;
error.service = SERVICE_NAME; error.service = SERVICE_NAME;
error.message = error.message = error.details?.[0]?.message || error.message || "Validation Error";
error.details?.[0]?.message || error.message || "Validation Error";
next(error); next(error);
return; return;
} }
@@ -287,12 +267,10 @@ const inviteVerifyController = async (req, res, next) => {
const invite = await req.db.getInviteToken(req, res); const invite = await req.db.getInviteToken(req, res);
res res
.status(200) .status(200)
.json({ status: "success", msg: "Invite verified", data: invite }); .json({status: "success", msg: "Invite verified", data: invite});
} catch (error) { } catch (error) {
error.service === undefined ? (error.service = SERVICE_NAME) : null; error.service === undefined ? (error.service = SERVICE_NAME) : null;
error.method === undefined error.method === undefined ? (error.method = "inviteVerifyController") : null;
? (error.method = "inviteVerifyController")
: null;
next(error); next(error);
return; return;
} }
@@ -306,19 +284,15 @@ const inviteVerifyController = async (req, res, next) => {
* @returns {Promise<Express.Response>} * @returns {Promise<Express.Response>}
*/ */
const checkSuperadminController = async (req, res) => { const checkSuperadminExists = async (req, res) => {
try { try {
const superAdminExists = await req.db.checkSuperadmin(req, res); const superAdminExists = await req.db.checkSuperadmin(req, res);
return res.status(200).json({ return res.status(200).json({
success: true, success: true, msg: successMessages.AUTH_ADMIN_EXISTS, data: superAdminExists,
msg: successMessages.AUTH_ADMIN_EXISTS,
data: superAdminExists,
}); });
} catch (error) { } catch (error) {
error.service === undefined ? (error.service = SERVICE_NAME) : null; error.service === undefined ? (error.service = SERVICE_NAME) : null;
error.method === undefined error.method === undefined ? (error.method = "checkSuperadminController") : null;
? (error.method = "checkSuperadminController")
: null;
next(error); next(error);
return; return;
} }
@@ -333,46 +307,40 @@ const checkSuperadminController = async (req, res) => {
* @property {EmailService} req.body.emailService * @property {EmailService} req.body.emailService
* @returns {Promise<Express.Response>} * @returns {Promise<Express.Response>}
*/ */
const recoveryRequestController = async (req, res, next) => { const requestRecovery = async (req, res, next) => {
try { try {
await recoveryValidation.validateAsync(req.body); await recoveryValidation.validateAsync(req.body);
} catch (error) { } catch (error) {
error.status = 422; error.status = 422;
error.service = SERVICE_NAME; error.service = SERVICE_NAME;
error.message = error.message = error.details?.[0]?.message || error.message || "Validation Error";
error.details?.[0]?.message || error.message || "Validation Error";
next(error); next(error);
return; return;
} }
try { try {
const { email } = req.body; const {email} = req.body;
const user = await req.db.getUserByEmail(email); const user = await req.db.getUserByEmail(email);
if (user) { if (user) {
const recoveryToken = await req.db.requestRecoveryToken(req, res); const recoveryToken = await req.db.requestRecoveryToken(req, res);
const name = user.firstName; const name = user.firstName;
const email = req.body.email; const email = req.body.email;
const { clientHost } = req.settingsService.getSettings(); const {clientHost} = req.settingsService.getSettings();
const url = `${clientHost}/set-new-password/${recoveryToken.token}`; const url = `${clientHost}/set-new-password/${recoveryToken.token}`;
const msgId = await req.emailService.buildAndSendEmail( const msgId = await req.emailService.buildAndSendEmail("passwordResetTemplate", {
"passwordResetTemplate", name,
{ name, email, url },
email, email,
"Bluewaves Uptime Password Resest" url
); }, email, "Bluewaves Uptime Password Resest");
return res.status(200).json({ return res.status(200).json({
success: true, success: true, msg: successMessages.AUTH_CREATE_RECOVERY_TOKEN, data: msgId,
msg: successMessages.AUTH_CREATE_RECOVERY_TOKEN,
data: msgId,
}); });
} }
} catch (error) { } catch (error) {
error.service === undefined ? (error.service = SERVICE_NAME) : null; error.service === undefined ? (error.service = SERVICE_NAME) : null;
error.method === undefined error.method === undefined ? (error.method = "recoveryRequestController") : null;
? (error.method = "recoveryRequestController")
: null;
next(error); next(error);
return; return;
} }
@@ -387,30 +355,25 @@ const recoveryRequestController = async (req, res, next) => {
* @param {Express.Response} res * @param {Express.Response} res
* @returns {Promise<Express.Response>} * @returns {Promise<Express.Response>}
*/ */
const validateRecoveryTokenController = 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) {
error.status = 422; error.status = 422;
error.service = SERVICE_NAME; error.service = SERVICE_NAME;
error.message = error.message = error.details?.[0]?.message || error.message || "Validation Error";
error.details?.[0]?.message || error.message || "Validation Error";
next(error); next(error);
return; return;
} }
try { try {
await req.db.validateRecoveryToken(req, res); await req.db.validateRecoveryToken(req, res);
// TODO Redirect user to reset password after validating token
return res.status(200).json({ return res.status(200).json({
success: true, success: true, msg: successMessages.AUTH_VERIFY_RECOVERY_TOKEN,
msg: successMessages.AUTH_VERIFY_RECOVERY_TOKEN,
}); });
} catch (error) { } catch (error) {
error.service === undefined ? (error.service = SERVICE_NAME) : null; error.service === undefined ? (error.service = SERVICE_NAME) : null;
error.method === undefined error.method === undefined ? (error.method = "validateRecoveryTokenController") : null;
? (error.method = "validateRecoveryTokenController")
: null;
next(error); next(error);
return; return;
} }
@@ -426,14 +389,13 @@ const validateRecoveryTokenController = async (req, res, next) => {
* @param {Express.Response} res * @param {Express.Response} res
* @returns {Promise<Express.Response>} * @returns {Promise<Express.Response>}
*/ */
const resetPasswordController = async (req, res, next) => { const resetPassword = async (req, res, next) => {
try { try {
await newPasswordValidation.validateAsync(req.body); await newPasswordValidation.validateAsync(req.body);
} catch (error) { } catch (error) {
error.status = 422; error.status = 422;
error.service = SERVICE_NAME; error.service = SERVICE_NAME;
error.message = error.message = error.details?.[0]?.message || error.message || "Validation Error";
error.details?.[0]?.message || error.message || "Validation Error";
next(error); next(error);
return; return;
} }
@@ -443,15 +405,11 @@ const resetPasswordController = async (req, res, next) => {
const appSettings = await req.settingsService.getSettings(); const appSettings = await req.settingsService.getSettings();
const token = issueToken(user._doc, appSettings); const token = issueToken(user._doc, appSettings);
res.status(200).json({ res.status(200).json({
success: true, success: true, msg: successMessages.AUTH_RESET_PASSWORD, data: {user, token},
msg: successMessages.AUTH_RESET_PASSWORD,
data: { user, token },
}); });
} catch (error) { } catch (error) {
error.service === undefined ? (error.service = SERVICE_NAME) : null; error.service === undefined ? (error.service = SERVICE_NAME) : null;
error.method === undefined error.method === undefined ? (error.method = "resetPasswordController") : null;
? (error.method = "resetPasswordController")
: null;
next(error); next(error);
} }
}; };
@@ -465,11 +423,11 @@ const resetPasswordController = async (req, res, next) => {
* @returns {Object} The response object with success status and message. * @returns {Object} The response object with success status and message.
* @throws {Error} If user validation fails or user is not found in the database. * @throws {Error} If user validation fails or user is not found in the database.
*/ */
const deleteUserController = async (req, res, next) => { const deleteUser = async (req, res, next) => {
try { try {
const token = getTokenFromHeaders(req.headers); const token = getTokenFromHeaders(req.headers);
const decodedToken = jwt.decode(token); const decodedToken = jwt.decode(token);
const { _id, email } = decodedToken; const {_id, email} = decodedToken;
// Check if the user exists // Check if the user exists
const user = await req.db.getUserByEmail(email); const user = await req.db.getUserByEmail(email);
@@ -480,19 +438,16 @@ const deleteUserController = async (req, res, next) => {
// 1. Find all the monitors associated with the team ID if superadmin // 1. Find all the monitors associated with the team ID if superadmin
const result = await req.db.getMonitorsByTeamId({ const result = await req.db.getMonitorsByTeamId({
params: { teamId: user.teamId }, params: {teamId: user.teamId},
}); });
if (user.role.includes("superadmin")) { if (user.role.includes("superadmin")) {
//2. Remove all jobs, delete checks and alerts //2. Remove all jobs, delete checks and alerts
result?.monitors.length > 0 && result?.monitors.length > 0 && (await Promise.all(result.monitors.map(async (monitor) => {
(await Promise.all(
result.monitors.map(async (monitor) => {
await req.jobQueue.deleteJob(monitor); await req.jobQueue.deleteJob(monitor);
await req.db.deleteChecks(monitor._id); await req.db.deleteChecks(monitor._id);
await req.db.deletePageSpeedChecksByMonitorId(monitor._id); await req.db.deletePageSpeedChecksByMonitorId(monitor._id);
await req.db.deleteNotificationsByMonitorId(monitor._id); await req.db.deleteNotificationsByMonitorId(monitor._id);
}) })));
));
// 3. Delete team // 3. Delete team
await req.db.deleteTeam(user.teamId); await req.db.deleteTeam(user.teamId);
@@ -505,8 +460,7 @@ const deleteUserController = async (req, res, next) => {
await req.db.deleteUser(user._id); await req.db.deleteUser(user._id);
return res.status(200).json({ return res.status(200).json({
success: true, success: true, msg: successMessages.AUTH_DELETE_USER,
msg: successMessages.AUTH_DELETE_USER,
}); });
} catch (error) { } catch (error) {
error.service === undefined ? (error.service = SERVICE_NAME) : null; error.service === undefined ? (error.service = SERVICE_NAME) : null;
@@ -515,31 +469,29 @@ const deleteUserController = async (req, res, next) => {
} }
}; };
const getAllUsersController = async (req, res) => { const getAllUsers = async (req, res) => {
try { try {
const allUsers = await req.db.getAllUsers(req, res); const allUsers = await req.db.getAllUsers(req, res);
res res
.status(200) .status(200)
.json({ success: true, msg: "Got all users", data: allUsers }); .json({success: true, msg: "Got all users", data: allUsers});
} catch (error) { } catch (error) {
error.service === undefined ? (error.service = SERVICE_NAME) : null; error.service === undefined ? (error.service = SERVICE_NAME) : null;
error.method === undefined error.method === undefined ? (error.method = "getAllUsersController") : null;
? (error.method = "getAllUsersController")
: null;
next(error); next(error);
} }
}; };
module.exports = { module.exports = {
registerController, registerUser,
loginController, loginUser,
userEditController, editUser,
inviteController, createInvitation,
inviteVerifyController, verifyInvitation,
checkSuperadminController, checkSuperadminExists,
recoveryRequestController, requestRecovery,
validateRecoveryTokenController, validateRecovery,
resetPasswordController, resetPassword,
deleteUserController, deleteUser,
getAllUsersController, getAllUsers,
}; };
+2 -2
View File
@@ -1,7 +1,7 @@
const { const {
inviteRoleValidation, inviteRoleValidation,
inviteBodyValidation, inviteBodyValidation,
inviteVerifciationBodyValidation, inviteVerificationBodyValidation,
} = require("../validation/joi"); } = require("../validation/joi");
const logger = require("../utils/logger"); const logger = require("../utils/logger");
require("dotenv").config(); require("dotenv").config();
@@ -70,7 +70,7 @@ const inviteController = async (req, res, next) => {
const inviteVerifyController = async (req, res, next) => { const inviteVerifyController = async (req, res, next) => {
try { try {
await inviteVerifciationBodyValidation.validateAsync(req.body); await inviteVerificationBodyValidation.validateAsync(req.body);
} catch (error) { } catch (error) {
error.status = 422; error.status = 422;
error.service = SERVICE_NAME; error.service = SERVICE_NAME;
+91 -42
View File
@@ -11,8 +11,6 @@ const {
getMonitorStatsByIdParamValidation, getMonitorStatsByIdParamValidation,
getMonitorStatsByIdQueryValidation, getMonitorStatsByIdQueryValidation,
getCertificateParamValidation, getCertificateParamValidation,
getMonitorAggregateStatsParamValidation,
getMonitorAggregateStatsQueryValidation,
} = require("../validation/joi"); } = require("../validation/joi");
const sslChecker = require("ssl-checker"); const sslChecker = require("ssl-checker");
@@ -27,6 +25,7 @@ const logger = require("../utils/logger");
* @async * @async
* @param {Express.Request} req * @param {Express.Request} req
* @param {Express.Response} res * @param {Express.Response} res
* @param {function} next
* @returns {Promise<Express.Response>} * @returns {Promise<Express.Response>}
* @throws {Error} * @throws {Error}
*/ */
@@ -50,6 +49,7 @@ const getAllMonitors = async (req, res, next) => {
* @async * @async
* @param {Express.Request} req * @param {Express.Request} req
* @param {Express.Response} res * @param {Express.Response} res
* @param {function} next
* @returns {Promise<Express.Response>} * @returns {Promise<Express.Response>}
* @throws {Error} * @throws {Error}
*/ */
@@ -119,12 +119,15 @@ const getMonitorCertificate = async (req, res, next) => {
}; };
/** /**
* Returns monitor with matching ID * Retrieves a monitor by its ID.
* @async * @async
* @param {Express.Request} req * @param {Object} req - The Express request object.
* @param {Express.Response} res * @property {Object} req.params - The parameters of the request.
* @returns {Promise<Express.Response>} * @property {string} req.params.monitorId - The ID of the monitor to be retrieved.
* @throws {Error} * @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) => { const getMonitorById = async (req, res, next) => {
try { try {
@@ -143,7 +146,6 @@ const getMonitorById = async (req, res, next) => {
if (!monitor) { if (!monitor) {
const error = new Error(errorMessages.MONITOR_GET_BY_ID); const error = new Error(errorMessages.MONITOR_GET_BY_ID);
error.status = 404; error.status = 404;
throw error;
} }
return res.json({ return res.json({
@@ -159,14 +161,18 @@ const getMonitorById = async (req, res, next) => {
}; };
/** /**
* Returns all monitors and a sumamry for a team with TeamID * Retrieves all monitors and a summary for a team based on the team ID.
* @async * @async
* @param {Express.Request} req * @param {Object} req - The Express request object.
* @param {Express.Response} res * @property {Object} req.params - The parameters of the request.
* @returns {Promise<Express.Response>} * @property {string} req.params.teamId - The ID of the team.
* @throws {Error} * @property {Object} req.query - The query parameters of the request.
* @property {string} req.query.type - The type 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 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) => { const getMonitorsAndSummaryByTeamId = async (req, res, next) => {
try { try {
await getMonitorsAndSummaryByTeamIdParamValidation.validateAsync( await getMonitorsAndSummaryByTeamIdParamValidation.validateAsync(
@@ -177,8 +183,7 @@ const getMonitorsAndSummaryByTeamId = async (req, res, next) => {
} catch (error) { } catch (error) {
error.status = 422; error.status = 422;
error.service = SERVICE_NAME; error.service = SERVICE_NAME;
error.method === undefined && error.method === undefined? error.method = "getMonitorsAndSummaryByTeamId": null;
error.method === "getMonitorsAndSummaryByTeamId";
error.message = error.message =
error.details?.[0]?.message || error.message || "Validation Error"; error.details?.[0]?.message || error.message || "Validation Error";
next(error); next(error);
@@ -207,12 +212,16 @@ const getMonitorsAndSummaryByTeamId = async (req, res, next) => {
}; };
/** /**
* Returns all monitors belong to team with TeamID * Retrieves all monitors associated with a team by the team's ID.
* @async * @async
* @param {Express.Request} req * @param {Object} req - The Express request object.
* @param {Express.Response} res * @property {Object} req.params - The parameters of the request.
* @returns {Promise<Express.Response>} * @property {string} req.params.teamId - The ID of the team.
* @throws {Error} * @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).
*/ */
const getMonitorsByTeamId = async (req, res, next) => { const getMonitorsByTeamId = async (req, res, next) => {
try { try {
@@ -243,14 +252,16 @@ const getMonitorsByTeamId = async (req, res, next) => {
}; };
/** /**
* Creates a new monitor * Creates a new monitor and adds it to the job queue.
* @async * @async
* @param {Express.Request} req * @param {Object} req - The Express request object.
* @param {Express.Response} res * @property {Object} req.body - The body of the request.
* @returns {Promise<Express.Response>} * @property {Array} req.body.notifications - The notifications associated with the monitor.
* @throws {Error} * @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).
*/ */
const createMonitor = async (req, res, next) => { const createMonitor = async (req, res, next) => {
try { try {
await createMonitorBodyValidation.validateAsync(req.body); await createMonitorBodyValidation.validateAsync(req.body);
@@ -269,13 +280,12 @@ const createMonitor = async (req, res, next) => {
const monitor = await req.db.createMonitor(req, res); const monitor = await req.db.createMonitor(req, res);
if (notifications && notifications.length !== 0) { if (notifications && notifications.length !== 0) {
const setNotifications = await Promise.all( monitor.notifications = await Promise.all(
notifications.map(async (notification) => { notifications.map(async (notification) => {
notification.monitorId = monitor._id; notification.monitorId = monitor._id;
await req.db.createNotification(notification); await req.db.createNotification(notification);
}) })
); );
monitor.notifications = setNotifications;
await monitor.save(); await monitor.save();
} }
// Add monitor to job queue // Add monitor to job queue
@@ -293,14 +303,16 @@ const createMonitor = async (req, res, next) => {
}; };
/** /**
* Delete a monitor by ID * Deletes a monitor by its ID and also deletes associated checks, alerts, and notifications.
* @async * @async
* @param {Express.Request} req * @param {Object} req - The Express request object.
* @param {Express.Response} res * @property {Object} req.params - The parameters of the request.
* @returns {Promise<Express.Response>} * @property {string} req.params.monitorId - The ID of the monitor to be deleted.
* @throws {Error} * @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) => { const deleteMonitor = async (req, res, next) => {
try { try {
await getMonitorByIdParamValidation.validateAsync(req.params); await getMonitorByIdParamValidation.validateAsync(req.params);
@@ -331,7 +343,6 @@ const deleteMonitor = async (req, res, next) => {
} }
); );
} }
return res return res
.status(200) .status(200)
.json({ success: true, msg: successMessages.MONITOR_DELETE }); .json({ success: true, msg: successMessages.MONITOR_DELETE });
@@ -342,7 +353,18 @@ const deleteMonitor = async (req, res, next) => {
} }
}; };
const deleteAllMonitors = async (req, res) => { /**
* 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.
*/
const deleteAllMonitors = async (req, res, next) => {
try { try {
const token = getTokenFromHeaders(req.headers); const token = getTokenFromHeaders(req.headers);
const { jwtSecret } = req.settingsService.getSettings(); const { jwtSecret } = req.settingsService.getSettings();
@@ -367,12 +389,17 @@ const deleteAllMonitors = async (req, res) => {
}; };
/** /**
* Edit a monitor by ID * Edits a monitor by its ID, updates its notifications, and updates its job in the job queue.
* @async * @async
* @param {Express.Request} req * @param {Object} req - The Express request object.
* @param {Express.Response} res * @property {Object} req.params - The parameters of the request.
* @returns {Promise<Express.Response>} * @property {string} req.params.monitorId - The ID of the monitor to be edited.
* @throws {Error} * @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) => { const editMonitor = async (req, res, next) => {
try { try {
@@ -423,6 +450,17 @@ const editMonitor = async (req, res, next) => {
} }
}; };
/**
* Pauses or resumes a monitor based on its current state.
* @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 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) => { const pauseMonitor = async (req, res, next) => {
try { try {
await pauseMonitorParamValidation.validateAsync(req.params); await pauseMonitorParamValidation.validateAsync(req.params);
@@ -458,6 +496,17 @@ const pauseMonitor = async (req, res, next) => {
} }
}; };
/**
* Adds demo monitors for 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 - 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) => { const addDemoMonitors = async (req, res, next) => {
try { try {
const token = getTokenFromHeaders(req.headers); const token = getTokenFromHeaders(req.headers);
+18 -18
View File
@@ -7,44 +7,44 @@ const upload = multer();
const User = require("../db/models/User"); const User = require("../db/models/User");
const { const {
registerController, registerUser,
loginController, loginUser,
logoutController, logoutController,
userEditController, editUser,
recoveryRequestController, requestRecovery,
validateRecoveryTokenController, validateRecovery,
resetPasswordController, resetPassword,
checkSuperadminController, checkSuperadminExists,
getAllUsersController, getAllUsers,
deleteUserController, deleteUser,
} = require("../controllers/authController"); } = require("../controllers/authController");
//Auth routes //Auth routes
router.post("/register", upload.single("profileImage"), registerController); router.post("/register", upload.single("profileImage"), registerUser);
router.post("/login", loginController); router.post("/login", loginUser);
router.put( router.put(
"/user/:userId", "/user/:userId",
upload.single("profileImage"), upload.single("profileImage"),
verifyJWT, verifyJWT,
userEditController editUser
); );
router.get("/users/superadmin", checkSuperadminController); router.get("/users/superadmin", checkSuperadminExists);
router.get( router.get(
"/users", "/users",
verifyJWT, verifyJWT,
isAllowed(["admin", "superadmin"]), isAllowed(["admin", "superadmin"]),
getAllUsersController getAllUsers
); );
router.delete( router.delete(
"/user/:userId", "/user/:userId",
verifyJWT, verifyJWT,
verifyOwnership(User, "userId"), verifyOwnership(User, "userId"),
deleteUserController deleteUser
); );
//Recovery routes //Recovery routes
router.post("/recovery/request", recoveryRequestController); router.post("/recovery/request", requestRecovery);
router.post("/recovery/validate", validateRecoveryTokenController); router.post("/recovery/validate", validateRecovery);
router.post("/recovery/reset/", resetPasswordController); router.post("/recovery/reset/", resetPassword);
module.exports = router; module.exports = router;
+1 -1
View File
@@ -410,7 +410,7 @@ module.exports = {
newPasswordValidation, newPasswordValidation,
inviteRoleValidation, inviteRoleValidation,
inviteBodyValidation, inviteBodyValidation,
inviteVerifciationBodyValidation, inviteVerificationBodyValidation: inviteVerifciationBodyValidation,
createMonitorBodyValidation, createMonitorBodyValidation,
getMonitorByIdParamValidation, getMonitorByIdParamValidation,
getMonitorByIdQueryValidation, getMonitorByIdQueryValidation,