Refactor for clarity and correctness, add JS docs
This commit is contained in:
1 parent
e0e80dc9c7
commit
c1d1e0ad1d
7 files changed
+180
-218
No files matched your search
@@ -1,4 +1,3 @@
|
|||||||
const express = require("express");
|
|
||||||
const {
|
const {
|
||||||
registrationBodyValidation,
|
registrationBodyValidation,
|
||||||
loginValidation,
|
loginValidation,
|
||||||
@@ -7,9 +6,6 @@ const {
|
|||||||
recoveryValidation,
|
recoveryValidation,
|
||||||
recoveryTokenValidation,
|
recoveryTokenValidation,
|
||||||
newPasswordValidation,
|
newPasswordValidation,
|
||||||
inviteRoleValidation,
|
|
||||||
inviteBodyValidation,
|
|
||||||
inviteVerificationBodyValidation,
|
|
||||||
} = require("../validation/joi");
|
} = require("../validation/joi");
|
||||||
const logger = require("../utils/logger");
|
const logger = require("../utils/logger");
|
||||||
require("dotenv").config();
|
require("dotenv").config();
|
||||||
@@ -24,28 +20,31 @@ const crypto = require("crypto");
|
|||||||
* @function
|
* @function
|
||||||
* @param {Object} payload
|
* @param {Object} payload
|
||||||
* @param {Object} appSettings
|
* @param {Object} appSettings
|
||||||
* @param {function} next
|
|
||||||
* @returns {String}
|
* @returns {String}
|
||||||
* @throws {Error}
|
* @throws {Error}
|
||||||
*/
|
*/
|
||||||
const issueToken = (payload, appSettings, next) => {
|
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;
|
error.service === undefined ? (error.service = SERVICE_NAME) : null;
|
||||||
error.method === undefined ? (error.method = "issueToken") : null;
|
error.method === undefined ? (error.method = "issueToken") : null;
|
||||||
next(error);
|
throw error;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @function
|
* Registers a new user. If the user is the first account, a JWT secret is created. If not, an invite token is required.
|
||||||
* @param {express.Request} req
|
* @async
|
||||||
* @param {express.Response} res
|
* @param {Object} req - The Express request object.
|
||||||
* @param {function} next
|
* @property {Object} req.body - The body of the request.
|
||||||
* @returns {{success: Boolean, msg: String}}
|
* @property {string} req.body.inviteToken - The invite token for registration.
|
||||||
* @throws {Error}
|
* @property {Object} req.file - The file object for the user's profile image.
|
||||||
|
* @param {Object} res - The Express response object.
|
||||||
|
* @param {function} next - The next middleware function.
|
||||||
|
* @returns {Object} The response object with a success status, a message indicating the creation of the user, the created user data, and a JWT token.
|
||||||
|
* @throws {Error} If there is an error during the process, especially if there is a validation error (422).
|
||||||
*/
|
*/
|
||||||
const registerUser = async (req, res, next) => {
|
const registerUser = async (req, res, next) => {
|
||||||
// joi validation
|
// joi validation
|
||||||
@@ -101,12 +100,16 @@ const registerUser = async (req, res, next) => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Returns JWT with User info
|
* Logs in a user by validating the user's credentials and issuing a JWT token.
|
||||||
* @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.
|
||||||
* @param {function} next
|
* @property {string} req.body.email - The email of the user.
|
||||||
* @returns {Promise<Express.Response>}
|
* @property {string} req.body.password - The password of the user.
|
||||||
|
* @param {Object} res - The Express response object.
|
||||||
|
* @param {function} next - The next middleware function.
|
||||||
|
* @returns {Object} The response object with a success status, a message indicating the login of the user, the user data (without password and avatar image), and a JWT token.
|
||||||
|
* @throws {Error} If there is an error during the process, especially if there is a validation error (422) or the password is incorrect.
|
||||||
*/
|
*/
|
||||||
const loginUser = async (req, res, next) => {
|
const loginUser = async (req, res, next) => {
|
||||||
try {
|
try {
|
||||||
@@ -126,7 +129,8 @@ const loginUser = async (req, res, next) => {
|
|||||||
// Compare password
|
// Compare password
|
||||||
const match = await user.comparePassword(password);
|
const match = await user.comparePassword(password);
|
||||||
if (match !== true) {
|
if (match !== true) {
|
||||||
throw new Error(errorMessages.AUTH_INCORRECT_PASSWORD);
|
next(new Error(errorMessages.AUTH_INCORRECT_PASSWORD));
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Remove password from user object. Should this be abstracted to DB layer?
|
// Remove password from user object. Should this be abstracted to DB layer?
|
||||||
@@ -151,6 +155,20 @@ const loginUser = async (req, res, next) => {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Edits a user's information. If the user wants to change their password, the current password is checked before updating to the new password.
|
||||||
|
* @async
|
||||||
|
* @param {Object} req - The Express request object.
|
||||||
|
* @property {Object} req.params - The parameters of the request.
|
||||||
|
* @property {string} req.params.userId - The ID of the user to be edited.
|
||||||
|
* @property {Object} req.body - The body of the request.
|
||||||
|
* @property {string} req.body.password - The current password of the user.
|
||||||
|
* @property {string} req.body.newPassword - The new password of the user.
|
||||||
|
* @param {Object} res - The Express response object.
|
||||||
|
* @param {function} next - The next middleware function.
|
||||||
|
* @returns {Object} The response object with a success status, a message indicating the update of the user, and the updated user data.
|
||||||
|
* @throws {Error} If there is an error during the process, especially if there is a validation error (422), the user is unauthorized (401), or the password is incorrect (403).
|
||||||
|
*/
|
||||||
const editUser = async (req, res, next) => {
|
const editUser = async (req, res, next) => {
|
||||||
try {
|
try {
|
||||||
await editUserParamValidation.validateAsync(req.params);
|
await editUserParamValidation.validateAsync(req.params);
|
||||||
@@ -175,10 +193,6 @@ const editUser = async (req, res, next) => {
|
|||||||
try {
|
try {
|
||||||
// Change Password check
|
// Change Password check
|
||||||
if (req.body.password && req.body.newPassword) {
|
if (req.body.password && req.body.newPassword) {
|
||||||
const newPassword = req.body.newPassword;
|
|
||||||
const password = req.body.password;
|
|
||||||
|
|
||||||
// Compare password
|
|
||||||
// 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
|
||||||
@@ -194,7 +208,8 @@ const editUser = async (req, res, next) => {
|
|||||||
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;
|
||||||
throw error;
|
next(error)
|
||||||
|
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;
|
||||||
@@ -208,83 +223,19 @@ const editUser = async (req, res, next) => {
|
|||||||
error.service === undefined ? (error.service = SERVICE_NAME) : null;
|
error.service === undefined ? (error.service = SERVICE_NAME) : null;
|
||||||
error.method === undefined ? (error.method = "userEditController") : null;
|
error.method === undefined ? (error.method = "userEditController") : null;
|
||||||
next(error);
|
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;
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Checks to see if an admin account exists
|
* Checks if a superadmin account exists in the database.
|
||||||
* @async
|
* @async
|
||||||
* @param {Express.Request} req
|
* @param {Object} req - The Express request object.
|
||||||
* @param {Express.Response} res
|
* @param {Object} res - The Express response object.
|
||||||
* @returns {Promise<Express.Response>}
|
* @param {function} next - The next middleware function.
|
||||||
|
* @returns {Object} The response object with a success status, a message indicating the existence of a superadmin, and a boolean indicating the existence of a superadmin.
|
||||||
|
* @throws {Error} If there is an error during the process.
|
||||||
*/
|
*/
|
||||||
|
const checkSuperAdminExists = async (req, res, next) => {
|
||||||
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({
|
||||||
@@ -294,18 +245,19 @@ const checkSuperadminExists = async (req, res) => {
|
|||||||
error.service === undefined ? (error.service = SERVICE_NAME) : null;
|
error.service === undefined ? (error.service = SERVICE_NAME) : null;
|
||||||
error.method === undefined ? (error.method = "checkSuperadminController") : null;
|
error.method === undefined ? (error.method = "checkSuperadminController") : null;
|
||||||
next(error);
|
next(error);
|
||||||
return;
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Returns a recovery token
|
* Requests a recovery token for a user. The user's email is validated and a recovery token is created and sent via email.
|
||||||
* @async
|
* @async
|
||||||
* @param {Express.Request} req
|
* @param {Object} req - The Express request object.
|
||||||
* @property {Object} req.body
|
* @property {Object} req.body - The body of the request.
|
||||||
* @property {string} req.body.email
|
* @property {string} req.body.email - The email of the user requesting recovery.
|
||||||
* @property {EmailService} req.body.emailService
|
* @param {Object} res - The Express response object.
|
||||||
* @returns {Promise<Express.Response>}
|
* @param {function} next - The next middleware function.
|
||||||
|
* @returns {Object} The response object with a success status, a message indicating the creation of the recovery token, and the message ID of the sent email.
|
||||||
|
* @throws {Error} If there is an error during the process, especially if there is a validation error (422).
|
||||||
*/
|
*/
|
||||||
const requestRecovery = async (req, res, next) => {
|
const requestRecovery = async (req, res, next) => {
|
||||||
try {
|
try {
|
||||||
@@ -332,7 +284,7 @@ const requestRecovery = async (req, res, next) => {
|
|||||||
name,
|
name,
|
||||||
email,
|
email,
|
||||||
url
|
url
|
||||||
}, email, "Bluewaves Uptime Password Resest");
|
}, email, "Bluewave Uptime Password Reset");
|
||||||
|
|
||||||
return res.status(200).json({
|
return res.status(200).json({
|
||||||
success: true, msg: successMessages.AUTH_CREATE_RECOVERY_TOKEN, data: msgId,
|
success: true, msg: successMessages.AUTH_CREATE_RECOVERY_TOKEN, data: msgId,
|
||||||
@@ -342,18 +294,19 @@ const requestRecovery = async (req, res, next) => {
|
|||||||
error.service === undefined ? (error.service = SERVICE_NAME) : null;
|
error.service === undefined ? (error.service = SERVICE_NAME) : null;
|
||||||
error.method === undefined ? (error.method = "recoveryRequestController") : null;
|
error.method === undefined ? (error.method = "recoveryRequestController") : null;
|
||||||
next(error);
|
next(error);
|
||||||
return;
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Returns a recovery token
|
* Validates a recovery token. The recovery token is validated and if valid, a success message is returned.
|
||||||
* @async
|
* @async
|
||||||
* @param {Express.Request} req
|
* @param {Object} req - The Express request object.
|
||||||
* @property {Object} req.body
|
* @property {Object} req.body - The body of the request.
|
||||||
* @property {string} req.body.token
|
* @property {string} req.body.token - The recovery token to be validated.
|
||||||
* @param {Express.Response} res
|
* @param {Object} res - The Express response object.
|
||||||
* @returns {Promise<Express.Response>}
|
* @param {function} next - The next middleware function.
|
||||||
|
* @returns {Object} The response object with a success status and a message indicating the validation of the recovery token.
|
||||||
|
* @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 {
|
||||||
@@ -375,19 +328,20 @@ const validateRecovery = async (req, res, next) => {
|
|||||||
error.service === undefined ? (error.service = SERVICE_NAME) : null;
|
error.service === undefined ? (error.service = SERVICE_NAME) : null;
|
||||||
error.method === undefined ? (error.method = "validateRecoveryTokenController") : null;
|
error.method === undefined ? (error.method = "validateRecoveryTokenController") : null;
|
||||||
next(error);
|
next(error);
|
||||||
return;
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Returns an updated user
|
* Resets a user's password. The new password is validated and if valid, the user's password is updated in the database and a new JWT token is issued.
|
||||||
* @async
|
* @async
|
||||||
* @param {Express.Request} req
|
* @param {Object} req - The Express request object.
|
||||||
* @property {Object} req.body
|
* @property {Object} req.body - The body of the request.
|
||||||
* @property {string} req.body.token
|
* @property {string} req.body.token - The recovery token.
|
||||||
* @property {string} req.body.password
|
* @property {string} req.body.password - The new password of the user.
|
||||||
* @param {Express.Response} res
|
* @param {Object} res - The Express response object.
|
||||||
* @returns {Promise<Express.Response>}
|
* @param {function} next - The next middleware function.
|
||||||
|
* @returns {Object} The response object with a success status, a message indicating the reset of the password, the updated user data (without password and avatar image), and a new JWT token.
|
||||||
|
* @throws {Error} If there is an error during the process, especially if there is a validation error (422).
|
||||||
*/
|
*/
|
||||||
const resetPassword = async (req, res, next) => {
|
const resetPassword = async (req, res, next) => {
|
||||||
try {
|
try {
|
||||||
@@ -427,12 +381,13 @@ 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 {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);
|
next(new Error(errorMessages.DB_USER_NOT_FOUND));
|
||||||
|
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
|
||||||
@@ -486,9 +441,7 @@ module.exports = {
|
|||||||
registerUser,
|
registerUser,
|
||||||
loginUser,
|
loginUser,
|
||||||
editUser,
|
editUser,
|
||||||
createInvitation,
|
checkSuperadminExists: checkSuperAdminExists,
|
||||||
verifyInvitation,
|
|
||||||
checkSuperadminExists,
|
|
||||||
requestRecovery,
|
requestRecovery,
|
||||||
validateRecovery,
|
validateRecovery,
|
||||||
resetPassword,
|
resetPassword,
|
||||||
|
|||||||
@@ -1,101 +1,111 @@
|
|||||||
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 { errorMessages, successMessages } = require("../utils/messages");
|
const jwt = require("jsonwebtoken");
|
||||||
var jwt = require("jsonwebtoken");
|
|
||||||
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];
|
||||||
};
|
};
|
||||||
|
|
||||||
const inviteController = async (req, res, next) => {
|
/**
|
||||||
try {
|
* Issues an invitation to a new user. Only admins can invite new users. An invitation token is created and sent via email.
|
||||||
// Only admins can invite
|
* @async
|
||||||
const token = getTokenFromHeaders(req.headers);
|
* @param {Object} req - The Express request object.
|
||||||
const { role, firstname, teamId } = jwt.decode(token);
|
* @property {Object} req.headers - The headers of the request.
|
||||||
req.body.teamId = teamId;
|
* @property {string} req.headers.authorization - The authorization header containing the JWT token.
|
||||||
|
* @property {Object} req.body - The body of the request.
|
||||||
|
* @property {string} req.body.email - The email of the user to be invited.
|
||||||
|
* @param {Object} res - The Express response object.
|
||||||
|
* @param {function} next - The next middleware function.
|
||||||
|
* @returns {Object} The response object with a success status, a message indicating the sending of the invitation, and the invitation token.
|
||||||
|
* @throws {Error} If there is an error during the process, especially if there is a validation error (422).
|
||||||
|
*/
|
||||||
|
const issueInvitation = async (req, res, next) => {
|
||||||
try {
|
try {
|
||||||
await inviteRoleValidation.validateAsync({ roles: role });
|
// Only admins can invite
|
||||||
await inviteBodyValidation.validateAsync(req.body);
|
const token = getTokenFromHeaders(req.headers);
|
||||||
|
const {role, firstname, teamId} = jwt.decode(token);
|
||||||
|
req.body.teamId = teamId;
|
||||||
|
try {
|
||||||
|
await inviteRoleValidation.validateAsync({roles: role});
|
||||||
|
await inviteBodyValidation.validateAsync(req.body);
|
||||||
|
} catch (error) {
|
||||||
|
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.status = 422;
|
error.service === undefined ? (error.service = SERVICE_NAME) : null;
|
||||||
error.service = SERVICE_NAME;
|
error.method === undefined ? (error.method = "inviteController") : null;
|
||||||
error.message =
|
next(error);
|
||||||
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) {
|
|
||||||
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 inviteVerifyController = async (req, res, next) => {
|
||||||
try {
|
try {
|
||||||
await inviteVerificationBodyValidation.validateAsync(req.body);
|
await inviteVerificationBodyValidation.validateAsync(req.body);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
error.status = 422;
|
error.status = 422;
|
||||||
error.service = SERVICE_NAME;
|
error.service = SERVICE_NAME;
|
||||||
error.message =
|
error.message =
|
||||||
error.details?.[0]?.message || error.message || "Validation Error";
|
error.details?.[0]?.message || error.message || "Validation Error";
|
||||||
next(error);
|
next(error);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
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;
|
error.service === undefined ? (error.service = SERVICE_NAME) : null;
|
||||||
error.method === undefined
|
error.method === undefined
|
||||||
? (error.method = "inviteVerifyController")
|
? (error.method = "inviteVerifyController")
|
||||||
: null;
|
: null;
|
||||||
next(error);
|
next(error);
|
||||||
return;
|
}
|
||||||
}
|
|
||||||
};
|
};
|
||||||
|
|
||||||
module.exports = {
|
module.exports = {
|
||||||
inviteController,
|
inviteController: issueInvitation,
|
||||||
inviteVerifyController,
|
inviteVerifyController,
|
||||||
};
|
};
|
||||||
@@ -5,8 +5,9 @@ const {
|
|||||||
getMaintenanceWindowsByMonitorIdParamValidation,
|
getMaintenanceWindowsByMonitorIdParamValidation,
|
||||||
} = require("../validation/joi");
|
} = require("../validation/joi");
|
||||||
|
|
||||||
|
const {successMessages} = require("../utils/messages")
|
||||||
|
|
||||||
const SERVICE_NAME = "maintenanceWindowController";
|
const SERVICE_NAME = "maintenanceWindowController";
|
||||||
const { errorMessages, successMessages } = require("../utils/messages");
|
|
||||||
|
|
||||||
const createMaintenanceWindow = async (req, res, next) => {
|
const createMaintenanceWindow = async (req, res, next) => {
|
||||||
try {
|
try {
|
||||||
@@ -67,7 +68,7 @@ const getMaintenanceWindowsByUserId = async (req, res, next) => {
|
|||||||
|
|
||||||
return res.status(201).json({
|
return res.status(201).json({
|
||||||
success: true,
|
success: true,
|
||||||
msg: successMessages.MAINTEANCE_WINDOW_GET_BY_USER,
|
msg: successMessages.MAINTENANCE_WINDOW_GET_BY_USER,
|
||||||
data: maintenanceWindows,
|
data: maintenanceWindows,
|
||||||
});
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
@@ -100,7 +101,7 @@ const getMaintenanceWindowsByMonitorId = async (req, res, next) => {
|
|||||||
|
|
||||||
return res.status(201).json({
|
return res.status(201).json({
|
||||||
success: true,
|
success: true,
|
||||||
msg: successMessages.MAINTEANCE_WINDOW_GET_BY_USER,
|
msg: successMessages.MAINTENANCE_WINDOW_GET_BY_USER,
|
||||||
data: maintenanceWindows,
|
data: maintenanceWindows,
|
||||||
});
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
|
|||||||
@@ -69,7 +69,7 @@ const getMonitorStatsById = async (req, res, next) => {
|
|||||||
const monitorStats = await req.db.getMonitorStatsById(req);
|
const monitorStats = await req.db.getMonitorStatsById(req);
|
||||||
return res.json({
|
return res.json({
|
||||||
success: true,
|
success: true,
|
||||||
msg: successMessages.MONTIOR_STATS_BY_ID,
|
msg: successMessages.MONITOR_STATS_BY_ID,
|
||||||
data: monitorStats,
|
data: monitorStats,
|
||||||
});
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
@@ -150,7 +150,7 @@ const getMonitorById = async (req, res, next) => {
|
|||||||
|
|
||||||
return res.json({
|
return res.json({
|
||||||
success: true,
|
success: true,
|
||||||
msg: successMessages.MONTIOR_GET_BY_ID,
|
msg: successMessages.MONITOR_GET_BY_ID,
|
||||||
data: monitor,
|
data: monitor,
|
||||||
});
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
|
|||||||
@@ -147,7 +147,7 @@ const getMonitorStatsById = async (req) => {
|
|||||||
let { limit, sortOrder, dateRange, numToDisplay, normalize } = req.query;
|
let { limit, sortOrder, dateRange, numToDisplay, normalize } = req.query;
|
||||||
const monitor = await Monitor.findById(monitorId);
|
const monitor = await Monitor.findById(monitorId);
|
||||||
if (monitor === null || monitor === undefined) {
|
if (monitor === null || monitor === undefined) {
|
||||||
throw new Error(errorMessages.DB_FIND_MONTIOR_BY_ID(monitorId));
|
throw new Error(errorMessages.DB_FIND_MONITOR_BY_ID(monitorId));
|
||||||
}
|
}
|
||||||
// This effectively removes limit, returning all checks
|
// This effectively removes limit, returning all checks
|
||||||
if (limit === undefined) limit = 0;
|
if (limit === undefined) limit = 0;
|
||||||
@@ -283,7 +283,7 @@ const getMonitorById = async (monitorId) => {
|
|||||||
try {
|
try {
|
||||||
const monitor = await Monitor.findById(monitorId);
|
const monitor = await Monitor.findById(monitorId);
|
||||||
if (monitor === null || monitor === undefined) {
|
if (monitor === null || monitor === undefined) {
|
||||||
throw new Error(errorMessages.DB_FIND_MONTIOR_BY_ID(monitorId));
|
throw new Error(errorMessages.DB_FIND_MONITOR_BY_ID(monitorId));
|
||||||
}
|
}
|
||||||
// Get notifications
|
// Get notifications
|
||||||
const notifications = await Notification.find({
|
const notifications = await Notification.find({
|
||||||
@@ -481,7 +481,7 @@ const deleteMonitor = async (req, res) => {
|
|||||||
try {
|
try {
|
||||||
const monitor = await Monitor.findByIdAndDelete(monitorId);
|
const monitor = await Monitor.findByIdAndDelete(monitorId);
|
||||||
if (!monitor) {
|
if (!monitor) {
|
||||||
throw new Error(errorMessages.DB_FIND_MONTIOR_BY_ID(monitorId));
|
throw new Error(errorMessages.DB_FIND_MONITOR_BY_ID(monitorId));
|
||||||
}
|
}
|
||||||
return monitor;
|
return monitor;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
|
|||||||
@@ -9,7 +9,6 @@ const User = require("../db/models/User");
|
|||||||
const {
|
const {
|
||||||
registerUser,
|
registerUser,
|
||||||
loginUser,
|
loginUser,
|
||||||
logoutController,
|
|
||||||
editUser,
|
editUser,
|
||||||
requestRecovery,
|
requestRecovery,
|
||||||
validateRecovery,
|
validateRecovery,
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ const errorMessages = {
|
|||||||
NO_AUTH_TOKEN: "No auth token provided",
|
NO_AUTH_TOKEN: "No auth token provided",
|
||||||
INVALID_AUTH_TOKEN: "Invalid auth token",
|
INVALID_AUTH_TOKEN: "Invalid auth token",
|
||||||
|
|
||||||
//Onwership Middleware
|
//Ownership Middleware
|
||||||
VERIFY_OWNER_NOT_FOUND: "Document not found",
|
VERIFY_OWNER_NOT_FOUND: "Document not found",
|
||||||
VERIFY_OWNER_UNAUTHORIZED: "Unauthorized access",
|
VERIFY_OWNER_UNAUTHORIZED: "Unauthorized access",
|
||||||
|
|
||||||
@@ -26,17 +26,16 @@ const errorMessages = {
|
|||||||
DB_TOKEN_NOT_FOUND: "Token not found",
|
DB_TOKEN_NOT_FOUND: "Token not found",
|
||||||
DB_RESET_PASSWORD_BAD_MATCH:
|
DB_RESET_PASSWORD_BAD_MATCH:
|
||||||
"New password must be different from old password",
|
"New password must be different from old password",
|
||||||
DB_FIND_MONTIOR_BY_ID: (monitorId) =>
|
DB_FIND_MONITOR_BY_ID: (monitorId) =>
|
||||||
`Monitor with id ${monitorId} not found`,
|
`Monitor with id ${monitorId} not found`,
|
||||||
DB_DELETE_CHECKS: (monitorId) =>
|
DB_DELETE_CHECKS: (monitorId) =>
|
||||||
`No checks found for monitor with id ${monitorId}`,
|
`No checks found for monitor with id ${monitorId}`,
|
||||||
DB_DELETE_ALERT: (alertId) => `Alert with id ${alertId} not found`,
|
|
||||||
|
|
||||||
//Auth errors
|
//Auth errors
|
||||||
AUTH_INCORRECT_PASSWORD: "Incorrect password",
|
AUTH_INCORRECT_PASSWORD: "Incorrect password",
|
||||||
AUTH_UNAUTHORIZED: "Unauthorized access",
|
AUTH_UNAUTHORIZED: "Unauthorized access",
|
||||||
|
|
||||||
// Monitor Errros
|
// Monitor Errors
|
||||||
MONITOR_GET_BY_ID: "Monitor not found",
|
MONITOR_GET_BY_ID: "Monitor not found",
|
||||||
MONITOR_GET_BY_USER_ID: "No monitors found for user",
|
MONITOR_GET_BY_USER_ID: "No monitors found for user",
|
||||||
|
|
||||||
@@ -77,8 +76,8 @@ const successMessages = {
|
|||||||
|
|
||||||
//Monitor Controller
|
//Monitor Controller
|
||||||
MONITOR_GET_ALL: "Got all monitors successfully",
|
MONITOR_GET_ALL: "Got all monitors successfully",
|
||||||
MONTIOR_STATS_BY_ID: "Got monitor stats by Id successfully",
|
MONITOR_STATS_BY_ID: "Got monitor stats by Id successfully",
|
||||||
MONTIOR_GET_BY_ID: "Got monitor by Id successfully",
|
MONITOR_GET_BY_ID: "Got monitor by Id successfully",
|
||||||
MONITOR_GET_BY_USER_ID: (userId) => `Got monitor for ${userId} successfully"`,
|
MONITOR_GET_BY_USER_ID: (userId) => `Got monitor for ${userId} successfully"`,
|
||||||
MONITOR_CREATE: "Monitor created successfully",
|
MONITOR_CREATE: "Monitor created successfully",
|
||||||
MONITOR_DELETE: "Monitor deleted successfully",
|
MONITOR_DELETE: "Monitor deleted successfully",
|
||||||
@@ -94,7 +93,7 @@ const successMessages = {
|
|||||||
|
|
||||||
//Maintenance Window Controller
|
//Maintenance Window Controller
|
||||||
MAINTENANCE_WINDOW_CREATE: "Maintenance Window created successfully",
|
MAINTENANCE_WINDOW_CREATE: "Maintenance Window created successfully",
|
||||||
MAINTEANCE_WINDOW_GET_BY_USER: "Got Maintenance Windows by User successfully",
|
MAINTENANCE_WINDOW_GET_BY_USER: "Got Maintenance Windows by User successfully",
|
||||||
|
|
||||||
//Ping Operations
|
//Ping Operations
|
||||||
PING_SUCCESS: "Success",
|
PING_SUCCESS: "Success",
|
||||||
|
|||||||
Reference in new issue
Block a user