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
+1731 -2075

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;
setInfrastructureMonitor({ const gt = globalSettings?.data?.settings?.globalThresholds || {};
url: monitor.url.replace(/^https?:\/\//, ""),
name: monitor.name || "",
notifications: monitor.notifications,
interval: monitor.interval / MS_PER_MINUTE,
cpu: monitor.thresholds?.usage_cpu !== undefined,
usage_cpu: monitor.thresholds?.usage_cpu ? monitor.thresholds.usage_cpu * 100 : "",
memory: monitor.thresholds?.usage_memory !== undefined, setHttps(false);
usage_memory: monitor.thresholds?.usage_memory
? monitor.thresholds.usage_memory * 100
: "",
disk: monitor.thresholds?.usage_disk !== undefined, setInfrastructureMonitor({
usage_disk: monitor.thresholds?.usage_disk url: "",
? monitor.thresholds.usage_disk * 100 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;
temperature: monitor.thresholds?.usage_temperature !== undefined, setHttps(monitor.url.startsWith("https"));
usage_temperature: monitor.thresholds?.usage_temperature
? monitor.thresholds.usage_temperature * 100 setInfrastructureMonitor({
: "", url: monitor.url.replace(/^https?:\/\//, ""),
secret: monitor.secret || "", name: monitor.name || "",
}); notifications: monitor.notifications || [],
setHttps(monitor.url.startsWith("https")); interval: monitor.interval / MS_PER_MINUTE,
}, [isCreate, monitor]); cpu: thresholds.usage_cpu !== undefined,
usage_cpu:
thresholds.usage_cpu !== undefined
? (thresholds.usage_cpu * 100).toString()
: "",
memory: thresholds.usage_memory !== undefined,
usage_memory:
thresholds.usage_memory !== undefined
? (thresholds.usage_memory * 100).toString()
: "",
disk: thresholds.usage_disk !== undefined,
usage_disk:
thresholds.usage_disk !== undefined
? (thresholds.usage_disk * 100).toString()
: "",
temperature: thresholds.usage_temperature !== undefined,
usage_temperature:
thresholds.usage_temperature !== undefined
? (thresholds.usage_temperature * 100).toString()
: "",
secret: monitor.secret || "",
});
}
}, [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,70 +1,22 @@
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) => {
try {
const { monitorId, status } = hardwareCheckData;
const n = (await HardwareCheck.countDocuments({ monitorId })) + 1;
const monitor = await Monitor.findById(monitorId);
if (!monitor) { class HardwareCheckModule {
logger.error({ constructor({ HardwareCheck, Monitor, logger }) {
message: "Monitor not found", this.HardwareCheck = HardwareCheck;
service: SERVICE_NAME, this.Monitor = Monitor;
method: "createHardwareCheck", this.logger = logger;
details: `monitor ID: ${monitorId}`, }
});
return null; createHardwareChecks = async (hardwareChecks) => {
try {
await this.HardwareCheck.insertMany(hardwareChecks, { ordered: false });
return true;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "createHardwareChecks";
throw error;
} }
};
}
let newUptimePercentage; export default HardwareCheckModule;
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;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "createHardwareChecks";
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 };
+50 -83
View File
@@ -1,89 +1,56 @@
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.
*
* This function deletes any existing invite tokens for the user's email,
* generates a new token, saves it, and then returns the new token.
*
* @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.
* @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 {
await InviteToken.deleteMany({ email: userData.email });
userData.token = crypto.randomBytes(32).toString("hex");
let inviteToken = new InviteToken(userData);
await inviteToken.save();
return inviteToken;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "requestInviteToken";
throw error;
}
};
/** class InviteModule {
* Retrieves an invite token constructor({ InviteToken, crypto, stringService }) {
* this.InviteToken = InviteToken;
* This function searches for an invite token in the database and deletes it. this.crypto = crypto;
* If the invite token is not found, it throws an error. this.stringService = stringService;
* }
* @param {string} token - The invite token to search for.
* @returns {Promise<InviteToken>} The invite token data. requestInviteToken = async (userData) => {
* @throws {Error} If the invite token is not found or there is another error. try {
*/ await this.InviteToken.deleteMany({ email: userData.email });
const getInviteToken = async (token) => { userData.token = this.crypto.randomBytes(32).toString("hex");
const stringService = ServiceRegistry.get(StringService.SERVICE_NAME); let inviteToken = new this.InviteToken(userData);
try { await inviteToken.save();
const invite = await InviteToken.findOne({ return inviteToken;
token, } catch (error) {
}); error.service = SERVICE_NAME;
if (invite === null) { error.method = "requestInviteToken";
throw new Error(stringService.authInviteNotFound); throw error;
} }
return invite; };
} catch (error) {
error.service = SERVICE_NAME;
error.method = "getInviteToken";
throw error;
}
};
/** getInviteToken = async (token) => {
* Retrieves and deletes an invite token try {
* const invite = await this.InviteToken.findOne({
* This function searches for an invite token in the database and deletes it. token,
* If the invite token is not found, it throws an error. });
* if (invite === null) {
* @param {string} token - The invite token to search for. throw new Error(this.stringService.authInviteNotFound);
* @returns {Promise<InviteToken>} The invite token data. }
* @throws {Error} If the invite token is not found or there is another error. return invite;
*/ } catch (error) {
const getInviteTokenAndDelete = async (token) => { error.service = SERVICE_NAME;
const stringService = ServiceRegistry.get(StringService.SERVICE_NAME); error.method = "getInviteToken";
try { throw error;
const invite = await InviteToken.findOneAndDelete({
token,
});
if (invite === null) {
throw new Error(stringService.authInviteNotFound);
} }
return invite; };
} catch (error) { getInviteTokenAndDelete = async (token) => {
error.service = SERVICE_NAME; try {
error.method = "getInviteTokenAndDelete"; const invite = await this.InviteToken.findOneAndDelete({
throw error; token,
} });
}; if (invite === null) {
throw new Error(this.stringService.authInviteNotFound);
}
return invite;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "getInviteTokenAndDelete";
throw error;
}
};
}
export { requestInviteToken, getInviteToken, getInviteTokenAndDelete }; export default InviteModule;
@@ -1,192 +1,106 @@
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. try {
* @param {mongoose.Schema.Types.ObjectId} maintenanceWindowData.monitorId - The ID of the monitor. const maintenanceWindow = new this.MaintenanceWindow({
* @param {Boolean} maintenanceWindowData.active - Indicates whether the maintenance window is active. ...maintenanceWindowData,
* @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 {
const maintenanceWindow = new MaintenanceWindow({
...maintenanceWindowData,
});
// If the maintenance window is a one time window, set the expiry to the end date // If the maintenance window is a one time window, set the expiry to the end date
if (maintenanceWindowData.oneTime) { if (maintenanceWindowData.oneTime) {
maintenanceWindow.expiry = maintenanceWindowData.end; maintenanceWindow.expiry = maintenanceWindowData.end;
}
const result = await maintenanceWindow.save();
return result;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "createMaintenanceWindow";
throw error;
} }
const result = await maintenanceWindow.save(); };
return result; getMaintenanceWindowById = async ({ id, teamId }) => {
} catch (error) { try {
error.service = SERVICE_NAME; const maintenanceWindow = await this.MaintenanceWindow.findOne({
error.method = "createMaintenanceWindow"; _id: id,
throw error; teamId: teamId,
} });
}; return maintenanceWindow;
} catch (error) {
const getMaintenanceWindowById = async ({ id, teamId }) => { error.service = SERVICE_NAME;
try { error.method = "getMaintenanceWindowById";
const maintenanceWindow = await MaintenanceWindow.findOne({ throw error;
_id: id,
teamId: teamId,
});
return maintenanceWindow;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "getMaintenanceWindowById";
throw error;
}
};
/**
* 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 {
let { active, page, rowsPerPage, field, order } = query || {};
const maintenanceQuery = { teamId };
if (active !== undefined) maintenanceQuery.active = active;
const maintenanceWindowCount = await MaintenanceWindow.countDocuments(maintenanceQuery);
// Pagination
let skip = 0;
if (page && rowsPerPage) {
skip = page * rowsPerPage;
} }
};
// Sorting getMaintenanceWindowsByTeamId = async (teamId, query) => {
let sort = {}; try {
if (field !== undefined && order !== undefined) { let { active, page, rowsPerPage, field, order } = query || {};
sort[field] = order === "asc" ? 1 : -1; const maintenanceQuery = { teamId };
if (active !== undefined) maintenanceQuery.active = active;
const maintenanceWindowCount = await this.MaintenanceWindow.countDocuments(maintenanceQuery);
// Pagination
let skip = 0;
if (page && rowsPerPage) {
skip = page * rowsPerPage;
}
// Sorting
let sort = {};
if (field !== undefined && order !== undefined) {
sort[field] = order === "asc" ? 1 : -1;
}
const maintenanceWindows = await this.MaintenanceWindow.find(maintenanceQuery).skip(skip).limit(rowsPerPage).sort(sort);
return { maintenanceWindows, maintenanceWindowCount };
} catch (error) {
error.service = SERVICE_NAME;
error.method = "getMaintenanceWindowByUserId";
throw error;
} }
};
getMaintenanceWindowsByMonitorId = async ({ monitorId, teamId }) => {
try {
const maintenanceWindows = await this.MaintenanceWindow.find({
monitorId: monitorId,
teamId: teamId,
});
return maintenanceWindows;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "getMaintenanceWindowsByMonitorId";
throw error;
}
};
const maintenanceWindows = await MaintenanceWindow.find(maintenanceQuery).skip(skip).limit(rowsPerPage).sort(sort); deleteMaintenanceWindowById = async ({ id, teamId }) => {
try {
const maintenanceWindow = await this.MaintenanceWindow.findOneAndDelete({ _id: id, teamId });
return maintenanceWindow;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "deleteMaintenanceWindowById";
throw error;
}
};
return { maintenanceWindows, maintenanceWindowCount }; editMaintenanceWindowById = async ({ id, body }) => {
} catch (error) { try {
error.service = SERVICE_NAME; const editedMaintenanceWindow = await this.MaintenanceWindow.findByIdAndUpdate(id, body, { new: true });
error.method = "getMaintenanceWindowByUserId"; return editedMaintenanceWindow;
throw error; } catch (error) {
} error.service = SERVICE_NAME;
}; error.method = "editMaintenanceWindowById";
throw error;
}
};
}
/** export default MaintenanceWindowModule;
* 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 {
const maintenanceWindows = await MaintenanceWindow.find({
monitorId: monitorId,
teamId: teamId,
});
return maintenanceWindows;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "getMaintenanceWindowsByMonitorId";
throw error;
}
};
/**
* 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 {
const maintenanceWindow = await MaintenanceWindow.findOneAndDelete({ _id: id, teamId });
return maintenanceWindow;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "deleteMaintenanceWindowById";
throw error;
}
};
/**
* 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 {
const result = await MaintenanceWindow.deleteMany({ monitorId: monitorId });
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;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "editMaintenanceWindowById";
throw error;
}
};
export {
createMaintenanceWindow,
getMaintenanceWindowById,
getMaintenanceWindowsByTeamId,
getMaintenanceWindowsByMonitorId,
deleteMaintenanceWindowById,
deleteMaintenanceWindowByMonitorId,
deleteMaintenanceWindowByUserId,
editMaintenanceWindowById,
};
File diff suppressed because it is too large. Load diff
@@ -1,44 +1,30 @@
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.
* @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 {
const networkCheck = await new NetworkCheck(networkCheckData);
await networkCheck.save();
return networkCheck;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "createNetworkCheck";
throw error;
} }
}; createNetworkCheck = async (networkCheckData) => {
try {
const networkCheck = await new this.NetworkCheck(networkCheckData);
await networkCheck.save();
return networkCheck;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "createNetworkCheck";
throw error;
}
};
getNetworkChecksByMonitorId = async (monitorId, limit = 100) => {
try {
const networkChecks = await this.NetworkCheck.find({ monitorId }).sort({ createdAt: -1 }).limit(limit);
return networkChecks;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "getNetworkChecksByMonitorId";
throw error;
}
};
}
/** export default NetworkCheckModule;
* 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 {
const networkChecks = await NetworkCheck.find({ monitorId }).sort({ createdAt: -1 }).limit(limit);
return networkChecks;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "getNetworkChecksByMonitorId";
throw error;
}
};
export { createNetworkCheck, getNetworkChecksByMonitorId };
+94 -119
View File
@@ -1,125 +1,100 @@
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.
* @param {Object} notificationData - The data for the new notification.
* @param {mongoose.Types.ObjectId} notificationData.monitorId - The ID of the monitor.
* @param {string} notificationData.type - The type of the notification (e.g., "email", "sms").
* @param {string} [notificationData.address] - The address for the notification (if applicable).
* @param {string} [notificationData.phone] - The phone number for the notification (if applicable).
* @returns {Promise<Object>} The created notification.
* @throws Will throw an error if the notification cannot be created.
*/
const createNotification = async (notificationData) => {
try {
const notification = await new Notification({ ...notificationData }).save();
return notification;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "createNotification";
throw error;
}
};
const getNotificationsByTeamId = async (teamId) => { class NotificationModule {
try { constructor({ Notification, Monitor }) {
const notifications = await Notification.find({ teamId }); this.Notification = Notification;
return notifications; this.Monitor = Monitor;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "getNotificationsByTeamId";
throw error;
} }
}; createNotification = async (notificationData) => {
try {
const getNotificationsByIds = async (notificationIds) => { const notification = await new this.Notification({ ...notificationData }).save();
try { return notification;
const notifications = await Notification.find({ _id: { $in: notificationIds } }); } catch (error) {
return notifications; error.service = SERVICE_NAME;
} catch (error) { error.method = "createNotification";
error.service = SERVICE_NAME; throw error;
error.method = "getNotificationsByIds";
throw error;
}
};
/**
* 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 {
const notifications = await Notification.find({ monitorId });
return notifications;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "getNotificationsByMonitorId";
throw error;
}
};
const deleteNotificationsByMonitorId = async (monitorId) => {
try {
const result = await Notification.deleteMany({ monitorId });
return result.deletedCount;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "deleteNotificationsByMonitorId";
throw error;
}
};
const deleteNotificationById = async (id) => {
try {
const notification = await Notification.findById(id);
if (!notification) {
throw new Error("Notification not found");
} }
};
getNotificationsByTeamId = async (teamId) => {
try {
const notifications = await this.Notification.find({ teamId });
return notifications;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "getNotificationsByTeamId";
throw error;
}
};
getNotificationsByIds = async (notificationIds) => {
try {
const notifications = await this.Notification.find({ _id: { $in: notificationIds } });
return notifications;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "getNotificationsByIds";
throw error;
}
};
getNotificationsByMonitorId = async (monitorId) => {
try {
const notifications = await this.Notification.find({ monitorId });
return notifications;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "getNotificationsByMonitorId";
throw error;
}
};
deleteNotificationsByMonitorId = async (monitorId) => {
try {
const result = await this.Notification.deleteMany({ monitorId });
return result.deletedCount;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "deleteNotificationsByMonitorId";
throw error;
}
};
deleteNotificationById = async (id) => {
try {
const notification = await this.Notification.findById(id);
if (!notification) {
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;
error.method = "deleteNotificationById"; error.method = "deleteNotificationById";
throw error; throw error;
} }
}; };
getNotificationById = async (id) => {
try {
const notification = await this.Notification.findById(id);
return notification;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "getNotificationById";
throw error;
}
};
editNotification = async (id, notificationData) => {
try {
const notification = await this.Notification.findByIdAndUpdate(id, notificationData, {
new: true,
});
return notification;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "editNotification";
throw error;
}
};
}
const getNotificationById = async (id) => { export default NotificationModule;
try {
const notification = await Notification.findById(id);
return notification;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "getNotificationById";
throw error;
}
};
const editNotification = async (id, notificationData) => {
try {
const notification = await Notification.findByIdAndUpdate(id, notificationData, {
new: true,
});
return notification;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "editNotification";
throw error;
}
};
export {
createNotification,
getNotificationsByTeamId,
getNotificationsByIds,
getNotificationsByMonitorId,
deleteNotificationsByMonitorId,
deleteNotificationById,
getNotificationById,
editNotification,
};
@@ -1,57 +1,31 @@
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
* @async
* @param {Object} pageSpeedCheckData
* @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) => {
try {
await PageSpeedCheck.insertMany(pageSpeedChecks, { ordered: false });
return true;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "createPageSpeedCheck";
throw error;
}
};
/** class PageSpeedCheckModule {
* Delete all PageSpeed checks for a monitor constructor({ PageSpeedCheck }) {
* @async this.PageSpeedCheck = PageSpeedCheck;
* @param {string} monitorId
* @returns {number}
* @throws {Error}
*/
const deletePageSpeedChecksByMonitorId = async (monitorId) => {
try {
const result = await PageSpeedCheck.deleteMany({ monitorId });
return result.deletedCount;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "deletePageSpeedChecksByMonitorId";
throw error;
} }
};
export { createPageSpeedCheck, createPageSpeedChecks, deletePageSpeedChecksByMonitorId }; createPageSpeedChecks = async (pageSpeedChecks) => {
try {
await this.PageSpeedCheck.insertMany(pageSpeedChecks, { ordered: false });
return true;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "createPageSpeedCheck";
throw error;
}
};
deletePageSpeedChecksByMonitorId = async (monitorId) => {
try {
const result = await this.PageSpeedCheck.deleteMany({ monitorId });
return result.deletedCount;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "deletePageSpeedChecksByMonitorId";
throw error;
}
};
}
export default PageSpeedCheckModule;
+70 -76
View File
@@ -1,86 +1,80 @@
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) => {
try {
// Delete any existing tokens
await RecoveryToken.deleteMany({ email });
let recoveryToken = new RecoveryToken({
email,
token: crypto.randomBytes(32).toString("hex"),
});
await recoveryToken.save();
return recoveryToken;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "requestRecoveryToken";
throw error;
} }
};
const validateRecoveryToken = async (candidateToken) => { requestRecoveryToken = async (email) => {
const stringService = serviceRegistry.get(StringService.SERVICE_NAME); try {
try { // Delete any existing tokens
const recoveryToken = await RecoveryToken.findOne({ await this.RecoveryToken.deleteMany({ email });
token: candidateToken, let recoveryToken = new this.RecoveryToken({
}); email,
if (recoveryToken !== null) { token: this.crypto.randomBytes(32).toString("hex"),
});
await recoveryToken.save();
return recoveryToken; return recoveryToken;
} else { } catch (error) {
throw new Error(stringService.dbTokenNotFound); error.service = SERVICE_NAME;
error.method = "requestRecoveryToken";
throw error;
} }
} catch (error) { };
error.service = SERVICE_NAME; validateRecoveryToken = async (candidateToken) => {
error.method = "validateRecoveryToken"; try {
throw error; const recoveryToken = await this.RecoveryToken.findOne({
} token: candidateToken,
}; });
if (recoveryToken !== null) {
const resetPassword = async (password, candidateToken) => { return recoveryToken;
const stringService = serviceRegistry.get(StringService.SERVICE_NAME); } else {
try { throw new Error(this.stringService.dbTokenNotFound);
const newPassword = password; }
} catch (error) {
// Validate token again error.service = SERVICE_NAME;
const recoveryToken = await validateRecoveryToken(candidateToken); error.method = "validateRecoveryToken";
const user = await UserModel.findOne({ email: recoveryToken.email }); throw error;
if (user === null) {
throw new Error(stringService.dbUserNotFound);
} }
};
const match = await user.comparePassword(newPassword); resetPassword = async (password, candidateToken) => {
if (match === true) { try {
throw new Error(stringService.dbResetPasswordBadMatch); const newPassword = password;
// Validate token again
const recoveryToken = await this.validateRecoveryToken(candidateToken);
const user = await this.User.findOne({ email: recoveryToken.email });
if (user === null) {
throw new Error(this.stringService.dbUserNotFound);
}
const match = await user.comparePassword(newPassword);
if (match === true) {
throw new Error("Password cannot be the same as the old password");
}
user.password = newPassword;
await user.save();
await this.RecoveryToken.deleteMany({ email: recoveryToken.email });
// Fetch the user again without the password
const userWithoutPassword = await this.User.findOne({
email: recoveryToken.email,
})
.select("-password")
.select("-profileImage");
return userWithoutPassword;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "resetPassword";
throw error;
} }
};
}
user.password = newPassword; export default RecoveryModule;
await user.save();
await RecoveryToken.deleteMany({ email: recoveryToken.email });
// Fetch the user again without the password
const userWithoutPassword = await UserModel.findOne({
email: recoveryToken.email,
})
.select("-password")
.select("-profileImage");
return userWithoutPassword;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "resetPassword";
throw error;
}
};
export { requestRecoveryToken, validateRecoveryToken, resetPassword };
+29 -34
View File
@@ -1,41 +1,36 @@
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 } };
if (newSettings.pagespeedApiKey === "") { if (newSettings.pagespeedApiKey === "") {
update.$unset = { pagespeedApiKey: "" }; update.$unset = { pagespeedApiKey: "" };
delete update.$set.pagespeedApiKey; delete update.$set.pagespeedApiKey;
}
if (newSettings.systemEmailPassword === "") {
update.$unset = { systemEmailPassword: "" };
delete update.$set.systemEmailPassword;
}
await this.AppSettings.findOneAndUpdate({}, update, {
upsert: true,
});
const settings = await this.AppSettings.findOne().select("-__v -_id -createdAt -updatedAt -singleton").lean();
return settings;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "updateAppSettings";
throw error;
} }
};
}
if (newSettings.systemEmailPassword === "") { export default SettingsModule;
update.$unset = { systemEmailPassword: "" };
delete update.$set.systemEmailPassword;
}
await AppSettings.findOneAndUpdate({}, update, {
upsert: true,
});
const settings = await AppSettings.findOne().select("-__v -_id -createdAt -updatedAt -singleton").lean();
return settings;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "updateAppSettings";
throw error;
}
};
export { getAppSettings, updateAppSettings };
+268 -273
View File
@@ -1,292 +1,287 @@
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;
try { this.NormalizeData = NormalizeData;
const statusPage = new StatusPage({ this.stringService = stringService;
...statusPageData,
userId,
teamId,
});
if (image) {
statusPage.logo = {
data: image.buffer,
contentType: image.mimetype,
};
}
await statusPage.save();
return statusPage;
} catch (error) {
if (error?.code === 11000) {
// Handle duplicate URL errors
error.status = 400;
error.message = stringService.statusPageUrlNotUnique;
}
error.service = SERVICE_NAME;
error.method = "createStatusPage";
throw error;
} }
};
const updateStatusPage = async (statusPageData, image) => { createStatusPage = async ({ statusPageData, image, userId, teamId }) => {
try { try {
if (image) { const statusPage = new this.StatusPage({
statusPageData.logo = { ...statusPageData,
data: image.buffer, userId,
contentType: image.mimetype, teamId,
}; });
} else { if (image) {
statusPageData.logo = null; statusPage.logo = {
} data: image.buffer,
contentType: image.mimetype,
if (statusPageData.deleteSubmonitors === "true") { };
statusPageData.subMonitors = []; }
} await statusPage.save();
const statusPage = await StatusPage.findOneAndUpdate({ url: statusPageData.url }, statusPageData, { return statusPage;
new: true, } catch (error) {
}); if (error?.code === 11000) {
// Handle duplicate URL errors
return statusPage; error.status = 400;
} catch (error) { error.message = this.stringService.statusPageUrlNotUnique;
error.service = SERVICE_NAME; }
error.method = "updateStatusPage"; error.service = SERVICE_NAME;
throw error; error.method = "createStatusPage";
}
};
const getStatusPageByUrl = async (url, type) => {
// TODO This is deprecated, can remove and have controller call getStatusPage
try {
return getStatusPage(url);
} catch (error) {
error.service = SERVICE_NAME;
error.method = "getStatusPageByUrl";
throw error;
}
};
const getStatusPagesByTeamId = async (teamId) => {
try {
const statusPages = await StatusPage.find({ teamId });
return statusPages;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "getStatusPagesByTeamId";
throw error;
}
};
const getStatusPage = async (url) => {
const stringService = ServiceRegistry.get(StringService.SERVICE_NAME);
try {
const preliminaryStatusPage = await StatusPage.findOne({ url });
if (!preliminaryStatusPage) {
const error = new Error(stringService.statusPageNotFound);
error.status = 404;
throw error; throw error;
} }
};
if (!preliminaryStatusPage.monitors || preliminaryStatusPage.monitors.length === 0) { updateStatusPage = async (statusPageData, image) => {
const { _id, color, companyName, isPublished, logo, originalMonitors, showCharts, showUptimePercentage, timezone, showAdminLoginLink, url } = try {
preliminaryStatusPage; if (image) {
return { statusPageData.logo = {
statusPage: { data: image.buffer,
_id, contentType: image.mimetype,
color, };
companyName, } else {
isPublished, statusPageData.logo = null;
logo, }
originalMonitors,
showCharts, if (statusPageData.deleteSubmonitors === "true") {
showUptimePercentage, statusPageData.subMonitors = [];
timezone, }
showAdminLoginLink, const statusPage = await this.StatusPage.findOneAndUpdate({ url: statusPageData.url }, statusPageData, {
url, new: true,
}, });
monitors: [],
}; return statusPage;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "updateStatusPage";
throw error;
} }
};
const statusPageQuery = await StatusPage.aggregate([ getStatusPageByUrl = async (url) => {
{ $match: { url: url } }, // TODO This is deprecated, can remove and have controller call getStatusPage
{ try {
$set: { return this.getStatusPage(url);
originalMonitors: "$monitors", } catch (error) {
}, error.service = SERVICE_NAME;
}, error.method = "getStatusPageByUrl";
{ throw error;
$lookup: { }
from: "monitors", };
localField: "monitors",
foreignField: "_id",
as: "monitors",
},
},
{
$unwind: {
path: "$monitors",
preserveNullAndEmptyArrays: true,
},
},
{
$lookup: {
from: "maintenancewindows",
let: { monitorId: "$monitors._id" },
pipeline: [{ $match: { $expr: { $eq: ["$monitorId", "$$monitorId"] } } }],
as: "monitors.maintenanceWindows",
},
},
{
$lookup: {
from: "checks",
let: { monitorId: "$monitors._id" },
pipeline: [
{
$match: {
$expr: { $eq: ["$monitorId", "$$monitorId"] },
},
},
{ $sort: { createdAt: -1 } },
{ $limit: 25 },
],
as: "monitors.checks",
},
},
{
$addFields: {
"monitors.orderIndex": {
$indexOfArray: ["$originalMonitors", "$monitors._id"],
},
"monitors.isMaintenance": {
$reduce: {
input: "$monitors.maintenanceWindows",
initialValue: false,
in: {
$or: [
"$$value",
{
$and: [{ $eq: ["$$this.active", true] }, { $lte: ["$$this.start", "$$NOW"] }, { $gte: ["$$this.end", "$$NOW"] }],
},
],
},
},
},
},
},
{ $match: { "monitors.orderIndex": { $ne: -1 } } },
{ $sort: { "monitors.orderIndex": 1 } },
{ getStatusPagesByTeamId = async (teamId) => {
$group: { try {
_id: "$_id", const statusPages = await this.StatusPage.find({ teamId });
statusPage: { $first: "$$ROOT" }, return statusPages;
monitors: { $push: "$monitors" }, } catch (error) {
}, error.service = SERVICE_NAME;
}, error.method = "getStatusPagesByTeamId";
{ throw error;
$project: { }
};
getStatusPage = async (url) => {
try {
const preliminaryStatusPage = await this.StatusPage.findOne({ url });
if (!preliminaryStatusPage) {
const error = new Error(this.stringService.statusPageNotFound);
error.status = 404;
throw error;
}
if (!preliminaryStatusPage.monitors || preliminaryStatusPage.monitors.length === 0) {
const { _id, color, companyName, isPublished, logo, originalMonitors, showCharts, showUptimePercentage, timezone, showAdminLoginLink, url } =
preliminaryStatusPage;
return {
statusPage: { statusPage: {
_id: 1, _id,
color: 1, color,
companyName: 1, companyName,
isPublished: 1, isPublished,
logo: 1, logo,
originalMonitors: 1, originalMonitors,
showCharts: 1, showCharts,
showUptimePercentage: 1, showUptimePercentage,
timezone: 1, timezone,
showAdminLoginLink: 1, showAdminLoginLink,
url: 1, url,
}, },
monitors: { monitors: [],
_id: 1, };
userId: 1, }
teamId: 1,
name: 1, const statusPageQuery = await this.StatusPage.aggregate([
description: 1, { $match: { url: url } },
status: 1, {
type: 1, $set: {
ignoreTlsErrors: 1, originalMonitors: "$monitors",
jsonPath: 1,
expectedValue: 1,
matchMethod: 1,
url: 1,
port: 1,
isActive: 1,
interval: 1,
uptimePercentage: 1,
notifications: 1,
secret: 1,
thresholds: 1,
alertThreshold: 1,
cpuAlertThreshold: 1,
memoryAlertThreshold: 1,
diskAlertThreshold: 1,
tempAlertThreshold: 1,
checks: 1,
isMaintenance: 1,
createdAt: 1,
updatedAt: 1,
}, },
}, },
}, {
]); $lookup: {
if (!statusPageQuery.length) { from: "monitors",
const error = new Error(stringService.statusPageNotFound); localField: "monitors",
error.status = 404; foreignField: "_id",
as: "monitors",
},
},
{
$unwind: {
path: "$monitors",
preserveNullAndEmptyArrays: true,
},
},
{
$lookup: {
from: "maintenancewindows",
let: { monitorId: "$monitors._id" },
pipeline: [{ $match: { $expr: { $eq: ["$monitorId", "$$monitorId"] } } }],
as: "monitors.maintenanceWindows",
},
},
{
$lookup: {
from: "checks",
let: { monitorId: "$monitors._id" },
pipeline: [
{
$match: {
$expr: { $eq: ["$monitorId", "$$monitorId"] },
},
},
{ $sort: { createdAt: -1 } },
{ $limit: 25 },
],
as: "monitors.checks",
},
},
{
$addFields: {
"monitors.orderIndex": {
$indexOfArray: ["$originalMonitors", "$monitors._id"],
},
"monitors.isMaintenance": {
$reduce: {
input: "$monitors.maintenanceWindows",
initialValue: false,
in: {
$or: [
"$$value",
{
$and: [{ $eq: ["$$this.active", true] }, { $lte: ["$$this.start", "$$NOW"] }, { $gte: ["$$this.end", "$$NOW"] }],
},
],
},
},
},
},
},
{ $match: { "monitors.orderIndex": { $ne: -1 } } },
{ $sort: { "monitors.orderIndex": 1 } },
{
$group: {
_id: "$_id",
statusPage: { $first: "$$ROOT" },
monitors: { $push: "$monitors" },
},
},
{
$project: {
statusPage: {
_id: 1,
color: 1,
companyName: 1,
isPublished: 1,
logo: 1,
originalMonitors: 1,
showCharts: 1,
showUptimePercentage: 1,
timezone: 1,
showAdminLoginLink: 1,
url: 1,
},
monitors: {
_id: 1,
userId: 1,
teamId: 1,
name: 1,
description: 1,
status: 1,
type: 1,
ignoreTlsErrors: 1,
jsonPath: 1,
expectedValue: 1,
matchMethod: 1,
url: 1,
port: 1,
isActive: 1,
interval: 1,
uptimePercentage: 1,
notifications: 1,
secret: 1,
thresholds: 1,
alertThreshold: 1,
cpuAlertThreshold: 1,
memoryAlertThreshold: 1,
diskAlertThreshold: 1,
tempAlertThreshold: 1,
checks: 1,
isMaintenance: 1,
createdAt: 1,
updatedAt: 1,
},
},
},
]);
if (!statusPageQuery.length) {
const error = new Error(this.stringService.statusPageNotFound);
error.status = 404;
throw error;
}
const { statusPage, monitors } = statusPageQuery[0];
const normalizedMonitors = monitors.map((monitor) => {
return {
...monitor,
checks: this.NormalizeData(monitor.checks, 10, 100),
};
});
return { statusPage, monitors: normalizedMonitors };
} catch (error) {
error.service = SERVICE_NAME;
error.method = "getStatusPageByUrl";
throw error; throw error;
} }
};
const { statusPage, monitors } = statusPageQuery[0]; deleteStatusPage = async (url) => {
try {
await this.StatusPage.deleteOne({ url });
} catch (error) {
error.service = SERVICE_NAME;
error.method = "deleteStatusPage";
throw error;
}
};
deleteStatusPagesByMonitorId = async (monitorId) => {
try {
await this.StatusPage.deleteMany({ monitors: { $in: [monitorId] } });
} catch (error) {
error.service = SERVICE_NAME;
error.method = "deleteStatusPageByMonitorId";
throw error;
}
};
}
const normalizedMonitors = monitors.map((monitor) => { export default StatusPageModule;
return {
...monitor,
checks: NormalizeData(monitor.checks, 10, 100),
};
});
return { statusPage, monitors: normalizedMonitors };
} catch (error) {
error.service = SERVICE_NAME;
error.method = "getStatusPageByUrl";
throw error;
}
};
const deleteStatusPage = async (url) => {
try {
await StatusPage.deleteOne({ url });
} catch (error) {
error.service = SERVICE_NAME;
error.method = "deleteStatusPage";
throw error;
}
};
const deleteStatusPagesByMonitorId = async (monitorId) => {
try {
await StatusPage.deleteMany({ monitors: { $in: [monitorId] } });
} catch (error) {
error.service = SERVICE_NAME;
error.method = "deleteStatusPageByMonitorId";
throw error;
}
};
export {
createStatusPage,
updateStatusPage,
getStatusPagesByTeamId,
getStatusPage,
getStatusPageByUrl,
deleteStatusPage,
deleteStatusPagesByMonitorId,
};
+153 -243
View File
@@ -1,261 +1,171 @@
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 }) {
if (superAdmin !== null) { this.User = User;
return true; this.Team = Team;
this.GenerateAvatarImage = GenerateAvatarImage;
this.ParseBoolean = ParseBoolean;
this.stringService = stringService;
} }
return false;
};
/** checkSuperadmin = async () => {
* Insert a User try {
* @async const superAdmin = await this.User.findOne({ role: "superadmin" });
* @param {Express.Request} req if (superAdmin !== null) {
* @param {Express.Response} res return true;
* @returns {Promise<UserModel>} }
* @throws {Error} return false;
*/ } catch (error) {
const insertUser = async (userData, imageFile, generateAvatarImage = GenerateAvatarImage) => { error.service = SERVICE_NAME;
const stringService = ServiceRegistry.get(StringService.SERVICE_NAME); error.method = "checkSuperadmin";
try { throw error;
if (imageFile) { }
// 1. Save the full size image };
userData.profileImage = {
data: imageFile.buffer,
contentType: imageFile.mimetype,
};
// 2. Get the avatar sized image insertUser = async (userData, imageFile) => {
const avatar = await generateAvatarImage(imageFile); try {
userData.avatarImage = avatar; if (imageFile) {
// 1. Save the full size image
userData.profileImage = {
data: imageFile.buffer,
contentType: imageFile.mimetype,
};
// 2. Get the avatar sized image
const avatar = await this.GenerateAvatarImage(imageFile);
userData.avatarImage = avatar;
}
// Handle creating team if superadmin
if (userData.role.includes("superadmin")) {
const team = new this.Team({
email: userData.email,
});
userData.teamId = team._id;
userData.checkTTL = 60 * 60 * 24 * 30;
await team.save();
}
const newUser = new this.User(userData);
await newUser.save();
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) {
if (error.code === DUPLICATE_KEY_CODE) {
error.message = this.stringService.dbUserExists;
}
error.service = SERVICE_NAME;
error.method = "insertUser";
throw error;
}
};
getUserByEmail = async (email) => {
try {
// Need the password to be able to compare, removed .select()
// We can strip the hash before returning the user
const user = await this.User.findOne({ email: email }).select("-profileImage");
if (!user) {
throw new Error(this.stringService.dbUserNotFound);
}
return user;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "getUserByEmail";
throw error;
}
};
updateUser = async ({ userId, user, file }) => {
if (!userId) {
throw new Error("No user in request");
} }
// Handle creating team if superadmin try {
if (userData.role.includes("superadmin")) { const candidateUser = { ...user };
const team = new TeamModel({
email: userData.email, if (this.ParseBoolean(candidateUser.deleteProfileImage) === true) {
}); candidateUser.profileImage = null;
userData.teamId = team._id; candidateUser.avatarImage = null;
userData.checkTTL = 60 * 60 * 24 * 30; } else if (file) {
await team.save(); // 1. Save the full size image
candidateUser.profileImage = {
data: file.buffer,
contentType: file.mimetype,
};
// 2. Get the avatar sized image
const avatar = await this.GenerateAvatarImage(file);
candidateUser.avatarImage = avatar;
}
const updatedUser = await this.User.findByIdAndUpdate(
userId,
candidateUser,
{ new: true } // Returns updated user instead of pre-update user
)
.select("-password")
.select("-profileImage");
return updatedUser;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "updateUser";
throw error;
} }
};
const newUser = new UserModel(userData); deleteUser = async (userId) => {
await newUser.save(); try {
return await UserModel.findOne({ _id: newUser._id }).select("-password").select("-profileImage"); // .select() doesn't work with create, need to save then find const deletedUser = await this.User.findByIdAndDelete(userId);
} catch (error) { if (!deletedUser) {
if (error.code === DUPLICATE_KEY_CODE) { throw new Error(this.stringService.dbUserNotFound);
error.message = stringService.dbUserExists; }
return deletedUser;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "deleteUser";
throw error;
} }
error.service = SERVICE_NAME; };
error.method = "insertUser";
throw error;
}
};
/** getAllUsers = async () => {
* Get User by Email try {
* Gets a user by Email. Not sure if we'll ever need this except for login. const users = await this.User.find().select("-password").select("-profileImage");
* If not needed except for login, we can move password comparison here return users;
* Throws error if user not found } catch (error) {
* @async error.service = SERVICE_NAME;
* @param {Express.Request} req error.method = "getAllUsers";
* @param {Express.Response} res throw error;
* @returns {Promise<UserModel>}
* @throws {Error}
*/
const getUserByEmail = async (email) => {
const stringService = ServiceRegistry.get(StringService.SERVICE_NAME);
try {
// Need the password to be able to compare, removed .select()
// We can strip the hash before returning the user
const user = await UserModel.findOne({ email: email }).select("-profileImage");
if (!user) {
throw new Error(stringService.dbUserNotFound);
} }
return user; };
} catch (error) {
error.service = SERVICE_NAME;
error.method = "getUserByEmail";
throw error;
}
};
/** getUserById = async (roles, userId) => {
* Update a user by ID try {
* @async if (!roles.includes("superadmin")) {
* @param {Express.Request} req throw new Error("User is not a superadmin");
* @param {Express.Response} res }
* @returns {Promise<UserModel>}
* @throws {Error}
*/
const updateUser = async ({ userId, user, file }) => { const user = await this.User.findById(userId).select("-password").select("-profileImage");
if (!userId) { if (!user) {
throw new Error("No user in request"); throw new Error("User not found");
} }
try { return user;
const candidateUser = { ...user }; } catch (error) {
error.service = SERVICE_NAME;
if (ParseBoolean(candidateUser.deleteProfileImage) === true) { error.method = "getUserById";
candidateUser.profileImage = null; throw error;
candidateUser.avatarImage = null;
} else if (file) {
// 1. Save the full size image
candidateUser.profileImage = {
data: file.buffer,
contentType: file.mimetype,
};
// 2. Get the avatar sized image
const avatar = await GenerateAvatarImage(file);
candidateUser.avatarImage = avatar;
} }
};
// ****************************************** editUserById = async (userId, user) => {
// End handling profile image try {
// ****************************************** await this.User.findByIdAndUpdate(userId, user, { new: true }).select("-password").select("-profileImage");
} catch (error) {
const updatedUser = await UserModel.findByIdAndUpdate( error.service = SERVICE_NAME;
userId, error.method = "editUserById";
candidateUser, throw error;
{ new: true } // Returns updated user instead of pre-update user
)
.select("-password")
.select("-profileImage");
return updatedUser;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "updateUser";
throw error;
}
};
/**
* 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 {
const deletedUser = await UserModel.findByIdAndDelete(userId);
if (!deletedUser) {
throw new Error(stringService.dbUserNotFound);
} }
return deletedUser; };
} catch (error) { }
error.service = SERVICE_NAME;
error.method = "deleteUser";
throw error;
}
};
/** export default UserModule;
* Delete a user by ID
* @async
* @param {string} teamId
* @returns {void}
* @throws {Error}
*/
const deleteTeam = async (teamId) => {
try {
await TeamModel.findByIdAndDelete(teamId);
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;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "getAllUsers";
throw error;
}
};
const logoutUser = async (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 {
if (!roles.includes("superadmin")) {
throw new Error("User is not a superadmin");
}
const user = await UserModel.findById(userId).select("-password").select("-profileImage");
if (!user) {
throw new Error("User not found");
}
return user;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "getUserById";
throw error;
}
};
const editUserById = async (userId, user) => {
try {
await UserModel.findByIdAndUpdate(userId, user, { new: true }).select("-password").select("-profileImage");
} catch (error) {
error.service = SERVICE_NAME;
error.method = "editUserById";
throw error;
}
};
export {
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(),
}); });
//**************************************** //****************************************