Merge branch 'develop' into improve/login-page

This commit is contained in:
karenvicent committed 2025-07-31 16:33:12 -04:00
commit 37a3028540
36 files changed
+743 -1087

No files matched your search

+23
View File
@@ -300,6 +300,28 @@ const useCreateMonitor = () => {
return [createMonitor, isLoading]; return [createMonitor, isLoading];
}; };
const useFetchGlobalSettings = () => {
const [isLoading, setIsLoading] = useState(true);
const [globalSettings, setGlobalSettings] = useState(undefined);
useEffect(() => {
const fetchGlobalSettings = async () => {
try {
const res = await networkService.getAppSettings();
setGlobalSettings(res?.data);
} catch (error) {
console.error("Failed to fetch global settings:", error);
createToast({ body: "Failed to load global settings" });
} finally {
setIsLoading(false);
}
};
fetchGlobalSettings();
}, []);
return [globalSettings, isLoading];
};
const useDeleteMonitor = () => { const useDeleteMonitor = () => {
const [isLoading, setIsLoading] = useState(false); const [isLoading, setIsLoading] = useState(false);
const navigate = useNavigate(); const navigate = useNavigate();
@@ -499,6 +521,7 @@ export {
useFetchUptimeMonitorById, useFetchUptimeMonitorById,
useFetchHardwareMonitorById, useFetchHardwareMonitorById,
useCreateMonitor, useCreateMonitor,
useFetchGlobalSettings,
useDeleteMonitor, useDeleteMonitor,
useUpdateMonitor, useUpdateMonitor,
usePauseMonitor, usePauseMonitor,
@@ -3,7 +3,6 @@ import { useTheme } from "@emotion/react";
import { useParams } from "react-router-dom"; import { useParams } from "react-router-dom";
import { useState, useEffect } from "react"; import { useState, useEffect } from "react";
import { useSelector } from "react-redux"; import { useSelector } from "react-redux";
// Utility and Network // Utility and Network
import { infrastructureMonitorValidation } from "../../../Validation/validation"; import { infrastructureMonitorValidation } from "../../../Validation/validation";
import { useFetchHardwareMonitorById } from "../../../Hooks/monitorHooks"; import { useFetchHardwareMonitorById } from "../../../Hooks/monitorHooks";
@@ -11,7 +10,11 @@ import { capitalizeFirstLetter } from "../../../Utils/stringUtils";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { useGetNotificationsByTeamId } from "../../../Hooks/useNotifications"; import { useGetNotificationsByTeamId } from "../../../Hooks/useNotifications";
import NotificationsConfig from "../../../Components/NotificationConfig"; import NotificationsConfig from "../../../Components/NotificationConfig";
import { useUpdateMonitor, useCreateMonitor } from "../../../Hooks/monitorHooks"; import {
useUpdateMonitor,
useCreateMonitor,
useFetchGlobalSettings,
} from "../../../Hooks/monitorHooks";
// MUI // MUI
import { Box, Stack, Typography, Button, ButtonGroup } from "@mui/material"; import { Box, Stack, Typography, Button, ButtonGroup } from "@mui/material";
@@ -65,6 +68,7 @@ const CreateInfrastructureMonitor = () => {
useGetNotificationsByTeamId(); useGetNotificationsByTeamId();
const [updateMonitor, isUpdating] = useUpdateMonitor(); const [updateMonitor, isUpdating] = useUpdateMonitor();
const [createMonitor, isCreating] = useCreateMonitor(); const [createMonitor, isCreating] = useCreateMonitor();
const [globalSettings, globalSettingsLoading] = useFetchGlobalSettings();
// State // State
const [errors, setErrors] = useState({}); const [errors, setErrors] = useState({});
@@ -87,35 +91,64 @@ const CreateInfrastructureMonitor = () => {
}); });
// Populate form fields if editing // Populate form fields if editing
useEffect(() => { useEffect(() => {
if (isCreate || !monitor) return; if (isCreate) {
if (globalSettingsLoading) return;
const gt = globalSettings?.data?.settings?.globalThresholds || {};
setHttps(false);
setInfrastructureMonitor({
url: "",
name: "",
notifications: [],
interval: 0.25,
cpu: gt.cpu !== undefined,
usage_cpu: gt.cpu !== undefined ? gt.cpu.toString() : "",
memory: gt.memory !== undefined,
usage_memory: gt.memory !== undefined ? gt.memory.toString() : "",
disk: gt.disk !== undefined,
usage_disk: gt.disk !== undefined ? gt.disk.toString() : "",
temperature: gt.temperature !== undefined,
usage_temperature: gt.temperature !== undefined ? gt.temperature.toString() : "",
secret: "",
});
} else if (monitor) {
const { thresholds = {} } = monitor;
setHttps(monitor.url.startsWith("https"));
setInfrastructureMonitor({ setInfrastructureMonitor({
url: monitor.url.replace(/^https?:\/\//, ""), url: monitor.url.replace(/^https?:\/\//, ""),
name: monitor.name || "", name: monitor.name || "",
notifications: monitor.notifications, notifications: monitor.notifications || [],
interval: monitor.interval / MS_PER_MINUTE, interval: monitor.interval / MS_PER_MINUTE,
cpu: monitor.thresholds?.usage_cpu !== undefined, cpu: thresholds.usage_cpu !== undefined,
usage_cpu: monitor.thresholds?.usage_cpu ? monitor.thresholds.usage_cpu * 100 : "", usage_cpu:
thresholds.usage_cpu !== undefined
memory: monitor.thresholds?.usage_memory !== undefined, ? (thresholds.usage_cpu * 100).toString()
usage_memory: monitor.thresholds?.usage_memory
? monitor.thresholds.usage_memory * 100
: "", : "",
memory: thresholds.usage_memory !== undefined,
disk: monitor.thresholds?.usage_disk !== undefined, usage_memory:
usage_disk: monitor.thresholds?.usage_disk thresholds.usage_memory !== undefined
? monitor.thresholds.usage_disk * 100 ? (thresholds.usage_memory * 100).toString()
: "", : "",
disk: thresholds.usage_disk !== undefined,
temperature: monitor.thresholds?.usage_temperature !== undefined, usage_disk:
usage_temperature: monitor.thresholds?.usage_temperature thresholds.usage_disk !== undefined
? monitor.thresholds.usage_temperature * 100 ? (thresholds.usage_disk * 100).toString()
: "",
temperature: thresholds.usage_temperature !== undefined,
usage_temperature:
thresholds.usage_temperature !== undefined
? (thresholds.usage_temperature * 100).toString()
: "", : "",
secret: monitor.secret || "", secret: monitor.secret || "",
}); });
setHttps(monitor.url.startsWith("https")); }
}, [isCreate, monitor]); }, [isCreate, monitor, globalSettings, globalSettingsLoading]);
// Handlers // Handlers
const onSubmit = async (event) => { const onSubmit = async (event) => {
@@ -0,0 +1,95 @@
import Box from "@mui/material/Box";
import Stack from "@mui/material/Stack";
import Typography from "@mui/material/Typography";
import ConfigBox from "../../Components/ConfigBox";
import TextInput from "../../Components/Inputs/TextInput";
import { useTheme } from "@emotion/react";
import { PropTypes } from "prop-types";
import { useTranslation } from "react-i18next";
const SettingsGlobalThresholds = ({
isAdmin,
HEADING_SX,
settingsData,
setSettingsData,
}) => {
const { t } = useTranslation(); // For language translation
const theme = useTheme(); // MUI theme access
// Handles input change and updates parent state
const handleChange = (e, min, max) => {
const { name, value } = e.target;
const numValue = parseFloat(value);
const isValidNumber =
value === "" ||
(!isNaN(numValue) && isFinite(numValue) && numValue >= min && numValue <= max);
if (isValidNumber) {
setSettingsData((prev) => ({
...prev,
settings: {
...prev.settings,
globalThresholds: {
...prev.settings?.globalThresholds,
[name]: value,
},
},
}));
}
};
// Only render this section for admins
if (!isAdmin) return null;
return (
<ConfigBox>
{/* Header and description */}
<Box>
<Typography
component="h1"
variant="h2"
>
{t("settingsPage.globalThresholds.title", "Global Thresholds")}
</Typography>
<Typography sx={HEADING_SX}>
{t(
"settingsPage.globalThresholds.description",
"Configure global CPU, Memory, Disk, and Temperature thresholds."
)}
</Typography>
</Box>
{/* Threshold inputs */}
<Stack gap={theme.spacing(20)}>
{[
["CPU Threshold (%)", "cpu", 1, 100],
["Memory Threshold (%)", "memory", 1, 100],
["Disk Threshold (%)", "disk", 1, 100],
["Temperature Threshold (°C)", "temperature", 1, 150],
].map(([label, name, min, max]) => (
<TextInput
key={name}
name={name}
label={label}
placeholder={`${min} - ${max}`}
type="number"
value={settingsData?.settings?.globalThresholds?.[name] || ""}
onChange={(e) => handleChange(e, min, max)}
/>
))}
</Stack>
</ConfigBox>
);
};
// Prop types
SettingsGlobalThresholds.propTypes = {
isAdmin: PropTypes.bool,
HEADING_SX: PropTypes.object,
settingsData: PropTypes.object,
setSettingsData: PropTypes.func,
};
export default SettingsGlobalThresholds;
+10
View File
@@ -8,6 +8,7 @@ import SettingsPagespeed from "./SettingsPagespeed";
import SettingsDemoMonitors from "./SettingsDemoMonitors"; import SettingsDemoMonitors from "./SettingsDemoMonitors";
import SettingsAbout from "./SettingsAbout"; import SettingsAbout from "./SettingsAbout";
import SettingsEmail from "./SettingsEmail"; import SettingsEmail from "./SettingsEmail";
import SettingsGlobalThresholds from "./SettingsGlobalThresholds";
import Button from "@mui/material/Button"; import Button from "@mui/material/Button";
// Utils // Utils
import { settingsValidation } from "../../Validation/validation"; import { settingsValidation } from "../../Validation/validation";
@@ -48,6 +49,7 @@ const Settings = () => {
setIsApiKeySet, setIsApiKeySet,
setIsEmailPasswordSet, setIsEmailPasswordSet,
}); });
const [addDemoMonitors, isAddingDemoMonitors] = useAddDemoMonitors(); const [addDemoMonitors, isAddingDemoMonitors] = useAddDemoMonitors();
const [isSaving, saveError, saveSettings] = useSaveSettings({ const [isSaving, saveError, saveSettings] = useSaveSettings({
@@ -149,6 +151,7 @@ const Settings = () => {
error.details.forEach((err) => { error.details.forEach((err) => {
newErrors[err.path[0]] = err.message; newErrors[err.path[0]] = err.message;
}); });
setErrors(newErrors); setErrors(newErrors);
} }
saveSettings(settingsData?.settings); saveSettings(settingsData?.settings);
@@ -190,6 +193,13 @@ const Settings = () => {
handleChange={handleChange} handleChange={handleChange}
errors={errors} errors={errors}
/> />
<SettingsGlobalThresholds
isAdmin={isAdmin}
HEADING_SX={HEADING_SX}
settingsData={settingsData}
setSettingsData={setSettingsData}
/>
<SettingsDemoMonitors <SettingsDemoMonitors
isAdmin={isAdmin} isAdmin={isAdmin}
HEADER_SX={HEADING_SX} HEADER_SX={HEADING_SX}
+8
View File
@@ -302,6 +302,14 @@ const settingsValidation = joi.object({
systemEmailIgnoreTLS: joi.boolean(), systemEmailIgnoreTLS: joi.boolean(),
systemEmailRequireTLS: joi.boolean(), systemEmailRequireTLS: joi.boolean(),
systemEmailRejectUnauthorized: joi.boolean(), systemEmailRejectUnauthorized: joi.boolean(),
globalThresholds: joi
.object({
cpu: joi.number().min(1).max(100).allow("").optional(),
memory: joi.number().min(1).max(100).allow("").optional(),
disk: joi.number().min(1).max(100).allow("").optional(),
temperature: joi.number().min(1).max(150).allow("").optional(),
})
.optional(),
}); });
const dayjsValidator = (value, helpers) => { const dayjsValidator = (value, helpers) => {
+4
View File
@@ -874,6 +874,10 @@
"title": "Display timezone" "title": "Display timezone"
}, },
"title": "Settings", "title": "Settings",
"globalThresholds": {
"title": "Global Thresholds",
"description": "Configure global CPU, Memory, Disk, and Temperature thresholds. If a value is provided, it will automatically be enabled for monitoring."
},
"uiSettings": { "uiSettings": {
"description": "Switch between light and dark mode, or change user interface language.", "description": "Switch between light and dark mode, or change user interface language.",
"labelLanguage": "Language", "labelLanguage": "Language",
+70 -1
View File
@@ -32,14 +32,42 @@ import mjml2html from "mjml";
import jwt from "jsonwebtoken"; import jwt from "jsonwebtoken";
import crypto from "crypto"; import crypto from "crypto";
import { fileURLToPath } from "url";
import { ObjectId } from "mongodb";
// DB Modules // DB Modules
import { NormalizeData, NormalizeDataUptimeDetails } from "../utils/dataUtils.js";
import { GenerateAvatarImage } from "../utils/imageProcessing.js";
import { ParseBoolean } from "../utils/utils.js";
// Models
import Check from "../db/models/Check.js"; import Check from "../db/models/Check.js";
import HardwareCheck from "../db/models/HardwareCheck.js"; import HardwareCheck from "../db/models/HardwareCheck.js";
import PageSpeedCheck from "../db/models/PageSpeedCheck.js"; import PageSpeedCheck from "../db/models/PageSpeedCheck.js";
import Monitor from "../db/models/Monitor.js"; import Monitor from "../db/models/Monitor.js";
import User from "../db/models/User.js"; import User from "../db/models/User.js";
import InviteToken from "../db/models/InviteToken.js";
import StatusPage from "../db/models/StatusPage.js";
import Team from "../db/models/Team.js";
import MaintenanceWindow from "../db/models/MaintenanceWindow.js";
import MonitorStats from "../db/models/MonitorStats.js";
import NetworkCheck from "../db/models/NetworkCheck.js";
import Notification from "../db/models/Notification.js";
import RecoveryToken from "../db/models/RecoveryToken.js";
import AppSettings from "../db/models/AppSettings.js";
import InviteModule from "../db/mongo/modules/inviteModule.js";
import CheckModule from "../db/mongo/modules/checkModule.js"; import CheckModule from "../db/mongo/modules/checkModule.js";
import StatusPageModule from "../db/mongo/modules/statusPageModule.js";
import UserModule from "../db/mongo/modules/userModule.js";
import HardwareCheckModule from "../db/mongo/modules/hardwareCheckModule.js";
import MaintenanceWindowModule from "../db/mongo/modules/maintenanceWindowModule.js";
import MonitorModule from "../db/mongo/modules/monitorModule.js";
import NetworkCheckModule from "../db/mongo/modules/networkCheckModule.js";
import NotificationModule from "../db/mongo/modules/notificationModule.js";
import PageSpeedCheckModule from "../db/mongo/modules/pageSpeedCheckModule.js";
import RecoveryModule from "../db/mongo/modules/recoveryModule.js";
import SettingsModule from "../db/mongo/modules/settingsModule.js";
export const initializeServices = async ({ logger, envSettings, settingsService }) => { export const initializeServices = async ({ logger, envSettings, settingsService }) => {
const serviceRegistry = new ServiceRegistry({ logger }); const serviceRegistry = new ServiceRegistry({ logger });
@@ -52,7 +80,48 @@ export const initializeServices = async ({ logger, envSettings, settingsService
// Create DB // Create DB
const checkModule = new CheckModule({ logger, Check, HardwareCheck, PageSpeedCheck, Monitor, User }); const checkModule = new CheckModule({ logger, Check, HardwareCheck, PageSpeedCheck, Monitor, User });
const db = new MongoDB({ logger, envSettings, checkModule }); const inviteModule = new InviteModule({ InviteToken, crypto, stringService });
const statusPageModule = new StatusPageModule({ StatusPage, NormalizeData, stringService });
const userModule = new UserModule({ User, Team, GenerateAvatarImage, ParseBoolean, stringService });
const hardwareCheckModule = new HardwareCheckModule({ HardwareCheck, Monitor, logger });
const maintenanceWindowModule = new MaintenanceWindowModule({ MaintenanceWindow });
const monitorModule = new MonitorModule({
Monitor,
MonitorStats,
Check,
PageSpeedCheck,
HardwareCheck,
stringService,
fs,
path,
fileURLToPath,
ObjectId,
NormalizeData,
NormalizeDataUptimeDetails,
});
const networkCheckModule = new NetworkCheckModule({ NetworkCheck });
const notificationModule = new NotificationModule({ Notification, Monitor });
const pageSpeedCheckModule = new PageSpeedCheckModule({ PageSpeedCheck });
const recoveryModule = new RecoveryModule({ User, RecoveryToken, crypto, stringService });
const settingsModule = new SettingsModule({ AppSettings });
const db = new MongoDB({
logger,
envSettings,
checkModule,
inviteModule,
statusPageModule,
userModule,
hardwareCheckModule,
maintenanceWindowModule,
monitorModule,
networkCheckModule,
notificationModule,
pageSpeedCheckModule,
recoveryModule,
settingsModule,
});
await db.connect(); await db.connect();
const networkService = new NetworkService(axios, ping, logger, http, Docker, net, stringService, settingsService); const networkService = new NetworkService(axios, ping, logger, http, Docker, net, stringService, settingsService);
+2 -2
View File
@@ -32,7 +32,7 @@ class MonitorController extends BaseController {
} }
async verifyTeamAccess(teamId, monitorId) { async verifyTeamAccess(teamId, monitorId) {
const monitor = await this.db.getMonitorById(monitorId); const monitor = await this.db.monitorModule.getMonitorById(monitorId);
if (!monitor.teamId.equals(teamId)) { if (!monitor.teamId.equals(teamId)) {
throw this.errorService.createAuthorizationError(); throw this.errorService.createAuthorizationError();
} }
@@ -150,7 +150,7 @@ class MonitorController extends BaseController {
await getCertificateParamValidation.validateAsync(req.params); await getCertificateParamValidation.validateAsync(req.params);
const { monitorId } = req.params; const { monitorId } = req.params;
const monitor = await this.db.getMonitorById(monitorId); const monitor = await this.db.monitorModule.getMonitorById(monitorId);
const certificate = await fetchMonitorCertificate(sslChecker, monitor); const certificate = await fetchMonitorCertificate(sslChecker, monitor);
return res.success({ return res.success({
@@ -53,7 +53,7 @@ class NotificationController extends BaseController {
body.userId = userId; body.userId = userId;
body.teamId = teamId; body.teamId = teamId;
const notification = await this.db.createNotification(body); const notification = await this.db.notificationModule.createNotification(body);
return res.success({ return res.success({
msg: "Notification created successfully", msg: "Notification created successfully",
data: notification, data: notification,
@@ -70,7 +70,7 @@ class NotificationController extends BaseController {
throw this.errorService.createBadRequestError("Team ID is required"); throw this.errorService.createBadRequestError("Team ID is required");
} }
const notifications = await this.db.getNotificationsByTeamId(teamId); const notifications = await this.db.notificationModule.getNotificationsByTeamId(teamId);
return res.success({ return res.success({
msg: "Notifications fetched successfully", msg: "Notifications fetched successfully",
@@ -88,12 +88,12 @@ class NotificationController extends BaseController {
throw this.errorService.createBadRequestError("Team ID is required"); throw this.errorService.createBadRequestError("Team ID is required");
} }
const notification = await this.db.getNotificationById(req.params.id); const notification = await this.db.notificationModule.getNotificationById(req.params.id);
if (!notification.teamId.equals(teamId)) { if (!notification.teamId.equals(teamId)) {
throw this.errorService.createAuthorizationError(); throw this.errorService.createAuthorizationError();
} }
await this.db.deleteNotificationById(req.params.id); await this.db.notificationModule.deleteNotificationById(req.params.id);
return res.success({ return res.success({
msg: "Notification deleted successfully", msg: "Notification deleted successfully",
}); });
@@ -104,7 +104,7 @@ class NotificationController extends BaseController {
getNotificationById = this.asyncHandler( getNotificationById = this.asyncHandler(
async (req, res) => { async (req, res) => {
const notification = await this.db.getNotificationById(req.params.id); const notification = await this.db.notificationModule.getNotificationById(req.params.id);
const teamId = req?.user?.teamId; const teamId = req?.user?.teamId;
if (!teamId) { if (!teamId) {
@@ -134,13 +134,13 @@ class NotificationController extends BaseController {
throw this.errorService.createBadRequestError("Team ID is required"); throw this.errorService.createBadRequestError("Team ID is required");
} }
const notification = await this.db.getNotificationById(req.params.id); const notification = await this.db.notificationModule.getNotificationById(req.params.id);
if (!notification.teamId.equals(teamId)) { if (!notification.teamId.equals(teamId)) {
throw this.errorService.createAuthorizationError(); throw this.errorService.createAuthorizationError();
} }
const editedNotification = await this.db.editNotification(req.params.id, req.body); const editedNotification = await this.db.notificationModule.editNotification(req.params.id, req.body);
return res.success({ return res.success({
msg: "Notification updated successfully", msg: "Notification updated successfully",
data: editedNotification, data: editedNotification,
@@ -158,7 +158,7 @@ class NotificationController extends BaseController {
throw this.errorService.createBadRequestError("Team ID is required"); throw this.errorService.createBadRequestError("Team ID is required");
} }
const monitor = await this.db.getMonitorById(monitorId); const monitor = await this.db.monitorModule.getMonitorById(monitorId);
if (!monitor.teamId.equals(teamId)) { if (!monitor.teamId.equals(teamId)) {
throw this.errorService.createAuthorizationError(); throw this.errorService.createAuthorizationError();
+1 -1
View File
@@ -55,7 +55,7 @@ class SettingsController extends BaseController {
async (req, res) => { async (req, res) => {
await updateAppSettingsBodyValidation.validateAsync(req.body); await updateAppSettingsBodyValidation.validateAsync(req.body);
const updatedSettings = await this.db.updateAppSettings(req.body); const updatedSettings = await this.db.settingsModule.updateAppSettings(req.body);
const returnSettings = this.buildAppSettings(updatedSettings); const returnSettings = this.buildAppSettings(updatedSettings);
return res.success({ return res.success({
msg: this.stringService.updateAppSettings, msg: this.stringService.updateAppSettings,
@@ -19,7 +19,7 @@ class StatusPageController extends BaseController {
await imageValidation.validateAsync(req.file); await imageValidation.validateAsync(req.file);
const { _id, teamId } = req.user; const { _id, teamId } = req.user;
const statusPage = await this.db.createStatusPage({ const statusPage = await this.db.statusPageModule.createStatusPage({
statusPageData: req.body, statusPageData: req.body,
image: req.file, image: req.file,
userId: _id, userId: _id,
@@ -39,7 +39,7 @@ class StatusPageController extends BaseController {
await createStatusPageBodyValidation.validateAsync(req.body); await createStatusPageBodyValidation.validateAsync(req.body);
await imageValidation.validateAsync(req.file); await imageValidation.validateAsync(req.file);
const statusPage = await this.db.updateStatusPage(req.body, req.file); const statusPage = await this.db.statusPageModule.updateStatusPage(req.body, req.file);
if (statusPage === null) { if (statusPage === null) {
throw this.errorService.createNotFoundError(this.stringService.statusPageNotFound); throw this.errorService.createNotFoundError(this.stringService.statusPageNotFound);
} }
@@ -54,7 +54,7 @@ class StatusPageController extends BaseController {
getStatusPage = this.asyncHandler( getStatusPage = this.asyncHandler(
async (req, res) => { async (req, res) => {
const statusPage = await this.db.getStatusPage(); const statusPage = await this.db.statusPageModule.getStatusPage();
return res.success({ return res.success({
msg: this.stringService.statusPageByUrl, msg: this.stringService.statusPageByUrl,
data: statusPage, data: statusPage,
@@ -69,7 +69,7 @@ class StatusPageController extends BaseController {
await getStatusPageParamValidation.validateAsync(req.params); await getStatusPageParamValidation.validateAsync(req.params);
await getStatusPageQueryValidation.validateAsync(req.query); await getStatusPageQueryValidation.validateAsync(req.query);
const statusPage = await this.db.getStatusPageByUrl(req.params.url, req.query.type); const statusPage = await this.db.statusPageModule.getStatusPageByUrl(req.params.url);
return res.success({ return res.success({
msg: this.stringService.statusPageByUrl, msg: this.stringService.statusPageByUrl,
data: statusPage, data: statusPage,
@@ -82,7 +82,7 @@ class StatusPageController extends BaseController {
getStatusPagesByTeamId = this.asyncHandler( getStatusPagesByTeamId = this.asyncHandler(
async (req, res) => { async (req, res) => {
const teamId = req.user.teamId; const teamId = req.user.teamId;
const statusPages = await this.db.getStatusPagesByTeamId(teamId); const statusPages = await this.db.statusPageModule.getStatusPagesByTeamId(teamId);
return res.success({ return res.success({
msg: this.stringService.statusPageByTeamId, msg: this.stringService.statusPageByTeamId,
+6
View File
@@ -65,6 +65,12 @@ const AppSettingsSchema = mongoose.Schema(
type: Number, type: Number,
default: 1, default: 1,
}, },
globalThresholds: {
cpu: { type: Number },
memory: { type: Number },
disk: { type: Number },
temperature: { type: Number },
},
}, },
{ {
timestamps: true, timestamps: true,
+27 -77
View File
@@ -1,89 +1,39 @@
import mongoose from "mongoose"; import mongoose from "mongoose";
import AppSettings from "../models/AppSettings.js"; import AppSettings from "../models/AppSettings.js";
//****************************************
// User Operations
//****************************************
import * as userModule from "./modules/userModule.js";
//****************************************
// Invite Token Operations
//****************************************
import * as inviteModule from "./modules/inviteModule.js";
//****************************************
// Recovery Operations
//****************************************
import * as recoveryModule from "./modules/recoveryModule.js";
//****************************************
// Monitors
//****************************************
import * as monitorModule from "./modules/monitorModule.js";
//****************************************
// Page Speed Checks
//****************************************
import * as pageSpeedCheckModule from "./modules/pageSpeedCheckModule.js";
//****************************************
// Hardware Checks
//****************************************
import * as hardwareCheckModule from "./modules/hardwareCheckModule.js";
//****************************************
// Checks
//****************************************
import * as checkModule from "./modules/checkModule.js";
//****************************************
// Maintenance Window
//****************************************
import * as maintenanceWindowModule from "./modules/maintenanceWindowModule.js";
//****************************************
// Notifications
//****************************************
import * as notificationModule from "./modules/notificationModule.js";
//****************************************
// AppSettings
//****************************************
import * as settingsModule from "./modules/settingsModule.js";
//****************************************
// Status Page
//****************************************
import * as statusPageModule from "./modules/statusPageModule.js";
//****************************************
// Diagnostic
//****************************************
import * as diagnosticModule from "./modules/diagnosticModule.js";
class MongoDB { class MongoDB {
static SERVICE_NAME = "MongoDB"; static SERVICE_NAME = "MongoDB";
constructor({ logger, envSettings, checkModule }) { constructor({
logger,
envSettings,
checkModule,
inviteModule,
statusPageModule,
userModule,
hardwareCheckModule,
maintenanceWindowModule,
monitorModule,
networkCheckModule,
notificationModule,
pageSpeedCheckModule,
recoveryModule,
settingsModule,
}) {
this.logger = logger; this.logger = logger;
this.envSettings = envSettings; this.envSettings = envSettings;
Object.assign(this, userModule); this.userModule = userModule;
Object.assign(this, inviteModule); this.inviteModule = inviteModule;
Object.assign(this, recoveryModule); this.recoveryModule = recoveryModule;
Object.assign(this, monitorModule); this.pageSpeedCheckModule = pageSpeedCheckModule;
Object.assign(this, pageSpeedCheckModule); this.hardwareCheckModule = hardwareCheckModule;
Object.assign(this, hardwareCheckModule);
this.checkModule = checkModule; this.checkModule = checkModule;
Object.assign(this, maintenanceWindowModule); this.maintenanceWindowModule = maintenanceWindowModule;
Object.assign(this, notificationModule); this.monitorModule = monitorModule;
Object.assign(this, settingsModule); this.notificationModule = notificationModule;
Object.assign(this, statusPageModule); this.settingsModule = settingsModule;
Object.assign(this, diagnosticModule); this.statusPageModule = statusPageModule;
this.networkCheckModule = networkCheckModule;
} }
get serviceName() { get serviceName() {
@@ -1,48 +0,0 @@
import Monitor from "../../models/Monitor.js";
import { ObjectId } from "mongodb";
const SERVICE_NAME = "diagnosticModule";
import { buildMonitorSummaryByTeamIdPipeline, buildMonitorsByTeamIdPipeline, buildFilteredMonitorsByTeamIdPipeline } from "./monitorModuleQueries.js";
const getMonitorsByTeamIdExecutionStats = async (req) => {
try {
let { limit, type, page, rowsPerPage, filter, field, order } = req.query;
limit = parseInt(limit);
page = parseInt(page);
rowsPerPage = parseInt(rowsPerPage);
if (field === undefined) {
field = "name";
order = "asc";
}
// Build match stage
const matchStage = { teamId: new ObjectId(req.params.teamId) };
if (type !== undefined) {
matchStage.type = Array.isArray(type) ? { $in: type } : type;
}
const summary = await Monitor.aggregate(buildMonitorSummaryByTeamIdPipeline({ matchStage })).explain("executionStats");
const monitors = await Monitor.aggregate(buildMonitorsByTeamIdPipeline({ matchStage, field, order })).explain("executionStats");
const filteredMonitors = await Monitor.aggregate(
buildFilteredMonitorsByTeamIdPipeline({
matchStage,
filter,
page,
rowsPerPage,
field,
order,
limit,
type,
})
).explain("executionStats");
return { summary, monitors, filteredMonitors };
} catch (error) {
error.service = SERVICE_NAME;
error.method = "getMonitorSummaryByTeamIdExecutionStats";
throw error;
}
};
export { getMonitorsByTeamIdExecutionStats };
@@ -1,53 +1,15 @@
import HardwareCheck from "../../models/HardwareCheck.js";
import Monitor from "../../models/Monitor.js";
import { logger } from "../../../utils/logger.js";
const SERVICE_NAME = "hardwareCheckModule"; const SERVICE_NAME = "hardwareCheckModule";
const createHardwareCheck = async (hardwareCheckData) => {
class HardwareCheckModule {
constructor({ HardwareCheck, Monitor, logger }) {
this.HardwareCheck = HardwareCheck;
this.Monitor = Monitor;
this.logger = logger;
}
createHardwareChecks = async (hardwareChecks) => {
try { try {
const { monitorId, status } = hardwareCheckData; await this.HardwareCheck.insertMany(hardwareChecks, { ordered: false });
const n = (await HardwareCheck.countDocuments({ monitorId })) + 1;
const monitor = await Monitor.findById(monitorId);
if (!monitor) {
logger.error({
message: "Monitor not found",
service: SERVICE_NAME,
method: "createHardwareCheck",
details: `monitor ID: ${monitorId}`,
});
return null;
}
let newUptimePercentage;
if (monitor.uptimePercentage === undefined) {
newUptimePercentage = status === true ? 1 : 0;
} else {
newUptimePercentage = (monitor.uptimePercentage * (n - 1) + (status === true ? 1 : 0)) / n;
}
await Monitor.findOneAndUpdate({ _id: monitorId }, { uptimePercentage: newUptimePercentage });
const hardwareCheck = await new HardwareCheck({
...hardwareCheckData,
}).save();
return hardwareCheck;
} catch (error) {
logger.error({
message: "Error creating hardware check",
service: SERVICE_NAME,
method: "createHardwareCheck",
stack: error.stack,
});
error.service = SERVICE_NAME;
error.method = "createHardwareCheck";
throw error;
}
};
const createHardwareChecks = async (hardwareChecks) => {
try {
await HardwareCheck.insertMany(hardwareChecks, { ordered: false });
return true; return true;
} catch (error) { } catch (error) {
error.service = SERVICE_NAME; error.service = SERVICE_NAME;
@@ -55,16 +17,6 @@ const createHardwareChecks = async (hardwareChecks) => {
throw error; throw error;
} }
}; };
const deleteHardwareChecksByMonitorId = async (monitorId) => {
try {
const result = await HardwareCheck.deleteMany({ monitorId });
return result.deletedCount;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "deleteHardwareChecksByMonitorId";
throw error;
} }
};
export { createHardwareCheck, createHardwareChecks, deleteHardwareChecksByMonitorId }; export default HardwareCheckModule;
+20 -53
View File
@@ -1,28 +1,17 @@
import InviteToken from "../../models/InviteToken.js";
import crypto from "crypto";
import ServiceRegistry from "../../../service/system/serviceRegistry.js";
import StringService from "../../../service/system/stringService.js";
const SERVICE_NAME = "inviteModule"; const SERVICE_NAME = "inviteModule";
/**
* Request an invite token for a user. class InviteModule {
* constructor({ InviteToken, crypto, stringService }) {
* This function deletes any existing invite tokens for the user's email, this.InviteToken = InviteToken;
* generates a new token, saves it, and then returns the new token. this.crypto = crypto;
* this.stringService = stringService;
* @param {Object} userData - The user data. }
* @param {string} userData.email - The user's email.
* @param {mongoose.Schema.Types.ObjectId} userData.teamId - The ID of the team. requestInviteToken = async (userData) => {
* @param {Array} userData.role - The user's role(s).
* @param {Date} [userData.expiry=Date.now] - The expiry date of the token. Defaults to the current date and time.
* @returns {Promise<InviteToken>} The invite token.
* @throws {Error} If there is an error.
*/
const requestInviteToken = async (userData) => {
try { try {
await InviteToken.deleteMany({ email: userData.email }); await this.InviteToken.deleteMany({ email: userData.email });
userData.token = crypto.randomBytes(32).toString("hex"); userData.token = this.crypto.randomBytes(32).toString("hex");
let inviteToken = new InviteToken(userData); let inviteToken = new this.InviteToken(userData);
await inviteToken.save(); await inviteToken.save();
return inviteToken; return inviteToken;
} catch (error) { } catch (error) {
@@ -32,24 +21,13 @@ const requestInviteToken = async (userData) => {
} }
}; };
/** getInviteToken = async (token) => {
* Retrieves an invite token
*
* This function searches for an invite token in the database and deletes it.
* If the invite token is not found, it throws an error.
*
* @param {string} token - The invite token to search for.
* @returns {Promise<InviteToken>} The invite token data.
* @throws {Error} If the invite token is not found or there is another error.
*/
const getInviteToken = async (token) => {
const stringService = ServiceRegistry.get(StringService.SERVICE_NAME);
try { try {
const invite = await InviteToken.findOne({ const invite = await this.InviteToken.findOne({
token, token,
}); });
if (invite === null) { if (invite === null) {
throw new Error(stringService.authInviteNotFound); throw new Error(this.stringService.authInviteNotFound);
} }
return invite; return invite;
} catch (error) { } catch (error) {
@@ -58,25 +36,13 @@ const getInviteToken = async (token) => {
throw error; throw error;
} }
}; };
getInviteTokenAndDelete = async (token) => {
/**
* Retrieves and deletes an invite token
*
* This function searches for an invite token in the database and deletes it.
* If the invite token is not found, it throws an error.
*
* @param {string} token - The invite token to search for.
* @returns {Promise<InviteToken>} The invite token data.
* @throws {Error} If the invite token is not found or there is another error.
*/
const getInviteTokenAndDelete = async (token) => {
const stringService = ServiceRegistry.get(StringService.SERVICE_NAME);
try { try {
const invite = await InviteToken.findOneAndDelete({ const invite = await this.InviteToken.findOneAndDelete({
token, token,
}); });
if (invite === null) { if (invite === null) {
throw new Error(stringService.authInviteNotFound); throw new Error(this.stringService.authInviteNotFound);
} }
return invite; return invite;
} catch (error) { } catch (error) {
@@ -85,5 +51,6 @@ const getInviteTokenAndDelete = async (token) => {
throw error; throw error;
} }
}; };
}
export { requestInviteToken, getInviteToken, getInviteTokenAndDelete }; export default InviteModule;
@@ -1,23 +1,12 @@
import MaintenanceWindow from "../../models/MaintenanceWindow.js";
const SERVICE_NAME = "maintenanceWindowModule"; const SERVICE_NAME = "maintenanceWindowModule";
/** class MaintenanceWindowModule {
* Asynchronously creates a new MaintenanceWindow document and saves it to the database. constructor({ MaintenanceWindow }) {
* If the maintenance window is a one-time event, the expiry field is set to the same value as the end field. this.MaintenanceWindow = MaintenanceWindow;
* @async }
* @function createMaintenanceWindow createMaintenanceWindow = async (maintenanceWindowData) => {
* @param {Object} maintenanceWindowData - The data for the new MaintenanceWindow document.
* @param {mongoose.Schema.Types.ObjectId} maintenanceWindowData.monitorId - The ID of the monitor.
* @param {Boolean} maintenanceWindowData.active - Indicates whether the maintenance window is active.
* @param {Boolean} maintenanceWindowData.oneTime - Indicates whether the maintenance window is a one-time event.
* @param {Date} maintenanceWindowData.start - The start date and time of the maintenance window.
* @param {Date} maintenanceWindowData.end - The end date and time of the maintenance window.
* @returns {Promise<MaintenanceWindow>} The saved MaintenanceWindow document.
* @throws {Error} If there is an error saving the document.
*/
const createMaintenanceWindow = async (maintenanceWindowData) => {
try { try {
const maintenanceWindow = new MaintenanceWindow({ const maintenanceWindow = new this.MaintenanceWindow({
...maintenanceWindowData, ...maintenanceWindowData,
}); });
@@ -33,10 +22,9 @@ const createMaintenanceWindow = async (maintenanceWindowData) => {
throw error; throw error;
} }
}; };
getMaintenanceWindowById = async ({ id, teamId }) => {
const getMaintenanceWindowById = async ({ id, teamId }) => {
try { try {
const maintenanceWindow = await MaintenanceWindow.findOne({ const maintenanceWindow = await this.MaintenanceWindow.findOne({
_id: id, _id: id,
teamId: teamId, teamId: teamId,
}); });
@@ -48,23 +36,14 @@ const getMaintenanceWindowById = async ({ id, teamId }) => {
} }
}; };
/** getMaintenanceWindowsByTeamId = async (teamId, query) => {
* Asynchronously retrieves all MaintenanceWindow documents associated with a specific team ID.
* @async
* @function getMaintenanceWindowByUserId
* @param {String} teamId - The ID of the team.
* @param {Object} query - The request body.
* @returns {Promise<Array<MaintenanceWindow>>} An array of MaintenanceWindow documents.
* @throws {Error} If there is an error retrieving the documents.
*/
const getMaintenanceWindowsByTeamId = async (teamId, query) => {
try { try {
let { active, page, rowsPerPage, field, order } = query || {}; let { active, page, rowsPerPage, field, order } = query || {};
const maintenanceQuery = { teamId }; const maintenanceQuery = { teamId };
if (active !== undefined) maintenanceQuery.active = active; if (active !== undefined) maintenanceQuery.active = active;
const maintenanceWindowCount = await MaintenanceWindow.countDocuments(maintenanceQuery); const maintenanceWindowCount = await this.MaintenanceWindow.countDocuments(maintenanceQuery);
// Pagination // Pagination
let skip = 0; let skip = 0;
@@ -78,7 +57,7 @@ const getMaintenanceWindowsByTeamId = async (teamId, query) => {
sort[field] = order === "asc" ? 1 : -1; sort[field] = order === "asc" ? 1 : -1;
} }
const maintenanceWindows = await MaintenanceWindow.find(maintenanceQuery).skip(skip).limit(rowsPerPage).sort(sort); const maintenanceWindows = await this.MaintenanceWindow.find(maintenanceQuery).skip(skip).limit(rowsPerPage).sort(sort);
return { maintenanceWindows, maintenanceWindowCount }; return { maintenanceWindows, maintenanceWindowCount };
} catch (error) { } catch (error) {
@@ -87,18 +66,9 @@ const getMaintenanceWindowsByTeamId = async (teamId, query) => {
throw error; throw error;
} }
}; };
getMaintenanceWindowsByMonitorId = async ({ monitorId, teamId }) => {
/**
* Asynchronously retrieves all MaintenanceWindow documents associated with a specific monitor ID.
* @async
* @function getMaintenanceWindowsByMonitorId
* @param {mongoose.Schema.Types.ObjectId} monitorId - The ID of the monitor.
* @returns {Promise<Array<MaintenanceWindow>>} An array of MaintenanceWindow documents.
* @throws {Error} If there is an error retrieving the documents.
*/
const getMaintenanceWindowsByMonitorId = async ({ monitorId, teamId }) => {
try { try {
const maintenanceWindows = await MaintenanceWindow.find({ const maintenanceWindows = await this.MaintenanceWindow.find({
monitorId: monitorId, monitorId: monitorId,
teamId: teamId, teamId: teamId,
}); });
@@ -110,17 +80,9 @@ const getMaintenanceWindowsByMonitorId = async ({ monitorId, teamId }) => {
} }
}; };
/** deleteMaintenanceWindowById = async ({ id, teamId }) => {
* Asynchronously deletes a MaintenanceWindow document by its ID.
* @async
* @function deleteMaintenanceWindowById
* @param {mongoose.Schema.Types.ObjectId} maintenanceWindowId - The ID of the MaintenanceWindow document to delete.
* @returns {Promise<MaintenanceWindow>} The deleted MaintenanceWindow document.
* @throws {Error} If there is an error deleting the document.
*/
const deleteMaintenanceWindowById = async ({ id, teamId }) => {
try { try {
const maintenanceWindow = await MaintenanceWindow.findOneAndDelete({ _id: id, teamId }); const maintenanceWindow = await this.MaintenanceWindow.findOneAndDelete({ _id: id, teamId });
return maintenanceWindow; return maintenanceWindow;
} catch (error) { } catch (error) {
error.service = SERVICE_NAME; error.service = SERVICE_NAME;
@@ -129,49 +91,9 @@ const deleteMaintenanceWindowById = async ({ id, teamId }) => {
} }
}; };
/** editMaintenanceWindowById = async ({ id, body }) => {
* Asynchronously deletes all MaintenanceWindow documents associated with a specific monitor ID.
* @async
* @function deleteMaintenanceWindowByMonitorId
* @param {mongoose.Schema.Types.ObjectId} monitorId - The ID of the monitor.
* @returns {Promise<Object>} The result of the delete operation. This object contains information about the operation, such as the number of documents deleted.
* @throws {Error} If there is an error deleting the documents.
* @example
*/
const deleteMaintenanceWindowByMonitorId = async (monitorId) => {
try { try {
const result = await MaintenanceWindow.deleteMany({ monitorId: monitorId }); const editedMaintenanceWindow = await this.MaintenanceWindow.findByIdAndUpdate(id, body, { new: true });
return result;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "deleteMaintenanceWindowByMonitorId";
throw error;
}
};
/**
* Asynchronously deletes all MaintenanceWindow documents associated with a specific user ID.
* @async
* @function deleteMaintenanceWindowByUserId
* @param {String} userId - The ID of the user.
* @returns {Promise<Object>} The result of the delete operation. This object contains information about the operation, such as the number of documents deleted.
* @throws {Error} If there is an error deleting the documents.
* @example
*/
const deleteMaintenanceWindowByUserId = async (userId) => {
try {
const result = await MaintenanceWindow.deleteMany({ userId: userId });
return result;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "deleteMaintenanceWindowByUserId";
throw error;
}
};
const editMaintenanceWindowById = async ({ id, body, teamId }) => {
try {
const editedMaintenanceWindow = await MaintenanceWindow.findByIdAndUpdate(id, body, { new: true });
return editedMaintenanceWindow; return editedMaintenanceWindow;
} catch (error) { } catch (error) {
error.service = SERVICE_NAME; error.service = SERVICE_NAME;
@@ -179,14 +101,6 @@ const editMaintenanceWindowById = async ({ id, body, teamId }) => {
throw error; throw error;
} }
}; };
}
export { export default MaintenanceWindowModule;
createMaintenanceWindow,
getMaintenanceWindowById,
getMaintenanceWindowsByTeamId,
getMaintenanceWindowsByMonitorId,
deleteMaintenanceWindowById,
deleteMaintenanceWindowByMonitorId,
deleteMaintenanceWindowByUserId,
editMaintenanceWindowById,
};
+158 -323
View File
@@ -1,16 +1,3 @@
import Monitor from "../../models/Monitor.js";
import MonitorStats from "../../models/MonitorStats.js";
import Check from "../../models/Check.js";
import PageSpeedCheck from "../../models/PageSpeedCheck.js";
import HardwareCheck from "../../models/HardwareCheck.js";
import { NormalizeData, NormalizeDataUptimeDetails } from "../../../utils/dataUtils.js";
import ServiceRegistry from "../../../service/system/serviceRegistry.js";
import StringService from "../../../service/system/stringService.js";
import fs from "fs";
import path from "path";
import { fileURLToPath } from "url";
import { ObjectId } from "mongodb";
import { import {
buildUptimeDetailsPipeline, buildUptimeDetailsPipeline,
buildHardwareDetailsPipeline, buildHardwareDetailsPipeline,
@@ -20,15 +7,38 @@ import {
buildMonitorsWithChecksByTeamIdPipeline, buildMonitorsWithChecksByTeamIdPipeline,
buildFilteredMonitorsByTeamIdPipeline, buildFilteredMonitorsByTeamIdPipeline,
} from "./monitorModuleQueries.js"; } from "./monitorModuleQueries.js";
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const demoMonitorsPath = path.resolve(__dirname, "../../../utils/demoMonitors.json");
const demoMonitors = JSON.parse(fs.readFileSync(demoMonitorsPath, "utf8"));
const SERVICE_NAME = "monitorModule"; const SERVICE_NAME = "monitorModule";
const CHECK_MODEL_LOOKUP = { class MonitorModule {
constructor({
Monitor,
MonitorStats,
Check,
PageSpeedCheck,
HardwareCheck,
stringService,
fs,
path,
fileURLToPath,
ObjectId,
NormalizeData,
NormalizeDataUptimeDetails,
}) {
this.Monitor = Monitor;
this.MonitorStats = MonitorStats;
this.Check = Check;
this.PageSpeedCheck = PageSpeedCheck;
this.HardwareCheck = HardwareCheck;
this.stringService = stringService;
this.fs = fs;
this.path = path;
this.fileURLToPath = fileURLToPath;
this.ObjectId = ObjectId;
this.NormalizeData = NormalizeData;
this.NormalizeDataUptimeDetails = NormalizeDataUptimeDetails;
this.CHECK_MODEL_LOOKUP = {
http: Check, http: Check,
ping: Check, ping: Check,
docker: Check, docker: Check,
@@ -37,31 +47,14 @@ const CHECK_MODEL_LOOKUP = {
hardware: HardwareCheck, hardware: HardwareCheck,
}; };
/** const __filename = fileURLToPath(import.meta.url);
* Get all monitors const __dirname = path.dirname(__filename);
* @async
* @param {Express.Request} req
* @param {Express.Response} res
* @returns {Promise<Array<Monitor>>}
* @throws {Error}
*/
const getAllMonitors = async (req, res) => {
try {
const monitors = await Monitor.find();
return monitors;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "getAllMonitors";
throw error;
}
};
/** this.demoMonitorsPath = path.resolve(__dirname, "../../../utils/demoMonitors.json");
* Function to calculate uptime duration based on the most recent check. }
* @param {Array} checks Array of check objects.
* @returns {number} Uptime duration in ms. // Helper
*/ calculateUptimeDuration = (checks) => {
const calculateUptimeDuration = (checks) => {
if (!checks || checks.length === 0) { if (!checks || checks.length === 0) {
return 0; return 0;
} }
@@ -84,25 +77,15 @@ const calculateUptimeDuration = (checks) => {
return latestCheck - latestDownCheck; return latestCheck - latestDownCheck;
}; };
/** // Helper
* Helper function to get duration since last check getLastChecked = (checks) => {
* @param {Array} checks Array of check objects.
* @returns {number} Timestamp of the most recent check.
*/
const getLastChecked = (checks) => {
if (!checks || checks.length === 0) { if (!checks || checks.length === 0) {
return 0; // Handle case when no checks are available return 0; // Handle case when no checks are available
} }
// Data is sorted newest->oldest, so last check is the most recent // Data is sorted newest->oldest, so last check is the most recent
return new Date() - new Date(checks[0].createdAt); return new Date() - new Date(checks[0].createdAt);
}; };
getLatestResponseTime = (checks) => {
/**
* Helper function to get latestResponseTime
* @param {Array} checks Array of check objects.
* @returns {number} Timestamp of the most recent check.
*/
const getLatestResponseTime = (checks) => {
if (!checks || checks.length === 0) { if (!checks || checks.length === 0) {
return 0; return 0;
} }
@@ -110,12 +93,8 @@ const getLatestResponseTime = (checks) => {
return checks[0]?.responseTime ?? 0; return checks[0]?.responseTime ?? 0;
}; };
/** // Helper
* Helper function to get average response time getAverageResponseTime = (checks) => {
* @param {Array} checks Array of check objects.
* @returns {number} Timestamp of the most recent check.
*/
const getAverageResponseTime = (checks) => {
if (!checks || checks.length === 0) { if (!checks || checks.length === 0) {
return 0; return 0;
} }
@@ -130,13 +109,8 @@ const getAverageResponseTime = (checks) => {
return aggResponseTime / validChecks.length; return aggResponseTime / validChecks.length;
}; };
/** // Helper
* Helper function to get percentage 24h uptime getUptimePercentage = (checks) => {
* @param {Array} checks Array of check objects.
* @returns {number} Timestamp of the most recent check.
*/
const getUptimePercentage = (checks) => {
if (!checks || checks.length === 0) { if (!checks || checks.length === 0) {
return 0; return 0;
} }
@@ -146,13 +120,8 @@ const getUptimePercentage = (checks) => {
return (upCount / checks.length) * 100; return (upCount / checks.length) * 100;
}; };
/** // Helper
* Helper function to get all incidents getIncidents = (checks) => {
* @param {Array} checks Array of check objects.
* @returns {number} Timestamp of the most recent check.
*/
const getIncidents = (checks) => {
if (!checks || checks.length === 0) { if (!checks || checks.length === 0) {
return 0; // Handle case when no checks are available return 0; // Handle case when no checks are available
} }
@@ -161,12 +130,8 @@ const getIncidents = (checks) => {
}, 0); }, 0);
}; };
/** // Helper
* Get date range parameters getDateRange = (dateRange) => {
* @param {string} dateRange - 'day' | 'week' | 'month' | 'all'
* @returns {Object} Start and end dates
*/
const getDateRange = (dateRange) => {
const startDates = { const startDates = {
recent: new Date(new Date().setHours(new Date().getHours() - 2)), recent: new Date(new Date().setHours(new Date().getHours() - 2)),
day: new Date(new Date().setDate(new Date().getDate() - 1)), day: new Date(new Date().setDate(new Date().getDate() - 1)),
@@ -180,15 +145,8 @@ const getDateRange = (dateRange) => {
}; };
}; };
/** //Helper
* Get checks for a monitor getMonitorChecks = async (monitorId, model, dateRange, sortOrder) => {
* @param {string} monitorId - Monitor ID
* @param {Object} model - Check model to use
* @param {Object} dateRange - Date range parameters
* @param {number} sortOrder - Sort order (1 for ascending, -1 for descending)
* @returns {Promise<Object>} All checks and date-ranged checks
*/
const getMonitorChecks = async (monitorId, model, dateRange, sortOrder) => {
const indexSpec = { const indexSpec = {
monitorId: 1, monitorId: 1,
createdAt: sortOrder, // This will be 1 or -1 createdAt: sortOrder, // This will be 1 or -1
@@ -208,14 +166,8 @@ const getMonitorChecks = async (monitorId, model, dateRange, sortOrder) => {
return { checksAll, checksForDateRange }; return { checksAll, checksForDateRange };
}; };
/** // Helper
* Process checks for display processChecksForDisplay = (normalizeData, checks, numToDisplay, normalize) => {
* @param {Array} checks - Checks to process
* @param {number} numToDisplay - Number of checks to display
* @param {boolean} normalize - Whether to normalize the data
* @returns {Array} Processed checks
*/
const processChecksForDisplay = (normalizeData, checks, numToDisplay, normalize) => {
let processedChecks = checks; let processedChecks = checks;
if (numToDisplay && checks.length > numToDisplay) { if (numToDisplay && checks.length > numToDisplay) {
const n = Math.ceil(checks.length / numToDisplay); const n = Math.ceil(checks.length / numToDisplay);
@@ -224,13 +176,8 @@ const processChecksForDisplay = (normalizeData, checks, numToDisplay, normalize)
return normalize ? normalizeData(processedChecks, 1, 100) : processedChecks; return normalize ? normalizeData(processedChecks, 1, 100) : processedChecks;
}; };
/** // Helper
* Get time-grouped checks based on date range groupChecksByTime = (checks, dateRange) => {
* @param {Array} checks Array of check objects
* @param {string} dateRange 'day' | 'week' | 'month'
* @returns {Object} Grouped checks by time period
*/
const groupChecksByTime = (checks, dateRange) => {
return checks.reduce((acc, check) => { return checks.reduce((acc, check) => {
// Validate the date // Validate the date
const checkDate = new Date(check.createdAt); const checkDate = new Date(check.createdAt);
@@ -248,19 +195,15 @@ const groupChecksByTime = (checks, dateRange) => {
}, {}); }, {});
}; };
/** // Helper
* Calculate aggregate stats for a group of checks calculateGroupStats = (group) => {
* @param {Object} group Group of checks
* @returns {Object} Stats for the group
*/
const calculateGroupStats = (group) => {
const totalChecks = group.checks.length; const totalChecks = group.checks.length;
const checksWithResponseTime = group.checks.filter((check) => typeof check.responseTime === "number" && !Number.isNaN(check.responseTime)); const checksWithResponseTime = group.checks.filter((check) => typeof check.responseTime === "number" && !Number.isNaN(check.responseTime));
return { return {
time: group.time, time: group.time,
uptimePercentage: getUptimePercentage(group.checks), uptimePercentage: this.getUptimePercentage(group.checks),
totalChecks, totalChecks,
totalIncidents: group.checks.filter((check) => !check.status).length, totalIncidents: group.checks.filter((check) => !check.status).length,
avgResponseTime: avgResponseTime:
@@ -270,17 +213,47 @@ const calculateGroupStats = (group) => {
}; };
}; };
/** getAllMonitors = async () => {
* Get uptime details by monitor ID
* @async
* @param {Express.Request} req
* @param {Express.Response} res
* @returns {Promise<Monitor>}
* @throws {Error}
*/
const getUptimeDetailsById = async ({ monitorId, dateRange, normalize }) => {
try { try {
const dates = getDateRange(dateRange); const monitors = await this.Monitor.find();
return monitors;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "getAllMonitors";
throw error;
}
};
getMonitorById = async (monitorId) => {
try {
const monitor = await this.Monitor.findById(monitorId);
if (monitor === null || monitor === undefined) {
const error = new Error(this.stringService.getDbFindMonitorById(monitorId));
error.status = 404;
throw error;
}
return monitor;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "getMonitorById";
throw error;
}
};
getMonitorsByIds = async (monitorIds) => {
try {
const objectIds = monitorIds.map((id) => new this.ObjectId(id));
return await this.Monitor.find({ _id: { $in: objectIds } }, { _id: 1, teamId: 1 }).lean();
} catch (error) {
error.service = SERVICE_NAME;
error.method = "getMonitorsByIds";
throw error;
}
};
getUptimeDetailsById = async ({ monitorId, dateRange }) => {
try {
const dates = this.getDateRange(dateRange);
const formatLookup = { const formatLookup = {
recent: "%Y-%m-%dT%H:%M:00Z", recent: "%Y-%m-%dT%H:%M:00Z",
day: "%Y-%m-%dT%H:00:00Z", day: "%Y-%m-%dT%H:00:00Z",
@@ -290,18 +263,18 @@ const getUptimeDetailsById = async ({ monitorId, dateRange, normalize }) => {
const dateString = formatLookup[dateRange]; const dateString = formatLookup[dateRange];
const results = await Check.aggregate(buildUptimeDetailsPipeline(monitorId, dates, dateString)); const results = await this.Check.aggregate(buildUptimeDetailsPipeline(monitorId, dates, dateString));
const monitorData = results[0]; const monitorData = results[0];
monitorData.groupedUpChecks = NormalizeDataUptimeDetails(monitorData.groupedUpChecks, 10, 100); monitorData.groupedUpChecks = this.NormalizeDataUptimeDetails(monitorData.groupedUpChecks, 10, 100);
monitorData.groupedDownChecks = NormalizeDataUptimeDetails(monitorData.groupedDownChecks, 10, 100); monitorData.groupedDownChecks = this.NormalizeDataUptimeDetails(monitorData.groupedDownChecks, 10, 100);
const normalizedGroupChecks = NormalizeDataUptimeDetails(monitorData.groupedChecks, 10, 100); const normalizedGroupChecks = this.NormalizeDataUptimeDetails(monitorData.groupedChecks, 10, 100);
monitorData.groupedChecks = normalizedGroupChecks; monitorData.groupedChecks = normalizedGroupChecks;
const monitorStats = await MonitorStats.findOne({ monitorId }); const monitorStats = await this.MonitorStats.findOne({ monitorId });
return { monitorData, monitorStats }; return { monitorData, monitorStats };
} catch (error) { } catch (error) {
error.service = SERVICE_NAME; error.service = SERVICE_NAME;
@@ -310,48 +283,39 @@ const getUptimeDetailsById = async ({ monitorId, dateRange, normalize }) => {
} }
}; };
/** getMonitorStatsById = async ({ monitorId, sortOrder, dateRange, numToDisplay, normalize }) => {
* Get stats by monitor ID
* @async
* @param {Express.Request} req
* @param {Express.Response} res
* @returns {Promise<Monitor>}
* @throws {Error}
*/
const getMonitorStatsById = async ({ monitorId, limit, sortOrder, dateRange, numToDisplay, normalize }) => {
const stringService = ServiceRegistry.get(StringService.SERVICE_NAME);
try { try {
// Get monitor, if we can't find it, abort with error // Get monitor, if we can't find it, abort with error
const monitor = await Monitor.findById(monitorId); const monitor = await this.Monitor.findById(monitorId);
if (monitor === null || monitor === undefined) { if (monitor === null || monitor === undefined) {
throw new Error(stringService.getDbFindMonitorById(monitorId)); throw new Error(this.stringService.getDbFindMonitorById(monitorId));
} }
// Get query params // Get query params
const sort = sortOrder === "asc" ? 1 : -1; const sort = sortOrder === "asc" ? 1 : -1;
// Get Checks for monitor in date range requested // Get Checks for monitor in date range requested
const model = CHECK_MODEL_LOOKUP[monitor.type]; const model = this.CHECK_MODEL_LOOKUP[monitor.type];
const dates = getDateRange(dateRange); const dates = this.getDateRange(dateRange);
const { checksAll, checksForDateRange } = await getMonitorChecks(monitorId, model, dates, sort); const { checksAll, checksForDateRange } = await this.getMonitorChecks(monitorId, model, dates, sort);
// Build monitor stats // Build monitor stats
const monitorStats = { const monitorStats = {
...monitor.toObject(), ...monitor.toObject(),
uptimeDuration: calculateUptimeDuration(checksAll), uptimeDuration: this.calculateUptimeDuration(checksAll),
lastChecked: getLastChecked(checksAll), lastChecked: this.getLastChecked(checksAll),
latestResponseTime: getLatestResponseTime(checksAll), latestResponseTime: this.getLatestResponseTime(checksAll),
periodIncidents: getIncidents(checksForDateRange), periodIncidents: this.getIncidents(checksForDateRange),
periodTotalChecks: checksForDateRange.length, periodTotalChecks: checksForDateRange.length,
checks: processChecksForDisplay(NormalizeData, checksForDateRange, numToDisplay, normalize), checks: this.processChecksForDisplay(this.NormalizeData, checksForDateRange, numToDisplay, normalize),
}; };
if (monitor.type === "http" || monitor.type === "ping" || monitor.type === "docker" || monitor.type === "port") { if (monitor.type === "http" || monitor.type === "ping" || monitor.type === "docker" || monitor.type === "port") {
// HTTP/PING Specific stats // HTTP/PING Specific stats
monitorStats.periodAvgResponseTime = getAverageResponseTime(checksForDateRange); monitorStats.periodAvgResponseTime = this.getAverageResponseTime(checksForDateRange);
monitorStats.periodUptime = getUptimePercentage(checksForDateRange); monitorStats.periodUptime = this.getUptimePercentage(checksForDateRange);
const groupedChecks = groupChecksByTime(checksForDateRange, dateRange); const groupedChecks = this.groupChecksByTime(checksForDateRange, dateRange);
monitorStats.aggregateData = Object.values(groupedChecks).map(calculateGroupStats); monitorStats.aggregateData = Object.values(groupedChecks).map(this.calculateGroupStats);
} }
return monitorStats; return monitorStats;
@@ -362,10 +326,10 @@ const getMonitorStatsById = async ({ monitorId, limit, sortOrder, dateRange, num
} }
}; };
const getHardwareDetailsById = async ({ monitorId, dateRange }) => { getHardwareDetailsById = async ({ monitorId, dateRange }) => {
try { try {
const monitor = await Monitor.findById(monitorId); const monitor = await this.Monitor.findById(monitorId);
const dates = getDateRange(dateRange); const dates = this.getDateRange(dateRange);
const formatLookup = { const formatLookup = {
recent: "%Y-%m-%dT%H:%M:00Z", recent: "%Y-%m-%dT%H:%M:00Z",
day: "%Y-%m-%dT%H:00:00Z", day: "%Y-%m-%dT%H:00:00Z",
@@ -373,7 +337,7 @@ const getHardwareDetailsById = async ({ monitorId, dateRange }) => {
month: "%Y-%m-%dT00:00:00Z", month: "%Y-%m-%dT00:00:00Z",
}; };
const dateString = formatLookup[dateRange]; const dateString = formatLookup[dateRange];
const hardwareStats = await HardwareCheck.aggregate(buildHardwareDetailsPipeline(monitor, dates, dateString)); const hardwareStats = await this.HardwareCheck.aggregate(buildHardwareDetailsPipeline(monitor, dates, dateString));
const monitorStats = { const monitorStats = {
...monitor.toObject(), ...monitor.toObject(),
@@ -387,44 +351,7 @@ const getHardwareDetailsById = async ({ monitorId, dateRange }) => {
} }
}; };
/** getMonitorsByTeamId = async ({ limit, type, page, rowsPerPage, filter, field, order, teamId }) => {
* Get a monitor by ID
* @async
* @param {Express.Request} req
* @param {Express.Response} res
* @returns {Promise<Monitor>}
* @throws {Error}
*/
const getMonitorById = async (monitorId) => {
const stringService = ServiceRegistry.get(StringService.SERVICE_NAME);
try {
const monitor = await Monitor.findById(monitorId);
if (monitor === null || monitor === undefined) {
const error = new Error(stringService.getDbFindMonitorById(monitorId));
error.status = 404;
throw error;
}
return monitor;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "getMonitorById";
throw error;
}
};
const getMonitorsByIds = async (monitorIds) => {
try {
const objectIds = monitorIds.map((id) => new ObjectId(id));
return await Monitor.find({ _id: { $in: objectIds } }, { _id: 1, teamId: 1 }).lean();
} catch (error) {
error.service = SERVICE_NAME;
error.method = "getMonitorsByIds";
throw error;
}
};
const getMonitorsByTeamId = async ({ limit, type, page, rowsPerPage, filter, field, order, teamId }) => {
limit = parseInt(limit); limit = parseInt(limit);
page = parseInt(page); page = parseInt(page);
rowsPerPage = parseInt(rowsPerPage); rowsPerPage = parseInt(rowsPerPage);
@@ -433,17 +360,17 @@ const getMonitorsByTeamId = async ({ limit, type, page, rowsPerPage, filter, fie
order = "asc"; order = "asc";
} }
// Build match stage // Build match stage
const matchStage = { teamId: new ObjectId(teamId) }; const matchStage = { teamId: new this.ObjectId(teamId) };
if (type !== undefined) { if (type !== undefined) {
matchStage.type = Array.isArray(type) ? { $in: type } : type; matchStage.type = Array.isArray(type) ? { $in: type } : type;
} }
const summaryResult = await Monitor.aggregate(buildMonitorSummaryByTeamIdPipeline({ matchStage })); const summaryResult = await this.Monitor.aggregate(buildMonitorSummaryByTeamIdPipeline({ matchStage }));
const summary = summaryResult[0]; const summary = summaryResult[0];
const monitors = await Monitor.aggregate(buildMonitorsByTeamIdPipeline({ matchStage, field, order })); const monitors = await this.Monitor.aggregate(buildMonitorsByTeamIdPipeline({ matchStage, field, order }));
const filteredMonitors = await Monitor.aggregate( const filteredMonitors = await this.Monitor.aggregate(
buildFilteredMonitorsByTeamIdPipeline({ buildFilteredMonitorsByTeamIdPipeline({
matchStage, matchStage,
filter, filter,
@@ -460,25 +387,25 @@ const getMonitorsByTeamId = async ({ limit, type, page, rowsPerPage, filter, fie
if (!monitor.checks) { if (!monitor.checks) {
return monitor; return monitor;
} }
monitor.checks = NormalizeData(monitor.checks, 10, 100); monitor.checks = this.NormalizeData(monitor.checks, 10, 100);
return monitor; return monitor;
}); });
return { summary, monitors, filteredMonitors: normalizedFilteredMonitors }; return { summary, monitors, filteredMonitors: normalizedFilteredMonitors };
}; };
const getMonitorsAndSummaryByTeamId = async ({ type, explain, teamId }) => { getMonitorsAndSummaryByTeamId = async ({ type, explain, teamId }) => {
try { try {
const matchStage = { teamId: new ObjectId(teamId) }; const matchStage = { teamId: new this.ObjectId(teamId) };
if (type !== undefined) { if (type !== undefined) {
matchStage.type = Array.isArray(type) ? { $in: type } : type; matchStage.type = Array.isArray(type) ? { $in: type } : type;
} }
if (explain === true) { if (explain === true) {
return Monitor.aggregate(buildMonitorsAndSummaryByTeamIdPipeline({ matchStage })).explain("executionStats"); return this.Monitor.aggregate(buildMonitorsAndSummaryByTeamIdPipeline({ matchStage })).explain("executionStats");
} }
const queryResult = await Monitor.aggregate(buildMonitorsAndSummaryByTeamIdPipeline({ matchStage })); const queryResult = await this.Monitor.aggregate(buildMonitorsAndSummaryByTeamIdPipeline({ matchStage }));
const { monitors, summary } = queryResult?.[0] ?? {}; const { monitors, summary } = queryResult?.[0] ?? {};
return { monitors, summary }; return { monitors, summary };
} catch (error) { } catch (error) {
@@ -488,7 +415,7 @@ const getMonitorsAndSummaryByTeamId = async ({ type, explain, teamId }) => {
} }
}; };
const getMonitorsWithChecksByTeamId = async ({ limit, type, page, rowsPerPage, filter, field, order, teamId, explain }) => { getMonitorsWithChecksByTeamId = async ({ limit, type, page, rowsPerPage, filter, field, order, teamId, explain }) => {
try { try {
limit = parseInt(limit); limit = parseInt(limit);
page = parseInt(page); page = parseInt(page);
@@ -498,13 +425,13 @@ const getMonitorsWithChecksByTeamId = async ({ limit, type, page, rowsPerPage, f
order = "asc"; order = "asc";
} }
// Build match stage // Build match stage
const matchStage = { teamId: new ObjectId(teamId) }; const matchStage = { teamId: new this.ObjectId(teamId) };
if (type !== undefined) { if (type !== undefined) {
matchStage.type = Array.isArray(type) ? { $in: type } : type; matchStage.type = Array.isArray(type) ? { $in: type } : type;
} }
if (explain === true) { if (explain === true) {
return Monitor.aggregate( return this.Monitor.aggregate(
buildMonitorsWithChecksByTeamIdPipeline({ buildMonitorsWithChecksByTeamIdPipeline({
matchStage, matchStage,
filter, filter,
@@ -518,7 +445,7 @@ const getMonitorsWithChecksByTeamId = async ({ limit, type, page, rowsPerPage, f
).explain("executionStats"); ).explain("executionStats");
} }
const queryResult = await Monitor.aggregate( const queryResult = await this.Monitor.aggregate(
buildMonitorsWithChecksByTeamIdPipeline({ buildMonitorsWithChecksByTeamIdPipeline({
matchStage, matchStage,
filter, filter,
@@ -536,7 +463,7 @@ const getMonitorsWithChecksByTeamId = async ({ limit, type, page, rowsPerPage, f
if (!monitor.checks) { if (!monitor.checks) {
return monitor; return monitor;
} }
monitor.checks = NormalizeData(monitor.checks, 10, 100); monitor.checks = this.NormalizeData(monitor.checks, 10, 100);
return monitor; return monitor;
}); });
return { count, monitors: normalizedFilteredMonitors }; return { count, monitors: normalizedFilteredMonitors };
@@ -546,18 +473,9 @@ const getMonitorsWithChecksByTeamId = async ({ limit, type, page, rowsPerPage, f
throw error; throw error;
} }
}; };
createMonitor = async ({ body, teamId, userId }) => {
/**
* Create a monitor
* @async
* @param {Express.Request} req
* @param {Express.Response} res
* @returns {Promise<Monitor>}
* @throws {Error}
*/
const createMonitor = async ({ body, teamId, userId }) => {
try { try {
const monitor = new Monitor({ ...body, teamId, userId }); const monitor = new this.Monitor({ ...body, teamId, userId });
const saved = await monitor.save(); const saved = await monitor.save();
return saved; return saved;
} catch (error) { } catch (error) {
@@ -567,17 +485,10 @@ const createMonitor = async ({ body, teamId, userId }) => {
} }
}; };
/** createBulkMonitors = async (req) => {
* Create bulk monitors
* @async
* @param {Express.Request} req
* @returns {Promise<Monitors>}
* @throws {Error}
*/
const createBulkMonitors = async (req) => {
try { try {
const monitors = req.map((item) => new Monitor({ ...item, notifications: undefined })); const monitors = req.map((item) => new this.Monitor({ ...item, notifications: undefined }));
await Monitor.bulkSave(monitors); await this.Monitor.bulkSave(monitors);
return monitors; return monitors;
} catch (error) { } catch (error) {
error.service = SERVICE_NAME; error.service = SERVICE_NAME;
@@ -586,21 +497,12 @@ const createBulkMonitors = async (req) => {
} }
}; };
/** deleteMonitor = async ({ teamId, monitorId }) => {
* Delete a monitor by ID
* @async
* @param {Express.Request} req
* @param {Express.Response} res
* @returns {Promise<Monitor>}
* @throws {Error}
*/
const deleteMonitor = async ({ teamId, monitorId }) => {
const stringService = ServiceRegistry.get(StringService.SERVICE_NAME);
try { try {
const deletedMonitor = await Monitor.findOneAndDelete({ _id: monitorId, teamId }); const deletedMonitor = await this.Monitor.findOneAndDelete({ _id: monitorId, teamId });
if (!deletedMonitor) { if (!deletedMonitor) {
throw new Error(stringService.getDbFindMonitorById(monitorId)); throw new Error(this.stringService.getDbFindMonitorById(monitorId));
} }
return deletedMonitor; return deletedMonitor;
@@ -611,14 +513,10 @@ const deleteMonitor = async ({ teamId, monitorId }) => {
} }
}; };
/** deleteAllMonitors = async (teamId) => {
* DELETE ALL MONITORS (TEMP)
*/
const deleteAllMonitors = async (teamId) => {
try { try {
const monitors = await Monitor.find({ teamId }); const monitors = await this.Monitor.find({ teamId });
const { deletedCount } = await Monitor.deleteMany({ teamId }); const { deletedCount } = await this.Monitor.deleteMany({ teamId });
return { monitors, deletedCount }; return { monitors, deletedCount };
} catch (error) { } catch (error) {
@@ -628,15 +526,9 @@ const deleteAllMonitors = async (teamId) => {
} }
}; };
/** deleteMonitorsByUserId = async (userId) => {
* Delete all monitors associated with a user ID
* @async
* @param {string} userId - The ID of the user whose monitors are to be deleted.
* @returns {Promise} A promise that resolves when the operation is complete.
*/
const deleteMonitorsByUserId = async (userId) => {
try { try {
const result = await Monitor.deleteMany({ userId: userId }); const result = await this.Monitor.deleteMany({ userId: userId });
return result; return result;
} catch (error) { } catch (error) {
error.service = SERVICE_NAME; error.service = SERVICE_NAME;
@@ -645,17 +537,9 @@ const deleteMonitorsByUserId = async (userId) => {
} }
}; };
/** editMonitor = async ({ monitorId, body }) => {
* Edit a monitor by ID
* @async
* @param {Express.Request} req
* @param {Express.Response} res
* @returns {Promise<Monitor>}
* @throws {Error}
*/
const editMonitor = async ({ monitorId, body }) => {
try { try {
const editedMonitor = await Monitor.findByIdAndUpdate(monitorId, body, { const editedMonitor = await this.Monitor.findByIdAndUpdate(monitorId, body, {
new: true, new: true,
}); });
return editedMonitor; return editedMonitor;
@@ -666,8 +550,10 @@ const editMonitor = async ({ monitorId, body }) => {
} }
}; };
const addDemoMonitors = async (userId, teamId) => { addDemoMonitors = async (userId, teamId) => {
try { try {
const demoMonitors = JSON.parse(this.fs.readFileSync(this.demoMonitorsPath, "utf8"));
const demoMonitorsToInsert = demoMonitors.map((monitor) => { const demoMonitorsToInsert = demoMonitors.map((monitor) => {
return { return {
userId, userId,
@@ -679,7 +565,7 @@ const addDemoMonitors = async (userId, teamId) => {
interval: 60000, interval: 60000,
}; };
}); });
const insertedMonitors = await Monitor.insertMany(demoMonitorsToInsert); const insertedMonitors = await this.Monitor.insertMany(demoMonitorsToInsert);
return insertedMonitors; return insertedMonitors;
} catch (error) { } catch (error) {
error.service = SERVICE_NAME; error.service = SERVICE_NAME;
@@ -688,9 +574,9 @@ const addDemoMonitors = async (userId, teamId) => {
} }
}; };
const pauseMonitor = async ({ monitorId }) => { pauseMonitor = async ({ monitorId }) => {
try { try {
const monitor = await Monitor.findOneAndUpdate( const monitor = await this.Monitor.findOneAndUpdate(
{ _id: monitorId }, { _id: monitorId },
[ [
{ {
@@ -710,57 +596,6 @@ const pauseMonitor = async ({ monitorId }) => {
throw error; throw error;
} }
}; };
}
export { export default MonitorModule;
getAllMonitors,
getMonitorStatsById,
getMonitorById,
getMonitorsByIds,
getMonitorsByTeamId,
getMonitorsAndSummaryByTeamId,
getMonitorsWithChecksByTeamId,
getUptimeDetailsById,
createMonitor,
createBulkMonitors,
deleteMonitor,
deleteAllMonitors,
deleteMonitorsByUserId,
editMonitor,
addDemoMonitors,
getHardwareDetailsById,
pauseMonitor,
};
// Helper functions
export {
calculateUptimeDuration,
getLastChecked,
getLatestResponseTime,
getAverageResponseTime,
getUptimePercentage,
getIncidents,
getDateRange,
getMonitorChecks,
processChecksForDisplay,
groupChecksByTime,
calculateGroupStats,
};
// limit 25
// page 1
// rowsPerPage 25
// filter undefined
// field name
// order asc
// skip 25
// sort { name: 1 }
// filteredMonitors []
// limit 25
// page NaN
// rowsPerPage 25
// filter undefined
// field name
// order asc
// skip 0
// sort { name: 1 }
@@ -1,18 +1,12 @@
import NetworkCheck from "../../models/NetworkCheck.js";
const SERVICE_NAME = "networkCheckModule"; const SERVICE_NAME = "networkCheckModule";
/** class NetworkCheckModule {
* Creates and saves a new network check document to the database. constructor({ NetworkCheck }) {
* @async this.NetworkCheck = NetworkCheck;
* @param {object} networkCheckData - The data for the new network check. This should conform to the NetworkCheckSchema. }
* @param {string} networkCheckData.monitorId - The ID of the monitor associated with this check. createNetworkCheck = async (networkCheckData) => {
* @returns {Promise<object>} A promise that resolves to the newly created network check document.
* @throws {Error} Throws an error if the database operation fails.
*/
const createNetworkCheck = async (networkCheckData) => {
try { try {
const networkCheck = await new NetworkCheck(networkCheckData); const networkCheck = await new this.NetworkCheck(networkCheckData);
await networkCheck.save(); await networkCheck.save();
return networkCheck; return networkCheck;
} catch (error) { } catch (error) {
@@ -21,18 +15,9 @@ const createNetworkCheck = async (networkCheckData) => {
throw error; throw error;
} }
}; };
getNetworkChecksByMonitorId = async (monitorId, limit = 100) => {
/**
* Retrieves a list of network checks for a specific monitor, sorted by most recent.
* @async
* @param {string} monitorId - The ID of the monitor to retrieve checks for.
* @param {number} [limit=100] - The maximum number of checks to return. Defaults to 100.
* @returns {Promise<Array<object>>} A promise that resolves to an array of network check documents.
* @throws {Error} Throws an error if the database operation fails.
*/
const getNetworkChecksByMonitorId = async (monitorId, limit = 100) => {
try { try {
const networkChecks = await NetworkCheck.find({ monitorId }).sort({ createdAt: -1 }).limit(limit); const networkChecks = await this.NetworkCheck.find({ monitorId }).sort({ createdAt: -1 }).limit(limit);
return networkChecks; return networkChecks;
} catch (error) { } catch (error) {
error.service = SERVICE_NAME; error.service = SERVICE_NAME;
@@ -40,5 +25,6 @@ const getNetworkChecksByMonitorId = async (monitorId, limit = 100) => {
throw error; throw error;
} }
}; };
}
export { createNetworkCheck, getNetworkChecksByMonitorId }; export default NetworkCheckModule;
@@ -1,19 +1,15 @@
import Notification from "../../models/Notification.js"; // import Notification from "../../models/Notification.js";
import Monitor from "../../models/Monitor.js"; // import Monitor from "../../models/Monitor.js";
const SERVICE_NAME = "notificationModule"; const SERVICE_NAME = "notificationModule";
/**
* Creates a new notification. class NotificationModule {
* @param {Object} notificationData - The data for the new notification. constructor({ Notification, Monitor }) {
* @param {mongoose.Types.ObjectId} notificationData.monitorId - The ID of the monitor. this.Notification = Notification;
* @param {string} notificationData.type - The type of the notification (e.g., "email", "sms"). this.Monitor = Monitor;
* @param {string} [notificationData.address] - The address for the notification (if applicable). }
* @param {string} [notificationData.phone] - The phone number for the notification (if applicable). createNotification = async (notificationData) => {
* @returns {Promise<Object>} The created notification.
* @throws Will throw an error if the notification cannot be created.
*/
const createNotification = async (notificationData) => {
try { try {
const notification = await new Notification({ ...notificationData }).save(); const notification = await new this.Notification({ ...notificationData }).save();
return notification; return notification;
} catch (error) { } catch (error) {
error.service = SERVICE_NAME; error.service = SERVICE_NAME;
@@ -21,10 +17,9 @@ const createNotification = async (notificationData) => {
throw error; throw error;
} }
}; };
getNotificationsByTeamId = async (teamId) => {
const getNotificationsByTeamId = async (teamId) => {
try { try {
const notifications = await Notification.find({ teamId }); const notifications = await this.Notification.find({ teamId });
return notifications; return notifications;
} catch (error) { } catch (error) {
error.service = SERVICE_NAME; error.service = SERVICE_NAME;
@@ -32,10 +27,9 @@ const getNotificationsByTeamId = async (teamId) => {
throw error; throw error;
} }
}; };
getNotificationsByIds = async (notificationIds) => {
const getNotificationsByIds = async (notificationIds) => {
try { try {
const notifications = await Notification.find({ _id: { $in: notificationIds } }); const notifications = await this.Notification.find({ _id: { $in: notificationIds } });
return notifications; return notifications;
} catch (error) { } catch (error) {
error.service = SERVICE_NAME; error.service = SERVICE_NAME;
@@ -43,16 +37,9 @@ const getNotificationsByIds = async (notificationIds) => {
throw error; throw error;
} }
}; };
getNotificationsByMonitorId = async (monitorId) => {
/**
* Retrieves notifications by monitor ID.
* @param {mongoose.Types.ObjectId} monitorId - The ID of the monitor.
* @returns {Promise<Array<Object>>} An array of notifications.
* @throws Will throw an error if the notifications cannot be retrieved.
*/
const getNotificationsByMonitorId = async (monitorId) => {
try { try {
const notifications = await Notification.find({ monitorId }); const notifications = await this.Notification.find({ monitorId });
return notifications; return notifications;
} catch (error) { } catch (error) {
error.service = SERVICE_NAME; error.service = SERVICE_NAME;
@@ -60,10 +47,9 @@ const getNotificationsByMonitorId = async (monitorId) => {
throw error; throw error;
} }
}; };
deleteNotificationsByMonitorId = async (monitorId) => {
const deleteNotificationsByMonitorId = async (monitorId) => {
try { try {
const result = await Notification.deleteMany({ monitorId }); const result = await this.Notification.deleteMany({ monitorId });
return result.deletedCount; return result.deletedCount;
} catch (error) { } catch (error) {
error.service = SERVICE_NAME; error.service = SERVICE_NAME;
@@ -71,16 +57,15 @@ const deleteNotificationsByMonitorId = async (monitorId) => {
throw error; throw error;
} }
}; };
deleteNotificationById = async (id) => {
const deleteNotificationById = async (id) => {
try { try {
const notification = await Notification.findById(id); const notification = await this.Notification.findById(id);
if (!notification) { if (!notification) {
throw new Error("Notification not found"); throw new Error("Notification not found");
} }
const result = await Notification.findByIdAndDelete(id); const result = await this.Notification.findByIdAndDelete(id);
await Monitor.updateMany({ notifications: id }, { $pull: { notifications: id } }); await this.Monitor.updateMany({ notifications: id }, { $pull: { notifications: id } });
return result; return result;
} catch (error) { } catch (error) {
error.service = SERVICE_NAME; error.service = SERVICE_NAME;
@@ -88,10 +73,9 @@ const deleteNotificationById = async (id) => {
throw error; throw error;
} }
}; };
getNotificationById = async (id) => {
const getNotificationById = async (id) => {
try { try {
const notification = await Notification.findById(id); const notification = await this.Notification.findById(id);
return notification; return notification;
} catch (error) { } catch (error) {
error.service = SERVICE_NAME; error.service = SERVICE_NAME;
@@ -99,10 +83,9 @@ const getNotificationById = async (id) => {
throw error; throw error;
} }
}; };
editNotification = async (id, notificationData) => {
const editNotification = async (id, notificationData) => {
try { try {
const notification = await Notification.findByIdAndUpdate(id, notificationData, { const notification = await this.Notification.findByIdAndUpdate(id, notificationData, {
new: true, new: true,
}); });
return notification; return notification;
@@ -112,14 +95,6 @@ const editNotification = async (id, notificationData) => {
throw error; throw error;
} }
}; };
}
export { export default NotificationModule;
createNotification,
getNotificationsByTeamId,
getNotificationsByIds,
getNotificationsByMonitorId,
deleteNotificationsByMonitorId,
deleteNotificationById,
getNotificationById,
editNotification,
};
@@ -1,32 +1,14 @@
import PageSpeedCheck from "../../models/PageSpeedCheck.js"; // import PageSpeedCheck from "../../models/PageSpeedCheck.js";
const SERVICE_NAME = "pageSpeedCheckModule"; const SERVICE_NAME = "pageSpeedCheckModule";
/**
* Create a PageSpeed check for a monitor class PageSpeedCheckModule {
* @async constructor({ PageSpeedCheck }) {
* @param {Object} pageSpeedCheckData this.PageSpeedCheck = PageSpeedCheck;
* @param {string} pageSpeedCheckData.monitorId
* @param {number} pageSpeedCheckData.accessibility
* @param {number} pageSpeedCheckData.bestPractices
* @param {number} pageSpeedCheckData.seo
* @param {number} pageSpeedCheckData.performance
* @returns {Promise<PageSpeedCheck>}
* @throws {Error}
*/
const createPageSpeedCheck = async (pageSpeedCheckData) => {
try {
const pageSpeedCheck = await new PageSpeedCheck({
...pageSpeedCheckData,
}).save();
return pageSpeedCheck;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "createPageSpeedCheck";
throw error;
} }
};
const createPageSpeedChecks = async (pageSpeedChecks) => { createPageSpeedChecks = async (pageSpeedChecks) => {
try { try {
await PageSpeedCheck.insertMany(pageSpeedChecks, { ordered: false }); await this.PageSpeedCheck.insertMany(pageSpeedChecks, { ordered: false });
return true; return true;
} catch (error) { } catch (error) {
error.service = SERVICE_NAME; error.service = SERVICE_NAME;
@@ -35,17 +17,9 @@ const createPageSpeedChecks = async (pageSpeedChecks) => {
} }
}; };
/** deletePageSpeedChecksByMonitorId = async (monitorId) => {
* Delete all PageSpeed checks for a monitor
* @async
* @param {string} monitorId
* @returns {number}
* @throws {Error}
*/
const deletePageSpeedChecksByMonitorId = async (monitorId) => {
try { try {
const result = await PageSpeedCheck.deleteMany({ monitorId }); const result = await this.PageSpeedCheck.deleteMany({ monitorId });
return result.deletedCount; return result.deletedCount;
} catch (error) { } catch (error) {
error.service = SERVICE_NAME; error.service = SERVICE_NAME;
@@ -53,5 +27,5 @@ const deletePageSpeedChecksByMonitorId = async (monitorId) => {
throw error; throw error;
} }
}; };
}
export { createPageSpeedCheck, createPageSpeedChecks, deletePageSpeedChecksByMonitorId }; export default PageSpeedCheckModule;
+25 -31
View File
@@ -1,25 +1,20 @@
import UserModel from "../../models/User.js";
import RecoveryToken from "../../models/RecoveryToken.js";
import crypto from "crypto";
import serviceRegistry from "../../../service/system/serviceRegistry.js";
import StringService from "../../../service/system/stringService.js";
const SERVICE_NAME = "recoveryModule"; const SERVICE_NAME = "recoveryModule";
/** class RecoveryModule {
* Request a recovery token constructor({ User, RecoveryToken, crypto, stringService }) {
* @async this.User = User;
* @param {string} email this.RecoveryToken = RecoveryToken;
* @returns {Promise<UserModel>} this.crypto = crypto;
* @throws {Error} this.stringService = stringService;
*/ }
const requestRecoveryToken = async (email) => {
requestRecoveryToken = async (email) => {
try { try {
// Delete any existing tokens // Delete any existing tokens
await RecoveryToken.deleteMany({ email }); await this.RecoveryToken.deleteMany({ email });
let recoveryToken = new RecoveryToken({ let recoveryToken = new this.RecoveryToken({
email, email,
token: crypto.randomBytes(32).toString("hex"), token: this.crypto.randomBytes(32).toString("hex"),
}); });
await recoveryToken.save(); await recoveryToken.save();
return recoveryToken; return recoveryToken;
@@ -29,17 +24,15 @@ const requestRecoveryToken = async (email) => {
throw error; throw error;
} }
}; };
validateRecoveryToken = async (candidateToken) => {
const validateRecoveryToken = async (candidateToken) => {
const stringService = serviceRegistry.get(StringService.SERVICE_NAME);
try { try {
const recoveryToken = await RecoveryToken.findOne({ const recoveryToken = await this.RecoveryToken.findOne({
token: candidateToken, token: candidateToken,
}); });
if (recoveryToken !== null) { if (recoveryToken !== null) {
return recoveryToken; return recoveryToken;
} else { } else {
throw new Error(stringService.dbTokenNotFound); throw new Error(this.stringService.dbTokenNotFound);
} }
} catch (error) { } catch (error) {
error.service = SERVICE_NAME; error.service = SERVICE_NAME;
@@ -48,29 +41,29 @@ const validateRecoveryToken = async (candidateToken) => {
} }
}; };
const resetPassword = async (password, candidateToken) => { resetPassword = async (password, candidateToken) => {
const stringService = serviceRegistry.get(StringService.SERVICE_NAME);
try { try {
const newPassword = password; const newPassword = password;
// Validate token again // Validate token again
const recoveryToken = await validateRecoveryToken(candidateToken); const recoveryToken = await this.validateRecoveryToken(candidateToken);
const user = await UserModel.findOne({ email: recoveryToken.email }); const user = await this.User.findOne({ email: recoveryToken.email });
if (user === null) { if (user === null) {
throw new Error(stringService.dbUserNotFound); throw new Error(this.stringService.dbUserNotFound);
} }
const match = await user.comparePassword(newPassword); const match = await user.comparePassword(newPassword);
if (match === true) { if (match === true) {
throw new Error(stringService.dbResetPasswordBadMatch); throw new Error("Password cannot be the same as the old password");
} }
user.password = newPassword; user.password = newPassword;
await user.save(); await user.save();
await RecoveryToken.deleteMany({ email: recoveryToken.email }); await this.RecoveryToken.deleteMany({ email: recoveryToken.email });
// Fetch the user again without the password // Fetch the user again without the password
const userWithoutPassword = await UserModel.findOne({ const userWithoutPassword = await this.User.findOne({
email: recoveryToken.email, email: recoveryToken.email,
}) })
.select("-password") .select("-password")
@@ -82,5 +75,6 @@ const resetPassword = async (password, candidateToken) => {
throw error; throw error;
} }
}; };
}
export { requestRecoveryToken, validateRecoveryToken, resetPassword }; export default RecoveryModule;
+9 -14
View File
@@ -1,18 +1,12 @@
import AppSettings from "../../models/AppSettings.js"; // import AppSettings from "../../models/AppSettings.js";
const SERVICE_NAME = "SettingsModule"; const SERVICE_NAME = "SettingsModule";
const getAppSettings = async () => { class SettingsModule {
try { constructor({ AppSettings }) {
const settings = AppSettings.findOne(); this.AppSettings = AppSettings;
return settings;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "getSettings";
throw error;
} }
};
const updateAppSettings = async (newSettings) => { updateAppSettings = async (newSettings) => {
try { try {
const update = { $set: { ...newSettings } }; const update = { $set: { ...newSettings } };
@@ -26,10 +20,10 @@ const updateAppSettings = async (newSettings) => {
delete update.$set.systemEmailPassword; delete update.$set.systemEmailPassword;
} }
await AppSettings.findOneAndUpdate({}, update, { await this.AppSettings.findOneAndUpdate({}, update, {
upsert: true, upsert: true,
}); });
const settings = await AppSettings.findOne().select("-__v -_id -createdAt -updatedAt -singleton").lean(); const settings = await this.AppSettings.findOne().select("-__v -_id -createdAt -updatedAt -singleton").lean();
return settings; return settings;
} catch (error) { } catch (error) {
error.service = SERVICE_NAME; error.service = SERVICE_NAME;
@@ -37,5 +31,6 @@ const updateAppSettings = async (newSettings) => {
throw error; throw error;
} }
}; };
}
export { getAppSettings, updateAppSettings }; export default SettingsModule;
+31 -36
View File
@@ -1,15 +1,20 @@
import StatusPage from "../../models/StatusPage.js"; // import StatusPage from "../../models/StatusPage.js";
import { NormalizeData } from "../../../utils/dataUtils.js"; // import { NormalizeData } from "../../../utils/dataUtils.js";
import ServiceRegistry from "../../../service/system/serviceRegistry.js"; // import ServiceRegistry from "../../../service/system/serviceRegistry.js";
import StringService from "../../../service/system/stringService.js"; // import StringService from "../../../service/system/stringService.js";
const SERVICE_NAME = "statusPageModule"; const SERVICE_NAME = "statusPageModule";
const createStatusPage = async ({ statusPageData, image, userId, teamId }) => { class StatusPageModule {
const stringService = ServiceRegistry.get(StringService.SERVICE_NAME); constructor({ StatusPage, NormalizeData, stringService }) {
this.StatusPage = StatusPage;
this.NormalizeData = NormalizeData;
this.stringService = stringService;
}
createStatusPage = async ({ statusPageData, image, userId, teamId }) => {
try { try {
const statusPage = new StatusPage({ const statusPage = new this.StatusPage({
...statusPageData, ...statusPageData,
userId, userId,
teamId, teamId,
@@ -26,7 +31,7 @@ const createStatusPage = async ({ statusPageData, image, userId, teamId }) => {
if (error?.code === 11000) { if (error?.code === 11000) {
// Handle duplicate URL errors // Handle duplicate URL errors
error.status = 400; error.status = 400;
error.message = stringService.statusPageUrlNotUnique; error.message = this.stringService.statusPageUrlNotUnique;
} }
error.service = SERVICE_NAME; error.service = SERVICE_NAME;
error.method = "createStatusPage"; error.method = "createStatusPage";
@@ -34,7 +39,7 @@ const createStatusPage = async ({ statusPageData, image, userId, teamId }) => {
} }
}; };
const updateStatusPage = async (statusPageData, image) => { updateStatusPage = async (statusPageData, image) => {
try { try {
if (image) { if (image) {
statusPageData.logo = { statusPageData.logo = {
@@ -48,7 +53,7 @@ const updateStatusPage = async (statusPageData, image) => {
if (statusPageData.deleteSubmonitors === "true") { if (statusPageData.deleteSubmonitors === "true") {
statusPageData.subMonitors = []; statusPageData.subMonitors = [];
} }
const statusPage = await StatusPage.findOneAndUpdate({ url: statusPageData.url }, statusPageData, { const statusPage = await this.StatusPage.findOneAndUpdate({ url: statusPageData.url }, statusPageData, {
new: true, new: true,
}); });
@@ -60,10 +65,10 @@ const updateStatusPage = async (statusPageData, image) => {
} }
}; };
const getStatusPageByUrl = async (url, type) => { getStatusPageByUrl = async (url) => {
// TODO This is deprecated, can remove and have controller call getStatusPage // TODO This is deprecated, can remove and have controller call getStatusPage
try { try {
return getStatusPage(url); return this.getStatusPage(url);
} catch (error) { } catch (error) {
error.service = SERVICE_NAME; error.service = SERVICE_NAME;
error.method = "getStatusPageByUrl"; error.method = "getStatusPageByUrl";
@@ -71,9 +76,9 @@ const getStatusPageByUrl = async (url, type) => {
} }
}; };
const getStatusPagesByTeamId = async (teamId) => { getStatusPagesByTeamId = async (teamId) => {
try { try {
const statusPages = await StatusPage.find({ teamId }); const statusPages = await this.StatusPage.find({ teamId });
return statusPages; return statusPages;
} catch (error) { } catch (error) {
error.service = SERVICE_NAME; error.service = SERVICE_NAME;
@@ -82,13 +87,11 @@ const getStatusPagesByTeamId = async (teamId) => {
} }
}; };
const getStatusPage = async (url) => { getStatusPage = async (url) => {
const stringService = ServiceRegistry.get(StringService.SERVICE_NAME);
try { try {
const preliminaryStatusPage = await StatusPage.findOne({ url }); const preliminaryStatusPage = await this.StatusPage.findOne({ url });
if (!preliminaryStatusPage) { if (!preliminaryStatusPage) {
const error = new Error(stringService.statusPageNotFound); const error = new Error(this.stringService.statusPageNotFound);
error.status = 404; error.status = 404;
throw error; throw error;
} }
@@ -114,7 +117,7 @@ const getStatusPage = async (url) => {
}; };
} }
const statusPageQuery = await StatusPage.aggregate([ const statusPageQuery = await this.StatusPage.aggregate([
{ $match: { url: url } }, { $match: { url: url } },
{ {
$set: { $set: {
@@ -239,7 +242,7 @@ const getStatusPage = async (url) => {
}, },
]); ]);
if (!statusPageQuery.length) { if (!statusPageQuery.length) {
const error = new Error(stringService.statusPageNotFound); const error = new Error(this.stringService.statusPageNotFound);
error.status = 404; error.status = 404;
throw error; throw error;
} }
@@ -249,7 +252,7 @@ const getStatusPage = async (url) => {
const normalizedMonitors = monitors.map((monitor) => { const normalizedMonitors = monitors.map((monitor) => {
return { return {
...monitor, ...monitor,
checks: NormalizeData(monitor.checks, 10, 100), checks: this.NormalizeData(monitor.checks, 10, 100),
}; };
}); });
@@ -261,32 +264,24 @@ const getStatusPage = async (url) => {
} }
}; };
const deleteStatusPage = async (url) => { deleteStatusPage = async (url) => {
try { try {
await StatusPage.deleteOne({ url }); await this.StatusPage.deleteOne({ url });
} catch (error) { } catch (error) {
error.service = SERVICE_NAME; error.service = SERVICE_NAME;
error.method = "deleteStatusPage"; error.method = "deleteStatusPage";
throw error; throw error;
} }
}; };
deleteStatusPagesByMonitorId = async (monitorId) => {
const deleteStatusPagesByMonitorId = async (monitorId) => {
try { try {
await StatusPage.deleteMany({ monitors: { $in: [monitorId] } }); await this.StatusPage.deleteMany({ monitors: { $in: [monitorId] } });
} catch (error) { } catch (error) {
error.service = SERVICE_NAME; error.service = SERVICE_NAME;
error.method = "deleteStatusPageByMonitorId"; error.method = "deleteStatusPageByMonitorId";
throw error; throw error;
} }
}; };
}
export { export default StatusPageModule;
createStatusPage,
updateStatusPage,
getStatusPagesByTeamId,
getStatusPage,
getStatusPageByUrl,
deleteStatusPage,
deleteStatusPagesByMonitorId,
};
+42 -132
View File
@@ -1,31 +1,30 @@
import UserModel from "../../models/User.js";
import TeamModel from "../../models/Team.js";
import { GenerateAvatarImage } from "../../../utils/imageProcessing.js";
const DUPLICATE_KEY_CODE = 11000; // MongoDB error code for duplicate key
import { ParseBoolean } from "../../../utils/utils.js";
import ServiceRegistry from "../../../service/system/serviceRegistry.js";
import StringService from "../../../service/system/stringService.js";
const SERVICE_NAME = "userModule"; const SERVICE_NAME = "userModule";
const DUPLICATE_KEY_CODE = 11000; // MongoDB error code for duplicate key
const checkSuperadmin = async () => { class UserModule {
const superAdmin = await UserModel.findOne({ role: "superadmin" }); constructor({ User, Team, GenerateAvatarImage, ParseBoolean, stringService }) {
this.User = User;
this.Team = Team;
this.GenerateAvatarImage = GenerateAvatarImage;
this.ParseBoolean = ParseBoolean;
this.stringService = stringService;
}
checkSuperadmin = async () => {
try {
const superAdmin = await this.User.findOne({ role: "superadmin" });
if (superAdmin !== null) { if (superAdmin !== null) {
return true; return true;
} }
return false; return false;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "checkSuperadmin";
throw error;
}
}; };
/** insertUser = async (userData, imageFile) => {
* Insert a User
* @async
* @param {Express.Request} req
* @param {Express.Response} res
* @returns {Promise<UserModel>}
* @throws {Error}
*/
const insertUser = async (userData, imageFile, generateAvatarImage = GenerateAvatarImage) => {
const stringService = ServiceRegistry.get(StringService.SERVICE_NAME);
try { try {
if (imageFile) { if (imageFile) {
// 1. Save the full size image // 1. Save the full size image
@@ -35,13 +34,13 @@ const insertUser = async (userData, imageFile, generateAvatarImage = GenerateAva
}; };
// 2. Get the avatar sized image // 2. Get the avatar sized image
const avatar = await generateAvatarImage(imageFile); const avatar = await this.GenerateAvatarImage(imageFile);
userData.avatarImage = avatar; userData.avatarImage = avatar;
} }
// Handle creating team if superadmin // Handle creating team if superadmin
if (userData.role.includes("superadmin")) { if (userData.role.includes("superadmin")) {
const team = new TeamModel({ const team = new this.Team({
email: userData.email, email: userData.email,
}); });
userData.teamId = team._id; userData.teamId = team._id;
@@ -49,39 +48,25 @@ const insertUser = async (userData, imageFile, generateAvatarImage = GenerateAva
await team.save(); await team.save();
} }
const newUser = new UserModel(userData); const newUser = new this.User(userData);
await newUser.save(); await newUser.save();
return await UserModel.findOne({ _id: newUser._id }).select("-password").select("-profileImage"); // .select() doesn't work with create, need to save then find return await this.User.findOne({ _id: newUser._id }).select("-password").select("-profileImage"); // .select() doesn't work with create, need to save then find
} catch (error) { } catch (error) {
if (error.code === DUPLICATE_KEY_CODE) { if (error.code === DUPLICATE_KEY_CODE) {
error.message = stringService.dbUserExists; error.message = this.stringService.dbUserExists;
} }
error.service = SERVICE_NAME; error.service = SERVICE_NAME;
error.method = "insertUser"; error.method = "insertUser";
throw error; throw error;
} }
}; };
getUserByEmail = async (email) => {
/**
* Get User by Email
* Gets a user by Email. Not sure if we'll ever need this except for login.
* If not needed except for login, we can move password comparison here
* Throws error if user not found
* @async
* @param {Express.Request} req
* @param {Express.Response} res
* @returns {Promise<UserModel>}
* @throws {Error}
*/
const getUserByEmail = async (email) => {
const stringService = ServiceRegistry.get(StringService.SERVICE_NAME);
try { try {
// Need the password to be able to compare, removed .select() // Need the password to be able to compare, removed .select()
// We can strip the hash before returning the user // We can strip the hash before returning the user
const user = await UserModel.findOne({ email: email }).select("-profileImage"); const user = await this.User.findOne({ email: email }).select("-profileImage");
if (!user) { if (!user) {
throw new Error(stringService.dbUserNotFound); throw new Error(this.stringService.dbUserNotFound);
} }
return user; return user;
} catch (error) { } catch (error) {
@@ -91,16 +76,7 @@ const getUserByEmail = async (email) => {
} }
}; };
/** updateUser = async ({ userId, user, file }) => {
* Update a user by ID
* @async
* @param {Express.Request} req
* @param {Express.Response} res
* @returns {Promise<UserModel>}
* @throws {Error}
*/
const updateUser = async ({ userId, user, file }) => {
if (!userId) { if (!userId) {
throw new Error("No user in request"); throw new Error("No user in request");
} }
@@ -108,7 +84,7 @@ const updateUser = async ({ userId, user, file }) => {
try { try {
const candidateUser = { ...user }; const candidateUser = { ...user };
if (ParseBoolean(candidateUser.deleteProfileImage) === true) { if (this.ParseBoolean(candidateUser.deleteProfileImage) === true) {
candidateUser.profileImage = null; candidateUser.profileImage = null;
candidateUser.avatarImage = null; candidateUser.avatarImage = null;
} else if (file) { } else if (file) {
@@ -119,15 +95,11 @@ const updateUser = async ({ userId, user, file }) => {
}; };
// 2. Get the avatar sized image // 2. Get the avatar sized image
const avatar = await GenerateAvatarImage(file); const avatar = await this.GenerateAvatarImage(file);
candidateUser.avatarImage = avatar; candidateUser.avatarImage = avatar;
} }
// ****************************************** const updatedUser = await this.User.findByIdAndUpdate(
// End handling profile image
// ******************************************
const updatedUser = await UserModel.findByIdAndUpdate(
userId, userId,
candidateUser, candidateUser,
{ new: true } // Returns updated user instead of pre-update user { new: true } // Returns updated user instead of pre-update user
@@ -141,22 +113,11 @@ const updateUser = async ({ userId, user, file }) => {
throw error; throw error;
} }
}; };
deleteUser = async (userId) => {
/**
* Delete a user by ID
* @async
* @param {Express.Request} req
* @param {Express.Response} res
* @returns {Promise<UserModel>}
* @throws {Error}
*/
const deleteUser = async (userId) => {
const stringService = ServiceRegistry.get(StringService.SERVICE_NAME);
try { try {
const deletedUser = await UserModel.findByIdAndDelete(userId); const deletedUser = await this.User.findByIdAndDelete(userId);
if (!deletedUser) { if (!deletedUser) {
throw new Error(stringService.dbUserNotFound); throw new Error(this.stringService.dbUserNotFound);
} }
return deletedUser; return deletedUser;
} catch (error) { } catch (error) {
@@ -166,38 +127,9 @@ const deleteUser = async (userId) => {
} }
}; };
/** getAllUsers = async () => {
* Delete a user by ID
* @async
* @param {string} teamId
* @returns {void}
* @throws {Error}
*/
const deleteTeam = async (teamId) => {
try { try {
await TeamModel.findByIdAndDelete(teamId); const users = await this.User.find().select("-password").select("-profileImage");
return true;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "deleteTeam";
throw error;
}
};
const deleteAllOtherUsers = async () => {
try {
await UserModel.deleteMany({ role: { $ne: "superadmin" } });
return true;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "deleteAllOtherUsers";
throw error;
}
};
const getAllUsers = async () => {
try {
const users = await UserModel.find().select("-password").select("-profileImage");
return users; return users;
} catch (error) { } catch (error) {
error.service = SERVICE_NAME; error.service = SERVICE_NAME;
@@ -206,24 +138,13 @@ const getAllUsers = async () => {
} }
}; };
const logoutUser = async (userId) => { getUserById = async (roles, userId) => {
try {
await UserModel.updateOne({ _id: userId }, { $unset: { authToken: null } });
return true;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "logoutUser";
throw error;
}
};
const getUserById = async (roles, userId) => {
try { try {
if (!roles.includes("superadmin")) { if (!roles.includes("superadmin")) {
throw new Error("User is not a superadmin"); throw new Error("User is not a superadmin");
} }
const user = await UserModel.findById(userId).select("-password").select("-profileImage"); const user = await this.User.findById(userId).select("-password").select("-profileImage");
if (!user) { if (!user) {
throw new Error("User not found"); throw new Error("User not found");
} }
@@ -236,26 +157,15 @@ const getUserById = async (roles, userId) => {
} }
}; };
const editUserById = async (userId, user) => { editUserById = async (userId, user) => {
try { try {
await UserModel.findByIdAndUpdate(userId, user, { new: true }).select("-password").select("-profileImage"); await this.User.findByIdAndUpdate(userId, user, { new: true }).select("-password").select("-profileImage");
} catch (error) { } catch (error) {
error.service = SERVICE_NAME; error.service = SERVICE_NAME;
error.method = "editUserById"; error.method = "editUserById";
throw error; throw error;
} }
}; };
}
export { export default UserModule;
checkSuperadmin,
insertUser,
getUserByEmail,
updateUser,
deleteUser,
deleteTeam,
deleteAllOtherUsers,
getAllUsers,
logoutUser,
getUserById,
editUserById,
};
+3 -3
View File
@@ -23,7 +23,7 @@ class CheckService {
throw this.errorService.createBadRequestError("No team ID in request"); throw this.errorService.createBadRequestError("No team ID in request");
} }
const monitor = await this.db.getMonitorById(monitorId); const monitor = await this.db.monitorModule.getMonitorById(monitorId);
if (!monitor) { if (!monitor) {
throw this.errorService.createNotFoundError("Monitor not found"); throw this.errorService.createNotFoundError("Monitor not found");
@@ -95,7 +95,7 @@ class CheckService {
throw this.errorService.createBadRequestError("No monitor ID in request"); throw this.errorService.createBadRequestError("No monitor ID in request");
} }
const monitor = await this.db.getMonitorById(monitorId); const monitor = await this.db.monitorModule.getMonitorById(monitorId);
if (!monitor) { if (!monitor) {
throw this.errorService.createNotFoundError("Monitor not found"); throw this.errorService.createNotFoundError("Monitor not found");
} }
@@ -118,7 +118,7 @@ class CheckService {
throw this.errorService.createBadRequestError("No team ID in request"); throw this.errorService.createBadRequestError("No team ID in request");
} }
const monitor = await this.db.getMonitorById(monitorId); const monitor = await this.db.monitorModule.getMonitorById(monitorId);
if (!monitor) { if (!monitor) {
throw this.errorService.createNotFoundError("Monitor not found"); throw this.errorService.createNotFoundError("Monitor not found");
+3 -3
View File
@@ -17,12 +17,12 @@ class InviteService {
getInviteToken = async ({ invite, teamId }) => { getInviteToken = async ({ invite, teamId }) => {
invite.teamId = teamId; invite.teamId = teamId;
const inviteToken = await this.db.requestInviteToken(invite); const inviteToken = await this.db.inviteModule.requestInviteToken(invite);
return inviteToken; return inviteToken;
}; };
sendInviteEmail = async ({ inviteRequest, firstName }) => { sendInviteEmail = async ({ inviteRequest, firstName }) => {
const inviteToken = await this.db.requestInviteToken({ ...inviteRequest }); const inviteToken = await this.db.inviteModule.requestInviteToken({ ...inviteRequest });
const { clientHost } = this.settingsService.getSettings(); const { clientHost } = this.settingsService.getSettings();
const html = await this.emailService.buildEmail("employeeActivationTemplate", { const html = await this.emailService.buildEmail("employeeActivationTemplate", {
@@ -36,7 +36,7 @@ class InviteService {
}; };
verifyInviteToken = async ({ inviteToken }) => { verifyInviteToken = async ({ inviteToken }) => {
const invite = await this.db.getInviteToken(inviteToken); const invite = await this.db.inviteModule.getInviteToken(inviteToken);
return invite; return invite;
}; };
} }
@@ -16,7 +16,7 @@ class MaintenanceWindowService {
createMaintenanceWindow = async ({ teamId, body }) => { createMaintenanceWindow = async ({ teamId, body }) => {
const monitorIds = body.monitors; const monitorIds = body.monitors;
const monitors = await this.db.getMonitorsByIds(monitorIds); const monitors = await this.db.monitorModule.getMonitorsByIds(monitorIds);
const unauthorizedMonitors = monitors.filter((monitor) => !monitor.teamId.equals(teamId)); const unauthorizedMonitors = monitors.filter((monitor) => !monitor.teamId.equals(teamId));
@@ -25,7 +25,7 @@ class MaintenanceWindowService {
} }
const dbTransactions = monitorIds.map((monitorId) => { const dbTransactions = monitorIds.map((monitorId) => {
return this.db.createMaintenanceWindow({ return this.db.maintenanceWindowModule.createMaintenanceWindow({
teamId, teamId,
monitorId, monitorId,
name: body.name, name: body.name,
@@ -39,26 +39,26 @@ class MaintenanceWindowService {
}; };
getMaintenanceWindowById = async ({ id, teamId }) => { getMaintenanceWindowById = async ({ id, teamId }) => {
const maintenanceWindow = await this.db.getMaintenanceWindowById({ id, teamId }); const maintenanceWindow = await this.db.maintenanceWindowModule.getMaintenanceWindowById({ id, teamId });
return maintenanceWindow; return maintenanceWindow;
}; };
getMaintenanceWindowsByTeamId = async ({ teamId, query }) => { getMaintenanceWindowsByTeamId = async ({ teamId, query }) => {
const maintenanceWindows = await this.db.getMaintenanceWindowsByTeamId(teamId, query); const maintenanceWindows = await this.db.maintenanceWindowModule.getMaintenanceWindowsByTeamId(teamId, query);
return maintenanceWindows; return maintenanceWindows;
}; };
getMaintenanceWindowsByMonitorId = async ({ monitorId, teamId }) => { getMaintenanceWindowsByMonitorId = async ({ monitorId, teamId }) => {
const maintenanceWindows = await this.db.getMaintenanceWindowsByMonitorId({ monitorId, teamId }); const maintenanceWindows = await this.db.maintenanceWindowModule.getMaintenanceWindowsByMonitorId({ monitorId, teamId });
return maintenanceWindows; return maintenanceWindows;
}; };
deleteMaintenanceWindow = async ({ id, teamId }) => { deleteMaintenanceWindow = async ({ id, teamId }) => {
await this.db.deleteMaintenanceWindowById({ id, teamId }); await this.db.maintenanceWindowModule.deleteMaintenanceWindowById({ id, teamId });
}; };
editMaintenanceWindow = async ({ id, teamId, body }) => { editMaintenanceWindow = async ({ id, teamId, body }) => {
const editedMaintenanceWindow = await this.db.editMaintenanceWindowById({ id, body, teamId }); const editedMaintenanceWindow = await this.db.maintenanceWindowModule.editMaintenanceWindowById({ id, body, teamId });
return editedMaintenanceWindow; return editedMaintenanceWindow;
}; };
} }
+20 -20
View File
@@ -20,20 +20,20 @@ class MonitorService {
} }
verifyTeamAccess = async ({ teamId, monitorId }) => { verifyTeamAccess = async ({ teamId, monitorId }) => {
const monitor = await this.db.getMonitorById(monitorId); const monitor = await this.db.monitorModule.getMonitorById(monitorId);
if (!monitor?.teamId?.equals(teamId)) { if (!monitor?.teamId?.equals(teamId)) {
throw this.errorService.createAuthorizationError(); throw this.errorService.createAuthorizationError();
} }
}; };
getAllMonitors = async () => { getAllMonitors = async () => {
const monitors = await this.db.getAllMonitors(); const monitors = await this.db.monitorModule.getAllMonitors();
return monitors; return monitors;
}; };
getUptimeDetailsById = async ({ teamId, monitorId, dateRange, normalize }) => { getUptimeDetailsById = async ({ teamId, monitorId, dateRange, normalize }) => {
await this.verifyTeamAccess({ teamId, monitorId }); await this.verifyTeamAccess({ teamId, monitorId });
const data = await this.db.getUptimeDetailsById({ const data = await this.db.monitorModule.getUptimeDetailsById({
monitorId, monitorId,
dateRange, dateRange,
normalize, normalize,
@@ -44,7 +44,7 @@ class MonitorService {
getMonitorStatsById = async ({ teamId, monitorId, limit, sortOrder, dateRange, numToDisplay, normalize }) => { getMonitorStatsById = async ({ teamId, monitorId, limit, sortOrder, dateRange, numToDisplay, normalize }) => {
await this.verifyTeamAccess({ teamId, monitorId }); await this.verifyTeamAccess({ teamId, monitorId });
const monitorStats = await this.db.getMonitorStatsById({ const monitorStats = await this.db.monitorModule.getMonitorStatsById({
monitorId, monitorId,
limit, limit,
sortOrder, sortOrder,
@@ -58,20 +58,20 @@ class MonitorService {
getHardwareDetailsById = async ({ teamId, monitorId, dateRange }) => { getHardwareDetailsById = async ({ teamId, monitorId, dateRange }) => {
await this.verifyTeamAccess({ teamId, monitorId }); await this.verifyTeamAccess({ teamId, monitorId });
const monitor = await this.db.getHardwareDetailsById({ monitorId, dateRange }); const monitor = await this.db.monitorModule.getHardwareDetailsById({ monitorId, dateRange });
return monitor; return monitor;
}; };
getMonitorById = async ({ teamId, monitorId }) => { getMonitorById = async ({ teamId, monitorId }) => {
await this.verifyTeamAccess({ teamId, monitorId }); await this.verifyTeamAccess({ teamId, monitorId });
const monitor = await this.db.getMonitorById(monitorId); const monitor = await this.db.monitorModule.getMonitorById(monitorId);
return monitor; return monitor;
}; };
createMonitor = async ({ teamId, userId, body }) => { createMonitor = async ({ teamId, userId, body }) => {
const monitor = await this.db.createMonitor({ const monitor = await this.db.monitorModule.createMonitor({
body, body,
teamId, teamId,
userId, userId,
@@ -122,7 +122,7 @@ class MonitorService {
await createMonitorsBodyValidation.validateAsync(enrichedData); await createMonitorsBodyValidation.validateAsync(enrichedData);
const monitors = await this.db.createBulkMonitors(enrichedData); const monitors = await this.db.monitorModule.createBulkMonitors(enrichedData);
await Promise.all( await Promise.all(
monitors.map(async (monitor) => { monitors.map(async (monitor) => {
@@ -141,21 +141,21 @@ class MonitorService {
deleteMonitor = async ({ teamId, monitorId }) => { deleteMonitor = async ({ teamId, monitorId }) => {
await this.verifyTeamAccess({ teamId, monitorId }); await this.verifyTeamAccess({ teamId, monitorId });
const monitor = await this.db.deleteMonitor({ teamId, monitorId }); const monitor = await this.db.monitorModule.deleteMonitor({ teamId, monitorId });
await this.jobQueue.deleteJob(monitor); await this.jobQueue.deleteJob(monitor);
await this.db.deleteStatusPagesByMonitorId(monitor._id); await this.db.statusPageModule.deleteStatusPagesByMonitorId(monitor._id);
return monitor; return monitor;
}; };
deleteAllMonitors = async ({ teamId }) => { deleteAllMonitors = async ({ teamId }) => {
const { monitors, deletedCount } = await this.db.deleteAllMonitors(teamId); const { monitors, deletedCount } = await this.db.monitorModule.deleteAllMonitors(teamId);
await Promise.all( await Promise.all(
monitors.map(async (monitor) => { monitors.map(async (monitor) => {
try { try {
await this.jobQueue.deleteJob(monitor); await this.jobQueue.deleteJob(monitor);
await this.db.checkModule.deleteChecks(monitor._id); await this.db.checkModule.deleteChecks(monitor._id);
await this.db.deletePageSpeedChecksByMonitorId(monitor._id); await this.db.pageSpeedCheckModule.deletePageSpeedChecksByMonitorId(monitor._id);
await this.db.deleteNotificationsByMonitorId(monitor._id); await this.db.notificationsModule.deleteNotificationsByMonitorId(monitor._id);
} catch (error) { } catch (error) {
this.logger.warn({ this.logger.warn({
message: `Error deleting associated records for monitor ${monitor._id} with name ${monitor.name}`, message: `Error deleting associated records for monitor ${monitor._id} with name ${monitor.name}`,
@@ -171,19 +171,19 @@ class MonitorService {
editMonitor = async ({ teamId, monitorId, body }) => { editMonitor = async ({ teamId, monitorId, body }) => {
await this.verifyTeamAccess({ teamId, monitorId }); await this.verifyTeamAccess({ teamId, monitorId });
const editedMonitor = await this.db.editMonitor({ monitorId, body }); const editedMonitor = await this.db.monitorModule.editMonitor({ monitorId, body });
await this.jobQueue.updateJob(editedMonitor); await this.jobQueue.updateJob(editedMonitor);
}; };
pauseMonitor = async ({ teamId, monitorId }) => { pauseMonitor = async ({ teamId, monitorId }) => {
await this.verifyTeamAccess({ teamId, monitorId }); await this.verifyTeamAccess({ teamId, monitorId });
const monitor = await this.db.pauseMonitor({ monitorId }); const monitor = await this.db.monitorModule.pauseMonitor({ monitorId });
monitor.isActive === true ? await this.jobQueue.resumeJob(monitor._id, monitor) : await this.jobQueue.pauseJob(monitor); monitor.isActive === true ? await this.jobQueue.resumeJob(monitor._id, monitor) : await this.jobQueue.pauseJob(monitor);
return monitor; return monitor;
}; };
addDemoMonitors = async ({ userId, teamId }) => { addDemoMonitors = async ({ userId, teamId }) => {
const demoMonitors = await this.db.addDemoMonitors(userId, teamId); const demoMonitors = await this.db.monitorModuleaddDemoMonitors(userId, teamId);
await Promise.all(demoMonitors.map((monitor) => this.jobQueue.addJob(monitor._id, monitor))); await Promise.all(demoMonitors.map((monitor) => this.jobQueue.addJob(monitor._id, monitor)));
return demoMonitors; return demoMonitors;
}; };
@@ -203,7 +203,7 @@ class MonitorService {
}; };
getMonitorsByTeamId = async ({ teamId, limit, type, page, rowsPerPage, filter, field, order }) => { getMonitorsByTeamId = async ({ teamId, limit, type, page, rowsPerPage, filter, field, order }) => {
const monitors = await this.db.getMonitorsByTeamId({ const monitors = await this.db.monitorModule.getMonitorsByTeamId({
limit, limit,
type, type,
page, page,
@@ -217,7 +217,7 @@ class MonitorService {
}; };
getMonitorsAndSummaryByTeamId = async ({ teamId, type, explain }) => { getMonitorsAndSummaryByTeamId = async ({ teamId, type, explain }) => {
const result = await this.db.getMonitorsAndSummaryByTeamId({ const result = await this.db.monitorModule.getMonitorsAndSummaryByTeamId({
type, type,
explain, explain,
teamId, teamId,
@@ -226,7 +226,7 @@ class MonitorService {
}; };
getMonitorsWithChecksByTeamId = async ({ teamId, limit, type, page, rowsPerPage, filter, field, order, explain }) => { getMonitorsWithChecksByTeamId = async ({ teamId, limit, type, page, rowsPerPage, filter, field, order, explain }) => {
const result = await this.db.getMonitorsWithChecksByTeamId({ const result = await this.db.monitorModule.getMonitorsWithChecksByTeamId({
limit, limit,
type, type,
page, page,
@@ -241,7 +241,7 @@ class MonitorService {
}; };
exportMonitorsToCSV = async ({ teamId }) => { exportMonitorsToCSV = async ({ teamId }) => {
const monitors = await this.db.getMonitorsByTeamId({ teamId }); const monitors = await this.db.monitorModule.getMonitorsByTeamId({ teamId });
if (!monitors || monitors.length === 0) { if (!monitors || monitors.length === 0) {
throw this.errorService.createNotFoundError("No monitors to export"); throw this.errorService.createNotFoundError("No monitors to export");
+18 -18
View File
@@ -29,18 +29,18 @@ class UserService {
registerUser = async (user, file) => { registerUser = async (user, file) => {
// Create a new user // Create a new user
// 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 this.db.checkSuperadmin(); const superAdminExists = await this.db.userModule.checkSuperadmin();
if (superAdminExists) { if (superAdminExists) {
const invitedUser = await this.db.getInviteTokenAndDelete(user.inviteToken); const invitedUser = await this.db.inviteModule.getInviteTokenAndDelete(user.inviteToken);
user.role = invitedUser.role; user.role = invitedUser.role;
user.teamId = invitedUser.teamId; user.teamId = invitedUser.teamId;
} 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 = this.crypto.randomBytes(64).toString("hex");
await this.db.updateAppSettings({ jwtSecret }); await this.db.settingsModule.updateAppSettings({ jwtSecret });
} }
const newUser = await this.db.insertUser({ ...user }, file); const newUser = await this.db.userModule.insertUser({ ...user }, file);
this.logger.debug({ this.logger.debug({
message: "New user created", message: "New user created",
@@ -83,7 +83,7 @@ class UserService {
loginUser = async (email, password) => { loginUser = async (email, password) => {
// Check if user exists // Check if user exists
const user = await this.db.getUserByEmail(email); const user = await this.db.userModule.getUserByEmail(email);
// Compare password // Compare password
const match = await user.comparePassword(password); const match = await user.comparePassword(password);
if (match !== true) { if (match !== true) {
@@ -110,7 +110,7 @@ class UserService {
// Add user email to body for DB operation // Add user email to body for DB operation
updates.email = currentUser.email; updates.email = currentUser.email;
// Get user // Get user
const user = await this.db.getUserByEmail(currentUser.email); const user = await this.db.userModule.getUserByEmail(currentUser.email);
// Compare passwords // Compare passwords
const match = await user.comparePassword(updates?.password); const match = await user.comparePassword(updates?.password);
// If not a match, throw a 403 // If not a match, throw a 403
@@ -122,18 +122,18 @@ class UserService {
updates.password = updates.newPassword; updates.password = updates.newPassword;
} }
const updatedUser = await this.db.updateUser({ userId: currentUser?._id, user: updates, file: file }); const updatedUser = await this.db.userModule.updateUser({ userId: currentUser?._id, user: updates, file: file });
return updatedUser; return updatedUser;
}; };
checkSuperadminExists = async () => { checkSuperadminExists = async () => {
const superAdminExists = await this.db.checkSuperadmin(); const superAdminExists = await this.db.userModule.checkSuperadmin();
return superAdminExists; return superAdminExists;
}; };
requestRecovery = async (email) => { requestRecovery = async (email) => {
const user = await this.db.getUserByEmail(email); const user = await this.db.userModule.getUserByEmail(email);
const recoveryToken = await this.db.requestRecoveryToken(email); const recoveryToken = await this.db.recoveryModule.requestRecoveryToken(email);
const name = user.firstName; const name = user.firstName;
const { clientHost } = this.settingsService.getSettings(); const { clientHost } = this.settingsService.getSettings();
const url = `${clientHost}/set-new-password/${recoveryToken.token}`; const url = `${clientHost}/set-new-password/${recoveryToken.token}`;
@@ -148,11 +148,11 @@ class UserService {
}; };
validateRecovery = async (recoveryToken) => { validateRecovery = async (recoveryToken) => {
await this.db.validateRecoveryToken(recoveryToken); await this.db.recoveryModule.validateRecoveryToken(recoveryToken);
}; };
resetPassword = async (password, recoveryToken) => { resetPassword = async (password, recoveryToken) => {
const user = await this.db.resetPassword(password, recoveryToken); const user = await this.db.recoveryModule.resetPassword(password, recoveryToken);
const appSettings = await this.settingsService.getSettings(); const appSettings = await this.settingsService.getSettings();
const token = this.issueToken(user._doc, appSettings); const token = this.issueToken(user._doc, appSettings);
return { user, token }; return { user, token };
@@ -181,7 +181,7 @@ class UserService {
} }
// 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 this.db.getMonitorsByTeamId({ const result = await this.db.monitorModule.getMonitorsByTeamId({
teamId: teamId, teamId: teamId,
}); });
@@ -195,21 +195,21 @@ class UserService {
)); ));
} }
// 6. Delete the user by id // 6. Delete the user by id
await this.db.deleteUser(userId); await this.db.userModule.deleteUser(userId);
}; };
getAllUsers = async () => { getAllUsers = async () => {
const users = await this.db.getAllUsers(); const users = await this.db.userModule.getAllUsers();
return users; return users;
}; };
getUserById = async (roles, userId) => { getUserById = async (roles, userId) => {
const user = await this.db.getUserById(roles, userId); const user = await this.db.userModule.getUserById(roles, userId);
return user; return user;
}; };
editUserById = async (userId, user) => { editUserById = async (userId, user) => {
await this.db.editUserById(userId, user); await this.db.userModule.editUserById(userId, user);
}; };
} }
export default UserService; export default UserService;
@@ -33,7 +33,7 @@ class SuperSimpleQueue {
this.scheduler.start(); this.scheduler.start();
this.scheduler.addTemplate("monitor-job", this.helper.getMonitorJob()); this.scheduler.addTemplate("monitor-job", this.helper.getMonitorJob());
const monitors = await this.db.getAllMonitors(); const monitors = await this.db.monitorModule.getAllMonitors();
for (const monitor of monitors) { for (const monitor of monitors) {
await this.addJob(monitor._id, monitor); await this.addJob(monitor._id, monitor);
} }
@@ -67,7 +67,7 @@ class SuperSimpleQueueHelper {
}; };
async isInMaintenanceWindow(monitorId) { async isInMaintenanceWindow(monitorId) {
const maintenanceWindows = await this.db.getMaintenanceWindowsByMonitorId(monitorId); const maintenanceWindows = await this.db.maintenanceWindowModule.getMaintenanceWindowsByMonitorId(monitorId);
// Check for active maintenance window: // Check for active maintenance window:
const maintenanceWindowIsActive = maintenanceWindows.reduce((acc, window) => { const maintenanceWindowIsActive = maintenanceWindows.reduce((acc, window) => {
if (window.active) { if (window.active) {
@@ -22,8 +22,8 @@ class BufferService {
}; };
this.OPERATION_MAP = { this.OPERATION_MAP = {
checks: this.db.checkModule.createChecks, checks: this.db.checkModule.createChecks,
pagespeedChecks: this.db.createPageSpeedChecks, pagespeedChecks: this.db.pageSpeedCheckModule.createPageSpeedChecks,
hardwareChecks: this.db.createHardwareChecks, hardwareChecks: this.db.hardwareCheckModule.createHardwareChecks,
}; };
this.scheduleNextFlush(); this.scheduleNextFlush();
@@ -81,7 +81,7 @@ class NotificationService {
} }
async notifyAll({ notificationIDs, subject, html, content }) { async notifyAll({ notificationIDs, subject, html, content }) {
const notifications = await this.db.getNotificationsByIds(notificationIDs); const notifications = await this.db.notificationModule.getNotificationsByIds(notificationIDs);
// Map each notification to a test promise // Map each notification to a test promise
const promises = notifications.map(async (notification) => { const promises = notifications.map(async (notification) => {
@@ -122,7 +122,7 @@ class StatusService {
this.insertCheck(networkResponse); this.insertCheck(networkResponse);
try { try {
const { monitorId, status, code } = networkResponse; const { monitorId, status, code } = networkResponse;
const monitor = await this.db.getMonitorById(monitorId); const monitor = await this.db.monitorModule.getMonitorById(monitorId);
// Update running stats // Update running stats
this.updateRunningStats({ monitor, networkResponse }); this.updateRunningStats({ monitor, networkResponse });
+9
View File
@@ -416,6 +416,15 @@ const updateAppSettingsBodyValidation = joi.object({
systemEmailIgnoreTLS: joi.boolean(), systemEmailIgnoreTLS: joi.boolean(),
systemEmailRequireTLS: joi.boolean(), systemEmailRequireTLS: joi.boolean(),
systemEmailRejectUnauthorized: joi.boolean(), systemEmailRejectUnauthorized: joi.boolean(),
globalThresholds: joi
.object({
cpu: joi.number().min(1).max(100).allow("").optional(),
memory: joi.number().min(1).max(100).allow("").optional(),
disk: joi.number().min(1).max(100).allow("").optional(),
temperature: joi.number().min(1).max(150).allow("").optional(),
})
.optional(),
}); });
//**************************************** //****************************************