Merge pull request #921 from bluewave-labs/feat/be/error-handling
Refactor BE error handling
This commit is contained in:
9 files changed
+446
-600
No files matched your search
@@ -1,19 +1,20 @@
|
|||||||
const {
|
const {
|
||||||
registrationBodyValidation,
|
registrationBodyValidation,
|
||||||
loginValidation,
|
loginValidation,
|
||||||
editUserParamValidation,
|
editUserParamValidation,
|
||||||
editUserBodyValidation,
|
editUserBodyValidation,
|
||||||
recoveryValidation,
|
recoveryValidation,
|
||||||
recoveryTokenValidation,
|
recoveryTokenValidation,
|
||||||
newPasswordValidation,
|
newPasswordValidation,
|
||||||
} = 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");
|
||||||
const 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");
|
||||||
|
const { handleValidationError, handleError } = require("./controllerUtils");
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Creates and returns JWT token with an arbitrary payload
|
* Creates and returns JWT token with an arbitrary payload
|
||||||
@@ -24,14 +25,12 @@ const crypto = require("crypto");
|
|||||||
* @throws {Error}
|
* @throws {Error}
|
||||||
*/
|
*/
|
||||||
const issueToken = (payload, appSettings) => {
|
const issueToken = (payload, appSettings) => {
|
||||||
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;
|
throw handleError(error, SERVICE_NAME, "issueToken");
|
||||||
error.method === undefined ? (error.method = "issueToken") : null;
|
}
|
||||||
throw error;
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -47,56 +46,61 @@ const issueToken = (payload, appSettings) => {
|
|||||||
* @throws {Error} If there is an error during the process, especially if there is a validation error (422).
|
* @throws {Error} If there is an error during the process, especially if there is a validation error (422).
|
||||||
*/
|
*/
|
||||||
const registerUser = async (req, res, next) => {
|
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;
|
const validationError = handleValidationError(error, SERVICE_NAME);
|
||||||
error.service = SERVICE_NAME;
|
next(validationError);
|
||||||
error.message = error.details?.[0]?.message || error.message || "Validation Error";
|
return;
|
||||||
next(error);
|
}
|
||||||
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, userId: newUser._id,
|
service: SERVICE_NAME,
|
||||||
|
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,
|
||||||
});
|
});
|
||||||
|
});
|
||||||
|
|
||||||
const userForToken = {...newUser._doc};
|
return res.status(200).json({
|
||||||
delete userForToken.profileImage;
|
success: true,
|
||||||
delete userForToken.avatarImage;
|
msg: successMessages.AUTH_CREATE_USER,
|
||||||
|
data: { user: newUser, token: token },
|
||||||
const appSettings = await req.settingsService.getSettings();
|
});
|
||||||
const token = issueToken(userForToken, appSettings);
|
} catch (error) {
|
||||||
req.emailService
|
next(handleError(error, SERVICE_NAME, "registerController"));
|
||||||
.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({
|
|
||||||
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);
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -112,47 +116,44 @@ const registerUser = async (req, res, next) => {
|
|||||||
* @throws {Error} If there is an error during the process, especially if there is a validation error (422) or the password is incorrect.
|
* @throws {Error} If there is an error during the process, especially if there is a validation error (422) or the password is incorrect.
|
||||||
*/
|
*/
|
||||||
const loginUser = async (req, res, next) => {
|
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;
|
const validationError = handleValidationError(error, SERVICE_NAME);
|
||||||
error.service = SERVICE_NAME;
|
next(validationError);
|
||||||
error.message = error.details?.[0]?.message || error.message || "Validation Error";
|
return;
|
||||||
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) {
|
||||||
|
next(new Error(errorMessages.AUTH_INCORRECT_PASSWORD));
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
try {
|
|
||||||
const {email, password} = req.body;
|
|
||||||
// Check if user exists
|
|
||||||
const user = await req.db.getUserByEmail(email);
|
|
||||||
|
|
||||||
// Compare password
|
// Remove password from user object. Should this be abstracted to DB layer?
|
||||||
const match = await user.comparePassword(password);
|
const userWithoutPassword = { ...user._doc };
|
||||||
if (match !== true) {
|
delete userWithoutPassword.password;
|
||||||
next(new Error(errorMessages.AUTH_INCORRECT_PASSWORD));
|
delete userWithoutPassword.avatarImage;
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Remove password from user object. Should this be abstracted to DB layer?
|
// Happy path, return token
|
||||||
const userWithoutPassword = {...user._doc};
|
const appSettings = req.settingsService.getSettings();
|
||||||
delete userWithoutPassword.password;
|
const token = issueToken(userWithoutPassword, appSettings);
|
||||||
delete userWithoutPassword.avatarImage;
|
// reset avatar image
|
||||||
|
userWithoutPassword.avatarImage = user.avatarImage;
|
||||||
|
|
||||||
// Happy path, return token
|
return res.status(200).json({
|
||||||
const appSettings = req.settingsService.getSettings();
|
success: true,
|
||||||
const token = issueToken(userWithoutPassword, appSettings);
|
msg: successMessages.AUTH_LOGIN_USER,
|
||||||
// reset avatar image
|
data: { user: userWithoutPassword, token: token },
|
||||||
userWithoutPassword.avatarImage = user.avatarImage;
|
});
|
||||||
|
} catch (error) {
|
||||||
return res.status(200).json({
|
next(handleError(error, SERVICE_NAME, "loginController"));
|
||||||
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);
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -170,60 +171,58 @@ const loginUser = async (req, res, next) => {
|
|||||||
* @throws {Error} If there is an error during the process, especially if there is a validation error (422), the user is unauthorized (401), or the password is incorrect (403).
|
* @throws {Error} If there is an error during the process, especially if there is a validation error (422), the user is unauthorized (401), or the password is incorrect (403).
|
||||||
*/
|
*/
|
||||||
const editUser = async (req, res, next) => {
|
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;
|
const validationError = handleValidationError(error, SERVICE_NAME);
|
||||||
error.service = SERVICE_NAME;
|
next(validationError);
|
||||||
error.message = error.details?.[0]?.message || error.message || "Validation 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) {
|
||||||
|
// 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;
|
||||||
next(error);
|
next(error);
|
||||||
return;
|
return;
|
||||||
|
}
|
||||||
|
// If a match, update the password
|
||||||
|
req.body.password = req.body.newPassword;
|
||||||
}
|
}
|
||||||
|
|
||||||
// TODO is this neccessary any longer? Verify ownership middleware should handle this
|
const updatedUser = await req.db.updateUser(req, res);
|
||||||
if (req.params.userId !== req.user._id.toString()) {
|
return res.status(200).json({
|
||||||
const error = new Error(errorMessages.AUTH_UNAUTHORIZED);
|
success: true,
|
||||||
error.status = 401;
|
msg: successMessages.AUTH_UPDATE_USER,
|
||||||
error.service = SERVICE_NAME;
|
data: updatedUser,
|
||||||
next(error);
|
});
|
||||||
return;
|
} catch (error) {
|
||||||
}
|
next(handleError(error, SERVICE_NAME, "userEditController"));
|
||||||
|
}
|
||||||
try {
|
|
||||||
// Change Password check
|
|
||||||
if (req.body.password && req.body.newPassword) {
|
|
||||||
// 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;
|
|
||||||
next(error)
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
// 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);
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -236,16 +235,16 @@ const editUser = async (req, res, next) => {
|
|||||||
* @throws {Error} If there is an error during the process.
|
* @throws {Error} If there is an error during the process.
|
||||||
*/
|
*/
|
||||||
const checkSuperAdminExists = async (req, res, next) => {
|
const checkSuperAdminExists = async (req, res, next) => {
|
||||||
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, msg: successMessages.AUTH_ADMIN_EXISTS, data: superAdminExists,
|
success: true,
|
||||||
});
|
msg: successMessages.AUTH_ADMIN_EXISTS,
|
||||||
} catch (error) {
|
data: superAdminExists,
|
||||||
error.service === undefined ? (error.service = SERVICE_NAME) : null;
|
});
|
||||||
error.method === undefined ? (error.method = "checkSuperadminController") : null;
|
} catch (error) {
|
||||||
next(error);
|
next(handleError(error, SERVICE_NAME, "checkSuperadminController"));
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -260,41 +259,44 @@ const checkSuperAdminExists = async (req, res, next) => {
|
|||||||
* @throws {Error} If there is an error during the process, especially if there is a validation error (422).
|
* @throws {Error} If there is an error during the process, especially if there is a validation error (422).
|
||||||
*/
|
*/
|
||||||
const requestRecovery = async (req, res, next) => {
|
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;
|
const validationError = handleValidationError(error, SERVICE_NAME);
|
||||||
error.service = SERVICE_NAME;
|
next(validationError);
|
||||||
error.message = error.details?.[0]?.message || error.message || "Validation Error";
|
return;
|
||||||
next(error);
|
}
|
||||||
return;
|
|
||||||
}
|
try {
|
||||||
|
const { email } = req.body;
|
||||||
try {
|
const user = await req.db.getUserByEmail(email);
|
||||||
const {email} = req.body;
|
if (user) {
|
||||||
const user = await req.db.getUserByEmail(email);
|
const recoveryToken = await req.db.requestRecoveryToken(req, res);
|
||||||
if (user) {
|
const name = user.firstName;
|
||||||
const recoveryToken = await req.db.requestRecoveryToken(req, res);
|
const email = req.body.email;
|
||||||
const name = user.firstName;
|
const { clientHost } = req.settingsService.getSettings();
|
||||||
const email = req.body.email;
|
const url = `${clientHost}/set-new-password/${recoveryToken.token}`;
|
||||||
const {clientHost} = req.settingsService.getSettings();
|
|
||||||
const url = `${clientHost}/set-new-password/${recoveryToken.token}`;
|
const msgId = await req.emailService.buildAndSendEmail(
|
||||||
|
"passwordResetTemplate",
|
||||||
const msgId = await req.emailService.buildAndSendEmail("passwordResetTemplate", {
|
{
|
||||||
name,
|
name,
|
||||||
email,
|
email,
|
||||||
url
|
url,
|
||||||
}, email, "Bluewave Uptime Password Reset");
|
},
|
||||||
|
email,
|
||||||
return res.status(200).json({
|
"Bluewave Uptime Password Reset"
|
||||||
success: true, msg: successMessages.AUTH_CREATE_RECOVERY_TOKEN, data: msgId,
|
);
|
||||||
});
|
|
||||||
}
|
return res.status(200).json({
|
||||||
} catch (error) {
|
success: true,
|
||||||
error.service === undefined ? (error.service = SERVICE_NAME) : null;
|
msg: successMessages.AUTH_CREATE_RECOVERY_TOKEN,
|
||||||
error.method === undefined ? (error.method = "recoveryRequestController") : null;
|
data: msgId,
|
||||||
next(error);
|
});
|
||||||
}
|
}
|
||||||
|
} catch (error) {
|
||||||
|
next(handleError(error, SERVICE_NAME, "recoveryRequestController"));
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -309,26 +311,23 @@ const requestRecovery = async (req, res, next) => {
|
|||||||
* @throws {Error} If there is an error during the process, especially if there is a validation error (422).
|
* @throws {Error} If there is an error during the process, especially if there is a validation error (422).
|
||||||
*/
|
*/
|
||||||
const validateRecovery = async (req, res, next) => {
|
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;
|
const validationError = handleValidationError(error, SERVICE_NAME);
|
||||||
error.service = SERVICE_NAME;
|
next(validationError);
|
||||||
error.message = error.details?.[0]?.message || error.message || "Validation Error";
|
return;
|
||||||
next(error);
|
}
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await req.db.validateRecoveryToken(req, res);
|
await req.db.validateRecoveryToken(req, res);
|
||||||
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;
|
next(handleError(error, SERVICE_NAME, "validateRecoveryTokenController"));
|
||||||
next(error);
|
}
|
||||||
}
|
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -344,28 +343,26 @@ const validateRecovery = async (req, res, next) => {
|
|||||||
* @throws {Error} If there is an error during the process, especially if there is a validation error (422).
|
* @throws {Error} If there is an error during the process, especially if there is a validation error (422).
|
||||||
*/
|
*/
|
||||||
const resetPassword = async (req, res, next) => {
|
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;
|
const validationError = handleValidationError(error, SERVICE_NAME);
|
||||||
error.service = SERVICE_NAME;
|
next(validationError);
|
||||||
error.message = error.details?.[0]?.message || error.message || "Validation Error";
|
return;
|
||||||
next(error);
|
}
|
||||||
return;
|
try {
|
||||||
}
|
const user = await req.db.resetPassword(req, res);
|
||||||
try {
|
|
||||||
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, msg: successMessages.AUTH_RESET_PASSWORD, data: {user, token},
|
success: true,
|
||||||
});
|
msg: successMessages.AUTH_RESET_PASSWORD,
|
||||||
} catch (error) {
|
data: { user, token },
|
||||||
error.service === undefined ? (error.service = SERVICE_NAME) : null;
|
});
|
||||||
error.method === undefined ? (error.method = "resetPasswordController") : null;
|
} catch (error) {
|
||||||
next(error);
|
next(handleError(error, SERVICE_NAME, "resetPasswordController"));
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -378,73 +375,73 @@ const resetPassword = async (req, res, next) => {
|
|||||||
* @throws {Error} If user validation fails or user is not found in the database.
|
* @throws {Error} If user validation fails or user is not found in the database.
|
||||||
*/
|
*/
|
||||||
const deleteUser = async (req, res, next) => {
|
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 {email} = decodedToken;
|
const { email } = decodedToken;
|
||||||
|
|
||||||
// Check if the user exists
|
// Check if the user exists
|
||||||
const user = await req.db.getUserByEmail(email);
|
const user = await req.db.getUserByEmail(email);
|
||||||
if (!user) {
|
if (!user) {
|
||||||
next(new Error(errorMessages.DB_USER_NOT_FOUND));
|
next(new Error(errorMessages.DB_USER_NOT_FOUND));
|
||||||
return;
|
return;
|
||||||
}
|
|
||||||
|
|
||||||
// 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) {
|
||||||
|
next(handleError(error, SERVICE_NAME, "deleteUserController"));
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const getAllUsers = 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;
|
next(handleError(error, SERVICE_NAME, "getAllUsersController"));
|
||||||
error.method === undefined ? (error.method = "getAllUsersController") : null;
|
}
|
||||||
next(error);
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
|
|
||||||
module.exports = {
|
module.exports = {
|
||||||
registerUser,
|
registerUser,
|
||||||
loginUser,
|
loginUser,
|
||||||
editUser,
|
editUser,
|
||||||
checkSuperadminExists: checkSuperAdminExists,
|
checkSuperadminExists: checkSuperAdminExists,
|
||||||
requestRecovery,
|
requestRecovery,
|
||||||
validateRecovery,
|
validateRecovery,
|
||||||
resetPassword,
|
resetPassword,
|
||||||
deleteUser,
|
deleteUser,
|
||||||
getAllUsers,
|
getAllUsers,
|
||||||
};
|
};
|
||||||
@@ -13,17 +13,14 @@ const { successMessages } = require("../utils/messages");
|
|||||||
const jwt = require("jsonwebtoken");
|
const jwt = require("jsonwebtoken");
|
||||||
const { getTokenFromHeaders } = require("../utils/utils");
|
const { getTokenFromHeaders } = require("../utils/utils");
|
||||||
const SERVICE_NAME = "checkController";
|
const SERVICE_NAME = "checkController";
|
||||||
|
const { handleValidationError, handleError } = require("./controllerUtils");
|
||||||
|
|
||||||
const createCheck = async (req, res, next) => {
|
const createCheck = async (req, res, next) => {
|
||||||
try {
|
try {
|
||||||
await createCheckParamValidation.validateAsync(req.params);
|
await createCheckParamValidation.validateAsync(req.params);
|
||||||
await createCheckBodyValidation.validateAsync(req.body);
|
await createCheckBodyValidation.validateAsync(req.body);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
error.status = 422;
|
next(handleValidationError(error, SERVICE_NAME));
|
||||||
error.service = SERVICE_NAME;
|
|
||||||
error.message =
|
|
||||||
error.details?.[0]?.message || error.message || "Validation Error";
|
|
||||||
next(error);
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -34,9 +31,7 @@ const createCheck = async (req, res, next) => {
|
|||||||
.status(200)
|
.status(200)
|
||||||
.json({ success: true, msg: successMessages.CHECK_CREATE, data: check });
|
.json({ success: true, msg: successMessages.CHECK_CREATE, data: check });
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
error.service === undefined ? (error.service = SERVICE_NAME) : null;
|
next(handleError(error, SERVICE_NAME, "createCheck"));
|
||||||
error.method === undefined ? (error.method = "createCheck") : null;
|
|
||||||
next(error);
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -45,11 +40,7 @@ const getChecks = async (req, res, next) => {
|
|||||||
await getChecksParamValidation.validateAsync(req.params);
|
await getChecksParamValidation.validateAsync(req.params);
|
||||||
await getChecksQueryValidation.validateAsync(req.query);
|
await getChecksQueryValidation.validateAsync(req.query);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
error.status = 422;
|
next(handleValidationError(error, SERVICE_NAME));
|
||||||
error.service = SERVICE_NAME;
|
|
||||||
error.message =
|
|
||||||
error.details?.[0]?.message || error.message || "Validation Error";
|
|
||||||
next(error);
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -62,9 +53,7 @@ const getChecks = async (req, res, next) => {
|
|||||||
data: { checksCount, checks },
|
data: { checksCount, checks },
|
||||||
});
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
error.service === undefined ? (error.service = SERVICE_NAME) : null;
|
next(handleError(error, SERVICE_NAME, "getChecks"));
|
||||||
error.method === undefined ? (error.method = "getChecks") : null;
|
|
||||||
next(error);
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -73,11 +62,7 @@ const getTeamChecks = async (req, res, next) => {
|
|||||||
await getTeamChecksParamValidation.validateAsync(req.params);
|
await getTeamChecksParamValidation.validateAsync(req.params);
|
||||||
await getTeamChecksQueryValidation.validateAsync(req.query);
|
await getTeamChecksQueryValidation.validateAsync(req.query);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
error.status = 422;
|
next(handleValidationError(error, SERVICE_NAME));
|
||||||
error.service = SERVICE_NAME;
|
|
||||||
error.message =
|
|
||||||
error.details?.[0]?.message || error.message || "Validation Error";
|
|
||||||
next(error);
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
@@ -88,9 +73,7 @@ const getTeamChecks = async (req, res, next) => {
|
|||||||
data: checkData,
|
data: checkData,
|
||||||
});
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
error.service === undefined ? (error.service = SERVICE_NAME) : null;
|
next(handleError(error, SERVICE_NAME, "getTeamChecks"));
|
||||||
error.method === undefined ? (error.method = "getTeamChecks") : null;
|
|
||||||
next(error);
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -98,11 +81,7 @@ const deleteChecks = async (req, res, next) => {
|
|||||||
try {
|
try {
|
||||||
await deleteChecksParamValidation.validateAsync(req.params);
|
await deleteChecksParamValidation.validateAsync(req.params);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
error.status = 422;
|
next(handleValidationError(error, SERVICE_NAME));
|
||||||
error.service = SERVICE_NAME;
|
|
||||||
error.message =
|
|
||||||
error.details?.[0]?.message || error.message || "Validation Error";
|
|
||||||
next(error);
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -114,9 +93,7 @@ const deleteChecks = async (req, res, next) => {
|
|||||||
data: { deletedCount },
|
data: { deletedCount },
|
||||||
});
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
error.service === undefined ? (error.service = SERVICE_NAME) : null;
|
next(handleError(error, SERVICE_NAME, "deleteChecks"));
|
||||||
error.method === undefined ? (error.method = "deleteChecks") : null;
|
|
||||||
next(error);
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -124,10 +101,7 @@ const deleteChecksByTeamId = async (req, res, next) => {
|
|||||||
try {
|
try {
|
||||||
await deleteChecksByTeamIdParamValidation.validateAsync(req.params);
|
await deleteChecksByTeamIdParamValidation.validateAsync(req.params);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
error.service === undefined ? (error.service = SERVICE_NAME) : null;
|
next(handleValidationError(error, SERVICE_NAME));
|
||||||
error.method === undefined ? (error.method = "deleteChecksByTeam") : null;
|
|
||||||
error.status = 422;
|
|
||||||
next(error);
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -139,9 +113,7 @@ const deleteChecksByTeamId = async (req, res, next) => {
|
|||||||
data: { deletedCount },
|
data: { deletedCount },
|
||||||
});
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
error.service === undefined ? (error.service = SERVICE_NAME) : null;
|
next(handleError(error, SERVICE_NAME, "deleteChecksByTeamId"));
|
||||||
error.method === undefined ? (error.method = "deleteChecksByTeamId") : null;
|
|
||||||
next(error);
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -151,12 +123,7 @@ const updateChecksTTL = async (req, res, next) => {
|
|||||||
try {
|
try {
|
||||||
await updateChecksTTLBodyValidation.validateAsync(req.body);
|
await updateChecksTTLBodyValidation.validateAsync(req.body);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
error.status = 422;
|
next(handleValidationError(error, SERVICE_NAME));
|
||||||
error.service === undefined ? (error.service = SERVICE_NAME) : null;
|
|
||||||
error.method === undefined ? (error.method = "updateChecksTTL") : null;
|
|
||||||
error.message =
|
|
||||||
error.details?.[0]?.message || error.message || "Validation Error";
|
|
||||||
next(error);
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -172,9 +139,7 @@ const updateChecksTTL = async (req, res, next) => {
|
|||||||
msg: successMessages.CHECK_UPDATE_TTL,
|
msg: successMessages.CHECK_UPDATE_TTL,
|
||||||
});
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
error.service === undefined ? (error.service = SERVICE_NAME) : null;
|
next(handleError(error, SERVICE_NAME, "updateTTL"));
|
||||||
error.method === undefined ? (error.method = "updateTTL") : null;
|
|
||||||
next(error);
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,19 @@
|
|||||||
|
const handleValidationError = (error, serviceName) => {
|
||||||
|
error.status = 422;
|
||||||
|
error.service = serviceName;
|
||||||
|
error.message =
|
||||||
|
error.details?.[0]?.message || error.message || "Validation Error";
|
||||||
|
return error;
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleError = (error, serviceName, method, code = 500) => {
|
||||||
|
error.code === undefined ? (error.code = code) : null;
|
||||||
|
error.service === undefined ? (error.service = serviceName) : null;
|
||||||
|
error.method === undefined ? (error.method = method) : null;
|
||||||
|
return error;
|
||||||
|
};
|
||||||
|
|
||||||
|
module.exports = {
|
||||||
|
handleValidationError,
|
||||||
|
handleError,
|
||||||
|
};
|
||||||
@@ -1,22 +1,23 @@
|
|||||||
const {
|
const {
|
||||||
inviteRoleValidation,
|
inviteRoleValidation,
|
||||||
inviteBodyValidation,
|
inviteBodyValidation,
|
||||||
inviteVerificationBodyValidation,
|
inviteVerificationBodyValidation,
|
||||||
} = require("../validation/joi");
|
} = require("../validation/joi");
|
||||||
const logger = require("../utils/logger");
|
const logger = require("../utils/logger");
|
||||||
require("dotenv").config();
|
require("dotenv").config();
|
||||||
const jwt = require("jsonwebtoken");
|
const jwt = require("jsonwebtoken");
|
||||||
|
const { handleError, handleValidationError } = require("./controllerUtils");
|
||||||
const SERVICE_NAME = "inviteController";
|
const SERVICE_NAME = "inviteController";
|
||||||
|
|
||||||
const getTokenFromHeaders = (headers) => {
|
const getTokenFromHeaders = (headers) => {
|
||||||
const authorizationHeader = headers.authorization;
|
const authorizationHeader = headers.authorization;
|
||||||
if (!authorizationHeader) throw new Error("No auth headers");
|
if (!authorizationHeader) throw new Error("No auth headers");
|
||||||
|
|
||||||
const parts = authorizationHeader.split(" ");
|
const parts = authorizationHeader.split(" ");
|
||||||
if (parts.length !== 2 || parts[0] !== "Bearer")
|
if (parts.length !== 2 || parts[0] !== "Bearer")
|
||||||
throw new Error("Invalid auth headers");
|
throw new Error("Invalid auth headers");
|
||||||
|
|
||||||
return parts[1];
|
return parts[1];
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -33,79 +34,65 @@ const getTokenFromHeaders = (headers) => {
|
|||||||
* @throws {Error} If there is an error during the process, especially if there is a validation error (422).
|
* @throws {Error} If there is an error during the process, especially if there is a validation error (422).
|
||||||
*/
|
*/
|
||||||
const issueInvitation = async (req, res, next) => {
|
const issueInvitation = 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 {
|
||||||
// Only admins can invite
|
await inviteRoleValidation.validateAsync({ roles: role });
|
||||||
const token = getTokenFromHeaders(req.headers);
|
await inviteBodyValidation.validateAsync(req.body);
|
||||||
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.body});
|
|
||||||
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) {
|
} catch (error) {
|
||||||
error.service === undefined ? (error.service = SERVICE_NAME) : null;
|
next(handleValidationError(error, SERVICE_NAME));
|
||||||
error.method === undefined ? (error.method = "inviteController") : null;
|
return;
|
||||||
next(error);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const inviteToken = await req.db.requestInviteToken({ ...req.body });
|
||||||
|
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) {
|
||||||
|
next(handleError(error, SERVICE_NAME, "inviteController"));
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const inviteVerifyController = async (req, res, next) => {
|
const inviteVerifyController = async (req, res, next) => {
|
||||||
try {
|
try {
|
||||||
await inviteVerificationBodyValidation.validateAsync(req.body);
|
await inviteVerificationBodyValidation.validateAsync(req.body);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
error.status = 422;
|
next(handleValidationError(error, SERVICE_NAME));
|
||||||
error.service = SERVICE_NAME;
|
return;
|
||||||
error.message =
|
}
|
||||||
error.details?.[0]?.message || error.message || "Validation Error";
|
|
||||||
next(error);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const invite = await req.db.getInviteToken(req.body.token);
|
const invite = await req.db.getInviteToken(req.body.token);
|
||||||
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;
|
next(handleError(error, SERVICE_NAME, "inviteVerifyController"));
|
||||||
error.method === undefined
|
}
|
||||||
? (error.method = "inviteVerifyController")
|
|
||||||
: null;
|
|
||||||
next(error);
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
|
|
||||||
module.exports = {
|
module.exports = {
|
||||||
inviteController: issueInvitation,
|
inviteController: issueInvitation,
|
||||||
inviteVerifyController,
|
inviteVerifyController,
|
||||||
};
|
};
|
||||||
@@ -10,17 +10,14 @@ const {
|
|||||||
const jwt = require("jsonwebtoken");
|
const jwt = require("jsonwebtoken");
|
||||||
const { getTokenFromHeaders } = require("../utils/utils");
|
const { getTokenFromHeaders } = require("../utils/utils");
|
||||||
const { successMessages } = require("../utils/messages");
|
const { successMessages } = require("../utils/messages");
|
||||||
|
const { handleValidationError, handleError } = require("./controllerUtils");
|
||||||
const SERVICE_NAME = "maintenanceWindowController";
|
const SERVICE_NAME = "maintenanceWindowController";
|
||||||
|
|
||||||
const createMaintenanceWindows = async (req, res, next) => {
|
const createMaintenanceWindows = async (req, res, next) => {
|
||||||
try {
|
try {
|
||||||
await createMaintenanceWindowBodyValidation.validateAsync(req.body);
|
await createMaintenanceWindowBodyValidation.validateAsync(req.body);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
error.status = 422;
|
next(handleValidationError(error, SERVICE_NAME));
|
||||||
error.service = SERVICE_NAME;
|
|
||||||
error.message =
|
|
||||||
error.details?.[0]?.message || error.message || "Validation Error";
|
|
||||||
next(error);
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
@@ -45,11 +42,7 @@ const createMaintenanceWindows = async (req, res, next) => {
|
|||||||
msg: successMessages.MAINTENANCE_WINDOW_CREATE,
|
msg: successMessages.MAINTENANCE_WINDOW_CREATE,
|
||||||
});
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
error.service === undefined ? (error.service = SERVICE_NAME) : null;
|
next(handleError(error, SERVICE_NAME, "createMaintenanceWindow"));
|
||||||
error.method === undefined
|
|
||||||
? (error.method = "createMaintenanceWindow")
|
|
||||||
: null;
|
|
||||||
next(error);
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -57,11 +50,7 @@ const getMaintenanceWindowById = async (req, res, next) => {
|
|||||||
try {
|
try {
|
||||||
await getMaintenanceWindowByIdParamValidation.validateAsync(req.params);
|
await getMaintenanceWindowByIdParamValidation.validateAsync(req.params);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
error.status = 422;
|
next(handleValidationError(error, SERVICE_NAME));
|
||||||
error.service = SERVICE_NAME;
|
|
||||||
error.message =
|
|
||||||
error.details?.[0]?.message || error.message || "Validation Error";
|
|
||||||
next(error);
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
@@ -74,11 +63,7 @@ const getMaintenanceWindowById = async (req, res, next) => {
|
|||||||
data: maintenanceWindow,
|
data: maintenanceWindow,
|
||||||
});
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
error.service === undefined ? (error.service = SERVICE_NAME) : null;
|
next(handleError(error, SERVICE_NAME, "getMaintenanceWindowById"));
|
||||||
error.method === undefined
|
|
||||||
? (error.method = "getMaintenanceWindowById")
|
|
||||||
: null;
|
|
||||||
next(error);
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -86,11 +71,7 @@ const getMaintenanceWindowsByTeamId = async (req, res, next) => {
|
|||||||
try {
|
try {
|
||||||
await getMaintenanceWindowsByTeamIdQueryValidation.validateAsync(req.query);
|
await getMaintenanceWindowsByTeamIdQueryValidation.validateAsync(req.query);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
error.status = 422;
|
next(handleValidationError(error, SERVICE_NAME));
|
||||||
error.service = SERVICE_NAME;
|
|
||||||
error.message =
|
|
||||||
error.details?.[0]?.message || error.message || "Validation Error";
|
|
||||||
next(error);
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -109,11 +90,7 @@ const getMaintenanceWindowsByTeamId = async (req, res, next) => {
|
|||||||
data: maintenanceWindows,
|
data: maintenanceWindows,
|
||||||
});
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
error.service === undefined ? (error.service = SERVICE_NAME) : null;
|
next(handleError(error, SERVICE_NAME, "getMaintenanceWindowsByUserId"));
|
||||||
error.method === undefined
|
|
||||||
? (error.method = "getMaintenanceWindowsByUserId")
|
|
||||||
: null;
|
|
||||||
next(error);
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -123,11 +100,7 @@ const getMaintenanceWindowsByMonitorId = async (req, res, next) => {
|
|||||||
req.params
|
req.params
|
||||||
);
|
);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
error.status = 422;
|
next(handleValidationError(error, SERVICE_NAME));
|
||||||
error.service = SERVICE_NAME;
|
|
||||||
error.message =
|
|
||||||
error.details?.[0]?.message || error.message || "Validation Error";
|
|
||||||
next(error);
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -142,11 +115,7 @@ const getMaintenanceWindowsByMonitorId = async (req, res, next) => {
|
|||||||
data: maintenanceWindows,
|
data: maintenanceWindows,
|
||||||
});
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
error.service === undefined ? (error.service = SERVICE_NAME) : null;
|
next(handleError(error, SERVICE_NAME, "getMaintenanceWindowsByMonitorId"));
|
||||||
error.method === undefined
|
|
||||||
? (error.method = "getMaintenanceWindowsByMonitorId")
|
|
||||||
: null;
|
|
||||||
next(error);
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -154,11 +123,7 @@ const deleteMaintenanceWindow = async (req, res, next) => {
|
|||||||
try {
|
try {
|
||||||
await deleteMaintenanceWindowByIdParamValidation.validateAsync(req.params);
|
await deleteMaintenanceWindowByIdParamValidation.validateAsync(req.params);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
error.status = 422;
|
next(handleValidationError(error, SERVICE_NAME));
|
||||||
error.service = SERVICE_NAME;
|
|
||||||
error.message =
|
|
||||||
error.details?.[0]?.message || error.message || "Validation Error";
|
|
||||||
next(error);
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
@@ -168,10 +133,7 @@ const deleteMaintenanceWindow = async (req, res, next) => {
|
|||||||
msg: successMessages.MAINTENANCE_WINDOW_DELETE,
|
msg: successMessages.MAINTENANCE_WINDOW_DELETE,
|
||||||
});
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
error.service === undefined ? (error.service = SERVICE_NAME) : null;
|
next(handleError(error, SERVICE_NAME, "deleteMaintenanceWindow"));
|
||||||
error.method === undefined
|
|
||||||
? (error.method = "deleteMaintenanceWindow")
|
|
||||||
: null;
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -180,11 +142,7 @@ const editMaintenanceWindow = async (req, res, next) => {
|
|||||||
await editMaintenanceWindowByIdParamValidation.validateAsync(req.params);
|
await editMaintenanceWindowByIdParamValidation.validateAsync(req.params);
|
||||||
await editMaintenanceByIdWindowBodyValidation.validateAsync(req.body);
|
await editMaintenanceByIdWindowBodyValidation.validateAsync(req.body);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
error.status = 422;
|
next(handleValidationError(error, SERVICE_NAME));
|
||||||
error.service = SERVICE_NAME;
|
|
||||||
error.message =
|
|
||||||
error.details?.[0]?.message || error.message || "Validation Error";
|
|
||||||
next(error);
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
@@ -198,10 +156,7 @@ const editMaintenanceWindow = async (req, res, next) => {
|
|||||||
data: editedMaintenanceWindow,
|
data: editedMaintenanceWindow,
|
||||||
});
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
error.service === undefined ? (error.service = SERVICE_NAME) : null;
|
next(handleError(error, SERVICE_NAME, "editMaintenanceWindow"));
|
||||||
error.method === undefined
|
|
||||||
? (error.method = "editMaintenanceWindow")
|
|
||||||
: null;
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -19,6 +19,7 @@ const { errorMessages, successMessages } = require("../utils/messages");
|
|||||||
const jwt = require("jsonwebtoken");
|
const jwt = require("jsonwebtoken");
|
||||||
const { getTokenFromHeaders } = require("../utils/utils");
|
const { getTokenFromHeaders } = require("../utils/utils");
|
||||||
const logger = require("../utils/logger");
|
const logger = require("../utils/logger");
|
||||||
|
const { handleError, handleValidationError } = require("./controllerUtils");
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Returns all monitors
|
* Returns all monitors
|
||||||
@@ -38,9 +39,7 @@ const getAllMonitors = async (req, res, next) => {
|
|||||||
data: monitors,
|
data: monitors,
|
||||||
});
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
error.service === undefined ? (error.service = SERVICE_NAME) : null;
|
next(handleError(error, SERVICE_NAME, "getAllMonitors"));
|
||||||
error.method === undefined ? (error.method = "getAllMonitors") : null;
|
|
||||||
next(error);
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -58,10 +57,7 @@ const getMonitorStatsById = async (req, res, next) => {
|
|||||||
await getMonitorStatsByIdParamValidation.validateAsync(req.params);
|
await getMonitorStatsByIdParamValidation.validateAsync(req.params);
|
||||||
await getMonitorStatsByIdQueryValidation.validateAsync(req.query);
|
await getMonitorStatsByIdQueryValidation.validateAsync(req.query);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
error.status = 422;
|
next(handleValidationError(error, SERVICE_NAME));
|
||||||
error.message =
|
|
||||||
error.details?.[0]?.message || error.message || "Validation Error";
|
|
||||||
next(error);
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -73,9 +69,7 @@ const getMonitorStatsById = async (req, res, next) => {
|
|||||||
data: monitorStats,
|
data: monitorStats,
|
||||||
});
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
error.service === undefined ? (error.service = SERVICE_NAME) : null;
|
next(handleError(error, SERVICE_NAME, "getMonitorStatsById"));
|
||||||
error.method === undefined ? (error.method = "getMonitorStatsById") : null;
|
|
||||||
next(error);
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -83,10 +77,7 @@ const getMonitorCertificate = async (req, res, next) => {
|
|||||||
try {
|
try {
|
||||||
await getCertificateParamValidation.validateAsync(req.params);
|
await getCertificateParamValidation.validateAsync(req.params);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
error.status = 422;
|
next(handleValidationError(error, SERVICE_NAME));
|
||||||
error.message =
|
|
||||||
error.details?.[0]?.message || error.message || "Validation Error";
|
|
||||||
next(error);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
@@ -110,11 +101,7 @@ const getMonitorCertificate = async (req, res, next) => {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
error.service === undefined ? (error.service = SERVICE_NAME) : null;
|
next(handleError(error, SERVICE_NAME, "getMonitorCertificate"));
|
||||||
error.method === undefined
|
|
||||||
? (error.method = "getMonitorCertificate")
|
|
||||||
: null;
|
|
||||||
next(error);
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -134,10 +121,7 @@ const getMonitorById = async (req, res, next) => {
|
|||||||
await getMonitorByIdParamValidation.validateAsync(req.params);
|
await getMonitorByIdParamValidation.validateAsync(req.params);
|
||||||
await getMonitorByIdQueryValidation.validateAsync(req.query);
|
await getMonitorByIdQueryValidation.validateAsync(req.query);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
error.status = 422;
|
next(handleValidationError(error, SERVICE_NAME));
|
||||||
error.message =
|
|
||||||
error.details?.[0]?.message || error.message || "Validation Error";
|
|
||||||
next(error);
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -154,9 +138,7 @@ const getMonitorById = async (req, res, next) => {
|
|||||||
data: monitor,
|
data: monitor,
|
||||||
});
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
error.service === undefined ? (error.service = SERVICE_NAME) : null;
|
next(handleError(error, SERVICE_NAME, "getMonitorById"));
|
||||||
error.method === undefined ? (error.method = "getMonitorById") : null;
|
|
||||||
next(error);
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -179,14 +161,8 @@ const getMonitorsAndSummaryByTeamId = async (req, res, next) => {
|
|||||||
req.params
|
req.params
|
||||||
);
|
);
|
||||||
await getMonitorsAndSummaryByTeamIdQueryValidation.validateAsync(req.query);
|
await getMonitorsAndSummaryByTeamIdQueryValidation.validateAsync(req.query);
|
||||||
//validation
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
error.status = 422;
|
next(handleValidationError(error, SERVICE_NAME));
|
||||||
error.service = SERVICE_NAME;
|
|
||||||
error.method === undefined? error.method = "getMonitorsAndSummaryByTeamId": null;
|
|
||||||
error.message =
|
|
||||||
error.details?.[0]?.message || error.message || "Validation Error";
|
|
||||||
next(error);
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -203,11 +179,7 @@ const getMonitorsAndSummaryByTeamId = async (req, res, next) => {
|
|||||||
data: monitorsSummary,
|
data: monitorsSummary,
|
||||||
});
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
error.service === undefined ? (error.service = SERVICE_NAME) : null;
|
next(handleError(error, SERVICE_NAME, "getMonitorsAndSummaryByTeamId"));
|
||||||
error.method === undefined
|
|
||||||
? (error.method = "getMonitorsAndSummaryByTeamId")
|
|
||||||
: null;
|
|
||||||
next(error);
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -228,11 +200,7 @@ const getMonitorsByTeamId = async (req, res, next) => {
|
|||||||
await getMonitorsByTeamIdValidation.validateAsync(req.params);
|
await getMonitorsByTeamIdValidation.validateAsync(req.params);
|
||||||
await getMonitorsByTeamIdQueryValidation.validateAsync(req.query);
|
await getMonitorsByTeamIdQueryValidation.validateAsync(req.query);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
error.status = 422;
|
next(handleValidationError(error, SERVICE_NAME));
|
||||||
error.service = SERVICE_NAME;
|
|
||||||
error.message =
|
|
||||||
error.details?.[0]?.message || error.message || "Validation Error";
|
|
||||||
next(error);
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -245,8 +213,7 @@ const getMonitorsByTeamId = async (req, res, next) => {
|
|||||||
data: monitors,
|
data: monitors,
|
||||||
});
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
error.service === undefined ? (error.service = SERVICE_NAME) : null;
|
next(handleError(error, SERVICE_NAME, "getMonitorsByTeamId"));
|
||||||
error.method === undefined ? (error.method = "getMonitorsByTeamId") : null;
|
|
||||||
next(error);
|
next(error);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@@ -266,12 +233,7 @@ const createMonitor = async (req, res, next) => {
|
|||||||
try {
|
try {
|
||||||
await createMonitorBodyValidation.validateAsync(req.body);
|
await createMonitorBodyValidation.validateAsync(req.body);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
error.status = 422;
|
next(handleValidationError(error, SERVICE_NAME));
|
||||||
error.service = SERVICE_NAME;
|
|
||||||
error.message =
|
|
||||||
error.details?.[0]?.message || error.message || "Validation Error";
|
|
||||||
|
|
||||||
next(error);
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -281,10 +243,10 @@ const createMonitor = async (req, res, next) => {
|
|||||||
|
|
||||||
if (notifications && notifications.length !== 0) {
|
if (notifications && notifications.length !== 0) {
|
||||||
monitor.notifications = await Promise.all(
|
monitor.notifications = await Promise.all(
|
||||||
notifications.map(async (notification) => {
|
notifications.map(async (notification) => {
|
||||||
notification.monitorId = monitor._id;
|
notification.monitorId = monitor._id;
|
||||||
await req.db.createNotification(notification);
|
await req.db.createNotification(notification);
|
||||||
})
|
})
|
||||||
);
|
);
|
||||||
await monitor.save();
|
await monitor.save();
|
||||||
}
|
}
|
||||||
@@ -296,9 +258,7 @@ const createMonitor = async (req, res, next) => {
|
|||||||
data: monitor,
|
data: monitor,
|
||||||
});
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
error.service === undefined ? (error.service = SERVICE_NAME) : null;
|
next(handleError(error, SERVICE_NAME, "createMonitor"));
|
||||||
error.method === undefined ? (error.method = "createMonitor") : null;
|
|
||||||
next(error);
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -317,11 +277,7 @@ const deleteMonitor = async (req, res, next) => {
|
|||||||
try {
|
try {
|
||||||
await getMonitorByIdParamValidation.validateAsync(req.params);
|
await getMonitorByIdParamValidation.validateAsync(req.params);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
error.status = 422;
|
next(handleValidationError(error, SERVICE_NAME));
|
||||||
error.service = SERVICE_NAME;
|
|
||||||
error.message =
|
|
||||||
error.details?.[0]?.message || error.message || "Validation Error";
|
|
||||||
next(error);
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -347,9 +303,7 @@ const deleteMonitor = async (req, res, next) => {
|
|||||||
.status(200)
|
.status(200)
|
||||||
.json({ success: true, msg: successMessages.MONITOR_DELETE });
|
.json({ success: true, msg: successMessages.MONITOR_DELETE });
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
error.service === undefined ? (error.service = SERVICE_NAME) : null;
|
next(handleError(error, SERVICE_NAME, "deleteMonitor"));
|
||||||
error.method === undefined ? (error.method = "deleteMonitor") : null;
|
|
||||||
next(error);
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -382,9 +336,7 @@ const deleteAllMonitors = async (req, res, next) => {
|
|||||||
.status(200)
|
.status(200)
|
||||||
.json({ success: true, msg: `Deleted ${deletedCount} monitors` });
|
.json({ success: true, msg: `Deleted ${deletedCount} monitors` });
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
error.service === undefined ? (error.service = SERVICE_NAME) : null;
|
next(handleError(error, SERVICE_NAME, "deleteAllMonitors"));
|
||||||
error.method === undefined ? (error.method = "deleteAllMonitors") : null;
|
|
||||||
next(error);
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -406,11 +358,7 @@ const editMonitor = async (req, res, next) => {
|
|||||||
await getMonitorByIdParamValidation.validateAsync(req.params);
|
await getMonitorByIdParamValidation.validateAsync(req.params);
|
||||||
await editMonitorBodyValidation.validateAsync(req.body);
|
await editMonitorBodyValidation.validateAsync(req.body);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
error.status = 422;
|
next(handleValidationError(error, SERVICE_NAME));
|
||||||
error.service = SERVICE_NAME;
|
|
||||||
error.message =
|
|
||||||
error.details?.[0]?.message || error.message || "Validation Error";
|
|
||||||
next(error);
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -444,9 +392,7 @@ const editMonitor = async (req, res, next) => {
|
|||||||
data: editedMonitor,
|
data: editedMonitor,
|
||||||
});
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
error.service === undefined ? (error.service = SERVICE_NAME) : null;
|
next(handleError(error, SERVICE_NAME, "editMonitor"));
|
||||||
error.method === undefined ? (error.method = "editMonitor") : null;
|
|
||||||
next(error);
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -465,11 +411,7 @@ const pauseMonitor = async (req, res, next) => {
|
|||||||
try {
|
try {
|
||||||
await pauseMonitorParamValidation.validateAsync(req.params);
|
await pauseMonitorParamValidation.validateAsync(req.params);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
error.status = 422;
|
next(handleValidationError(error, SERVICE_NAME));
|
||||||
error.service = SERVICE_NAME;
|
|
||||||
error.message =
|
|
||||||
error.details?.[0]?.message || error.message || "Validation Error";
|
|
||||||
next(error);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
@@ -490,9 +432,7 @@ const pauseMonitor = async (req, res, next) => {
|
|||||||
data: monitor,
|
data: monitor,
|
||||||
});
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
error.service === undefined ? (error.service = SERVICE_NAME) : null;
|
next(handleError(error, SERVICE_NAME, "pauseMonitor"));
|
||||||
error.method === undefined ? (error.method = "pauseMonitor") : null;
|
|
||||||
next(error);
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -511,21 +451,19 @@ const addDemoMonitors = 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();
|
||||||
|
|
||||||
const { _id, teamId } = jwt.verify(token, jwtSecret);
|
const { _id, teamId } = jwt.verify(token, jwtSecret);
|
||||||
const demoMonitors = await req.db.addDemoMonitors(_id, teamId);
|
const demoMonitors = await req.db.addDemoMonitors(_id, teamId);
|
||||||
await demoMonitors.forEach(async (monitor) => {
|
await Promise.all(
|
||||||
await req.jobQueue.addJob(monitor._id, monitor);
|
demoMonitors.map((monitor) => req.jobQueue.addJob(monitor._id, monitor))
|
||||||
});
|
);
|
||||||
|
|
||||||
return res.status(200).json({
|
return res.status(200).json({
|
||||||
success: true,
|
success: true,
|
||||||
message: successMessages.MONITOR_DEMO_ADDED,
|
message: successMessages.MONITOR_DEMO_ADDED,
|
||||||
data: demoMonitors.length,
|
data: demoMonitors.length,
|
||||||
});
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
error.service === undefined ? (error.service = SERVICE_NAME) : null;
|
next(handleError(error, SERVICE_NAME, "addDemoMonitors"));
|
||||||
error.method === undefined ? (error.method = "addDemoMonitors") : null;
|
|
||||||
next(error);
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -1,3 +1,5 @@
|
|||||||
|
const { handleError } = require("./controllerUtils");
|
||||||
|
|
||||||
const SERVICE_NAME = "JobQueueController";
|
const SERVICE_NAME = "JobQueueController";
|
||||||
|
|
||||||
const getMetrics = async (req, res, next) => {
|
const getMetrics = async (req, res, next) => {
|
||||||
@@ -7,9 +9,7 @@ const getMetrics = async (req, res, next) => {
|
|||||||
.status(200)
|
.status(200)
|
||||||
.json({ success: true, msg: "Metrics retrieved", data: metrics });
|
.json({ success: true, msg: "Metrics retrieved", data: metrics });
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
error.service === undefined ? (error.service = SERVICE_NAME) : null;
|
next(handleError(error, SERVICE_NAME, "getMetrics"));
|
||||||
error.method === undefined ? (error.method = "getMetrics") : null;
|
|
||||||
next(error);
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@@ -19,9 +19,7 @@ const getJobs = async (req, res, next) => {
|
|||||||
const jobs = await req.jobQueue.getJobStats();
|
const jobs = await req.jobQueue.getJobStats();
|
||||||
return res.status(200).json({ jobs });
|
return res.status(200).json({ jobs });
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
error.service === undefined ? (error.service = SERVICE_NAME) : null;
|
next(handleError(error, SERVICE_NAME, "getJobs"));
|
||||||
error.method === undefined ? (error.method = "getJobs") : null;
|
|
||||||
next(error);
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@@ -31,21 +29,17 @@ const addJob = async (req, res, next) => {
|
|||||||
await req.jobQueue.addJob(Math.random().toString(36).substring(7));
|
await req.jobQueue.addJob(Math.random().toString(36).substring(7));
|
||||||
return res.send("Added job");
|
return res.send("Added job");
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
error.service === undefined ? (error.service = SERVICE_NAME) : null;
|
next(handleError(error, SERVICE_NAME, "addJob"));
|
||||||
error.method === undefined ? (error.method = "addJob") : null;
|
|
||||||
next(error);
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const obliterateQueue = async (req, res, next) => {
|
const obliterateQueue = async (req, res, next) => {
|
||||||
try {
|
try {
|
||||||
const obliterated = await req.jobQueue.obliterate();
|
await req.jobQueue.obliterate();
|
||||||
return res.status(200).send("Obliterated queue");
|
return res.status(200).send("Obliterated queue");
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
error.service === undefined ? (error.service = SERVICE_NAME) : null;
|
next(handleError(error, SERVICE_NAME, "obliterateQueue"));
|
||||||
error.method === undefined ? (error.method = "obliterateQueue") : null;
|
|
||||||
next(error);
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
const { successMessages } = require("../utils/messages");
|
const { successMessages } = require("../utils/messages");
|
||||||
const SERVICE_NAME = "SettingsController";
|
const SERVICE_NAME = "SettingsController";
|
||||||
const { updateAppSettingsBodyValidation } = require("../validation/joi");
|
const { updateAppSettingsBodyValidation } = require("../validation/joi");
|
||||||
|
const { handleValidationError, handleError } = require("./controllerUtils");
|
||||||
|
|
||||||
const getAppSettings = async (req, res, next) => {
|
const getAppSettings = async (req, res, next) => {
|
||||||
try {
|
try {
|
||||||
@@ -12,9 +13,7 @@ const getAppSettings = async (req, res, next) => {
|
|||||||
data: settings,
|
data: settings,
|
||||||
});
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
error.service === undefined ? (error.service = SERVICE_NAME) : null;
|
next(handleError(error, SERVICE_NAME, "getAppSettings"));
|
||||||
error.method === undefined ? (error.method = "getAppSettings") : null;
|
|
||||||
next(error);
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -22,11 +21,7 @@ const updateAppSettings = async (req, res, next) => {
|
|||||||
try {
|
try {
|
||||||
await updateAppSettingsBodyValidation.validateAsync(req.body);
|
await updateAppSettingsBodyValidation.validateAsync(req.body);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
error.status = 422;
|
next(handleValidationError(error, SERVICE_NAME));
|
||||||
error.service = SERVICE_NAME;
|
|
||||||
error.message =
|
|
||||||
error.details?.[0]?.message || error.message || "Validation Error";
|
|
||||||
next(error);
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -40,9 +35,7 @@ const updateAppSettings = async (req, res, next) => {
|
|||||||
data: updatedSettings,
|
data: updatedSettings,
|
||||||
});
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
error.service === undefined ? (error.service = SERVICE_NAME) : null;
|
next(handleError(error, SERVICE_NAME, "updateAppSettings"));
|
||||||
error.method === undefined ? (error.method = "updateAppSettings") : null;
|
|
||||||
next(error);
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -38,16 +38,14 @@ const verifyJWT = (req, res, next) => {
|
|||||||
const { jwtSecret } = req.settingsService.getSettings();
|
const { jwtSecret } = req.settingsService.getSettings();
|
||||||
jwt.verify(parsedToken, jwtSecret, (err, decoded) => {
|
jwt.verify(parsedToken, jwtSecret, (err, decoded) => {
|
||||||
if (err) {
|
if (err) {
|
||||||
if (err.name === "TokenExpiredError") {
|
const errorMessage =
|
||||||
res
|
err.name === "TokenExpiredError"
|
||||||
.status(401)
|
? errorMessages.EXPIRED_AUTH_TOKEN
|
||||||
.json({ success: false, msg: errorMessages.EXPIRED_AUTH_TOKEN });
|
: errorMessages.INVALID_AUTH_TOKEN;
|
||||||
}
|
return res.status(401).json({ success: false, msg: errorMessage });
|
||||||
return res
|
|
||||||
.status(401)
|
|
||||||
.json({ success: false, msg: errorMessages.INVALID_AUTH_TOKEN });
|
|
||||||
}
|
}
|
||||||
//Add the user to the request object for use in the route
|
|
||||||
|
// Add the user to the request object for use in the route
|
||||||
req.user = decoded;
|
req.user = decoded;
|
||||||
next();
|
next();
|
||||||
});
|
});
|
||||||
|
|||||||
Reference in new issue
Block a user