Prettier formatting

This commit is contained in:
Alex Holliday committed 2024-10-16 11:46:37 +08:00
1 parent 3ace148dc9
commit 5f6e0631c6
1 file changed
+288 -289
+288 -289
View File
@@ -1,11 +1,11 @@
import { import {
registrationBodyValidation, registrationBodyValidation,
loginValidation, loginValidation,
editUserParamValidation, editUserParamValidation,
editUserBodyValidation, editUserBodyValidation,
recoveryValidation, recoveryValidation,
recoveryTokenValidation, recoveryTokenValidation,
newPasswordValidation, newPasswordValidation,
} from "../validation/joi.js"; } from "../validation/joi.js";
import logger from "../utils/logger.js"; import logger from "../utils/logger.js";
import dotenv from "dotenv"; import dotenv from "dotenv";
@@ -26,12 +26,12 @@ dotenv.config();
* @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) {
throw handleError(error, SERVICE_NAME, "issueToken"); throw handleError(error, SERVICE_NAME, "issueToken");
} }
}; };
/** /**
@@ -47,65 +47,65 @@ 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) {
const validationError = handleValidationError(error, SERVICE_NAME); const validationError = handleValidationError(error, SERVICE_NAME);
next(validationError); next(validationError);
return; return;
} }
// Create a new user // Create a new user
try { try {
const { inviteToken } = req.body; const { inviteToken } = req.body;
// If superAdmin exists, a token should be attached to all further register requests // If superAdmin exists, a token should be attached to all further register requests
const superAdminExists = await req.db.checkSuperadmin(req, res); const superAdminExists = await req.db.checkSuperadmin(req, res);
if (superAdminExists) { if (superAdminExists) {
await req.db.getInviteTokenAndDelete(inviteToken); await req.db.getInviteTokenAndDelete(inviteToken);
} else { } else {
// This is the first account, create JWT secret to use if one is not supplied by env // This is the first account, create JWT secret to use if one is not supplied by env
const jwtSecret = crypto.randomBytes(64).toString("hex"); const jwtSecret = crypto.randomBytes(64).toString("hex");
await req.db.updateAppSettings({ jwtSecret }); await req.db.updateAppSettings({ jwtSecret });
} }
const newUser = await req.db.insertUser({ ...req.body }, req.file); const newUser = await req.db.insertUser({ ...req.body }, req.file);
logger.info(successMessages.AUTH_CREATE_USER, { logger.info(successMessages.AUTH_CREATE_USER, {
service: SERVICE_NAME, service: SERVICE_NAME,
userId: newUser._id, userId: newUser._id,
}); });
const userForToken = { ...newUser._doc }; const userForToken = { ...newUser._doc };
delete userForToken.profileImage; delete userForToken.profileImage;
delete userForToken.avatarImage; delete userForToken.avatarImage;
const appSettings = await req.settingsService.getSettings(); const appSettings = await req.settingsService.getSettings();
const token = issueToken(userForToken, appSettings); const token = issueToken(userForToken, appSettings);
req.emailService req.emailService
.buildAndSendEmail( .buildAndSendEmail(
"welcomeEmailTemplate", "welcomeEmailTemplate",
{ name: newUser.firstName }, { name: newUser.firstName },
newUser.email, newUser.email,
"Welcome to Uptime Monitor" "Welcome to Uptime Monitor"
) )
.catch((error) => { .catch((error) => {
logger.error("Error sending welcome email", { logger.error("Error sending welcome email", {
service: SERVICE_NAME, service: SERVICE_NAME,
error: error.message, error: error.message,
}); });
}); });
return res.status(200).json({ return res.status(200).json({
success: true, success: true,
msg: successMessages.AUTH_CREATE_USER, msg: successMessages.AUTH_CREATE_USER,
data: { user: newUser, token: token }, data: { user: newUser, token: token },
}); });
} catch (error) { } catch (error) {
console.log("ERROR", error); console.log("ERROR", error);
next(handleError(error, SERVICE_NAME, "registerController")); next(handleError(error, SERVICE_NAME, "registerController"));
} }
}; };
/** /**
@@ -121,44 +121,45 @@ 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) {
const validationError = handleValidationError(error, SERVICE_NAME); const validationError = handleValidationError(error, SERVICE_NAME);
next(validationError); next(validationError);
return; return;
} }
try { try {
const { email, password } = req.body; const { email, password } = req.body;
// Check if user exists
const user = await req.db.getUserByEmail(email);
// Compare password // Check if user exists
const match = await user.comparePassword(password); const user = await req.db.getUserByEmail(email);
if (match !== true) {
next(new Error(errorMessages.AUTH_INCORRECT_PASSWORD));
return;
}
// Remove password from user object. Should this be abstracted to DB layer? // Compare password
const userWithoutPassword = { ...user._doc }; const match = await user.comparePassword(password);
delete userWithoutPassword.password; if (match !== true) {
delete userWithoutPassword.avatarImage; next(new Error(errorMessages.AUTH_INCORRECT_PASSWORD));
return;
}
// Happy path, return token // Remove password from user object. Should this be abstracted to DB layer?
const appSettings = await req.settingsService.getSettings(); const userWithoutPassword = { ...user._doc };
const token = issueToken(userWithoutPassword, appSettings); delete userWithoutPassword.password;
// reset avatar image delete userWithoutPassword.avatarImage;
userWithoutPassword.avatarImage = user.avatarImage;
return res.status(200).json({ // Happy path, return token
success: true, const appSettings = await req.settingsService.getSettings();
msg: successMessages.AUTH_LOGIN_USER, const token = issueToken(userWithoutPassword, appSettings);
data: { user: userWithoutPassword, token: token }, // reset avatar image
}); userWithoutPassword.avatarImage = user.avatarImage;
} catch (error) {
next(handleError(error, SERVICE_NAME, "loginController")); return res.status(200).json({
} success: true,
msg: successMessages.AUTH_LOGIN_USER,
data: { user: userWithoutPassword, token: token },
});
} catch (error) {
next(handleError(error, SERVICE_NAME, "loginUser"));
}
}; };
/** /**
@@ -176,58 +177,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) {
const validationError = handleValidationError(error, SERVICE_NAME); const validationError = handleValidationError(error, SERVICE_NAME);
next(validationError); next(validationError);
return; return;
} }
// TODO is this neccessary any longer? Verify ownership middleware should handle this // TODO is this neccessary any longer? Verify ownership middleware should handle this
if (req.params.userId !== req.user._id.toString()) { if (req.params.userId !== req.user._id.toString()) {
const error = new Error(errorMessages.AUTH_UNAUTHORIZED); const error = new Error(errorMessages.AUTH_UNAUTHORIZED);
error.status = 401; error.status = 401;
error.service = SERVICE_NAME; error.service = SERVICE_NAME;
next(error); next(error);
return; return;
} }
try { try {
// Change Password check // Change Password check
if (req.body.password && req.body.newPassword) { if (req.body.password && req.body.newPassword) {
// Get token from headers // Get token from headers
const token = getTokenFromHeaders(req.headers); const token = getTokenFromHeaders(req.headers);
// Get email from token // Get email from token
const { jwtSecret } = req.settingsService.getSettings(); const { jwtSecret } = req.settingsService.getSettings();
const { email } = jwt.verify(token, jwtSecret); const { email } = jwt.verify(token, jwtSecret);
// Add user email to body for DB operation // Add user email to body for DB operation
req.body.email = email; req.body.email = email;
// Get user // Get user
const user = await req.db.getUserByEmail(email); const user = await req.db.getUserByEmail(email);
// Compare passwords // Compare passwords
const match = await user.comparePassword(req.body.password); const match = await user.comparePassword(req.body.password);
// If not a match, throw a 403 // If not a match, throw a 403
if (!match) { if (!match) {
const error = new Error(errorMessages.AUTH_INCORRECT_PASSWORD); const error = new Error(errorMessages.AUTH_INCORRECT_PASSWORD);
error.status = 403; error.status = 403;
next(error); next(error);
return; return;
} }
// If a match, update the password // If a match, update the password
req.body.password = req.body.newPassword; req.body.password = req.body.newPassword;
} }
const updatedUser = await req.db.updateUser(req, res); const updatedUser = await req.db.updateUser(req, res);
return res.status(200).json({ return res.status(200).json({
success: true, success: true,
msg: successMessages.AUTH_UPDATE_USER, msg: successMessages.AUTH_UPDATE_USER,
data: updatedUser, data: updatedUser,
}); });
} catch (error) { } catch (error) {
next(handleError(error, SERVICE_NAME, "userEditController")); next(handleError(error, SERVICE_NAME, "userEditController"));
} }
}; };
/** /**
@@ -240,16 +241,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, success: true,
msg: successMessages.AUTH_ADMIN_EXISTS, msg: successMessages.AUTH_ADMIN_EXISTS,
data: superAdminExists, data: superAdminExists,
}); });
} catch (error) { } catch (error) {
next(handleError(error, SERVICE_NAME, "checkSuperadminController")); next(handleError(error, SERVICE_NAME, "checkSuperadminController"));
} }
}; };
/** /**
@@ -264,46 +265,46 @@ 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) {
const validationError = handleValidationError(error, SERVICE_NAME); const validationError = handleValidationError(error, SERVICE_NAME);
next(validationError); next(validationError);
return; return;
} }
try { try {
const { email } = req.body; const { email } = req.body;
const user = await req.db.getUserByEmail(email); const user = await req.db.getUserByEmail(email);
if (user) { if (user) {
const recoveryToken = await req.db.requestRecoveryToken(req, res); const recoveryToken = await req.db.requestRecoveryToken(req, res);
const name = user.firstName; const name = user.firstName;
const email = req.body.email; const email = req.body.email;
const { clientHost } = req.settingsService.getSettings(); const { clientHost } = req.settingsService.getSettings();
const url = `${clientHost}/set-new-password/${recoveryToken.token}`; const url = `${clientHost}/set-new-password/${recoveryToken.token}`;
const msgId = await req.emailService.buildAndSendEmail( const msgId = await req.emailService.buildAndSendEmail(
"passwordResetTemplate", "passwordResetTemplate",
{ {
name, name,
email, email,
url, url,
}, },
email, email,
"Bluewave Uptime Password Reset" "Bluewave Uptime Password Reset"
); );
return res.status(200).json({ return res.status(200).json({
success: true, success: true,
msg: successMessages.AUTH_CREATE_RECOVERY_TOKEN, msg: successMessages.AUTH_CREATE_RECOVERY_TOKEN,
data: msgId, data: msgId,
}); });
} else { } else {
throw new Error(errorMessages.FRIENDLY_ERROR); throw new Error(errorMessages.FRIENDLY_ERROR);
} }
} catch (error) { } catch (error) {
next(handleError(error, SERVICE_NAME, "recoveryRequestController")); next(handleError(error, SERVICE_NAME, "recoveryRequestController"));
} }
}; };
/** /**
@@ -318,23 +319,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) {
const validationError = handleValidationError(error, SERVICE_NAME); const validationError = handleValidationError(error, SERVICE_NAME);
next(validationError); next(validationError);
return; 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, success: true,
msg: successMessages.AUTH_VERIFY_RECOVERY_TOKEN, msg: successMessages.AUTH_VERIFY_RECOVERY_TOKEN,
}); });
} catch (error) { } catch (error) {
next(handleError(error, SERVICE_NAME, "validateRecoveryTokenController")); next(handleError(error, SERVICE_NAME, "validateRecoveryTokenController"));
} }
}; };
/** /**
@@ -350,26 +351,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) {
const validationError = handleValidationError(error, SERVICE_NAME); const validationError = handleValidationError(error, SERVICE_NAME);
next(validationError); next(validationError);
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, msg: successMessages.AUTH_RESET_PASSWORD,
data: { user, token }, data: { user, token },
}); });
} catch (error) { } catch (error) {
next(handleError(error, SERVICE_NAME, "resetPasswordController")); next(handleError(error, SERVICE_NAME, "resetPasswordController"));
} }
}; };
/** /**
@@ -382,74 +383,72 @@ 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 // 1. Find all the monitors associated with the team ID if superadmin
const result = await req.db.getMonitorsByTeamId({ const result = await req.db.getMonitorsByTeamId({
params: { teamId: user.teamId }, params: { teamId: user.teamId },
}); });
if (user.role.includes("superadmin")) { if (user.role.includes("superadmin")) {
//2. Remove all jobs, delete checks and alerts //2. Remove all jobs, delete checks and alerts
result?.monitors.length > 0 && result?.monitors.length > 0 &&
(await Promise.all( (await Promise.all(
result.monitors.map(async (monitor) => { result.monitors.map(async (monitor) => {
await req.jobQueue.deleteJob(monitor); await req.jobQueue.deleteJob(monitor);
await req.db.deleteChecks(monitor._id); await req.db.deleteChecks(monitor._id);
await req.db.deletePageSpeedChecksByMonitorId(monitor._id); await req.db.deletePageSpeedChecksByMonitorId(monitor._id);
await req.db.deleteNotificationsByMonitorId(monitor._id); await req.db.deleteNotificationsByMonitorId(monitor._id);
}) })
)); ));
// 3. Delete team // 3. Delete team
await req.db.deleteTeam(user.teamId); await req.db.deleteTeam(user.teamId);
// 4. Delete all other team members // 4. Delete all other team members
await req.db.deleteAllOtherUsers(); await req.db.deleteAllOtherUsers();
// 5. Delete each monitor // 5. Delete each monitor
await req.db.deleteMonitorsByUserId(user._id); await req.db.deleteMonitorsByUserId(user._id);
} }
// 6. Delete the user by id // 6. Delete the user by id
await req.db.deleteUser(user._id); await req.db.deleteUser(user._id);
return res.status(200).json({ return res.status(200).json({
success: true, success: true,
msg: successMessages.AUTH_DELETE_USER, msg: successMessages.AUTH_DELETE_USER,
}); });
} catch (error) { } catch (error) {
next(handleError(error, SERVICE_NAME, "deleteUserController")); next(handleError(error, SERVICE_NAME, "deleteUserController"));
} }
}; };
const getAllUsers = async (req, res, next) => { const getAllUsers = async (req, res, next) => {
try { try {
const allUsers = await req.db.getAllUsers(req, res); const allUsers = await req.db.getAllUsers(req, res);
res res.status(200).json({ success: true, msg: "Got all users", data: allUsers });
.status(200) } catch (error) {
.json({ success: true, msg: "Got all users", data: allUsers }); next(handleError(error, SERVICE_NAME, "getAllUsersController"));
} catch (error) { }
next(handleError(error, SERVICE_NAME, "getAllUsersController"));
}
}; };
export { export {
issueToken, issueToken,
registerUser, registerUser,
loginUser, loginUser,
editUser, editUser,
checkSuperadminExists, checkSuperadminExists,
requestRecovery, requestRecovery,
validateRecovery, validateRecovery,
resetPassword, resetPassword,
deleteUser, deleteUser,
getAllUsers, getAllUsers,
}; };