Resolving merge issues.
This commit is contained in:
commit
c70b5b0ae8
54 files changed
+4312
-2532
No files matched your search
@@ -7,7 +7,6 @@ import {
|
||||
recoveryTokenValidation,
|
||||
newPasswordValidation,
|
||||
} from "../validation/joi.js";
|
||||
import logger from "../utils/logger.js";
|
||||
import jwt from "jsonwebtoken";
|
||||
import { getTokenFromHeaders } from "../utils/utils.js";
|
||||
import crypto from "crypto";
|
||||
@@ -15,12 +14,13 @@ import { handleValidationError, handleError } from "./controllerUtils.js";
|
||||
const SERVICE_NAME = "authController";
|
||||
|
||||
class AuthController {
|
||||
constructor(db, settingsService, emailService, jobQueue, stringService) {
|
||||
constructor({ db, settingsService, emailService, jobQueue, stringService, logger }) {
|
||||
this.db = db;
|
||||
this.settingsService = settingsService;
|
||||
this.emailService = emailService;
|
||||
this.jobQueue = jobQueue;
|
||||
this.stringService = stringService;
|
||||
this.logger = logger;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -96,21 +96,28 @@ class AuthController {
|
||||
|
||||
const token = this.issueToken(userForToken, appSettings);
|
||||
|
||||
this.emailService
|
||||
.buildAndSendEmail(
|
||||
"welcomeEmailTemplate",
|
||||
{ name: newUser.firstName },
|
||||
newUser.email,
|
||||
"Welcome to Uptime Monitor"
|
||||
)
|
||||
.catch((error) => {
|
||||
logger.error({
|
||||
message: error.message,
|
||||
service: SERVICE_NAME,
|
||||
method: "registerUser",
|
||||
stack: error.stack,
|
||||
});
|
||||
try {
|
||||
const html = await this.emailService.buildEmail("welcomeEmailTemplate", {
|
||||
name: newUser.firstName,
|
||||
});
|
||||
this.emailService
|
||||
.sendEmail(newUser.email, "Welcome to Uptime Monitor", html)
|
||||
.catch((error) => {
|
||||
this.logger.warn({
|
||||
message: error.message,
|
||||
service: SERVICE_NAME,
|
||||
method: "registerUser",
|
||||
stack: error.stack,
|
||||
});
|
||||
});
|
||||
} catch (error) {
|
||||
logger.warn({
|
||||
message: error.message,
|
||||
service: SERVICE_NAME,
|
||||
method: "registerUser",
|
||||
stack: error.stack,
|
||||
});
|
||||
}
|
||||
|
||||
res.success({
|
||||
msg: this.stringService.authCreateUser,
|
||||
@@ -300,15 +307,16 @@ class AuthController {
|
||||
const name = user.firstName;
|
||||
const { clientHost } = this.settingsService.getSettings();
|
||||
const url = `${clientHost}/set-new-password/${recoveryToken.token}`;
|
||||
const msgId = await this.emailService.buildAndSendEmail(
|
||||
"passwordResetTemplate",
|
||||
{
|
||||
name,
|
||||
email,
|
||||
url,
|
||||
},
|
||||
|
||||
const html = await this.emailService.buildEmail("passwordResetTemplate", {
|
||||
name,
|
||||
email,
|
||||
"Checkmate Password Reset"
|
||||
url,
|
||||
});
|
||||
const msgId = await this.emailService.sendEmail(
|
||||
email,
|
||||
"Checkmate Password Reset",
|
||||
html
|
||||
);
|
||||
|
||||
return res.success({
|
||||
|
||||
@@ -71,24 +71,25 @@ class InviteController {
|
||||
|
||||
const inviteToken = await this.db.requestInviteToken({ ...req.body });
|
||||
const { clientHost } = this.settingsService.getSettings();
|
||||
this.emailService
|
||||
.buildAndSendEmail(
|
||||
"employeeActivationTemplate",
|
||||
{
|
||||
name: firstname,
|
||||
link: `${clientHost}/register/${inviteToken.token}`,
|
||||
},
|
||||
req.body.email,
|
||||
"Welcome to Uptime Monitor"
|
||||
)
|
||||
.catch((error) => {
|
||||
logger.error({
|
||||
message: error.message,
|
||||
service: SERVICE_NAME,
|
||||
method: "issueInvitation",
|
||||
stack: error.stack,
|
||||
});
|
||||
|
||||
try {
|
||||
const html = await this.emailService.buildEmail("employeeActivationTemplate", {
|
||||
name: firstname,
|
||||
link: `${clientHost}/register/${inviteToken.token}`,
|
||||
});
|
||||
await this.emailService.sendEmail(
|
||||
req.body.email,
|
||||
"Welcome to Uptime Monitor",
|
||||
html
|
||||
);
|
||||
} catch (error) {
|
||||
logger.warn({
|
||||
message: error.message,
|
||||
service: SERVICE_NAME,
|
||||
method: "sendInviteEmail",
|
||||
stack: error.stack,
|
||||
});
|
||||
}
|
||||
|
||||
return res.success({
|
||||
msg: this.stringService.inviteIssued,
|
||||
|
||||
@@ -580,12 +580,8 @@ class MonitorController {
|
||||
const subject = this.stringService.testEmailSubject;
|
||||
const context = { testName: "Monitoring System" };
|
||||
|
||||
const messageId = await this.emailService.buildAndSendEmail(
|
||||
"testEmailTemplate",
|
||||
context,
|
||||
to,
|
||||
subject
|
||||
);
|
||||
const html = await this.emailService.buildEmail("testEmailTemplate", context);
|
||||
const messageId = await this.emailService.sendEmail(to, subject, html);
|
||||
|
||||
if (!messageId) {
|
||||
return res.error({
|
||||
|
||||
@@ -102,6 +102,7 @@ class NotificationController {
|
||||
success =
|
||||
await this.notificationService.sendTestPagerDutyNotification(notification);
|
||||
}
|
||||
|
||||
if (!success) {
|
||||
return res.error({
|
||||
msg: "Sending notification failed",
|
||||
@@ -128,7 +129,11 @@ class NotificationController {
|
||||
}
|
||||
|
||||
try {
|
||||
const notification = await this.db.createNotification(req.body);
|
||||
const body = req.body;
|
||||
const { _id, teamId } = req.user;
|
||||
body.userId = _id;
|
||||
body.teamId = teamId;
|
||||
const notification = await this.db.createNotification(body);
|
||||
return res.success({
|
||||
msg: "Notification created successfully",
|
||||
data: notification,
|
||||
|
||||
@@ -11,8 +11,7 @@ class SettingsController {
|
||||
this.emailService = emailService;
|
||||
}
|
||||
|
||||
getAppSettings = async (req, res, next) => {
|
||||
const dbSettings = await this.settingsService.getDBSettings();
|
||||
buildAppSettings = (dbSettings) => {
|
||||
const sanitizedSettings = { ...dbSettings };
|
||||
delete sanitizedSettings.version;
|
||||
|
||||
@@ -30,6 +29,13 @@ class SettingsController {
|
||||
delete sanitizedSettings.systemEmailPassword;
|
||||
}
|
||||
returnSettings.settings = sanitizedSettings;
|
||||
return returnSettings;
|
||||
};
|
||||
|
||||
getAppSettings = async (req, res, next) => {
|
||||
const dbSettings = await this.settingsService.getDBSettings();
|
||||
|
||||
const returnSettings = this.buildAppSettings(dbSettings);
|
||||
return res.success({
|
||||
msg: this.stringService.getAppSettings,
|
||||
data: returnSettings,
|
||||
@@ -45,12 +51,11 @@ class SettingsController {
|
||||
}
|
||||
|
||||
try {
|
||||
await this.db.updateAppSettings(req.body);
|
||||
const updatedSettings = { ...(await this.settingsService.reloadSettings()) };
|
||||
delete updatedSettings.jwtSecret;
|
||||
const updatedSettings = await this.db.updateAppSettings(req.body);
|
||||
const returnSettings = this.buildAppSettings(updatedSettings);
|
||||
return res.success({
|
||||
msg: this.stringService.updateAppSettings,
|
||||
data: updatedSettings,
|
||||
data: returnSettings,
|
||||
});
|
||||
} catch (error) {
|
||||
next(handleError(error, SERVICE_NAME, "updateAppSettings"));
|
||||
@@ -85,26 +90,21 @@ class SettingsController {
|
||||
const subject = this.stringService.testEmailSubject;
|
||||
const context = { testName: "Monitoring System" };
|
||||
|
||||
const messageId = await this.emailService.buildAndSendEmail(
|
||||
"testEmailTemplate",
|
||||
context,
|
||||
to,
|
||||
subject,
|
||||
{
|
||||
systemEmailHost,
|
||||
systemEmailPort,
|
||||
systemEmailUser,
|
||||
systemEmailAddress,
|
||||
systemEmailPassword,
|
||||
systemEmailConnectionHost,
|
||||
systemEmailSecure,
|
||||
systemEmailPool,
|
||||
systemEmailIgnoreTLS,
|
||||
systemEmailRequireTLS,
|
||||
systemEmailRejectUnauthorized,
|
||||
systemEmailTLSServername,
|
||||
}
|
||||
);
|
||||
const html = await this.emailService.buildEmail("testEmailTemplate", context);
|
||||
const messageId = await this.emailService.sendEmail(to, subject, html, {
|
||||
systemEmailHost,
|
||||
systemEmailPort,
|
||||
systemEmailUser,
|
||||
systemEmailAddress,
|
||||
systemEmailPassword,
|
||||
systemEmailConnectionHost,
|
||||
systemEmailSecure,
|
||||
systemEmailPool,
|
||||
systemEmailIgnoreTLS,
|
||||
systemEmailRequireTLS,
|
||||
systemEmailRejectUnauthorized,
|
||||
systemEmailTLSServername,
|
||||
});
|
||||
|
||||
if (!messageId) {
|
||||
return res.error({
|
||||
@@ -117,7 +117,7 @@ class SettingsController {
|
||||
data: { messageId },
|
||||
});
|
||||
} catch (error) {
|
||||
next(handleValidationError(error, SERVICE_NAME));
|
||||
next(handleError(error, SERVICE_NAME));
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
@@ -7,7 +7,7 @@ const configSchema = mongoose.Schema(
|
||||
chatId: { type: String },
|
||||
platform: {
|
||||
type: String,
|
||||
enum: ["slack", "pager_duty", "webhook"],
|
||||
enum: ["slack", "pager_duty", "webhook", "discord"],
|
||||
},
|
||||
routingKey: { type: String },
|
||||
},
|
||||
|
||||
@@ -26,10 +26,12 @@ const updateAppSettings = async (newSettings) => {
|
||||
delete update.$set.systemEmailPassword;
|
||||
}
|
||||
|
||||
const settings = await AppSettings.findOneAndUpdate({}, update, {
|
||||
new: true,
|
||||
await AppSettings.findOneAndUpdate({}, update, {
|
||||
upsert: true,
|
||||
});
|
||||
const settings = await AppSettings.findOne()
|
||||
.select("-__v -_id -createdAt -updatedAt -singleton")
|
||||
.lean();
|
||||
return settings;
|
||||
} catch (error) {
|
||||
error.service = SERVICE_NAME;
|
||||
|
||||
+8
-7
@@ -239,13 +239,14 @@ const startApp = async () => {
|
||||
process.on("SIGTERM", shutdown);
|
||||
|
||||
//Create controllers
|
||||
const authController = new AuthController(
|
||||
ServiceRegistry.get(MongoDB.SERVICE_NAME),
|
||||
ServiceRegistry.get(SettingsService.SERVICE_NAME),
|
||||
ServiceRegistry.get(EmailService.SERVICE_NAME),
|
||||
ServiceRegistry.get(JobQueue.SERVICE_NAME),
|
||||
ServiceRegistry.get(StringService.SERVICE_NAME)
|
||||
);
|
||||
const authController = new AuthController({
|
||||
db: ServiceRegistry.get(MongoDB.SERVICE_NAME),
|
||||
settingsService: ServiceRegistry.get(SettingsService.SERVICE_NAME),
|
||||
emailService: ServiceRegistry.get(EmailService.SERVICE_NAME),
|
||||
jobQueue: ServiceRegistry.get(JobQueue.SERVICE_NAME),
|
||||
stringService: ServiceRegistry.get(StringService.SERVICE_NAME),
|
||||
logger: logger,
|
||||
});
|
||||
|
||||
const monitorController = new MonitorController(
|
||||
ServiceRegistry.get(MongoDB.SERVICE_NAME),
|
||||
|
||||
@@ -80,24 +80,28 @@ class EmailService {
|
||||
*/
|
||||
};
|
||||
|
||||
/**
|
||||
* Asynchronously builds and sends an email using a specified template and context.
|
||||
*
|
||||
* @param {string} template - The name of the template to use for the email body.
|
||||
* @param {Object} context - The data context to render the template with.
|
||||
* @param {string} to - The recipient's email address.
|
||||
* @param {string} subject - The subject of the email.
|
||||
* @returns {Promise<string>} A promise that resolves to the messageId of the sent email.
|
||||
*/
|
||||
buildAndSendEmail = async (template, context, to, subject, transportConfig) => {
|
||||
// TODO - Consider an update transporter method so this only needs to be recreated when smtp settings change
|
||||
buildEmail = async (template, context) => {
|
||||
try {
|
||||
const mjml = this.templateLookup[template](context);
|
||||
const html = await this.mjml2html(mjml);
|
||||
return html.html;
|
||||
} catch (error) {
|
||||
this.logger.error({
|
||||
message: error.message,
|
||||
service: SERVICE_NAME,
|
||||
method: "buildEmail",
|
||||
stack: error.stack,
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
sendEmail = async (to, subject, html, transportConfig) => {
|
||||
let config;
|
||||
if (typeof transportConfig !== "undefined") {
|
||||
config = transportConfig;
|
||||
} else {
|
||||
config = await this.settingsService.getDBSettings();
|
||||
}
|
||||
|
||||
const {
|
||||
systemEmailHost,
|
||||
systemEmailPort,
|
||||
@@ -131,45 +135,24 @@ class EmailService {
|
||||
servername: systemEmailTLSServername,
|
||||
},
|
||||
};
|
||||
|
||||
this.transporter = this.nodemailer.createTransport(emailConfig);
|
||||
|
||||
const buildHtml = async (template, context) => {
|
||||
try {
|
||||
const mjml = this.templateLookup[template](context);
|
||||
const html = await this.mjml2html(mjml);
|
||||
return html.html;
|
||||
} catch (error) {
|
||||
this.logger.error({
|
||||
message: error.message,
|
||||
service: SERVICE_NAME,
|
||||
method: "buildAndSendEmail",
|
||||
stack: error.stack,
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const sendEmail = async (to, subject, html) => {
|
||||
try {
|
||||
const info = await this.transporter.sendMail({
|
||||
to: to,
|
||||
from: systemEmailAddress,
|
||||
subject: subject,
|
||||
html: html,
|
||||
});
|
||||
return info;
|
||||
} catch (error) {
|
||||
this.logger.error({
|
||||
message: error.message,
|
||||
service: SERVICE_NAME,
|
||||
method: "sendEmail",
|
||||
stack: error.stack,
|
||||
});
|
||||
}
|
||||
};
|
||||
const html = await buildHtml(template, context);
|
||||
const info = await sendEmail(to, subject, html);
|
||||
return info?.messageId;
|
||||
try {
|
||||
const info = await this.transporter.sendMail({
|
||||
to: to,
|
||||
from: systemEmailAddress,
|
||||
subject: subject,
|
||||
html: html,
|
||||
});
|
||||
return info?.messageId;
|
||||
} catch (error) {
|
||||
this.logger.error({
|
||||
message: error.message,
|
||||
service: SERVICE_NAME,
|
||||
method: "sendEmail",
|
||||
stack: error.stack,
|
||||
});
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -60,30 +60,30 @@ class NetworkService {
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends a ping request to the specified URL and returns the response.
|
||||
*
|
||||
* @param {Object} job - The job object containing the data for the ping request.
|
||||
* @param {Object} job.data - The data object within the job.
|
||||
* @param {string} job.data.url - The URL to ping.
|
||||
* @param {string} job.data._id - The monitor ID for the ping request.
|
||||
* @returns {Promise<Object>} An object containing the ping response details.
|
||||
* @property {string} monitorId - The monitor ID for the ping request.
|
||||
* @property {string} type - The type of request, which is "ping".
|
||||
* @property {number} responseTime - The time taken for the ping request to complete, in milliseconds.
|
||||
* @property {Object} payload - The response payload from the ping request.
|
||||
* @property {boolean} status - The status of the ping request (true if successful, false otherwise).
|
||||
* @property {number} code - The response code (200 if successful, error code otherwise).
|
||||
* @property {string} message - The message indicating the result of the ping request.
|
||||
* Performs a ping check to a specified host to verify its availability.
|
||||
* @async
|
||||
* @param {Object} monitor - The monitor configuration object
|
||||
* @param {string} monitor.url - The host URL to ping
|
||||
* @param {string} monitor._id - The unique identifier of the monitor
|
||||
* @returns {Promise<Object>} A promise that resolves to a ping response object
|
||||
* @returns {string} pingResponse.monitorId - The ID of the monitor
|
||||
* @returns {string} pingResponse.type - The type of monitor (always "ping")
|
||||
* @returns {number} pingResponse.responseTime - The time taken for the ping
|
||||
* @returns {Object} pingResponse.payload - The raw ping response data
|
||||
* @returns {boolean} pingResponse.status - Whether the host is alive (true) or not (false)
|
||||
* @returns {number} pingResponse.code - Status code (200 for success, PING_ERROR for failure)
|
||||
* @returns {string} pingResponse.message - Success or failure message
|
||||
* @throws {Error} If there's an error during the ping operation
|
||||
*/
|
||||
async requestPing(job) {
|
||||
async requestPing(monitor) {
|
||||
try {
|
||||
const url = job.data.url;
|
||||
const url = monitor.url;
|
||||
const { response, responseTime, error } = await this.timeRequest(() =>
|
||||
this.ping.promise.probe(url)
|
||||
);
|
||||
|
||||
const pingResponse = {
|
||||
monitorId: job.data._id,
|
||||
monitorId: monitor._id,
|
||||
type: "ping",
|
||||
responseTime,
|
||||
payload: response,
|
||||
@@ -107,21 +107,29 @@ class NetworkService {
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends an HTTP GET request to the specified URL and returns the response.
|
||||
*
|
||||
* @param {Object} job - The job object containing the data for the HTTP request.
|
||||
* @param {Object} job.data - The data object within the job.
|
||||
* @param {string} job.data.url - The URL to send the HTTP GET request to.
|
||||
* @param {string} job.data._id - The monitor ID for the HTTP request.
|
||||
* @param {string} [job.data.secret] - Secret for authorization if provided.
|
||||
* @returns {Promise<Object>} An object containing the HTTP response details.
|
||||
* @property {string} monitorId - The monitor ID for the HTTP request.
|
||||
* @property {string} type - The type of request, which is "http".
|
||||
* @property {number} responseTime - The time taken for the HTTP request to complete, in milliseconds.
|
||||
* @property {Object} payload - The response payload from the HTTP request.
|
||||
* @property {boolean} status - The status of the HTTP request (true if successful, false otherwise).
|
||||
* @property {number} code - The response code (200 if successful, error code otherwise).
|
||||
* @property {string} message - The message indicating the result of the HTTP request.
|
||||
* Performs an HTTP GET request to a specified URL with optional validation of response data.
|
||||
* @async
|
||||
* @param {Object} monitor - The monitor configuration object
|
||||
* @param {string} monitor.url - The URL to make the HTTP request to
|
||||
* @param {string} [monitor.secret] - Optional Bearer token for authentication
|
||||
* @param {string} monitor._id - The unique identifier of the monitor
|
||||
* @param {string} monitor.name - The name of the monitor
|
||||
* @param {string} monitor.teamId - The team ID associated with the monitor
|
||||
* @param {string} monitor.type - The type of monitor
|
||||
* @param {boolean} [monitor.ignoreTlsErrors] - Whether to ignore TLS certificate errors
|
||||
* @param {string} [monitor.jsonPath] - Optional JMESPath expression to extract data from JSON response
|
||||
* @param {string} [monitor.matchMethod] - Method to match response data ('include', 'regex', or exact match)
|
||||
* @param {string} [monitor.expectedValue] - Expected value to match against response data
|
||||
* @returns {Promise<Object>} A promise that resolves to an HTTP response object
|
||||
* @returns {string} httpResponse.monitorId - The ID of the monitor
|
||||
* @returns {string} httpResponse.teamId - The team ID
|
||||
* @returns {string} httpResponse.type - The type of monitor
|
||||
* @returns {number} httpResponse.responseTime - The time taken for the request
|
||||
* @returns {Object} httpResponse.payload - The response data
|
||||
* @returns {boolean} httpResponse.status - Whether the request was successful and matched expected value (if specified)
|
||||
* @returns {number} httpResponse.code - HTTP status code or NETWORK_ERROR
|
||||
* @returns {string} httpResponse.message - Success or failure message
|
||||
* @throws {Error} If there's an error during the HTTP request or data validation
|
||||
*/
|
||||
async requestHttp(monitor) {
|
||||
try {
|
||||
@@ -231,20 +239,19 @@ class NetworkService {
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends a request to the Google PageSpeed Insights API for the specified URL and returns the response.
|
||||
*
|
||||
* @param {Object} job - The job object containing the data for the PageSpeed request.
|
||||
* @param {Object} job.data - The data object within the job.
|
||||
* @param {string} job.data.url - The URL to analyze with PageSpeed Insights.
|
||||
* @param {string} job.data._id - The monitor ID for the PageSpeed request.
|
||||
* @returns {Promise<Object>} An object containing the PageSpeed response details.
|
||||
* @property {string} monitorId - The monitor ID for the PageSpeed request.
|
||||
* @property {string} type - The type of request, which is "pagespeed".
|
||||
* @property {number} responseTime - The time taken for the PageSpeed request to complete, in milliseconds.
|
||||
* @property {Object} payload - The response payload from the PageSpeed request.
|
||||
* @property {boolean} status - The status of the PageSpeed request (true if successful, false otherwise).
|
||||
* @property {number} code - The response code (200 if successful, error code otherwise).
|
||||
* @property {string} message - The message indicating the result of the PageSpeed request.
|
||||
* Checks the performance of a webpage using Google's PageSpeed Insights API.
|
||||
* @async
|
||||
* @param {Object} monitor - The monitor configuration object
|
||||
* @param {string} monitor.url - The URL of the webpage to analyze
|
||||
* @returns {Promise<Object|undefined>} A promise that resolves to a pagespeed response object or undefined if API key is missing
|
||||
* @returns {string} response.monitorId - The ID of the monitor
|
||||
* @returns {string} response.type - The type of monitor
|
||||
* @returns {number} response.responseTime - The time taken for the analysis
|
||||
* @returns {boolean} response.status - Whether the analysis was successful
|
||||
* @returns {number} response.code - HTTP status code from the PageSpeed API
|
||||
* @returns {string} response.message - Success or failure message
|
||||
* @returns {Object} response.payload - The PageSpeed analysis results
|
||||
* @throws {Error} If there's an error during the PageSpeed analysis
|
||||
*/
|
||||
async requestPagespeed(monitor) {
|
||||
try {
|
||||
@@ -273,23 +280,6 @@ class NetworkService {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends an HTTP request to check hardware status and returns the response.
|
||||
*
|
||||
* @param {Object} job - The job object containing the data for the hardware request.
|
||||
* @param {Object} job.data - The data object within the job.
|
||||
* @param {string} job.data.url - The URL to send the hardware status request to.
|
||||
* @param {string} job.data._id - The monitor ID for the hardware request.
|
||||
* @param {string} job.data.type - The type of request, which is "hardware".
|
||||
* @returns {Promise<Object>} An object containing the hardware status response details.
|
||||
* @property {string} monitorId - The monitor ID for the hardware request.
|
||||
* @property {string} type - The type of request ("hardware").
|
||||
* @property {number} responseTime - The time taken for the request to complete, in milliseconds.
|
||||
* @property {Object} payload - The response payload from the hardware status request.
|
||||
* @property {boolean} status - The status of the request (true if successful, false otherwise).
|
||||
* @property {number} code - The response code (200 if successful, error code otherwise).
|
||||
* @property {string} message - The message indicating the result of the hardware status request.
|
||||
*/
|
||||
async requestHardware(monitor) {
|
||||
try {
|
||||
return await this.requestHttp(monitor);
|
||||
@@ -301,20 +291,20 @@ class NetworkService {
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends a request to inspect a Docker container and returns its status.
|
||||
*
|
||||
* @param {Object} job - The job object containing the data for the Docker request.
|
||||
* @param {Object} job.data - The data object within the job.
|
||||
* @param {string} job.data.url - The container ID or name to inspect.
|
||||
* @param {string} job.data._id - The monitor ID for the Docker request.
|
||||
* @param {string} job.data.type - The type of request, which is "docker".
|
||||
* @returns {Promise<Object>} An object containing the Docker container status details.
|
||||
* @property {string} monitorId - The monitor ID for the Docker request.
|
||||
* @property {string} type - The type of request ("docker").
|
||||
* @property {number} responseTime - The time taken for the Docker inspection to complete, in milliseconds.
|
||||
* @property {boolean} status - The status of the container (true if running, false otherwise).
|
||||
* @property {number} code - The response code (200 if successful, error code otherwise).
|
||||
* @property {string} message - The message indicating the result of the Docker inspection.
|
||||
* Checks the status of a Docker container by its ID.
|
||||
* @async
|
||||
* @param {Object} monitor - The monitor configuration object
|
||||
* @param {string} monitor.url - The Docker container ID to check
|
||||
* @param {string} monitor._id - The unique identifier of the monitor
|
||||
* @param {string} monitor.type - The type of monitor
|
||||
* @returns {Promise<Object>} A promise that resolves to a docker response object
|
||||
* @returns {string} dockerResponse.monitorId - The ID of the monitor
|
||||
* @returns {string} dockerResponse.type - The type of monitor
|
||||
* @returns {number} dockerResponse.responseTime - The time taken for the container inspection
|
||||
* @returns {boolean} dockerResponse.status - Whether the container is running (true) or not (false)
|
||||
* @returns {number} dockerResponse.code - HTTP-like status code (200 for success, NETWORK_ERROR for failure)
|
||||
* @returns {string} dockerResponse.message - Success or failure message
|
||||
* @throws {Error} If the container is not found or if there's an error inspecting the container
|
||||
*/
|
||||
async requestDocker(monitor) {
|
||||
try {
|
||||
@@ -358,6 +348,23 @@ class NetworkService {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Attempts to establish a TCP connection to a specified host and port.
|
||||
* @async
|
||||
* @param {Object} monitor - The monitor configuration object
|
||||
* @param {string} monitor.url - The host URL to connect to
|
||||
* @param {number} monitor.port - The port number to connect to
|
||||
* @param {string} monitor._id - The unique identifier of the monitor
|
||||
* @param {string} monitor.type - The type of monitor
|
||||
* @returns {Promise<Object>} A promise that resolves to a port response object
|
||||
* @returns {string} portResponse.monitorId - The ID of the monitor
|
||||
* @returns {string} portResponse.type - The type of monitor
|
||||
* @returns {number} portResponse.responseTime - The time taken for the connection attempt
|
||||
* @returns {boolean} portResponse.status - Whether the connection was successful
|
||||
* @returns {number} portResponse.code - HTTP-like status code (200 for success, NETWORK_ERROR for failure)
|
||||
* @returns {string} portResponse.message - Success or failure message
|
||||
* @throws {Error} If the connection times out or encounters an error
|
||||
*/
|
||||
async requestPort(monitor) {
|
||||
try {
|
||||
const { url, port } = monitor;
|
||||
|
||||
@@ -95,6 +95,19 @@ class NotificationService {
|
||||
return MESSAGE_FORMATTERS[platform](messageText, chatId);
|
||||
}
|
||||
|
||||
formatHardwareNotificationMessage = (
|
||||
monitor,
|
||||
status,
|
||||
platform,
|
||||
chatId,
|
||||
code,
|
||||
timestamp,
|
||||
alerts
|
||||
) => {
|
||||
const messageText = alerts.map((alert) => alert).join("\n");
|
||||
return MESSAGE_FORMATTERS[platform](messageText, chatId);
|
||||
};
|
||||
|
||||
sendTestWebhookNotification = async (notification) => {
|
||||
const config = notification.config;
|
||||
const response = await this.networkService.requestWebhook(
|
||||
@@ -121,7 +134,7 @@ class NotificationService {
|
||||
* @returns {Promise<boolean>} A promise that resolves to true if the notification was sent successfully, otherwise false.
|
||||
*/
|
||||
|
||||
async sendWebhookNotification(networkResponse, notification) {
|
||||
async sendWebhookNotification(networkResponse, notification, alerts = []) {
|
||||
const { monitor, status, code } = networkResponse;
|
||||
const { webhookUrl, platform, botToken, chatId } = notification.config;
|
||||
|
||||
@@ -152,14 +165,27 @@ class NotificationService {
|
||||
url = `${TELEGRAM_API_BASE_URL}${botToken}/sendMessage`;
|
||||
}
|
||||
|
||||
const message = this.formatNotificationMessage(
|
||||
monitor,
|
||||
status,
|
||||
platform,
|
||||
chatId,
|
||||
code, // Pass the code field directly
|
||||
networkResponse.timestamp
|
||||
);
|
||||
let message;
|
||||
if (monitor.type === "hardware") {
|
||||
message = this.formatHardwareNotificationMessage(
|
||||
monitor,
|
||||
status,
|
||||
platform,
|
||||
chatId,
|
||||
code,
|
||||
networkResponse.timestamp,
|
||||
alerts
|
||||
);
|
||||
} else {
|
||||
message = this.formatNotificationMessage(
|
||||
monitor,
|
||||
status,
|
||||
platform,
|
||||
chatId,
|
||||
code, // Pass the code field directly
|
||||
networkResponse.timestamp
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await this.networkService.requestWebhook(platform, url, message);
|
||||
@@ -192,7 +218,16 @@ class NotificationService {
|
||||
const template = "hardwareIncidentTemplate";
|
||||
const context = { monitor: monitor.name, url: monitor.url, alerts };
|
||||
const subject = `Monitor ${monitor.name} infrastructure alerts`;
|
||||
this.emailService.buildAndSendEmail(template, context, address, subject);
|
||||
const html = await this.emailService.buildEmail(template, context);
|
||||
this.emailService.sendEmail(address, subject, html).catch((error) => {
|
||||
this.logger.warn({
|
||||
message: error.message,
|
||||
service: this.SERVICE_NAME,
|
||||
method: "sendHardwareEmail",
|
||||
stack: error.stack,
|
||||
});
|
||||
});
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -205,17 +240,22 @@ class NotificationService {
|
||||
const subject = this.stringService.testEmailSubject;
|
||||
const context = { testName: "Monitoring System" };
|
||||
|
||||
const messageId = await this.emailService.buildAndSendEmail(
|
||||
"testEmailTemplate",
|
||||
context,
|
||||
to,
|
||||
subject
|
||||
);
|
||||
try {
|
||||
const html = await this.emailService.buildEmail("testEmailTemplate", context);
|
||||
const messageId = await this.emailService.sendEmail(to, subject, html);
|
||||
|
||||
if (messageId) {
|
||||
return true;
|
||||
if (messageId) {
|
||||
return true;
|
||||
}
|
||||
} catch (error) {
|
||||
this.logger.warn({
|
||||
message: error.message,
|
||||
service: this.SERVICE_NAME,
|
||||
method: "sendTestEmail",
|
||||
stack: error.stack,
|
||||
});
|
||||
return false;
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -233,7 +273,17 @@ class NotificationService {
|
||||
const template = prevStatus === false ? "serverIsUpTemplate" : "serverIsDownTemplate";
|
||||
const context = { monitor: monitor.name, url: monitor.url };
|
||||
const subject = `Monitor ${monitor.name} is ${status === true ? "up" : "down"}`;
|
||||
this.emailService.buildAndSendEmail(template, context, address, subject);
|
||||
|
||||
const html = await this.emailService.buildEmail(template, context);
|
||||
this.emailService.sendEmail(address, subject, html).catch((error) => {
|
||||
this.logger.warn({
|
||||
message: error.message,
|
||||
service: this.SERVICE_NAME,
|
||||
method: "sendEmail",
|
||||
stack: error.stack,
|
||||
});
|
||||
});
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -247,19 +297,31 @@ class NotificationService {
|
||||
|
||||
return response;
|
||||
}
|
||||
async sendPagerDutyNotification(networkResponse, notification) {
|
||||
async sendPagerDutyNotification(networkResponse, notification, alerts = []) {
|
||||
const { monitor, status, code } = networkResponse;
|
||||
const { routingKey, platform } = notification.config;
|
||||
|
||||
const message = this.formatNotificationMessage(
|
||||
monitor,
|
||||
status,
|
||||
platform,
|
||||
null,
|
||||
code, // Pass the code field directly
|
||||
networkResponse.timestamp
|
||||
);
|
||||
|
||||
let message;
|
||||
if (monitor.type === "hardware") {
|
||||
message = this.formatHardwareNotificationMessage(
|
||||
monitor,
|
||||
status,
|
||||
platform,
|
||||
null,
|
||||
code,
|
||||
networkResponse.timestamp,
|
||||
alerts
|
||||
);
|
||||
} else {
|
||||
message = this.formatNotificationMessage(
|
||||
monitor,
|
||||
status,
|
||||
platform,
|
||||
null,
|
||||
code, // Pass the code field directly
|
||||
networkResponse.timestamp
|
||||
);
|
||||
}
|
||||
try {
|
||||
const response = await this.networkService.requestPagerDuty({
|
||||
message,
|
||||
@@ -350,9 +412,9 @@ class NotificationService {
|
||||
) ?? false,
|
||||
};
|
||||
|
||||
const notifications = await this.db.getNotificationsByMonitorId(
|
||||
networkResponse.monitorId
|
||||
);
|
||||
const notificationIDs = networkResponse.monitor?.notifications ?? [];
|
||||
const notifications = await this.db.getNotificationsByIds(notificationIDs);
|
||||
|
||||
for (const notification of notifications) {
|
||||
const alertsToSend = [];
|
||||
const alertTypes = ["cpu", "memory", "disk"];
|
||||
@@ -388,7 +450,11 @@ class NotificationService {
|
||||
if (alertsToSend.length === 0) continue; // No alerts to send, we're done
|
||||
|
||||
if (notification.type === "email") {
|
||||
this.sendHardwareEmail(networkResponse, notification.address, alertsToSend);
|
||||
await this.sendHardwareEmail(networkResponse, notification.address, alertsToSend);
|
||||
} else if (notification.type === "webhook") {
|
||||
await this.sendWebhookNotification(networkResponse, notification, alertsToSend);
|
||||
} else if (notification.type === "pager_duty") {
|
||||
await this.sendPagerDutyNotification(networkResponse, notification, alertsToSend);
|
||||
}
|
||||
}
|
||||
return true;
|
||||
|
||||
@@ -28,8 +28,8 @@ class SettingsService {
|
||||
* Constructs a new SettingsService
|
||||
* @constructor
|
||||
* @throws {Error}
|
||||
*/ constructor(appSettings) {
|
||||
this.appSettings = appSettings;
|
||||
*/ constructor(AppSettings) {
|
||||
this.AppSettings = AppSettings;
|
||||
this.settings = { ...envConfig };
|
||||
}
|
||||
/**
|
||||
@@ -60,16 +60,14 @@ class SettingsService {
|
||||
|
||||
async getDBSettings() {
|
||||
// Remove any old settings
|
||||
await this.appSettings.deleteMany({ version: { $exists: false } });
|
||||
await this.AppSettings.deleteMany({ version: { $exists: false } });
|
||||
|
||||
let settings = await this.appSettings
|
||||
.findOne({ singleton: true })
|
||||
let settings = await this.AppSettings.findOne({ singleton: true })
|
||||
.select("-__v -_id -createdAt -updatedAt -singleton")
|
||||
.lean();
|
||||
if (settings === null) {
|
||||
await this.appSettings.create({});
|
||||
settings = await this.appSettings
|
||||
.findOne({ singleton: true })
|
||||
await this.AppSettings.create({});
|
||||
settings = await this.AppSettings.findOne({ singleton: true })
|
||||
.select("-__v -_id -createdAt -updatedAt -singleton")
|
||||
.lean();
|
||||
}
|
||||
|
||||
@@ -29,12 +29,12 @@ const nameValidation = joi
|
||||
.string()
|
||||
.trim()
|
||||
.max(50)
|
||||
.pattern(/^(?=.*[\p{L}\p{Sc}])[\p{L}\p{Sc}\s']+$/u)
|
||||
.pattern(/^(?=.*[\p{L}\p{Sc}])[\p{L}\p{Sc}\s'\-().]+$/u)
|
||||
.messages({
|
||||
"string.empty": "Name is required",
|
||||
"string.max": "Name must be less than 50 characters",
|
||||
"string.pattern.base":
|
||||
"Name must contain at least 1 letter or currency symbol and only allow letters, spaces, apostrophes, and currency symbols",
|
||||
"Names must contain at least 1 letter and may only include letters, currency symbols, spaces, apostrophes, hyphens (-), periods (.), and parentheses ().",
|
||||
});
|
||||
|
||||
const registrationBodyValidation = joi.object({
|
||||
@@ -558,14 +558,6 @@ const triggerNotificationBodyValidation = joi.object({
|
||||
});
|
||||
|
||||
const createNotificationBodyValidation = joi.object({
|
||||
userId: joi.string().required().messages({
|
||||
"number.empty": "User ID is required",
|
||||
"any.required": "User ID is required",
|
||||
}),
|
||||
teamId: joi.string().required().messages({
|
||||
"string.empty": "Team ID is required",
|
||||
"any.required": "Team ID is required",
|
||||
}),
|
||||
notificationName: joi.string().required().messages({
|
||||
"string.empty": "Notification name is required",
|
||||
"any.required": "Notification name is required",
|
||||
|
||||
Reference in new issue
Block a user