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
+504 -503

No files matched your search

+388 -436
View File
@@ -1,109 +1,103 @@
const express = require("express"); const express = require("express");
const { const {
registrationBodyValidation, registrationBodyValidation,
loginValidation, loginValidation,
editUserParamValidation, editUserParamValidation,
editUserBodyValidation, editUserBodyValidation,
recoveryValidation, recoveryValidation,
recoveryTokenValidation, recoveryTokenValidation,
newPasswordValidation, newPasswordValidation,
deleteUserParamValidation, inviteRoleValidation,
inviteRoleValidation, inviteBodyValidation,
inviteBodyValidation, inviteVerificationBodyValidation,
inviteVerifciationBodyValidation,
} = 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;
next(error); next(error);
} }
}; };
/** /**
* @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
try {
const { inviteToken } = req.body;
// 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 });
} }
// 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 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); 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 };
delete userForToken.profileImage;
delete userForToken.avatarImage;
const appSettings = await req.settingsService.getSettings();
const token = issueToken(userForToken, appSettings);
req.emailService
.buildAndSendEmail(
"welcomeEmailTemplate",
{ name: newUser.firstName },
newUser.email,
"Welcome to Uptime Monitor"
)
.catch((error) => {
logger.error("Error sending welcome email", {
service: SERVICE_NAME,
error: error.message,
}); });
});
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 },
}); const appSettings = await req.settingsService.getSettings();
} catch (error) { const token = issueToken(userForToken, appSettings);
error.service === undefined ? (error.service = SERVICE_NAME) : null; req.emailService
error.method === undefined ? (error.method = "registerController") : null; .buildAndSendEmail("welcomeEmailTemplate", {name: newUser.firstName}, newUser.email, "Welcome to Uptime Monitor")
next(error); .catch((error) => {
} logger.error("Error sending welcome email", {
service: SERVICE_NAME, error: error.message,
});
});
return res.status(200).json({
success: true, msg: successMessages.AUTH_CREATE_USER, data: {user: newUser, token: token},
});
} catch (error) {
error.service === undefined ? (error.service = SERVICE_NAME) : null;
error.method === undefined ? (error.method = "registerController") : null;
next(error);
}
}; };
/** /**
@@ -111,191 +105,175 @@ 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 {
await loginValidation.validateAsync(req.body);
} catch (error) {
error.status = 422;
error.service = SERVICE_NAME;
error.message =
error.details?.[0]?.message || error.message || "Validation Error";
next(error);
return;
}
try {
const { email, password } = req.body;
// Check if user exists
const user = await req.db.getUserByEmail(email);
// Compare password
const match = await user.comparePassword(password);
if (match !== true) {
throw new Error(errorMessages.AUTH_INCORRECT_PASSWORD);
}
// 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 = req.settingsService.getSettings();
const token = issueToken(userWithoutPassword, 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 },
});
} catch (error) {
error.status = 500;
error.service === undefined ? (error.service = SERVICE_NAME) : null;
error.method === undefined ? (error.method = "loginController") : null;
next(error);
}
};
const userEditController = async (req, res, next) => {
try {
await editUserParamValidation.validateAsync(req.params);
await editUserBodyValidation.validateAsync(req.body);
} catch (error) {
error.status = 422;
error.service = SERVICE_NAME;
error.message =
error.details?.[0]?.message || error.message || "Validation Error";
next(error);
return;
}
// TODO is this neccessary any longer? Verify ownership middleware should handle this
if (req.params.userId !== req.user._id.toString()) {
const error = new Error(errorMessages.AUTH_UNAUTHORIZED);
error.status = 401;
error.service = SERVICE_NAME;
next(error);
return;
}
try {
// Change Password check
if (req.body.password && req.body.newPassword) {
const newPassword = req.body.newPassword;
const password = req.body.password;
// Compare password
// Get token from headers
const token = getTokenFromHeaders(req.headers);
// Get email from token
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
if (!match) {
const error = new Error(errorMessages.AUTH_INCORRECT_PASSWORD);
error.status = 403;
throw error;
}
// If a match, update the password
req.body.password = req.body.newPassword;
}
const updatedUser = await req.db.updateUser(req, res);
return res.status(200).json({
success: true,
msg: successMessages.AUTH_UPDATE_USER,
data: updatedUser,
});
} catch (error) {
error.service === undefined ? (error.service = SERVICE_NAME) : null;
error.method === undefined ? (error.method = "userEditController") : null;
next(error);
return;
}
};
const inviteController = async (req, res, next) => {
try {
// Only admins can invite
const token = getTokenFromHeaders(req.headers);
const { role, firstname, teamId } = jwt.decode(token);
req.body.teamId = teamId;
try { try {
await inviteRoleValidation.validateAsync({ roles: role }); await loginValidation.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;
} }
try {
const {email, password} = req.body;
// Check if user exists
const user = await req.db.getUserByEmail(email);
const inviteToken = await req.db.requestInviteToken(req, res); // Compare password
const { clientHost } = req.settingsService.getSettings(); const match = await user.comparePassword(password);
req.emailService if (match !== true) {
.buildAndSendEmail( throw new Error(errorMessages.AUTH_INCORRECT_PASSWORD);
"employeeActivationTemplate", }
{
name: firstname, // Remove password from user object. Should this be abstracted to DB layer?
link: `${clientHost}/register/${inviteToken.token}`, const userWithoutPassword = {...user._doc};
}, delete userWithoutPassword.password;
req.body.email, delete userWithoutPassword.avatarImage;
"Welcome to Uptime Monitor"
) // Happy path, return token
.catch((error) => { const appSettings = req.settingsService.getSettings();
logger.error("Error sending invite email", { const token = issueToken(userWithoutPassword, appSettings);
service: SERVICE_NAME, // reset avatar image
error: error.message, userWithoutPassword.avatarImage = user.avatarImage;
return res.status(200).json({
success: true, msg: successMessages.AUTH_LOGIN_USER, data: {user: userWithoutPassword, token: token},
}); });
}); } catch (error) {
error.status = 500;
return res error.service === undefined ? (error.service = SERVICE_NAME) : null;
.status(200) error.method === undefined ? (error.method = "loginController") : null;
.json({ success: true, msg: "Invite sent", data: inviteToken }); next(error);
} catch (error) { }
error.service === undefined ? (error.service = SERVICE_NAME) : null;
error.method === undefined ? (error.method = "inviteController") : null;
next(error);
return;
}
}; };
const inviteVerifyController = async (req, res, next) => { const editUser = async (req, res, next) => {
try { try {
await inviteVerifciationBodyValidation.validateAsync(req.body); await editUserParamValidation.validateAsync(req.params);
} catch (error) { await editUserBodyValidation.validateAsync(req.body);
error.status = 422; } catch (error) {
error.service = SERVICE_NAME; error.status = 422;
error.message = error.service = SERVICE_NAME;
error.details?.[0]?.message || error.message || "Validation Error"; error.message = error.details?.[0]?.message || error.message || "Validation Error";
next(error); next(error);
return; return;
} }
try { // TODO is this neccessary any longer? Verify ownership middleware should handle this
const invite = await req.db.getInviteToken(req, res); if (req.params.userId !== req.user._id.toString()) {
res const error = new Error(errorMessages.AUTH_UNAUTHORIZED);
.status(200) error.status = 401;
.json({ status: "success", msg: "Invite verified", data: invite }); error.service = SERVICE_NAME;
} catch (error) { next(error);
error.service === undefined ? (error.service = SERVICE_NAME) : null; return;
error.method === undefined }
? (error.method = "inviteVerifyController")
: null; try {
next(error); // Change Password check
return; if (req.body.password && req.body.newPassword) {
} const newPassword = req.body.newPassword;
const password = req.body.password;
// Compare password
// Get token from headers
const token = getTokenFromHeaders(req.headers);
// Get email from token
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
if (!match) {
const error = new Error(errorMessages.AUTH_INCORRECT_PASSWORD);
error.status = 403;
throw error;
}
// If a match, update the password
req.body.password = req.body.newPassword;
}
const updatedUser = await req.db.updateUser(req, res);
return res.status(200).json({
success: true, msg: successMessages.AUTH_UPDATE_USER, data: updatedUser,
});
} catch (error) {
error.service === undefined ? (error.service = SERVICE_NAME) : null;
error.method === undefined ? (error.method = "userEditController") : null;
next(error);
return;
}
};
const createInvitation = async (req, res, next) => {
try {
// Only admins can invite
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) {
error.status = 422;
error.service = SERVICE_NAME;
error.message = error.details?.[0]?.message || error.message || "Validation Error";
next(error);
return;
}
const inviteToken = await req.db.requestInviteToken(req, res);
const {clientHost} = req.settingsService.getSettings();
req.emailService
.buildAndSendEmail("employeeActivationTemplate", {
name: firstname, link: `${clientHost}/register/${inviteToken.token}`,
}, req.body.email, "Welcome to Uptime Monitor")
.catch((error) => {
logger.error("Error sending invite email", {
service: SERVICE_NAME, error: error.message,
});
});
return res
.status(200)
.json({success: true, msg: "Invite sent", data: inviteToken});
} catch (error) {
error.service === undefined ? (error.service = SERVICE_NAME) : null;
error.method === undefined ? (error.method = "inviteController") : null;
next(error);
return;
}
};
const verifyInvitation = async (req, res, next) => {
try {
await inviteVerificationBodyValidation.validateAsync(req.body);
} catch (error) {
error.status = 422;
error.service = SERVICE_NAME;
error.message = error.details?.[0]?.message || error.message || "Validation Error";
next(error);
return;
}
try {
const invite = await req.db.getInviteToken(req, res);
res
.status(200)
.json({status: "success", msg: "Invite verified", data: invite});
} catch (error) {
error.service === undefined ? (error.service = SERVICE_NAME) : null;
error.method === undefined ? (error.method = "inviteVerifyController") : null;
next(error);
return;
}
}; };
/** /**
@@ -306,22 +284,18 @@ 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) {
}); error.service === undefined ? (error.service = SERVICE_NAME) : null;
} catch (error) { error.method === undefined ? (error.method = "checkSuperadminController") : null;
error.service === undefined ? (error.service = SERVICE_NAME) : null; next(error);
error.method === undefined return;
? (error.method = "checkSuperadminController") }
: null;
next(error);
return;
}
}; };
/** /**
@@ -333,49 +307,43 @@ 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("passwordResetTemplate", {
const msgId = await req.emailService.buildAndSendEmail( name,
"passwordResetTemplate", email,
{ name, email, url }, url
email, }, email, "Bluewaves Uptime Password Resest");
"Bluewaves Uptime Password Resest"
); return res.status(200).json({
success: true, msg: successMessages.AUTH_CREATE_RECOVERY_TOKEN, data: msgId,
return res.status(200).json({ });
success: true, }
msg: successMessages.AUTH_CREATE_RECOVERY_TOKEN, } catch (error) {
data: msgId, error.service === undefined ? (error.service = SERVICE_NAME) : null;
}); error.method === undefined ? (error.method = "recoveryRequestController") : null;
next(error);
return;
} }
} catch (error) {
error.service === undefined ? (error.service = SERVICE_NAME) : null;
error.method === undefined
? (error.method = "recoveryRequestController")
: null;
next(error);
return;
}
}; };
/** /**
@@ -387,33 +355,28 @@ 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, msg: successMessages.AUTH_VERIFY_RECOVERY_TOKEN,
success: true, });
msg: successMessages.AUTH_VERIFY_RECOVERY_TOKEN, } catch (error) {
}); error.service === undefined ? (error.service = SERVICE_NAME) : null;
} catch (error) { error.method === undefined ? (error.method = "validateRecoveryTokenController") : null;
error.service === undefined ? (error.service = SERVICE_NAME) : null; next(error);
error.method === undefined return;
? (error.method = "validateRecoveryTokenController") }
: null;
next(error);
return;
}
}; };
/** /**
@@ -426,34 +389,29 @@ 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; }
} try {
try { const user = await req.db.resetPassword(req, res);
const user = await req.db.resetPassword(req, res);
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) {
}); error.service === undefined ? (error.service = SERVICE_NAME) : null;
} catch (error) { error.method === undefined ? (error.method = "resetPasswordController") : null;
error.service === undefined ? (error.service = SERVICE_NAME) : null; next(error);
error.method === undefined }
? (error.method = "resetPasswordController")
: null;
next(error);
}
}; };
/** /**
@@ -465,81 +423,75 @@ 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);
if (!user) { if (!user) {
throw new Error(errorMessages.DB_USER_NOT_FOUND); throw new Error(errorMessages.DB_USER_NOT_FOUND);
}
// 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) {
error.service === undefined ? (error.service = SERVICE_NAME) : null;
error.method === undefined ? (error.method = "deleteUserController") : null;
next(error);
} }
// 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) {
error.service === undefined ? (error.service = SERVICE_NAME) : null;
error.method === undefined ? (error.method = "deleteUserController") : null;
next(error);
}
}; };
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") next(error);
: null; }
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;
+95 -46
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,