Merge branch 'develop' into 915-be-add-middeware-for-verification-of-refresh-token

This commit is contained in:
Rushi Gandhi committed 2024-10-17 12:01:43 +05:30
commit 090f0df3e8
78 files changed
+10826 -11692

No files matched your search

+1 -1
View File
@@ -120,7 +120,7 @@
opacity: 0.4; opacity: 0.4;
} }
.monitors .MuiTable-root .MuiTableHead-root .MuiTableCell-root { .table-container .MuiTable-root .MuiTableHead-root .MuiTableCell-root {
text-transform: uppercase; text-transform: uppercase;
opacity: 0.8; opacity: 0.8;
font-size: var(--env-var-font-size-small-plus); font-size: var(--env-var-font-size-small-plus);
+80
View File
@@ -0,0 +1,80 @@
import LoadingButton from "@mui/lab/LoadingButton";
import { Button, Modal, Stack, Typography } from "@mui/material";
import PropTypes from "prop-types";
const Dialog = ({ modelTitle, modelDescription,
open, onClose, title, confirmationBtnLbl, confirmationBtnOnClick, cancelBtnLbl, cancelBtnOnClick, theme, isLoading, description }) => {
return <Modal
aria-labelledby={modelTitle}
aria-describedby={modelDescription}
open={open}
onClose={onClose} >
<Stack
gap={theme.spacing(2)}
sx={{
position: "absolute",
top: "50%",
left: "50%",
transform: "translate(-50%, -50%)",
width: 400,
bgcolor: theme.palette.background.main,
border: 1,
borderColor: theme.palette.border.light,
borderRadius: theme.shape.borderRadius,
boxShadow: 24,
p: theme.spacing(15),
"&:focus": {
outline: "none",
},
}}
>
<Typography id={modelTitle} component="h2"
fontSize={16}
color={theme.palette.text.primary}
fontWeight={600}>
{title}
</Typography>
{description && <Typography id={modelDescription} color={theme.palette.text.tertiary}>
{description}
</Typography>}
<Stack
direction="row"
gap={theme.spacing(4)}
mt={theme.spacing(12)}
justifyContent="flex-end"
>
<Button
variant="text"
color="info"
onClick={cancelBtnOnClick}
>
{cancelBtnLbl}
</Button>
<LoadingButton
variant="contained"
color="error"
loading= {isLoading}
onClick={confirmationBtnOnClick}
>
{confirmationBtnLbl}
</LoadingButton>
</Stack>
</Stack>
</Modal>
}
Dialog.propTypes = {
modelTitle: PropTypes.string.isRequired,
modelDescription: PropTypes.string.isRequired,
open: PropTypes.bool.isRequired,
onClose: PropTypes.func.isRequired,
title: PropTypes.string.isRequired,
confirmationBtnLbl: PropTypes.string.isRequired,
confirmationBtnOnClick: PropTypes.func.isRequired,
cancelBtnLbl: PropTypes.string.isRequired,
cancelBtnOnClick: PropTypes.func.isRequired,
theme: PropTypes.object.isRequired,
isLoading: PropTypes.bool.isRequired,
description: PropTypes.string
}
export default Dialog
@@ -223,6 +223,7 @@ const TeamPanel = () => {
return ( return (
<TabPanel <TabPanel
className="team-panel table-container"
value="team" value="team"
sx={{ sx={{
"& h1": { "& h1": {
+1 -1
View File
@@ -61,7 +61,7 @@ const Incidents = () => {
}; };
return ( return (
<Stack className="incidents" pt={theme.spacing(6)} gap={theme.spacing(12)}> <Stack className="incidents table-container" pt={theme.spacing(6)} gap={theme.spacing(12)}>
{loading ? ( {loading ? (
<SkeletonLayout /> <SkeletonLayout />
) : ( ) : (
+1 -1
View File
@@ -46,7 +46,7 @@ const Maintenance = ({ isAdmin }) => {
return ( return (
<Box <Box
className="maintenance" className="maintenance table-container"
sx={{ sx={{
':has(> [class*="fallback__"])': { ':has(> [class*="fallback__"])': {
position: "relative", position: "relative",
+14 -63
View File
@@ -2,7 +2,7 @@ import { useNavigate, useParams } from "react-router";
import { useTheme } from "@emotion/react"; import { useTheme } from "@emotion/react";
import { useDispatch, useSelector } from "react-redux"; import { useDispatch, useSelector } from "react-redux";
import { useEffect, useState } from "react"; import { useEffect, useState } from "react";
import { Box, Button, Modal, Stack, Tooltip, Typography } from "@mui/material"; import { Box, Stack, Tooltip, Typography } from "@mui/material";
import { monitorValidation } from "../../../Validation/validation"; import { monitorValidation } from "../../../Validation/validation";
import { createToast } from "../../../Utils/toastUtils"; import { createToast } from "../../../Utils/toastUtils";
import { logger } from "../../../Utils/Logger"; import { logger } from "../../../Utils/Logger";
@@ -24,6 +24,7 @@ import PulseDot from "../../../Components/Animated/PulseDot";
import SkeletonLayout from "./skeleton"; import SkeletonLayout from "./skeleton";
import LoadingButton from "@mui/lab/LoadingButton"; import LoadingButton from "@mui/lab/LoadingButton";
import "./index.css"; import "./index.css";
import Dialog from "../../../Components/Dialog";
/** /**
* Parses a URL string and returns a URL object. * Parses a URL string and returns a URL object.
@@ -447,71 +448,21 @@ const Configure = () => {
</Stack> </Stack>
</> </>
)} )}
<Modal <Dialog
aria-labelledby="modal-delete-monitor" modelTitle="modal-delete-monitor"
aria-describedby="delete-monitor-confirmation" modelDescription="delete-monitor-confirmation"
open={isOpen} open={isOpen}
onClose={() => setIsOpen(false)} onClose={() => setIsOpen(false)}
disablePortal title="Do you really want to delete this monitor?"
confirmationBtnLbl="Delete"
confirmationBtnOnClick={handleRemove}
cancelBtnLbl="Cancel"
cancelBtnOnClick={() => setIsOpen(false)}
theme={theme}
isLoading={isLoading}
description="Once deleted, this monitor cannot be retrieved."
> >
<Stack </Dialog>
gap={theme.spacing(2)}
sx={{
position: "absolute",
top: "50%",
left: "50%",
transform: "translate(-50%, -50%)",
width: 400,
bgcolor: theme.palette.background.main,
border: 1,
borderColor: theme.palette.border.light,
borderRadius: theme.shape.borderRadius,
boxShadow: 24,
p: theme.spacing(15),
"&:focus": {
outline: "none",
},
}}
>
<Typography
id="modal-delete-monitor"
component="h2"
fontSize={16}
color={theme.palette.text.primary}
fontWeight={600}
>
Do you really want to delete this monitor?
</Typography>
<Typography
id="delete-monitor-confirmation"
color={theme.palette.text.tertiary}
>
Once deleted, this monitor cannot be retrieved.
</Typography>
<Stack
direction="row"
gap={theme.spacing(4)}
mt={theme.spacing(12)}
justifyContent="flex-end"
>
<Button
variant="text"
color="info"
onClick={() => setIsOpen(false)}
>
Cancel
</Button>
<LoadingButton
variant="contained"
color="error"
loading={isLoading}
onClick={handleRemove}
>
Delete
</LoadingButton>
</Stack>
</Stack>
</Modal>
</Stack> </Stack>
); );
}; };
+446 -441
View File
@@ -1,22 +1,19 @@
import PropTypes from "prop-types"; import PropTypes from "prop-types";
import { useEffect, useState, useCallback } from "react"; import { useEffect, useState, useCallback } from "react";
import { import {
Box, Box,
Button, Button,
Popover, Popover,
Stack, Stack,
Tooltip, Tooltip,
Typography, Typography,
useTheme, useTheme,
} from "@mui/material"; } from "@mui/material";
import { useSelector } from "react-redux"; import { useSelector } from "react-redux";
import { useNavigate, useParams } from "react-router-dom"; import { useNavigate, useParams } from "react-router-dom";
import { networkService } from "../../../main"; import { networkService } from "../../../main";
import { logger } from "../../../Utils/Logger"; import { logger } from "../../../Utils/Logger";
import { import { formatDurationRounded, formatDurationSplit } from "../../../Utils/timeUtils";
formatDurationRounded,
formatDurationSplit,
} from "../../../Utils/timeUtils";
import MonitorDetailsAreaChart from "../../../Components/Charts/MonitorDetailsAreaChart"; import MonitorDetailsAreaChart from "../../../Components/Charts/MonitorDetailsAreaChart";
import ButtonGroup from "@mui/material/ButtonGroup"; import ButtonGroup from "@mui/material/ButtonGroup";
import SettingsIcon from "../../../assets/icons/settings-bold.svg?react"; import SettingsIcon from "../../../assets/icons/settings-bold.svg?react";
@@ -41,447 +38,455 @@ import { formatDateWithTz } from "../../../Utils/timeUtils";
* @component * @component
*/ */
const DetailsPage = ({ isAdmin }) => { const DetailsPage = ({ isAdmin }) => {
const theme = useTheme(); const theme = useTheme();
const { statusColor, statusStyles, statusMsg, determineState } = useUtils(); const { statusColor, statusStyles, statusMsg, determineState } = useUtils();
const [monitor, setMonitor] = useState({}); const [monitor, setMonitor] = useState({});
const { monitorId } = useParams(); const { monitorId } = useParams();
const { authToken } = useSelector((state) => state.auth); const { authToken } = useSelector((state) => state.auth);
const [dateRange, setDateRange] = useState("day"); const [dateRange, setDateRange] = useState("day");
const [certificateExpiry, setCertificateExpiry] = useState("N/A"); const [certificateExpiry, setCertificateExpiry] = useState("N/A");
const navigate = useNavigate(); const navigate = useNavigate();
const [anchorEl, setAnchorEl] = useState(null); const [anchorEl, setAnchorEl] = useState(null);
const openCertificate = (event) => { const openCertificate = (event) => {
setAnchorEl(event.currentTarget); setAnchorEl(event.currentTarget);
}; };
const closeCertificate = () => { const closeCertificate = () => {
setAnchorEl(null); setAnchorEl(null);
}; };
const dateFormat = dateRange === "day" ? "MMM D, h A" : "MMM D"; const dateFormat = dateRange === "day" ? "MMM D, h A" : "MMM D";
const uiTimezone = useSelector((state) => state.ui.timezone); const uiTimezone = useSelector((state) => state.ui.timezone);
const fetchMonitor = useCallback(async () => { const fetchMonitor = useCallback(async () => {
try { try {
const res = await networkService.getStatsByMonitorId({ const res = await networkService.getStatsByMonitorId({
authToken: authToken, authToken: authToken,
monitorId: monitorId, monitorId: monitorId,
sortOrder: null, sortOrder: null,
limit: null, limit: null,
dateRange: dateRange, dateRange: dateRange,
numToDisplay: 50, numToDisplay: 50,
normalize: true, normalize: true,
}); });
setMonitor(res?.data?.data ?? {}); setMonitor(res?.data?.data ?? {});
} catch (error) { } catch (error) {
logger.error(error); logger.error(error);
navigate("/not-found", { replace: true }); navigate("/not-found", { replace: true });
} }
}, [authToken, monitorId, navigate, dateRange]); }, [authToken, monitorId, navigate, dateRange]);
useEffect(() => { useEffect(() => {
fetchMonitor(); fetchMonitor();
}, [fetchMonitor]); }, [fetchMonitor]);
useEffect(() => { useEffect(() => {
const fetchCertificate = async () => { const fetchCertificate = async () => {
if (monitor?.type !== "http") { if (monitor?.type !== "http") {
return; return;
} }
try { try {
const res = await networkService.getCertificateExpiry({ const res = await networkService.getCertificateExpiry({
authToken: authToken, authToken: authToken,
monitorId: monitorId, monitorId: monitorId,
}); });
if (res?.data?.data?.certificateDate) {
const date = res.data.data.certificateDate;
setCertificateExpiry(formatDateWithTz(date, dateFormat, uiTimezone) ?? "N/A");
}
} catch (error) {
console.error(error);
}
};
fetchCertificate();
}, [authToken, monitorId, monitor]);
if (res?.data?.data?.certificateDate) { const splitDuration = (duration) => {
let [month, day, year] = res.data.data.certificateDate.split("/"); const { time, format } = formatDurationSplit(duration);
const date = new Date(year, month - 1, day); return (
<>
{time}
<Typography component="span">{format}</Typography>
</>
);
};
setCertificateExpiry( let loading = Object.keys(monitor).length === 0;
formatDateWithTz(date, dateFormat, uiTimezone) ?? "N/A"
);
}
} catch (error) {
console.error(error);
}
};
fetchCertificate();
}, [authToken, monitorId, monitor]);
const splitDuration = (duration) => { const [hoveredUptimeData, setHoveredUptimeData] = useState(null);
const { time, format } = formatDurationSplit(duration); const [hoveredIncidentsData, setHoveredIncidentsData] = useState(null);
return (
<>
{time}
<Typography component="span">{format}</Typography>
</>
);
};
let loading = Object.keys(monitor).length === 0; return (
<Box className="monitor-details">
const [hoveredUptimeData, setHoveredUptimeData] = useState(null); {loading ? (
const [hoveredIncidentsData, setHoveredIncidentsData] = useState(null); <SkeletonLayout />
) : (
return ( <>
<Box className="monitor-details"> <Breadcrumbs
{loading ? ( list={[
<SkeletonLayout /> { name: "monitors", path: "/monitors" },
) : ( { name: "details", path: `/monitors/${monitorId}` },
<> ]}
<Breadcrumbs />
list={[ <Stack
{ name: "monitors", path: "/monitors" }, gap={theme.spacing(10)}
{ name: "details", path: `/monitors/${monitorId}` }, mt={theme.spacing(10)}
]} >
/> <Stack
<Stack gap={theme.spacing(10)} mt={theme.spacing(10)}> direction="row"
<Stack direction="row" gap={theme.spacing(2)}> gap={theme.spacing(2)}
<Box> >
<Typography component="h1" variant="h1"> <Box>
{monitor.name} <Typography
</Typography> component="h1"
<Stack variant="h1"
direction="row" >
alignItems="center" {monitor.name}
height="fit-content" </Typography>
gap={theme.spacing(2)} <Stack
> direction="row"
<Tooltip alignItems="center"
title={statusMsg[determineState(monitor)]} height="fit-content"
disableInteractive gap={theme.spacing(2)}
slotProps={{ >
popper: { <Tooltip
modifiers: [ title={statusMsg[determineState(monitor)]}
{ disableInteractive
name: "offset", slotProps={{
options: { popper: {
offset: [0, -8], modifiers: [
}, {
}, name: "offset",
], options: {
}, offset: [0, -8],
}} },
> },
<Box> ],
<PulseDot color={statusColor[determineState(monitor)]} /> },
</Box> }}
</Tooltip> >
<Typography component="h2" variant="h2"> <Box>
{monitor.url?.replace(/^https?:\/\//, "") || "..."} <PulseDot color={statusColor[determineState(monitor)]} />
</Typography> </Box>
<Typography </Tooltip>
position="relative" <Typography
variant="body2" component="h2"
mt={theme.spacing(1)} variant="h2"
ml={theme.spacing(6)} >
sx={{ {monitor.url?.replace(/^https?:\/\//, "") || "..."}
"&:before": { </Typography>
position: "absolute", <Typography
content: `""`, position="relative"
width: 4, variant="body2"
height: 4, mt={theme.spacing(1)}
borderRadius: "50%", ml={theme.spacing(6)}
backgroundColor: theme.palette.text.tertiary, sx={{
opacity: 0.8, "&:before": {
left: -9, position: "absolute",
top: "50%", content: `""`,
transform: "translateY(-50%)", width: 4,
}, height: 4,
}} borderRadius: "50%",
> backgroundColor: theme.palette.text.tertiary,
Checking every {formatDurationRounded(monitor?.interval)}. opacity: 0.8,
</Typography> left: -9,
</Stack> top: "50%",
</Box> transform: "translateY(-50%)",
<Stack },
direction="row" }}
height={34} >
sx={{ Checking every {formatDurationRounded(monitor?.interval)}.
ml: "auto", </Typography>
alignSelf: "flex-end", </Stack>
}} </Box>
> <Stack
<IconBox direction="row"
mr={theme.spacing(4)} height={34}
onClick={openCertificate} sx={{
sx={{ ml: "auto",
cursor: "pointer", alignSelf: "flex-end",
"& svg": { }}
width: 23, >
height: 23, <IconBox
top: "52%", mr={theme.spacing(4)}
}, onClick={openCertificate}
}} sx={{
> cursor: "pointer",
<CertificateIcon /> "& svg": {
</IconBox> width: 23,
<Popover height: 23,
id="certificate-dropdown" top: "52%",
anchorEl={anchorEl} },
open={Boolean(anchorEl)} }}
onClose={closeCertificate} >
disableScrollLock <CertificateIcon />
marginThreshold={null} </IconBox>
anchorOrigin={{ <Popover
vertical: "bottom", id="certificate-dropdown"
horizontal: "center", anchorEl={anchorEl}
}} open={Boolean(anchorEl)}
transformOrigin={{ onClose={closeCertificate}
vertical: "top", disableScrollLock
horizontal: "center", marginThreshold={null}
}} anchorOrigin={{
slotProps={{ vertical: "bottom",
paper: { horizontal: "center",
sx: { }}
mt: theme.spacing(4), transformOrigin={{
py: theme.spacing(2), vertical: "top",
px: theme.spacing(4), horizontal: "center",
width: 140, }}
backgroundColor: theme.palette.background.accent, slotProps={{
}, paper: {
}, sx: {
}} mt: theme.spacing(4),
> py: theme.spacing(2),
<Typography variant="body2">Certificate Expiry</Typography> px: theme.spacing(4),
<Typography width: 140,
component="span" backgroundColor: theme.palette.background.accent,
fontSize={13} },
color={theme.palette.text.primary} },
> }}
{certificateExpiry} >
</Typography> <Typography variant="body2">Certificate Expiry</Typography>
</Popover> <Typography
{isAdmin && ( component="span"
<Button fontSize={13}
variant="contained" color={theme.palette.text.primary}
color="secondary" >
onClick={() => navigate(`/monitors/configure/${monitorId}`)} {certificateExpiry}
sx={{ </Typography>
px: theme.spacing(5), </Popover>
"& svg": { {isAdmin && (
mr: theme.spacing(3), <Button
"& path": { variant="contained"
stroke: theme.palette.text.tertiary, color="secondary"
}, onClick={() => navigate(`/monitors/configure/${monitorId}`)}
}, sx={{
}} px: theme.spacing(5),
> "& svg": {
<SettingsIcon /> Configure mr: theme.spacing(3),
</Button> "& path": {
)} stroke: theme.palette.text.tertiary,
</Stack> },
</Stack> },
<Stack direction="row" gap={theme.spacing(8)}> }}
<StatBox sx={statusStyles[determineState(monitor)]}> >
<Typography component="h2">active for</Typography> <SettingsIcon /> Configure
<Typography> </Button>
{splitDuration(monitor?.uptimeDuration)} )}
</Typography> </Stack>
</StatBox> </Stack>
<StatBox> <Stack
<Typography component="h2">last check</Typography> direction="row"
<Typography> gap={theme.spacing(8)}
{splitDuration(monitor?.lastChecked)} >
<Typography component="span">ago</Typography> <StatBox sx={statusStyles[determineState(monitor)]}>
</Typography> <Typography component="h2">active for</Typography>
</StatBox> <Typography>{splitDuration(monitor?.uptimeDuration)}</Typography>
<StatBox> </StatBox>
<Typography component="h2">last response time</Typography> <StatBox>
<Typography> <Typography component="h2">last check</Typography>
{monitor?.latestResponseTime} <Typography>
<Typography component="span">ms</Typography> {splitDuration(monitor?.lastChecked)}
</Typography> <Typography component="span">ago</Typography>
</StatBox> </Typography>
</Stack> </StatBox>
<Box> <StatBox>
<Stack <Typography component="h2">last response time</Typography>
direction="row" <Typography>
justifyContent="space-between" {monitor?.latestResponseTime}
alignItems="flex-end" <Typography component="span">ms</Typography>
gap={theme.spacing(4)} </Typography>
mb={theme.spacing(8)} </StatBox>
> </Stack>
<Typography variant="body2"> <Box>
Showing statistics for past{" "} <Stack
{dateRange === "day" direction="row"
? "24 hours" justifyContent="space-between"
: dateRange === "week" alignItems="flex-end"
? "7 days" gap={theme.spacing(4)}
: "30 days"} mb={theme.spacing(8)}
. >
</Typography> <Typography variant="body2">
<ButtonGroup sx={{ height: 32 }}> Showing statistics for past{" "}
<Button {dateRange === "day"
variant="group" ? "24 hours"
filled={(dateRange === "day").toString()} : dateRange === "week"
onClick={() => setDateRange("day")} ? "7 days"
> : "30 days"}
Day .
</Button> </Typography>
<Button <ButtonGroup sx={{ height: 32 }}>
variant="group" <Button
filled={(dateRange === "week").toString()} variant="group"
onClick={() => setDateRange("week")} filled={(dateRange === "day").toString()}
> onClick={() => setDateRange("day")}
Week >
</Button> Day
<Button </Button>
variant="group" <Button
filled={(dateRange === "month").toString()} variant="group"
onClick={() => setDateRange("month")} filled={(dateRange === "week").toString()}
> onClick={() => setDateRange("week")}
Month >
</Button> Week
</ButtonGroup> </Button>
</Stack> <Button
<Stack direction="row" flexWrap="wrap" gap={theme.spacing(8)}> variant="group"
<ChartBox> filled={(dateRange === "month").toString()}
<Stack> onClick={() => setDateRange("month")}
<IconBox> >
<UptimeIcon /> Month
</IconBox> </Button>
<Typography component="h2">Uptime</Typography> </ButtonGroup>
</Stack> </Stack>
<Stack justifyContent="space-between"> <Stack
<Box position="relative"> direction="row"
<Typography>Total Checks</Typography> flexWrap="wrap"
<Typography component="span"> gap={theme.spacing(8)}
{hoveredUptimeData !== null >
? hoveredUptimeData.totalChecks <ChartBox>
: monitor?.periodTotalChecks} <Stack>
</Typography> <IconBox>
{hoveredUptimeData !== null && <UptimeIcon />
hoveredUptimeData.time !== null && ( </IconBox>
<Typography <Typography component="h2">Uptime</Typography>
component="h5" </Stack>
position="absolute" <Stack justifyContent="space-between">
top="100%" <Box position="relative">
fontSize={11} <Typography>Total Checks</Typography>
color={theme.palette.text.tertiary} <Typography component="span">
> {hoveredUptimeData !== null
{formatDateWithTz( ? hoveredUptimeData.totalChecks
hoveredUptimeData.time, : monitor?.periodTotalChecks}
dateFormat, </Typography>
uiTimezone {hoveredUptimeData !== null && hoveredUptimeData.time !== null && (
)} <Typography
</Typography> component="h5"
)} position="absolute"
</Box> top="100%"
<Box> fontSize={11}
<Typography>Uptime Percentage</Typography> color={theme.palette.text.tertiary}
<Typography component="span"> >
{hoveredUptimeData !== null {formatDateWithTz(
? Math.floor( hoveredUptimeData.time,
hoveredUptimeData.uptimePercentage * 10 dateFormat,
) / 10 uiTimezone
: Math.floor(monitor?.periodUptime * 10) / 10} )}
<Typography component="span">%</Typography> </Typography>
</Typography> )}
</Box> </Box>
</Stack> <Box>
<UpBarChart <Typography>Uptime Percentage</Typography>
data={monitor?.aggregateData} <Typography component="span">
type={dateRange} {hoveredUptimeData !== null
onBarHover={setHoveredUptimeData} ? Math.floor(hoveredUptimeData.uptimePercentage * 10) / 10
/> : Math.floor(monitor?.periodUptime * 10) / 10}
</ChartBox> <Typography component="span">%</Typography>
<ChartBox> </Typography>
<Stack> </Box>
<IconBox> </Stack>
<IncidentsIcon /> <UpBarChart
</IconBox> data={monitor?.aggregateData}
<Typography component="h2">Incidents</Typography> type={dateRange}
</Stack> onBarHover={setHoveredUptimeData}
<Box position="relative"> />
<Typography>Total Incidents</Typography> </ChartBox>
<Typography component="span"> <ChartBox>
{hoveredIncidentsData !== null <Stack>
? hoveredIncidentsData.totalIncidents <IconBox>
: monitor?.periodIncidents} <IncidentsIcon />
</Typography> </IconBox>
{hoveredIncidentsData !== null && <Typography component="h2">Incidents</Typography>
hoveredIncidentsData.time !== null && ( </Stack>
<Typography <Box position="relative">
component="h5" <Typography>Total Incidents</Typography>
position="absolute" <Typography component="span">
top="100%" {hoveredIncidentsData !== null
fontSize={11} ? hoveredIncidentsData.totalIncidents
color={theme.palette.text.tertiary} : monitor?.periodIncidents}
> </Typography>
{formatDateWithTz( {hoveredIncidentsData !== null &&
hoveredIncidentsData.time, hoveredIncidentsData.time !== null && (
dateFormat, <Typography
uiTimezone component="h5"
)} position="absolute"
</Typography> top="100%"
)} fontSize={11}
</Box> color={theme.palette.text.tertiary}
<DownBarChart >
data={monitor?.aggregateData} {formatDateWithTz(
type={dateRange} hoveredIncidentsData.time,
onBarHover={setHoveredIncidentsData} dateFormat,
/> uiTimezone
</ChartBox> )}
<ChartBox justifyContent="space-between"> </Typography>
<Stack> )}
<IconBox> </Box>
<AverageResponseIcon /> <DownBarChart
</IconBox> data={monitor?.aggregateData}
<Typography component="h2"> type={dateRange}
Average Response Time onBarHover={setHoveredIncidentsData}
</Typography> />
</Stack> </ChartBox>
<ResponseGaugeChart <ChartBox justifyContent="space-between">
data={[{ response: monitor?.periodAvgResponseTime }]} <Stack>
/> <IconBox>
</ChartBox> <AverageResponseIcon />
<ChartBox sx={{ padding: 0 }}> </IconBox>
<Stack pt={theme.spacing(8)} pl={theme.spacing(8)}> <Typography component="h2">Average Response Time</Typography>
<IconBox> </Stack>
<ResponseTimeIcon /> <ResponseGaugeChart
</IconBox> data={[{ response: monitor?.periodAvgResponseTime }]}
<Typography component="h2">Response Times</Typography> />
</Stack> </ChartBox>
<MonitorDetailsAreaChart <ChartBox sx={{ padding: 0 }}>
checks={[...monitor.checks].reverse()} <Stack
/> pt={theme.spacing(8)}
</ChartBox> pl={theme.spacing(8)}
<ChartBox >
gap={theme.spacing(8)} <IconBox>
sx={{ <ResponseTimeIcon />
flex: "100%", </IconBox>
height: "fit-content", <Typography component="h2">Response Times</Typography>
"& nav": { mt: theme.spacing(12) }, </Stack>
}} <MonitorDetailsAreaChart checks={[...monitor.checks].reverse()} />
> </ChartBox>
<Stack mb={theme.spacing(8)}> <ChartBox
<IconBox> gap={theme.spacing(8)}
<HistoryIcon /> sx={{
</IconBox> flex: "100%",
<Typography height: "fit-content",
component="h2" "& nav": { mt: theme.spacing(12) },
color={theme.palette.text.secondary} }}
> >
History <Stack mb={theme.spacing(8)}>
</Typography> <IconBox>
</Stack> <HistoryIcon />
<PaginationTable </IconBox>
monitorId={monitorId} <Typography
dateRange={dateRange} component="h2"
/> color={theme.palette.text.secondary}
</ChartBox> >
</Stack> History
</Box> </Typography>
</Stack> </Stack>
</> <PaginationTable
)} monitorId={monitorId}
</Box> dateRange={dateRange}
); />
</ChartBox>
</Stack>
</Box>
</Stack>
</>
)}
</Box>
);
}; };
DetailsPage.propTypes = { DetailsPage.propTypes = {
isAdmin: PropTypes.bool, isAdmin: PropTypes.bool,
}; };
export default DetailsPage; export default DetailsPage;
+16 -67
View File
@@ -5,13 +5,9 @@ import { useNavigate } from "react-router-dom";
import { createToast } from "../../../Utils/toastUtils"; import { createToast } from "../../../Utils/toastUtils";
import { logger } from "../../../Utils/Logger"; import { logger } from "../../../Utils/Logger";
import { import {
Button,
IconButton, IconButton,
Menu, Menu,
MenuItem, MenuItem
Modal,
Stack,
Typography,
} from "@mui/material"; } from "@mui/material";
import { import {
deleteUptimeMonitor, deleteUptimeMonitor,
@@ -20,6 +16,7 @@ import {
} from "../../../Features/UptimeMonitors/uptimeMonitorsSlice"; } from "../../../Features/UptimeMonitors/uptimeMonitorsSlice";
import Settings from "../../../assets/icons/settings-bold.svg?react"; import Settings from "../../../assets/icons/settings-bold.svg?react";
import PropTypes from "prop-types"; import PropTypes from "prop-types";
import Dialog from "../../../Components/Dialog"
const ActionsMenu = ({ monitor, isAdmin, updateCallback }) => { const ActionsMenu = ({ monitor, isAdmin, updateCallback }) => {
const [anchorEl, setAnchorEl] = useState(null); const [anchorEl, setAnchorEl] = useState(null);
@@ -29,7 +26,7 @@ const ActionsMenu = ({ monitor, isAdmin, updateCallback }) => {
const theme = useTheme(); const theme = useTheme();
const authState = useSelector((state) => state.auth); const authState = useSelector((state) => state.auth);
const authToken = authState.authToken; const authToken = authState.authToken;
const { isLoading } = useSelector((state) => state.uptimeMonitors);
const handleRemove = async (event) => { const handleRemove = async (event) => {
event.preventDefault(); event.preventDefault();
@@ -199,69 +196,21 @@ const ActionsMenu = ({ monitor, isAdmin, updateCallback }) => {
</MenuItem> </MenuItem>
)} )}
</Menu> </Menu>
<Modal <Dialog
aria-labelledby="modal-delete-monitor" modelTitle="modal-delete-monitor"
aria-describedby="delete-monitor-confirmation" modelDescription="delete-monitor-confirmation"
open={isOpen} open={isOpen}
onClose={(e) => { onClose={() => setIsOpen(false)}
e.stopPropagation(); title="Do you really want to delete this monitor?"
setIsOpen(false); confirmationBtnLbl="Delete"
}} confirmationBtnOnClick={e => { e.stopPropagation(); handleRemove(e) }}
cancelBtnLbl="Cancel"
cancelBtnOnClick={e => { e.stopPropagation(); setIsOpen(false) }}
theme={theme}
isLoading={isLoading}
description="Once deleted, this monitor cannot be retrieved."
> >
<Stack </Dialog>
gap={theme.spacing(2)}
sx={{
position: "absolute",
top: "50%",
left: "50%",
transform: "translate(-50%, -50%)",
width: 400,
bgcolor: theme.palette.background.main,
border: 1,
borderColor: theme.palette.border.light,
borderRadius: theme.shape.borderRadius,
boxShadow: 24,
p: theme.spacing(15),
"&:focus": {
outline: "none",
},
}}
>
<Typography id="modal-delete-monitor" component="h2" variant="h2">
Do you really want to delete this monitor?
</Typography>
<Typography id="delete-monitor-confirmation" variant="body1">
Once deleted, this monitor cannot be retrieved.
</Typography>
<Stack
direction="row"
gap={theme.spacing(4)}
mt={theme.spacing(12)}
justifyContent="flex-end"
>
<Button
variant="text"
color="info"
onClick={(e) => {
e.stopPropagation();
setIsOpen(false);
}}
>
Cancel
</Button>
<Button
variant="contained"
color="error"
onClick={(e) => {
e.stopPropagation(e);
handleRemove(e);
}}
>
Delete
</Button>
</Stack>
</Stack>
</Modal>
</> </>
); );
}; };
+1 -1
View File
@@ -45,7 +45,7 @@ const Monitors = ({ isAdmin }) => {
monitorState?.monitorsSummary?.monitors?.length === 0; monitorState?.monitorsSummary?.monitors?.length === 0;
return ( return (
<Stack className="monitors" gap={theme.spacing(8)}> <Stack className="monitors table-container" gap={theme.spacing(8)}>
{loading ? ( {loading ? (
<SkeletonLayout /> <SkeletonLayout />
) : ( ) : (
+41 -7
View File
@@ -22,6 +22,7 @@ import { ConfigBox } from "./styled";
import { networkService } from "../../main"; import { networkService } from "../../main";
import { settingsValidation } from "../../Validation/validation"; import { settingsValidation } from "../../Validation/validation";
import { useNavigate } from "react-router"; import { useNavigate } from "react-router";
import Dialog from "../../Components/Dialog"
const SECONDS_PER_DAY = 86400; const SECONDS_PER_DAY = 86400;
@@ -39,6 +40,8 @@ const Settings = ({ isAdmin }) => {
}); });
const [version,setVersion]=useState("unknown"); const [version,setVersion]=useState("unknown");
const [errors, setErrors] = useState({}); const [errors, setErrors] = useState({});
const deleteStatsMonitorsInitState = { deleteMonitors: false, deleteStats: false };
const [isOpen, setIsOpen] = useState(deleteStatsMonitorsInitState);
const dispatch = useDispatch(); const dispatch = useDispatch();
const navigate = useNavigate(); const navigate = useNavigate();
@@ -139,6 +142,8 @@ const Settings = ({ isAdmin }) => {
} catch (error) { } catch (error) {
logger.error(error); logger.error(error);
createToast({ body: "Failed to clear stats" }); createToast({ body: "Failed to clear stats" });
} finally {
setIsOpen(deleteStatsMonitorsInitState)
} }
}; };
@@ -167,9 +172,11 @@ const Settings = ({ isAdmin }) => {
} catch (error) { } catch (error) {
logger.error(error); logger.error(error);
createToast({ Body: "Failed to delete all monitors" }); createToast({ Body: "Failed to delete all monitors" });
} finally {
setIsOpen(deleteStatsMonitorsInitState)
} }
}; };
return ( return (
<Box <Box
className="settings" className="settings"
@@ -243,17 +250,30 @@ const Settings = ({ isAdmin }) => {
/> />
<Box> <Box>
<Typography>Clear all stats. This is irreversible.</Typography> <Typography>Clear all stats. This is irreversible.</Typography>
<LoadingButton <Button
variant="contained" variant="contained"
color="error" color="error"
loading={isLoading || authIsLoading || checksIsLoading} onClick={()=>setIsOpen({...deleteStatsMonitorsInitState, deleteStats: true})}
onClick={handleClearStats}
sx={{ mt: theme.spacing(4) }} sx={{ mt: theme.spacing(4) }}
> >
Clear all stats Clear all stats
</LoadingButton> </Button>
</Box> </Box>
</Stack> </Stack>
<Dialog
modelTitle="model-clear-stats"
modelDescription="clear-stats-confirmation"
open={isOpen.deleteStats}
onClose={() => setIsOpen(deleteStatsMonitorsInitState)}
title="Do you want to clear all stats?"
confirmationBtnLbl="Yes, clear all stats"
confirmationBtnOnClick={handleClearStats}
cancelBtnLbl="Cancel"
cancelBtnOnClick={() => setIsOpen(deleteStatsMonitorsInitState)}
theme={theme}
isLoading={isLoading || authIsLoading || checksIsLoading}
>
</Dialog>
</ConfigBox> </ConfigBox>
)} )}
{isAdmin && ( {isAdmin && (
@@ -283,13 +303,27 @@ const Settings = ({ isAdmin }) => {
variant="contained" variant="contained"
color="error" color="error"
loading={isLoading || authIsLoading || checksIsLoading} loading={isLoading || authIsLoading || checksIsLoading}
onClick={handleDeleteAllMonitors} onClick={()=>setIsOpen({...deleteStatsMonitorsInitState, deleteMonitors: true})}
sx={{ mt: theme.spacing(4) }} sx={{ mt: theme.spacing(4) }}
> >
Remove all monitors Remove all monitors
</LoadingButton> </LoadingButton>
</Box> </Box>
</Stack> </Stack>
<Dialog
modelTitle="model-delete-all-monitors"
modelDescription="delete-all-monitors-confirmation"
open={isOpen.deleteMonitors}
onClose={() => setIsOpen(deleteStatsMonitorsInitState)}
title="Do you want to remove all monitors?"
confirmationBtnLbl="Yes, clear all monitors"
confirmationBtnOnClick={handleDeleteAllMonitors}
cancelBtnLbl="Cancel"
cancelBtnOnClick={() => setIsOpen(deleteStatsMonitorsInitState)}
theme={theme}
isLoading={isLoading || authIsLoading || checksIsLoading}
>
</Dialog>
</ConfigBox> </ConfigBox>
)} )}
{isAdmin && ( {isAdmin && (
+8
View File
@@ -0,0 +1,8 @@
module.exports = {
require: ["esm", "chai/register-expect.js"], // Include Chai's "expect" interface globally
spec: "tests/**/*.test.js", // Specify test files
timeout: 5000, // Set test-case timeout in milliseconds
recursive: true, // Include subdirectories
reporter: "spec", // Use the "spec" reporter
exit: true, // Force Mocha to quit after tests complete
};
-8
View File
@@ -1,8 +0,0 @@
module.exports = {
require: ["chai/register-expect.js"], // Include Chai's "expect" interface globally
spec: "tests/**/*.test.js", // Specify test files
timeout: 5000, // Set test-case timeout in milliseconds
recursive: true, // Include subdirectories
reporter: "spec", // Use the "spec" reporter
exit: true, // Force Mocha to quit after tests complete
};
+6 -6
View File
@@ -1,8 +1,8 @@
{ {
"all": true, "all": true,
"include": ["controllers/*.js"], "include": ["controllers/*.js", "utils/*.js"],
"exclude": ["**/*.test.js"], "exclude": ["**/*.test.js"],
"reporter": ["html", "text", "lcov"], "reporter": ["html", "text", "lcov"],
"sourceMap": false, "sourceMap": false,
"instrument": true "instrument": true
} }
+1 -1
View File
@@ -12,4 +12,4 @@ const connectDbAndRunServer = async (app, db) => {
} }
}; };
module.exports = { connectDbAndRunServer }; export { connectDbAndRunServer };
+311 -306
View File
@@ -1,20 +1,21 @@
const { import {
registrationBodyValidation, registrationBodyValidation,
loginValidation, loginValidation,
editUserParamValidation, editUserParamValidation,
editUserBodyValidation, editUserBodyValidation,
recoveryValidation, recoveryValidation,
recoveryTokenValidation, recoveryTokenValidation,
newPasswordValidation, newPasswordValidation,
} = require("../validation/joi"); } from "../validation/joi.js";
const logger = require("../utils/logger"); import logger from "../utils/logger.js";
require("dotenv").config(); import dotenv from "dotenv";
const { errorMessages, successMessages } = require("../utils/messages"); import { errorMessages, successMessages } from "../utils/messages.js";
const jwt = require("jsonwebtoken"); import jwt from "jsonwebtoken";
const SERVICE_NAME = "AuthController"; import { getTokenFromHeaders, tokenType } from "../utils/utils.js";
const { getTokenFromHeaders, tokenType } = require("../utils/utils"); import crypto from "crypto";
const crypto = require("crypto"); import { handleValidationError, handleError } from "./controllerUtils.js";
const { handleValidationError, handleError } = require("./controllerUtils"); const SERVICE_NAME = "authController";
dotenv.config();
/** /**
* Creates and returns JWT token with an arbitrary payload * Creates and returns JWT token with an arbitrary payload
@@ -26,15 +27,21 @@ const { handleValidationError, handleError } = require("./controllerUtils");
* @throws {Error} * @throws {Error}
*/ */
const issueToken = (payload, typeOfToken, appSettings) => { const issueToken = (payload, typeOfToken, appSettings) => {
try { try {
const tokenTTL = (typeOfToken === tokenType.REFRESH_TOKEN) ? (appSettings?.refreshTokenTTL?? "7d") : (appSettings?.jwtTTL?? "2h"); const tokenTTL =
const tokenSecret = (typeOfToken === tokenType.REFRESH_TOKEN) ? appSettings?.refreshTokenSecret : appSettings?.jwtSecret; typeOfToken === tokenType.REFRESH_TOKEN
const payloadData = (typeOfToken === tokenType.REFRESH_TOKEN) ? {} : payload; ? (appSettings?.refreshTokenTTL ?? "7d")
: (appSettings?.jwtTTL ?? "2h");
const tokenSecret =
typeOfToken === tokenType.REFRESH_TOKEN
? appSettings?.refreshTokenSecret
: appSettings?.jwtSecret;
const payloadData = typeOfToken === tokenType.REFRESH_TOKEN ? {} : payload;
return jwt.sign(payloadData, tokenSecret, { expiresIn: tokenTTL }); return jwt.sign(payloadData, tokenSecret, { expiresIn: tokenTTL });
} catch (error) { } catch (error) {
throw handleError(error, SERVICE_NAME, "issueToken"); throw handleError(error, SERVICE_NAME, "issueToken");
} }
}; };
/** /**
@@ -50,66 +57,65 @@ const issueToken = (payload, typeOfToken, appSettings) => {
* @throws {Error} If there is an error during the process, especially if there is a validation error (422). * @throws {Error} If there is an error during the process, especially if there is a validation error (422).
*/ */
const registerUser = async (req, res, next) => { const registerUser = async (req, res, next) => {
// joi validation // joi validation
try { try {
await registrationBodyValidation.validateAsync(req.body); await registrationBodyValidation.validateAsync(req.body);
} catch (error) { } catch (error) {
const validationError = handleValidationError(error, SERVICE_NAME); const validationError = handleValidationError(error, SERVICE_NAME);
next(validationError); next(validationError);
return; return;
} }
// Create a new user // Create a new user
try { try {
const { inviteToken } = req.body; const { inviteToken } = req.body;
// If superAdmin exists, a token should be attached to all further register requests // If superAdmin exists, a token should be attached to all further register requests
const superAdminExists = await req.db.checkSuperadmin(req, res); const superAdminExists = await req.db.checkSuperadmin(req, res);
if (superAdminExists) { if (superAdminExists) {
await req.db.getInviteTokenAndDelete(inviteToken); await req.db.getInviteTokenAndDelete(inviteToken);
} else { } else {
// This is the first account, create JWT secret to use if one is not supplied by env // This is the first account, create JWT secret to use if one is not supplied by env
const jwtSecret = crypto.randomBytes(64).toString("hex"); const jwtSecret = crypto.randomBytes(64).toString("hex");
await req.db.updateAppSettings({ jwtSecret }); await req.db.updateAppSettings({ jwtSecret });
} }
const newUser = await req.db.insertUser({ ...req.body }, req.file); const newUser = await req.db.insertUser({ ...req.body }, req.file);
logger.info(successMessages.AUTH_CREATE_USER, { logger.info(successMessages.AUTH_CREATE_USER, {
service: SERVICE_NAME, service: SERVICE_NAME,
userId: newUser._id, userId: newUser._id,
}); });
const userForToken = { ...newUser._doc }; const userForToken = { ...newUser._doc };
delete userForToken.profileImage; delete userForToken.profileImage;
delete userForToken.avatarImage; delete userForToken.avatarImage;
const appSettings = await req.settingsService.getSettings(); const appSettings = await req.settingsService.getSettings();
const token = issueToken(userForToken, tokenType.ACCESS_TOKEN, appSettings); const token = issueToken(userForToken, tokenType.ACCESS_TOKEN, appSettings);
const refreshToken = issueToken({}, tokenType.REFRESH_TOKEN, appSettings); const refreshToken = issueToken({}, tokenType.REFRESH_TOKEN, appSettings);
req.emailService req.emailService
.buildAndSendEmail( .buildAndSendEmail(
"welcomeEmailTemplate", "welcomeEmailTemplate",
{ name: newUser.firstName }, { name: newUser.firstName },
newUser.email, newUser.email,
"Welcome to Uptime Monitor" "Welcome to Uptime Monitor"
) )
.catch((error) => { .catch((error) => {
logger.error("Error sending welcome email", { logger.error("Error sending welcome email", {
service: SERVICE_NAME, service: SERVICE_NAME,
error: error.message, error: error.message,
}); });
}); });
return res.status(200).json({ return res.status(200).json({
success: true, success: true,
msg: successMessages.AUTH_CREATE_USER, msg: successMessages.AUTH_CREATE_USER,
data: { user: newUser, token: token, refreshToken: refreshToken }, data: { user: newUser, token: token, refreshToken: refreshToken },
}); });
} catch (error) { } catch (error) {
console.log("ERROR", error); next(handleError(error, SERVICE_NAME, "registerController"));
next(handleError(error, SERVICE_NAME, "registerController")); }
}
}; };
/** /**
@@ -125,45 +131,46 @@ const registerUser = async (req, res, next) => {
* @throws {Error} If there is an error during the process, especially if there is a validation error (422) or the password is incorrect. * @throws {Error} If there is an error during the process, especially if there is a validation error (422) or the password is incorrect.
*/ */
const loginUser = async (req, res, next) => { const loginUser = async (req, res, next) => {
try { try {
await loginValidation.validateAsync(req.body); await loginValidation.validateAsync(req.body);
} catch (error) { } catch (error) {
const validationError = handleValidationError(error, SERVICE_NAME); const validationError = handleValidationError(error, SERVICE_NAME);
next(validationError); next(validationError);
return; return;
} }
try { try {
const { email, password } = req.body; const { email, password } = req.body;
// Check if user exists
const user = await req.db.getUserByEmail(email);
// Compare password // Check if user exists
const match = await user.comparePassword(password); const user = await req.db.getUserByEmail(email);
if (match !== true) {
next(new Error(errorMessages.AUTH_INCORRECT_PASSWORD));
return;
}
// Remove password from user object. Should this be abstracted to DB layer? // Compare password
const userWithoutPassword = { ...user._doc }; const match = await user.comparePassword(password);
delete userWithoutPassword.password; if (match !== true) {
delete userWithoutPassword.avatarImage; next(new Error(errorMessages.AUTH_INCORRECT_PASSWORD));
return;
}
// Happy path, return token // Remove password from user object. Should this be abstracted to DB layer?
const appSettings = await req.settingsService.getSettings(); const userWithoutPassword = { ...user._doc };
const token = issueToken(userWithoutPassword, tokenType.ACCESS_TOKEN, appSettings); delete userWithoutPassword.password;
const refreshToken = issueToken({}, tokenType.REFRESH_TOKEN, appSettings); delete userWithoutPassword.avatarImage;
// reset avatar image
userWithoutPassword.avatarImage = user.avatarImage;
return res.status(200).json({ // Happy path, return token
success: true, const appSettings = await req.settingsService.getSettings();
msg: successMessages.AUTH_LOGIN_USER, const token = issueToken(userWithoutPassword, tokenType.ACCESS_TOKEN, appSettings);
data: { user: userWithoutPassword, token: token, refreshToken: refreshToken }, const refreshToken = issueToken({}, tokenType.REFRESH_TOKEN, appSettings);
}); // reset avatar image
} catch (error) { userWithoutPassword.avatarImage = user.avatarImage;
next(handleError(error, SERVICE_NAME, "loginController"));
} return res.status(200).json({
success: true,
msg: successMessages.AUTH_LOGIN_USER,
data: { user: userWithoutPassword, token: token, refreshToken: refreshToken },
});
} catch (error) {
next(handleError(error, SERVICE_NAME, "loginUser"));
}
}; };
/** /**
@@ -181,58 +188,58 @@ const loginUser = async (req, res, next) => {
* @throws {Error} If there is an error during the process, especially if there is a validation error (422), the user is unauthorized (401), or the password is incorrect (403). * @throws {Error} If there is an error during the process, especially if there is a validation error (422), the user is unauthorized (401), or the password is incorrect (403).
*/ */
const editUser = async (req, res, next) => { const editUser = async (req, res, next) => {
try { try {
await editUserParamValidation.validateAsync(req.params); await editUserParamValidation.validateAsync(req.params);
await editUserBodyValidation.validateAsync(req.body); await editUserBodyValidation.validateAsync(req.body);
} catch (error) { } catch (error) {
const validationError = handleValidationError(error, SERVICE_NAME); const validationError = handleValidationError(error, SERVICE_NAME);
next(validationError); next(validationError);
return; return;
} }
// TODO is this neccessary any longer? Verify ownership middleware should handle this // TODO is this neccessary any longer? Verify ownership middleware should handle this
if (req.params.userId !== req.user._id.toString()) { if (req.params.userId !== req.user._id.toString()) {
const error = new Error(errorMessages.AUTH_UNAUTHORIZED); const error = new Error(errorMessages.AUTH_UNAUTHORIZED);
error.status = 401; error.status = 401;
error.service = SERVICE_NAME; error.service = SERVICE_NAME;
next(error); next(error);
return; return;
} }
try { try {
// Change Password check // Change Password check
if (req.body.password && req.body.newPassword) { if (req.body.password && req.body.newPassword) {
// Get token from headers // Get token from headers
const token = getTokenFromHeaders(req.headers); const token = getTokenFromHeaders(req.headers);
// Get email from token // Get email from token
const { jwtSecret } = req.settingsService.getSettings(); const { jwtSecret } = req.settingsService.getSettings();
const { email } = jwt.verify(token, jwtSecret); const { email } = jwt.verify(token, jwtSecret);
// Add user email to body for DB operation // Add user email to body for DB operation
req.body.email = email; req.body.email = email;
// Get user // Get user
const user = await req.db.getUserByEmail(email); const user = await req.db.getUserByEmail(email);
// Compare passwords // Compare passwords
const match = await user.comparePassword(req.body.password); const match = await user.comparePassword(req.body.password);
// If not a match, throw a 403 // If not a match, throw a 403
if (!match) { if (!match) {
const error = new Error(errorMessages.AUTH_INCORRECT_PASSWORD); const error = new Error(errorMessages.AUTH_INCORRECT_PASSWORD);
error.status = 403; error.status = 403;
next(error); next(error);
return; return;
} }
// If a match, update the password // If a match, update the password
req.body.password = req.body.newPassword; req.body.password = req.body.newPassword;
} }
const updatedUser = await req.db.updateUser(req, res); const updatedUser = await req.db.updateUser(req, res);
return res.status(200).json({ return res.status(200).json({
success: true, success: true,
msg: successMessages.AUTH_UPDATE_USER, msg: successMessages.AUTH_UPDATE_USER,
data: updatedUser, data: updatedUser,
}); });
} catch (error) { } catch (error) {
next(handleError(error, SERVICE_NAME, "userEditController")); next(handleError(error, SERVICE_NAME, "userEditController"));
} }
}; };
/** /**
@@ -244,17 +251,17 @@ const editUser = async (req, res, next) => {
* @returns {Object} The response object with a success status, a message indicating the existence of a superadmin, and a boolean indicating the existence of a superadmin. * @returns {Object} The response object with a success status, a message indicating the existence of a superadmin, and a boolean indicating the existence of a superadmin.
* @throws {Error} If there is an error during the process. * @throws {Error} If there is an error during the process.
*/ */
const checkSuperAdminExists = async (req, res, next) => { const checkSuperadminExists = async (req, res, next) => {
try { try {
const superAdminExists = await req.db.checkSuperadmin(req, res); const superAdminExists = await req.db.checkSuperadmin(req, res);
return res.status(200).json({ return res.status(200).json({
success: true, success: true,
msg: successMessages.AUTH_ADMIN_EXISTS, msg: successMessages.AUTH_ADMIN_EXISTS,
data: superAdminExists, data: superAdminExists,
}); });
} catch (error) { } catch (error) {
next(handleError(error, SERVICE_NAME, "checkSuperadminController")); next(handleError(error, SERVICE_NAME, "checkSuperadminController"));
} }
}; };
/** /**
@@ -269,46 +276,46 @@ const checkSuperAdminExists = async (req, res, next) => {
* @throws {Error} If there is an error during the process, especially if there is a validation error (422). * @throws {Error} If there is an error during the process, especially if there is a validation error (422).
*/ */
const requestRecovery = async (req, res, next) => { const requestRecovery = async (req, res, next) => {
try { try {
await recoveryValidation.validateAsync(req.body); await recoveryValidation.validateAsync(req.body);
} catch (error) { } catch (error) {
const validationError = handleValidationError(error, SERVICE_NAME); const validationError = handleValidationError(error, SERVICE_NAME);
next(validationError); next(validationError);
return; return;
} }
try { try {
const { email } = req.body; const { email } = req.body;
const user = await req.db.getUserByEmail(email); const user = await req.db.getUserByEmail(email);
if (user) { if (user) {
const recoveryToken = await req.db.requestRecoveryToken(req, res); const recoveryToken = await req.db.requestRecoveryToken(req, res);
const name = user.firstName; const name = user.firstName;
const email = req.body.email; const email = req.body.email;
const { clientHost } = req.settingsService.getSettings(); const { clientHost } = req.settingsService.getSettings();
const url = `${clientHost}/set-new-password/${recoveryToken.token}`; const url = `${clientHost}/set-new-password/${recoveryToken.token}`;
const msgId = await req.emailService.buildAndSendEmail( const msgId = await req.emailService.buildAndSendEmail(
"passwordResetTemplate", "passwordResetTemplate",
{ {
name, name,
email, email,
url, url,
}, },
email, email,
"Bluewave Uptime Password Reset" "Bluewave Uptime Password Reset"
); );
return res.status(200).json({ return res.status(200).json({
success: true, success: true,
msg: successMessages.AUTH_CREATE_RECOVERY_TOKEN, msg: successMessages.AUTH_CREATE_RECOVERY_TOKEN,
data: msgId, data: msgId,
}); });
} else { } else {
throw new Error(errorMessages.FRIENDLY_ERROR); throw new Error(errorMessages.FRIENDLY_ERROR);
} }
} catch (error) { } catch (error) {
next(handleError(error, SERVICE_NAME, "recoveryRequestController")); next(handleError(error, SERVICE_NAME, "recoveryRequestController"));
} }
}; };
/** /**
@@ -323,23 +330,23 @@ const requestRecovery = async (req, res, next) => {
* @throws {Error} If there is an error during the process, especially if there is a validation error (422). * @throws {Error} If there is an error during the process, especially if there is a validation error (422).
*/ */
const validateRecovery = async (req, res, next) => { const validateRecovery = async (req, res, next) => {
try { try {
await recoveryTokenValidation.validateAsync(req.body); await recoveryTokenValidation.validateAsync(req.body);
} catch (error) { } catch (error) {
const validationError = handleValidationError(error, SERVICE_NAME); const validationError = handleValidationError(error, SERVICE_NAME);
next(validationError); next(validationError);
return; return;
} }
try { try {
await req.db.validateRecoveryToken(req, res); await req.db.validateRecoveryToken(req, res);
return res.status(200).json({ return res.status(200).json({
success: true, success: true,
msg: successMessages.AUTH_VERIFY_RECOVERY_TOKEN, msg: successMessages.AUTH_VERIFY_RECOVERY_TOKEN,
}); });
} catch (error) { } catch (error) {
next(handleError(error, SERVICE_NAME, "validateRecoveryTokenController")); next(handleError(error, SERVICE_NAME, "validateRecoveryTokenController"));
} }
}; };
/** /**
@@ -355,26 +362,26 @@ const validateRecovery = async (req, res, next) => {
* @throws {Error} If there is an error during the process, especially if there is a validation error (422). * @throws {Error} If there is an error during the process, especially if there is a validation error (422).
*/ */
const resetPassword = async (req, res, next) => { const resetPassword = async (req, res, next) => {
try { try {
await newPasswordValidation.validateAsync(req.body); await newPasswordValidation.validateAsync(req.body);
} catch (error) { } catch (error) {
const validationError = handleValidationError(error, SERVICE_NAME); const validationError = handleValidationError(error, SERVICE_NAME);
next(validationError); next(validationError);
return; return;
} }
try { try {
const user = await req.db.resetPassword(req, res); const user = await req.db.resetPassword(req, res);
const appSettings = await req.settingsService.getSettings(); const appSettings = await req.settingsService.getSettings();
const token = issueToken(user._doc, tokenType.ACCESS_TOKEN, appSettings); const token = issueToken(user._doc, tokenType.ACCESS_TOKEN, appSettings);
res.status(200).json({ res.status(200).json({
success: true, success: true,
msg: successMessages.AUTH_RESET_PASSWORD, msg: successMessages.AUTH_RESET_PASSWORD,
data: { user, token }, data: { user, token },
}); });
} catch (error) { } catch (error) {
next(handleError(error, SERVICE_NAME, "resetPasswordController")); next(handleError(error, SERVICE_NAME, "resetPasswordController"));
} }
}; };
/** /**
@@ -387,74 +394,72 @@ const resetPassword = async (req, res, next) => {
* @throws {Error} If user validation fails or user is not found in the database. * @throws {Error} If user validation fails or user is not found in the database.
*/ */
const deleteUser = async (req, res, next) => { const deleteUser = async (req, res, next) => {
try { try {
const token = getTokenFromHeaders(req.headers); const token = getTokenFromHeaders(req.headers);
const decodedToken = jwt.decode(token); const decodedToken = jwt.decode(token);
const { email } = decodedToken; const { email } = decodedToken;
// Check if the user exists // Check if the user exists
const user = await req.db.getUserByEmail(email); const user = await req.db.getUserByEmail(email);
if (!user) { if (!user) {
next(new Error(errorMessages.DB_USER_NOT_FOUND)); next(new Error(errorMessages.DB_USER_NOT_FOUND));
return; return;
} }
// 1. Find all the monitors associated with the team ID if superadmin // 1. Find all the monitors associated with the team ID if superadmin
const result = await req.db.getMonitorsByTeamId({ const result = await req.db.getMonitorsByTeamId({
params: { teamId: user.teamId }, params: { teamId: user.teamId },
}); });
if (user.role.includes("superadmin")) { if (user.role.includes("superadmin")) {
//2. Remove all jobs, delete checks and alerts //2. Remove all jobs, delete checks and alerts
result?.monitors.length > 0 && result?.monitors.length > 0 &&
(await Promise.all( (await Promise.all(
result.monitors.map(async (monitor) => { result.monitors.map(async (monitor) => {
await req.jobQueue.deleteJob(monitor); await req.jobQueue.deleteJob(monitor);
await req.db.deleteChecks(monitor._id); await req.db.deleteChecks(monitor._id);
await req.db.deletePageSpeedChecksByMonitorId(monitor._id); await req.db.deletePageSpeedChecksByMonitorId(monitor._id);
await req.db.deleteNotificationsByMonitorId(monitor._id); await req.db.deleteNotificationsByMonitorId(monitor._id);
}) })
)); ));
// 3. Delete team // 3. Delete team
await req.db.deleteTeam(user.teamId); await req.db.deleteTeam(user.teamId);
// 4. Delete all other team members // 4. Delete all other team members
await req.db.deleteAllOtherUsers(); await req.db.deleteAllOtherUsers();
// 5. Delete each monitor // 5. Delete each monitor
await req.db.deleteMonitorsByUserId(user._id); await req.db.deleteMonitorsByUserId(user._id);
} }
// 6. Delete the user by id // 6. Delete the user by id
await req.db.deleteUser(user._id); await req.db.deleteUser(user._id);
return res.status(200).json({ return res.status(200).json({
success: true, success: true,
msg: successMessages.AUTH_DELETE_USER, msg: successMessages.AUTH_DELETE_USER,
}); });
} catch (error) { } catch (error) {
next(handleError(error, SERVICE_NAME, "deleteUserController")); next(handleError(error, SERVICE_NAME, "deleteUserController"));
} }
}; };
const getAllUsers = async (req, res) => { const getAllUsers = async (req, res, next) => {
try { try {
const allUsers = await req.db.getAllUsers(req, res); const allUsers = await req.db.getAllUsers(req, res);
res res.status(200).json({ success: true, msg: "Got all users", data: allUsers });
.status(200) } catch (error) {
.json({ success: true, msg: "Got all users", data: allUsers }); next(handleError(error, SERVICE_NAME, "getAllUsersController"));
} catch (error) { }
next(handleError(error, SERVICE_NAME, "getAllUsersController"));
}
}; };
module.exports = { export {
issueToken, issueToken,
registerUser, registerUser,
loginUser, loginUser,
editUser, editUser,
checkSuperadminExists: checkSuperAdminExists, checkSuperadminExists,
requestRecovery, requestRecovery,
validateRecovery, validateRecovery,
resetPassword, resetPassword,
deleteUser, deleteUser,
getAllUsers, getAllUsers,
}; };
+8 -7
View File
@@ -1,4 +1,4 @@
const { import {
createCheckParamValidation, createCheckParamValidation,
createCheckBodyValidation, createCheckBodyValidation,
getChecksParamValidation, getChecksParamValidation,
@@ -8,12 +8,13 @@ const {
deleteChecksParamValidation, deleteChecksParamValidation,
deleteChecksByTeamIdParamValidation, deleteChecksByTeamIdParamValidation,
updateChecksTTLBodyValidation, updateChecksTTLBodyValidation,
} = require("../validation/joi"); } from "../validation/joi.js";
const { successMessages } = require("../utils/messages"); import { successMessages } from "../utils/messages.js";
const jwt = require("jsonwebtoken"); import jwt from "jsonwebtoken";
const { getTokenFromHeaders } = require("../utils/utils"); import { getTokenFromHeaders } from "../utils/utils.js";
import { handleValidationError, handleError } from "./controllerUtils.js";
const SERVICE_NAME = "checkController"; const SERVICE_NAME = "checkController";
const { handleValidationError, handleError } = require("./controllerUtils");
const createCheck = async (req, res, next) => { const createCheck = async (req, res, next) => {
try { try {
@@ -143,7 +144,7 @@ const updateChecksTTL = async (req, res, next) => {
} }
}; };
module.exports = { export {
createCheck, createCheck,
getChecks, getChecks,
getTeamChecks, getTeamChecks,
+36 -12
View File
@@ -1,19 +1,43 @@
const handleValidationError = (error, serviceName) => { const handleValidationError = (error, serviceName) => {
error.status = 422; error.status = 422;
error.service = serviceName; error.service = serviceName;
error.message = error.message = error.details?.[0]?.message || error.message || "Validation Error";
error.details?.[0]?.message || error.message || "Validation Error"; return error;
return error;
}; };
const handleError = (error, serviceName, method, status = 500) => { const handleError = (error, serviceName, method, status = 500) => {
error.status === undefined ? (error.status = status) : null; error.status === undefined ? (error.status = status) : null;
error.service === undefined ? (error.service = serviceName) : null; error.service === undefined ? (error.service = serviceName) : null;
error.method === undefined ? (error.method = method) : null; error.method === undefined ? (error.method = method) : null;
return error; return error;
}; };
module.exports = { const fetchMonitorCertificate = async (tls, monitor) => {
handleValidationError, return new Promise((resolve, reject) => {
handleError, const monitorUrl = new URL(monitor.url);
const hostname = monitorUrl.hostname;
try {
let socket = tls.connect(
{
port: 443,
host: hostname,
servername: hostname, // this is required in case the server enabled SNI
},
() => {
try {
let x509Certificate = socket.getPeerX509Certificate();
resolve(x509Certificate);
} catch (error) {
reject(error);
} finally {
socket.end();
}
}
);
} catch (error) {
reject(error);
}
});
}; };
export { handleValidationError, handleError, fetchMonitorCertificate };
+11 -11
View File
@@ -1,14 +1,17 @@
const { import {
inviteRoleValidation, inviteRoleValidation,
inviteBodyValidation, inviteBodyValidation,
inviteVerificationBodyValidation, inviteVerificationBodyValidation,
} = require("../validation/joi"); } from "../validation/joi.js";
const logger = require("../utils/logger"); import logger from "../utils/logger.js";
require("dotenv").config(); import dotenv from "dotenv";
const jwt = require("jsonwebtoken"); import jwt from "jsonwebtoken";
const { handleError, handleValidationError } = require("./controllerUtils"); import { handleError, handleValidationError } from "./controllerUtils.js";
import { getTokenFromHeaders } from "../utils/utils.js";
dotenv.config();
const SERVICE_NAME = "inviteController"; const SERVICE_NAME = "inviteController";
const { getTokenFromHeaders } = require("../utils/utils");
/** /**
* Issues an invitation to a new user. Only admins can invite new users. An invitation token is created and sent via email. * Issues an invitation to a new user. Only admins can invite new users. An invitation token is created and sent via email.
@@ -82,7 +85,4 @@ const inviteVerifyController = async (req, res, next) => {
} }
}; };
module.exports = { export { issueInvitation, inviteVerifyController };
issueInvitation,
inviteVerifyController,
};
@@ -1,4 +1,4 @@
const { import {
createMaintenanceWindowBodyValidation, createMaintenanceWindowBodyValidation,
editMaintenanceWindowByIdParamValidation, editMaintenanceWindowByIdParamValidation,
editMaintenanceByIdWindowBodyValidation, editMaintenanceByIdWindowBodyValidation,
@@ -6,11 +6,12 @@ const {
getMaintenanceWindowsByMonitorIdParamValidation, getMaintenanceWindowsByMonitorIdParamValidation,
getMaintenanceWindowsByTeamIdQueryValidation, getMaintenanceWindowsByTeamIdQueryValidation,
deleteMaintenanceWindowByIdParamValidation, deleteMaintenanceWindowByIdParamValidation,
} = require("../validation/joi"); } from "../validation/joi.js";
const jwt = require("jsonwebtoken"); import jwt from "jsonwebtoken";
const { getTokenFromHeaders } = require("../utils/utils"); import { getTokenFromHeaders } from "../utils/utils.js";
const { successMessages } = require("../utils/messages"); import { successMessages } from "../utils/messages.js";
const { handleValidationError, handleError } = require("./controllerUtils"); import { handleValidationError, handleError } from "./controllerUtils.js";
const SERVICE_NAME = "maintenanceWindowController"; const SERVICE_NAME = "maintenanceWindowController";
const createMaintenanceWindows = async (req, res, next) => { const createMaintenanceWindows = async (req, res, next) => {
@@ -160,7 +161,7 @@ const editMaintenanceWindow = async (req, res, next) => {
} }
}; };
module.exports = { export {
createMaintenanceWindows, createMaintenanceWindows,
getMaintenanceWindowById, getMaintenanceWindowById,
getMaintenanceWindowsByTeamId, getMaintenanceWindowsByTeamId,
+311 -315
View File
@@ -1,25 +1,29 @@
const { import {
getMonitorByIdParamValidation, getMonitorByIdParamValidation,
getMonitorByIdQueryValidation, getMonitorByIdQueryValidation,
getMonitorsByTeamIdValidation, getMonitorsByTeamIdValidation,
createMonitorBodyValidation, createMonitorBodyValidation,
editMonitorBodyValidation, editMonitorBodyValidation,
getMonitorsAndSummaryByTeamIdParamValidation, getMonitorsAndSummaryByTeamIdParamValidation,
getMonitorsAndSummaryByTeamIdQueryValidation, getMonitorsAndSummaryByTeamIdQueryValidation,
getMonitorsByTeamIdQueryValidation, getMonitorsByTeamIdQueryValidation,
pauseMonitorParamValidation, pauseMonitorParamValidation,
getMonitorStatsByIdParamValidation, getMonitorStatsByIdParamValidation,
getMonitorStatsByIdQueryValidation, getMonitorStatsByIdQueryValidation,
getCertificateParamValidation, getCertificateParamValidation,
} = require("../validation/joi"); } from "../validation/joi.js";
import * as tls from "tls";
const sslChecker = require("ssl-checker");
const SERVICE_NAME = "monitorController"; const SERVICE_NAME = "monitorController";
const { errorMessages, successMessages } = require("../utils/messages"); import { errorMessages, successMessages } from "../utils/messages.js";
const jwt = require("jsonwebtoken"); import jwt from "jsonwebtoken";
const { getTokenFromHeaders } = require("../utils/utils"); import { getTokenFromHeaders } from "../utils/utils.js";
const logger = require("../utils/logger"); import logger from "../utils/logger.js";
const { handleError, handleValidationError } = require("./controllerUtils"); import {
handleError,
handleValidationError,
fetchMonitorCertificate,
} from "./controllerUtils.js";
/** /**
* Returns all monitors * Returns all monitors
@@ -31,16 +35,16 @@ const { handleError, handleValidationError } = require("./controllerUtils");
* @throws {Error} * @throws {Error}
*/ */
const getAllMonitors = async (req, res, next) => { const getAllMonitors = async (req, res, next) => {
try { try {
const monitors = await req.db.getAllMonitors(); const monitors = await req.db.getAllMonitors();
return res.status(200).json({ return res.status(200).json({
success: true, success: true,
msg: successMessages.MONITOR_GET_ALL, msg: successMessages.MONITOR_GET_ALL,
data: monitors, data: monitors,
}); });
} catch (error) { } catch (error) {
next(handleError(error, SERVICE_NAME, "getAllMonitors")); next(handleError(error, SERVICE_NAME, "getAllMonitors"));
} }
}; };
/** /**
@@ -53,56 +57,55 @@ const getAllMonitors = async (req, res, next) => {
* @throws {Error} * @throws {Error}
*/ */
const getMonitorStatsById = async (req, res, next) => { const getMonitorStatsById = async (req, res, next) => {
try { try {
await getMonitorStatsByIdParamValidation.validateAsync(req.params); await getMonitorStatsByIdParamValidation.validateAsync(req.params);
await getMonitorStatsByIdQueryValidation.validateAsync(req.query); await getMonitorStatsByIdQueryValidation.validateAsync(req.query);
} catch (error) { } catch (error) {
next(handleValidationError(error, SERVICE_NAME)); next(handleValidationError(error, SERVICE_NAME));
return; return;
} }
try { try {
const monitorStats = await req.db.getMonitorStatsById(req); const monitorStats = await req.db.getMonitorStatsById(req);
return res.status(200).json({ return res.status(200).json({
success: true, success: true,
msg: successMessages.MONITOR_STATS_BY_ID, msg: successMessages.MONITOR_STATS_BY_ID,
data: monitorStats, data: monitorStats,
}); });
} catch (error) { } catch (error) {
next(handleError(error, SERVICE_NAME, "getMonitorStatsById")); next(handleError(error, SERVICE_NAME, "getMonitorStatsById"));
} }
}; };
const getMonitorCertificate = async (req, res, next) => { const getMonitorCertificate = async (req, res, next, fetchMonitorCertificate) => {
try { try {
await getCertificateParamValidation.validateAsync(req.params); await getCertificateParamValidation.validateAsync(req.params);
} catch (error) { } catch (error) {
next(handleValidationError(error, SERVICE_NAME)); next(handleValidationError(error, SERVICE_NAME));
} }
try { try {
const { monitorId } = req.params; const { monitorId } = req.params;
const monitor = await req.db.getMonitorById(monitorId); const monitor = await req.db.getMonitorById(monitorId);
const monitorUrl = new URL(monitor.url); const certificate = await fetchMonitorCertificate(tls, monitor);
const certificate = await sslChecker(monitorUrl.hostname); if (certificate && certificate.validTo) {
if (certificate && certificate.validTo) { return res.status(200).json({
return res.status(200).json({ success: true,
success: true, msg: successMessages.MONITOR_CERTIFICATE,
msg: successMessages.MONITOR_CERTIFICATE, data: {
data: { certificateDate: new Date(certificate.validTo),
certificateDate: new Date(certificate.validTo).toLocaleDateString(), },
}, });
}); } else {
} else { return res.status(200).json({
return res.status(200).json({ success: true,
success: true, msg: successMessages.MONITOR_CERTIFICATE,
msg: successMessages.MONITOR_CERTIFICATE, data: { certificateDate: "N/A" },
data: { certificateDate: "N/A" }, });
}); }
} } catch (error) {
} catch (error) { next(handleError(error, SERVICE_NAME, "getMonitorCertificate"));
next(handleError(error, SERVICE_NAME, "getMonitorCertificate")); }
}
}; };
/** /**
@@ -117,30 +120,30 @@ const getMonitorCertificate = async (req, res, next) => {
* @throws {Error} If there is an error during the process, especially if the monitor is not found (404) or if there is a validation error (422). * @throws {Error} If there is an error during the process, especially if the monitor is not found (404) or if there is a validation error (422).
*/ */
const getMonitorById = async (req, res, next) => { const getMonitorById = async (req, res, next) => {
try { try {
await getMonitorByIdParamValidation.validateAsync(req.params); await getMonitorByIdParamValidation.validateAsync(req.params);
await getMonitorByIdQueryValidation.validateAsync(req.query); await getMonitorByIdQueryValidation.validateAsync(req.query);
} catch (error) { } catch (error) {
next(handleValidationError(error, SERVICE_NAME)); next(handleValidationError(error, SERVICE_NAME));
return; return;
} }
try { try {
const monitor = await req.db.getMonitorById(req.params.monitorId); const monitor = await req.db.getMonitorById(req.params.monitorId);
if (!monitor) { if (!monitor) {
const error = new Error(errorMessages.MONITOR_GET_BY_ID); const error = new Error(errorMessages.MONITOR_GET_BY_ID);
error.status = 404; error.status = 404;
throw error; throw error;
} }
return res.status(200).json({ return res.status(200).json({
success: true, success: true,
msg: successMessages.MONITOR_GET_BY_ID, msg: successMessages.MONITOR_GET_BY_ID,
data: monitor, data: monitor,
}); });
} catch (error) { } catch (error) {
next(handleError(error, SERVICE_NAME, "getMonitorById")); next(handleError(error, SERVICE_NAME, "getMonitorById"));
} }
}; };
/** /**
@@ -157,31 +160,26 @@ const getMonitorById = async (req, res, next) => {
* @throws {Error} If there is an error during the process, especially if there is a validation error (422). * @throws {Error} If there is an error during the process, especially if there is a validation error (422).
*/ */
const getMonitorsAndSummaryByTeamId = async (req, res, next) => { const getMonitorsAndSummaryByTeamId = async (req, res, next) => {
try { try {
await getMonitorsAndSummaryByTeamIdParamValidation.validateAsync( await getMonitorsAndSummaryByTeamIdParamValidation.validateAsync(req.params);
req.params await getMonitorsAndSummaryByTeamIdQueryValidation.validateAsync(req.query);
); } catch (error) {
await getMonitorsAndSummaryByTeamIdQueryValidation.validateAsync(req.query); next(handleValidationError(error, SERVICE_NAME));
} catch (error) { return;
next(handleValidationError(error, SERVICE_NAME)); }
return;
}
try { try {
const { teamId } = req.params; const { teamId } = req.params;
const { type } = req.query; const { type } = req.query;
const monitorsSummary = await req.db.getMonitorsAndSummaryByTeamId( const monitorsSummary = await req.db.getMonitorsAndSummaryByTeamId(teamId, type);
teamId, return res.status(200).json({
type success: true,
); msg: successMessages.MONITOR_GET_BY_USER_ID(teamId),
return res.status(200).json({ data: monitorsSummary,
success: true, });
msg: successMessages.MONITOR_GET_BY_USER_ID(teamId), } catch (error) {
data: monitorsSummary, next(handleError(error, SERVICE_NAME, "getMonitorsAndSummaryByTeamId"));
}); }
} catch (error) {
next(handleError(error, SERVICE_NAME, "getMonitorsAndSummaryByTeamId"));
}
}; };
/** /**
@@ -197,26 +195,26 @@ const getMonitorsAndSummaryByTeamId = async (req, res, next) => {
* @throws {Error} If there is an error during the process, especially if there is a validation error (422). * @throws {Error} If there is an error during the process, especially if there is a validation error (422).
*/ */
const getMonitorsByTeamId = async (req, res, next) => { const getMonitorsByTeamId = async (req, res, next) => {
try { try {
await getMonitorsByTeamIdValidation.validateAsync(req.params); await getMonitorsByTeamIdValidation.validateAsync(req.params);
await getMonitorsByTeamIdQueryValidation.validateAsync(req.query); await getMonitorsByTeamIdQueryValidation.validateAsync(req.query);
} catch (error) { } catch (error) {
next(handleValidationError(error, SERVICE_NAME)); next(handleValidationError(error, SERVICE_NAME));
return; return;
} }
try { try {
const teamId = req.params.teamId; const teamId = req.params.teamId;
const monitors = await req.db.getMonitorsByTeamId(req, res); const monitors = await req.db.getMonitorsByTeamId(req, res);
return res.status(200).json({ return res.status(200).json({
success: true, success: true,
msg: successMessages.MONITOR_GET_BY_USER_ID(teamId), msg: successMessages.MONITOR_GET_BY_USER_ID(teamId),
data: monitors, data: monitors,
}); });
} catch (error) { } catch (error) {
next(handleError(error, SERVICE_NAME, "getMonitorsByTeamId")); next(handleError(error, SERVICE_NAME, "getMonitorsByTeamId"));
next(error); next(error);
} }
}; };
/** /**
@@ -231,36 +229,36 @@ const getMonitorsByTeamId = async (req, res, next) => {
* @throws {Error} If there is an error during the process, especially if there is a validation error (422). * @throws {Error} If there is an error during the process, especially if there is a validation error (422).
*/ */
const createMonitor = async (req, res, next) => { const createMonitor = async (req, res, next) => {
try { try {
await createMonitorBodyValidation.validateAsync(req.body); await createMonitorBodyValidation.validateAsync(req.body);
} catch (error) { } catch (error) {
next(handleValidationError(error, SERVICE_NAME)); next(handleValidationError(error, SERVICE_NAME));
return; return;
} }
try { try {
const notifications = req.body.notifications; const notifications = req.body.notifications;
const monitor = await req.db.createMonitor(req, res); const monitor = await req.db.createMonitor(req, res);
if (notifications && notifications.length !== 0) { if (notifications && notifications.length !== 0) {
monitor.notifications = await Promise.all( monitor.notifications = await Promise.all(
notifications.map(async (notification) => { notifications.map(async (notification) => {
notification.monitorId = monitor._id; notification.monitorId = monitor._id;
await req.db.createNotification(notification); await req.db.createNotification(notification);
}) })
); );
await monitor.save(); await monitor.save();
} }
// Add monitor to job queue // Add monitor to job queue
req.jobQueue.addJob(monitor._id, monitor); req.jobQueue.addJob(monitor._id, monitor);
return res.status(201).json({ return res.status(201).json({
success: true, success: true,
msg: successMessages.MONITOR_CREATE, msg: successMessages.MONITOR_CREATE,
data: monitor, data: monitor,
}); });
} catch (error) { } catch (error) {
next(handleError(error, SERVICE_NAME, "createMonitor")); next(handleError(error, SERVICE_NAME, "createMonitor"));
} }
}; };
/** /**
@@ -275,37 +273,35 @@ const createMonitor = async (req, res, next) => {
* @throws {Error} If there is an error during the process, especially if there is a validation error (422) or an error in deleting associated records. * @throws {Error} If there is an error during the process, especially if there is a validation error (422) or an error in deleting associated records.
*/ */
const deleteMonitor = async (req, res, next) => { const deleteMonitor = async (req, res, next) => {
try { try {
await getMonitorByIdParamValidation.validateAsync(req.params); await getMonitorByIdParamValidation.validateAsync(req.params);
} catch (error) { } catch (error) {
next(handleValidationError(error, SERVICE_NAME)); next(handleValidationError(error, SERVICE_NAME));
return; return;
} }
try { try {
const monitor = await req.db.deleteMonitor(req, res, next); const monitor = await req.db.deleteMonitor(req, res, next);
// Delete associated checks,alerts,and notifications // Delete associated checks,alerts,and notifications
try { try {
await req.jobQueue.deleteJob(monitor); await req.jobQueue.deleteJob(monitor);
await req.db.deleteChecks(monitor._id); await req.db.deleteChecks(monitor._id);
await req.db.deletePageSpeedChecksByMonitorId(monitor._id); await req.db.deletePageSpeedChecksByMonitorId(monitor._id);
await req.db.deleteNotificationsByMonitorId(monitor._id); await req.db.deleteNotificationsByMonitorId(monitor._id);
} catch (error) { } catch (error) {
logger.error( logger.error(
`Error deleting associated records for monitor ${monitor._id} with name ${monitor.name}`, `Error deleting associated records for monitor ${monitor._id} with name ${monitor.name}`,
{ {
method: "deleteMonitor", method: "deleteMonitor",
service: SERVICE_NAME, service: SERVICE_NAME,
error: error.message, error: error.message,
} }
); );
} }
return res return res.status(200).json({ success: true, msg: successMessages.MONITOR_DELETE });
.status(200) } catch (error) {
.json({ success: true, msg: successMessages.MONITOR_DELETE }); next(handleError(error, SERVICE_NAME, "deleteMonitor"));
} catch (error) { }
next(handleError(error, SERVICE_NAME, "deleteMonitor"));
}
}; };
/** /**
@@ -320,34 +316,34 @@ const deleteMonitor = async (req, res, next) => {
* @throws {Error} If there is an error during the deletion process. * @throws {Error} If there is an error during the deletion process.
*/ */
const deleteAllMonitors = async (req, res, next) => { const deleteAllMonitors = async (req, res, next) => {
try { try {
const token = getTokenFromHeaders(req.headers); const token = getTokenFromHeaders(req.headers);
const { jwtSecret } = req.settingsService.getSettings(); const { jwtSecret } = req.settingsService.getSettings();
const { teamId } = jwt.verify(token, jwtSecret); const { teamId } = jwt.verify(token, jwtSecret);
const { monitors, deletedCount } = await req.db.deleteAllMonitors(teamId); const { monitors, deletedCount } = await req.db.deleteAllMonitors(teamId);
await Promise.all( await Promise.all(
monitors.map(async (monitor) => { monitors.map(async (monitor) => {
try { try {
await req.jobQueue.deleteJob(monitor); await req.jobQueue.deleteJob(monitor);
await req.db.deleteChecks(monitor._id); await req.db.deleteChecks(monitor._id);
await req.db.deletePageSpeedChecksByMonitorId(monitor._id); await req.db.deletePageSpeedChecksByMonitorId(monitor._id);
await req.db.deleteNotificationsByMonitorId(monitor._id); await req.db.deleteNotificationsByMonitorId(monitor._id);
} catch (error) { } catch (error) {
logger.error( logger.error(
`Error deleting associated records for monitor ${monitor._id} with name ${monitor.name}`, `Error deleting associated records for monitor ${monitor._id} with name ${monitor.name}`,
{ {
method: "deleteAllMonitors", method: "deleteAllMonitors",
} }
); );
} }
}) })
); );
return res return res
.status(200) .status(200)
.json({ success: true, msg: `Deleted ${deletedCount} monitors` }); .json({ success: true, msg: `Deleted ${deletedCount} monitors` });
} catch (error) { } catch (error) {
next(handleError(error, SERVICE_NAME, "deleteAllMonitors")); next(handleError(error, SERVICE_NAME, "deleteAllMonitors"));
} }
}; };
/** /**
@@ -364,46 +360,46 @@ const deleteAllMonitors = async (req, res, next) => {
* @throws {Error} If there is an error during the process, especially if there is a validation error (422). * @throws {Error} If there is an error during the process, especially if there is a validation error (422).
*/ */
const editMonitor = async (req, res, next) => { const editMonitor = async (req, res, next) => {
try { try {
await getMonitorByIdParamValidation.validateAsync(req.params); await getMonitorByIdParamValidation.validateAsync(req.params);
await editMonitorBodyValidation.validateAsync(req.body); await editMonitorBodyValidation.validateAsync(req.body);
} catch (error) { } catch (error) {
next(handleValidationError(error, SERVICE_NAME)); next(handleValidationError(error, SERVICE_NAME));
return; return;
} }
try { try {
const { monitorId } = req.params; const { monitorId } = req.params;
const monitorBeforeEdit = await req.db.getMonitorById(monitorId); const monitorBeforeEdit = await req.db.getMonitorById(monitorId);
// Get notifications from the request body // Get notifications from the request body
const notifications = req.body.notifications; const notifications = req.body.notifications;
const editedMonitor = await req.db.editMonitor(monitorId, req.body); const editedMonitor = await req.db.editMonitor(monitorId, req.body);
await req.db.deleteNotificationsByMonitorId(editedMonitor._id); await req.db.deleteNotificationsByMonitorId(editedMonitor._id);
if (notifications && notifications.length !== 0) { if (notifications && notifications.length !== 0) {
await Promise.all( await Promise.all(
notifications.map(async (notification) => { notifications.map(async (notification) => {
notification.monitorId = editedMonitor._id; notification.monitorId = editedMonitor._id;
await req.db.createNotification(notification); await req.db.createNotification(notification);
}) })
); );
} }
// Delete the old job(editedMonitor has the same ID as the old monitor) // Delete the old job(editedMonitor has the same ID as the old monitor)
await req.jobQueue.deleteJob(monitorBeforeEdit); await req.jobQueue.deleteJob(monitorBeforeEdit);
// Add the new job back to the queue // Add the new job back to the queue
await req.jobQueue.addJob(editedMonitor._id, editedMonitor); await req.jobQueue.addJob(editedMonitor._id, editedMonitor);
return res.status(200).json({ return res.status(200).json({
success: true, success: true,
msg: successMessages.MONITOR_EDIT, msg: successMessages.MONITOR_EDIT,
data: editedMonitor, data: editedMonitor,
}); });
} catch (error) { } catch (error) {
next(handleError(error, SERVICE_NAME, "editMonitor")); next(handleError(error, SERVICE_NAME, "editMonitor"));
} }
}; };
/** /**
@@ -418,32 +414,32 @@ const editMonitor = async (req, res, next) => {
* @throws {Error} If there is an error during the process. * @throws {Error} If there is an error during the process.
*/ */
const pauseMonitor = async (req, res, next) => { const pauseMonitor = async (req, res, next) => {
try { try {
await pauseMonitorParamValidation.validateAsync(req.params); await pauseMonitorParamValidation.validateAsync(req.params);
} catch (error) { } catch (error) {
next(handleValidationError(error, SERVICE_NAME)); next(handleValidationError(error, SERVICE_NAME));
} }
try { try {
const monitor = await req.db.getMonitorById(req.params.monitorId); const monitor = await req.db.getMonitorById(req.params.monitorId);
if (monitor.isActive) { if (monitor.isActive) {
await req.jobQueue.deleteJob(monitor); await req.jobQueue.deleteJob(monitor);
} else { } else {
await req.jobQueue.addJob(monitor._id, monitor); await req.jobQueue.addJob(monitor._id, monitor);
} }
monitor.isActive = !monitor.isActive; monitor.isActive = !monitor.isActive;
monitor.status = undefined; monitor.status = undefined;
monitor.save(); monitor.save();
return res.status(200).json({ return res.status(200).json({
success: true, success: true,
msg: monitor.isActive msg: monitor.isActive
? successMessages.MONITOR_RESUME ? successMessages.MONITOR_RESUME
: successMessages.MONITOR_PAUSE, : successMessages.MONITOR_PAUSE,
data: monitor, data: monitor,
}); });
} catch (error) { } catch (error) {
next(handleError(error, SERVICE_NAME, "pauseMonitor")); next(handleError(error, SERVICE_NAME, "pauseMonitor"));
} }
}; };
/** /**
@@ -458,36 +454,36 @@ const pauseMonitor = async (req, res, next) => {
* @throws {Error} If there is an error during the process. * @throws {Error} If there is an error during the process.
*/ */
const addDemoMonitors = async (req, res, next) => { const addDemoMonitors = async (req, res, next) => {
try { try {
const token = getTokenFromHeaders(req.headers); const token = getTokenFromHeaders(req.headers);
const { jwtSecret } = req.settingsService.getSettings(); const { jwtSecret } = req.settingsService.getSettings();
const { _id, teamId } = jwt.verify(token, jwtSecret); const { _id, teamId } = jwt.verify(token, jwtSecret);
const demoMonitors = await req.db.addDemoMonitors(_id, teamId); const demoMonitors = await req.db.addDemoMonitors(_id, teamId);
await Promise.all( await Promise.all(
demoMonitors.map((monitor) => req.jobQueue.addJob(monitor._id, monitor)) demoMonitors.map((monitor) => req.jobQueue.addJob(monitor._id, monitor))
); );
return res.status(200).json({ return res.status(200).json({
success: true, success: true,
msg: successMessages.MONITOR_DEMO_ADDED, msg: successMessages.MONITOR_DEMO_ADDED,
data: demoMonitors.length, data: demoMonitors.length,
}); });
} catch (error) { } catch (error) {
next(handleError(error, SERVICE_NAME, "addDemoMonitors")); next(handleError(error, SERVICE_NAME, "addDemoMonitors"));
} }
}; };
module.exports = { export {
getAllMonitors, getAllMonitors,
getMonitorStatsById, getMonitorStatsById,
getMonitorCertificate, getMonitorCertificate,
getMonitorById, getMonitorById,
getMonitorsAndSummaryByTeamId, getMonitorsAndSummaryByTeamId,
getMonitorsByTeamId, getMonitorsByTeamId,
createMonitor, createMonitor,
deleteMonitor, deleteMonitor,
deleteAllMonitors, deleteAllMonitors,
editMonitor, editMonitor,
pauseMonitor, pauseMonitor,
addDemoMonitors, addDemoMonitors,
}; };
+4 -8
View File
@@ -1,5 +1,6 @@
const { handleError } = require("./controllerUtils"); import { handleError } from "./controllerUtils.js";
const { errorMessages, successMessages } = require("../utils/messages"); import { errorMessages, successMessages } from "../utils/messages.js";
const SERVICE_NAME = "JobQueueController"; const SERVICE_NAME = "JobQueueController";
const getMetrics = async (req, res, next) => { const getMetrics = async (req, res, next) => {
@@ -55,9 +56,4 @@ const obliterateQueue = async (req, res, next) => {
} }
}; };
module.exports = { export { getMetrics, getJobs, addJob, obliterateQueue };
getMetrics,
getJobs,
addJob,
obliterateQueue,
};
+4 -7
View File
@@ -1,7 +1,7 @@
const { successMessages } = require("../utils/messages"); import { successMessages } from "../utils/messages.js";
import { updateAppSettingsBodyValidation } from "../validation/joi.js";
import { handleValidationError, handleError } from "./controllerUtils.js";
const SERVICE_NAME = "SettingsController"; const SERVICE_NAME = "SettingsController";
const { updateAppSettingsBodyValidation } = require("../validation/joi");
const { handleValidationError, handleError } = require("./controllerUtils");
const getAppSettings = async (req, res, next) => { const getAppSettings = async (req, res, next) => {
try { try {
@@ -39,7 +39,4 @@ const updateAppSettings = async (req, res, next) => {
} }
}; };
module.exports = { export { getAppSettings, updateAppSettings };
getAppSettings,
updateAppSettings,
};
+2 -2
View File
@@ -1,4 +1,4 @@
const mongoose = require("mongoose"); import mongoose from "mongoose";
const AppSettingsSchema = mongoose.Schema( const AppSettingsSchema = mongoose.Schema(
{ {
@@ -88,4 +88,4 @@ const AppSettingsSchema = mongoose.Schema(
} }
); );
module.exports = mongoose.model("AppSettings", AppSettingsSchema); export default mongoose.model("AppSettings", AppSettingsSchema);
+4 -5
View File
@@ -1,6 +1,6 @@
const mongoose = require("mongoose"); import mongoose from "mongoose";
const EmailService = require("../../service/emailService"); import EmailService from "../../service/emailService.js";
const Notification = require("./Notification"); import Notification from "./Notification.js";
/** /**
* Check Schema for MongoDB collection. * Check Schema for MongoDB collection.
@@ -73,5 +73,4 @@ const CheckSchema = mongoose.Schema(
); );
CheckSchema.index({ createdAt: 1 }); CheckSchema.index({ createdAt: 1 });
export default mongoose.model("Check", CheckSchema);
module.exports = mongoose.model("Check", CheckSchema);
+2 -3
View File
@@ -1,5 +1,4 @@
const mongoose = require("mongoose"); import mongoose from "mongoose";
const InviteTokenSchema = mongoose.Schema( const InviteTokenSchema = mongoose.Schema(
{ {
email: { email: {
@@ -32,4 +31,4 @@ const InviteTokenSchema = mongoose.Schema(
} }
); );
module.exports = mongoose.model("InviteToken", InviteTokenSchema); export default mongoose.model("InviteToken", InviteTokenSchema);
+2 -3
View File
@@ -1,5 +1,4 @@
const mongoose = require("mongoose"); import mongoose from "mongoose";
/** /**
* MaintenanceWindow Schema * MaintenanceWindow Schema
* @module MaintenanceWindow * @module MaintenanceWindow
@@ -66,4 +65,4 @@ const MaintenanceWindow = mongoose.Schema(
} }
); );
module.exports = mongoose.model("MaintenanceWindow", MaintenanceWindow); export default mongoose.model("MaintenanceWindow", MaintenanceWindow);
+3 -3
View File
@@ -1,5 +1,5 @@
const mongoose = require("mongoose"); import mongoose from "mongoose";
const Notification = require("./Notification"); import Notification from "./Notification.js";
const MonitorSchema = mongoose.Schema( const MonitorSchema = mongoose.Schema(
{ {
@@ -60,4 +60,4 @@ const MonitorSchema = mongoose.Schema(
} }
); );
module.exports = mongoose.model("Monitor", MonitorSchema); export default mongoose.model("Monitor", MonitorSchema);
+2 -4
View File
@@ -1,5 +1,4 @@
const mongoose = require("mongoose"); import mongoose from "mongoose";
const NotificationSchema = mongoose.Schema( const NotificationSchema = mongoose.Schema(
{ {
monitorId: { monitorId: {
@@ -22,5 +21,4 @@ const NotificationSchema = mongoose.Schema(
timestamps: true, timestamps: true,
} }
); );
export default mongoose.model("Notification", NotificationSchema);
module.exports = mongoose.model("Notification", NotificationSchema);
+2 -3
View File
@@ -1,5 +1,4 @@
const mongoose = require("mongoose"); import mongoose from "mongoose";
const AuditSchema = mongoose.Schema({ const AuditSchema = mongoose.Schema({
id: { type: String, required: true }, id: { type: String, required: true },
title: { type: String, required: true }, title: { type: String, required: true },
@@ -109,4 +108,4 @@ PageSpeedCheck.pre("save", async function (next) {
} }
}); });
module.exports = mongoose.model("PageSpeedCheck", PageSpeedCheck); export default mongoose.model("PageSpeedCheck", PageSpeedCheck);
+2 -2
View File
@@ -1,4 +1,4 @@
const mongoose = require("mongoose"); import mongoose from "mongoose";
const RecoveryTokenSchema = mongoose.Schema( const RecoveryTokenSchema = mongoose.Schema(
{ {
@@ -22,4 +22,4 @@ const RecoveryTokenSchema = mongoose.Schema(
} }
); );
module.exports = mongoose.model("RecoveryToken", RecoveryTokenSchema); export default mongoose.model("RecoveryToken", RecoveryTokenSchema);
+2 -4
View File
@@ -1,5 +1,4 @@
const mongoose = require("mongoose"); import mongoose from "mongoose";
const TeamSchema = mongoose.Schema( const TeamSchema = mongoose.Schema(
{ {
email: { email: {
@@ -12,5 +11,4 @@ const TeamSchema = mongoose.Schema(
timestamps: true, timestamps: true,
} }
); );
export default mongoose.model("Team", TeamSchema);
module.exports = mongoose.model("Team", TeamSchema);
+68 -68
View File
@@ -1,87 +1,87 @@
const mongoose = require("mongoose"); import mongoose from "mongoose";
const bcrypt = require("bcrypt"); import bcrypt from "bcrypt";
const UserSchema = mongoose.Schema( const UserSchema = mongoose.Schema(
{ {
firstName: { firstName: {
type: String, type: String,
required: true, required: true,
}, },
lastName: { lastName: {
type: String, type: String,
required: true, required: true,
}, },
email: { email: {
type: String, type: String,
required: true, required: true,
unique: true, unique: true,
}, },
password: { password: {
type: String, type: String,
required: true, required: true,
}, },
avatarImage: { avatarImage: {
type: String, type: String,
}, },
profileImage: { profileImage: {
data: Buffer, data: Buffer,
contentType: String, contentType: String,
}, },
isActive: { isActive: {
type: Boolean, type: Boolean,
default: true, default: true,
}, },
isVerified: { isVerified: {
type: Boolean, type: Boolean,
default: false, default: false,
}, },
role: { role: {
type: [String], type: [String],
default: "user", default: "user",
enum: ["user", "admin", "superadmin", "demo"], enum: ["user", "admin", "superadmin", "demo"],
}, },
teamId: { teamId: {
type: mongoose.Schema.Types.ObjectId, type: mongoose.Schema.Types.ObjectId,
ref: "Team", ref: "Team",
immutable: true, immutable: true,
}, },
checkTTL: { checkTTL: {
type: Number, type: Number,
}, },
}, },
{ {
timestamps: true, timestamps: true,
} }
); );
UserSchema.pre("save", async function (next) { UserSchema.pre("save", async function (next) {
if (!this.isModified("password")) { if (!this.isModified("password")) {
next(); next();
} }
const salt = await bcrypt.genSalt(10); //genSalt is asynchronous, need to wait const salt = await bcrypt.genSalt(10); //genSalt is asynchronous, need to wait
this.password = await bcrypt.hash(this.password, salt); // hash is also async, need to eitehr await or use hashSync this.password = await bcrypt.hash(this.password, salt); // hash is also async, need to eitehr await or use hashSync
next(); next();
}); });
UserSchema.pre("findOneAndUpdate", async function (next) { UserSchema.pre("findOneAndUpdate", async function (next) {
const update = this.getUpdate(); const update = this.getUpdate();
if ("password" in update) { if ("password" in update) {
const salt = await bcrypt.genSalt(10); //genSalt is asynchronous, need to wait const salt = await bcrypt.genSalt(10); //genSalt is asynchronous, need to wait
update.password = await bcrypt.hash(update.password, salt); // hash is also async, need to eitehr await or use hashSync update.password = await bcrypt.hash(update.password, salt); // hash is also async, need to eitehr await or use hashSync
} }
next(); next();
}); });
UserSchema.methods.comparePassword = async function (submittedPassword) { UserSchema.methods.comparePassword = async function (submittedPassword) {
res = await bcrypt.compare(submittedPassword, this.password); const res = await bcrypt.compare(submittedPassword, this.password);
return res; return res;
}; };
const User = mongoose.model("User", UserSchema); const User = mongoose.model("User", UserSchema);
User.init().then(() => { User.init().then(() => {
console.log("User model initialized"); console.log("User model initialized");
}); });
module.exports = mongoose.model("User", UserSchema); export default mongoose.model("User", UserSchema);
+21 -24
View File
@@ -1,6 +1,6 @@
const mongoose = require("mongoose"); import mongoose from "mongoose";
const UserModel = require("../models/User"); import UserModel from "../models/User.js";
const AppSettings = require("../models/AppSettings"); import AppSettings from "../models/AppSettings.js";
//**************************************** //****************************************
// DB Connection // DB Connection
@@ -41,7 +41,7 @@ const checkSuperadmin = async (req, res) => {
// User Operations // User Operations
//**************************************** //****************************************
const { import {
insertUser, insertUser,
getUserByEmail, getUserByEmail,
updateUser, updateUser,
@@ -50,32 +50,32 @@ const {
deleteAllOtherUsers, deleteAllOtherUsers,
getAllUsers, getAllUsers,
logoutUser, logoutUser,
} = require("./modules/userModule"); } from "./modules/userModule.js";
//**************************************** //****************************************
// Invite Token Operations // Invite Token Operations
//**************************************** //****************************************
const { import {
requestInviteToken, requestInviteToken,
getInviteToken, getInviteToken,
getInviteTokenAndDelete, getInviteTokenAndDelete,
} = require("./modules/inviteModule"); } from "./modules/inviteModule.js";
//**************************************** //****************************************
// Recovery Operations // Recovery Operations
//**************************************** //****************************************
const { import {
requestRecoveryToken, requestRecoveryToken,
validateRecoveryToken, validateRecoveryToken,
resetPassword, resetPassword,
} = require("./modules/recoveryModule"); } from "./modules/recoveryModule.js";
//**************************************** //****************************************
// Monitors // Monitors
//**************************************** //****************************************
const { import {
getAllMonitors, getAllMonitors,
getMonitorStatsById, getMonitorStatsById,
getMonitorById, getMonitorById,
@@ -87,23 +87,23 @@ const {
deleteMonitorsByUserId, deleteMonitorsByUserId,
editMonitor, editMonitor,
addDemoMonitors, addDemoMonitors,
} = require("./modules/monitorModule"); } from "./modules/monitorModule.js";
//**************************************** //****************************************
// Page Speed Checks // Page Speed Checks
//**************************************** //****************************************
const { import {
createPageSpeedCheck, createPageSpeedCheck,
getPageSpeedChecks, getPageSpeedChecks,
deletePageSpeedChecksByMonitorId, deletePageSpeedChecksByMonitorId,
} = require("./modules/pageSpeedCheckModule"); } from "./modules/pageSpeedCheckModule.js";
//**************************************** //****************************************
// Checks // Checks
//**************************************** //****************************************
const { import {
createCheck, createCheck,
getChecksCount, getChecksCount,
getChecks, getChecks,
@@ -111,12 +111,12 @@ const {
deleteChecks, deleteChecks,
deleteChecksByTeamId, deleteChecksByTeamId,
updateChecksTTL, updateChecksTTL,
} = require("./modules/checkModule"); } from "./modules/checkModule.js";
//**************************************** //****************************************
// Maintenance Window // Maintenance Window
//**************************************** //****************************************
const { import {
createMaintenanceWindow, createMaintenanceWindow,
getMaintenanceWindowById, getMaintenanceWindowById,
getMaintenanceWindowsByTeamId, getMaintenanceWindowsByTeamId,
@@ -125,26 +125,23 @@ const {
deleteMaintenanceWindowByMonitorId, deleteMaintenanceWindowByMonitorId,
deleteMaintenanceWindowByUserId, deleteMaintenanceWindowByUserId,
editMaintenanceWindowById, editMaintenanceWindowById,
} = require("./modules/maintenanceWindowModule"); } from "./modules/maintenanceWindowModule.js";
//**************************************** //****************************************
// Notifications // Notifications
//**************************************** //****************************************
const { import {
createNotification, createNotification,
getNotificationsByMonitorId, getNotificationsByMonitorId,
deleteNotificationsByMonitorId, deleteNotificationsByMonitorId,
} = require("./modules/notificationModule"); } from "./modules/notificationModule.js";
//**************************************** //****************************************
// AppSettings // AppSettings
//**************************************** //****************************************
const { import { getAppSettings, updateAppSettings } from "./modules/settingsModule.js";
getAppSettings,
updateAppSettings,
} = require("./modules/settingsModule");
module.exports = { export default {
connect, connect,
insertUser, insertUser,
getUserByEmail, getUserByEmail,
+5 -5
View File
@@ -1,7 +1,7 @@
const Check = require("../../models/Check"); import Check from "../../models/Check.js";
const Monitor = require("../../models/Monitor"); import Monitor from "../../models/Monitor.js";
const User = require("../../models/User"); import User from "../../models/User.js";
const logger = require("../../../utils/logger"); import logger from "../../../utils/logger.js";
const SERVICE_NAME = "checkModule"; const SERVICE_NAME = "checkModule";
const dateRangeLookup = { const dateRangeLookup = {
day: new Date(new Date().setDate(new Date().getDate() - 1)), day: new Date(new Date().setDate(new Date().getDate() - 1)),
@@ -274,7 +274,7 @@ const updateChecksTTL = async (teamId, ttl) => {
} }
}; };
module.exports = { export {
createCheck, createCheck,
getChecksCount, getChecksCount,
getChecks, getChecks,
+5 -9
View File
@@ -1,8 +1,8 @@
const InviteToken = require("../../models/InviteToken"); import InviteToken from "../../models/InviteToken.js";
const crypto = require("crypto"); import crypto from "crypto";
const { errorMessages } = require("../../../utils/messages"); import { errorMessages } from "../../../utils/messages.js";
const SERVICE_NAME = "inviteModule";
const SERVICE_NAME = "inviteModule";
/** /**
* Request an invite token for a user. * Request an invite token for a user.
* *
@@ -83,8 +83,4 @@ const getInviteTokenAndDelete = async (token) => {
} }
}; };
module.exports = { export { requestInviteToken, getInviteToken, getInviteTokenAndDelete };
requestInviteToken,
getInviteToken,
getInviteTokenAndDelete,
};
@@ -1,4 +1,4 @@
const MaintenanceWindow = require("../../models/MaintenanceWindow"); import MaintenanceWindow from "../../models/MaintenanceWindow.js";
const SERVICE_NAME = "maintenanceWindowModule"; const SERVICE_NAME = "maintenanceWindowModule";
/** /**
@@ -220,7 +220,7 @@ const editMaintenanceWindowById = async (
} }
}; };
module.exports = { export {
createMaintenanceWindow, createMaintenanceWindow,
getMaintenanceWindowById, getMaintenanceWindowById,
getMaintenanceWindowsByTeamId, getMaintenanceWindowsByTeamId,
+20 -8
View File
@@ -1,10 +1,22 @@
const Monitor = require("../../models/Monitor"); import Monitor from "../../models/Monitor.js";
const Check = require("../../models/Check"); import Check from "../../models/Check.js";
const PageSpeedCheck = require("../../models/PageSpeedCheck"); import PageSpeedCheck from "../../models/PageSpeedCheck.js";
const { errorMessages } = require("../../../utils/messages"); import { errorMessages } from "../../../utils/messages.js";
const Notification = require("../../models/Notification"); import Notification from "../../models/Notification.js";
const { NormalizeData } = require("../../../utils/dataUtils"); import { NormalizeData } from "../../../utils/dataUtils.js";
const demoMonitors = require("../../../utils/demoMonitors.json"); import fs from "fs";
import path from "path";
import { fileURLToPath } from "url";
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const demoMonitorsPath = path.resolve(
__dirname,
"../../../utils/demoMonitors.json"
);
const demoMonitors = JSON.parse(fs.readFileSync(demoMonitorsPath, "utf8"));
const SERVICE_NAME = "monitorModule"; const SERVICE_NAME = "monitorModule";
/** /**
@@ -572,7 +584,7 @@ const addDemoMonitors = async (userId, teamId) => {
} }
}; };
module.exports = { export {
getAllMonitors, getAllMonitors,
getMonitorStatsById, getMonitorStatsById,
getMonitorById, getMonitorById,
@@ -1,4 +1,4 @@
const Notification = require("../../models/Notification"); import Notification from "../../models/Notification.js";
const SERVICE_NAME = "notificationModule"; const SERVICE_NAME = "notificationModule";
/** /**
* Creates a new notification. * Creates a new notification.
@@ -49,7 +49,7 @@ const deleteNotificationsByMonitorId = async (monitorId) => {
} }
}; };
module.exports = { export {
createNotification, createNotification,
getNotificationsByMonitorId, getNotificationsByMonitorId,
deleteNotificationsByMonitorId, deleteNotificationsByMonitorId,
@@ -1,4 +1,4 @@
const PageSpeedCheck = require("../../models/PageSpeedCheck"); import PageSpeedCheck from "../../models/PageSpeedCheck.js";
const SERVICE_NAME = "pageSpeedCheckModule"; const SERVICE_NAME = "pageSpeedCheckModule";
/** /**
* Create a PageSpeed check for a monitor * Create a PageSpeed check for a monitor
@@ -63,7 +63,7 @@ const deletePageSpeedChecksByMonitorId = async (monitorId) => {
} }
}; };
module.exports = { export {
createPageSpeedCheck, createPageSpeedCheck,
getPageSpeedChecks, getPageSpeedChecks,
deletePageSpeedChecksByMonitorId, deletePageSpeedChecksByMonitorId,
+6 -9
View File
@@ -1,7 +1,8 @@
const UserModel = require("../../models/User"); import UserModel from "../../models/User.js";
const RecoveryToken = require("../../models/RecoveryToken"); import RecoveryToken from "../../models/RecoveryToken.js";
const crypto = require("crypto"); import crypto from "crypto";
const { errorMessages } = require("../../../utils/messages"); import { errorMessages } from "../../../utils/messages.js";
const SERVICE_NAME = "recoveryModule"; const SERVICE_NAME = "recoveryModule";
/** /**
@@ -81,8 +82,4 @@ const resetPassword = async (req, res) => {
} }
}; };
module.exports = { export { requestRecoveryToken, validateRecoveryToken, resetPassword };
requestRecoveryToken,
validateRecoveryToken,
resetPassword,
};
+2 -5
View File
@@ -1,4 +1,4 @@
const AppSettings = require("../../models/AppSettings"); import AppSettings from "../../models/AppSettings.js";
const SERVICE_NAME = "SettingsModule"; const SERVICE_NAME = "SettingsModule";
const getAppSettings = async () => { const getAppSettings = async () => {
@@ -27,7 +27,4 @@ const updateAppSettings = async (newSettings) => {
} }
}; };
module.exports = { export { getAppSettings, updateAppSettings };
getAppSettings,
updateAppSettings,
};
+7 -7
View File
@@ -1,11 +1,11 @@
const UserModel = require("../../models/User"); import UserModel from "../../models/User.js";
const TeamModel = require("../../models/Team"); import TeamModel from "../../models/Team.js";
const { errorMessages } = require("../../../utils/messages"); import { errorMessages } from "../../../utils/messages.js";
const { GenerateAvatarImage } = require("../../../utils/imageProcessing"); import { GenerateAvatarImage } from "../../../utils/imageProcessing.js";
const DUPLICATE_KEY_CODE = 11000; // MongoDB error code for duplicate key const DUPLICATE_KEY_CODE = 11000; // MongoDB error code for duplicate key
const { ParseBoolean } = require("../../../utils/utils"); import { ParseBoolean } from "../../../utils/utils.js";
SERVICE_NAME = "userModule"; const SERVICE_NAME = "userModule";
/** /**
* Insert a User * Insert a User
@@ -208,7 +208,7 @@ const logoutUser = async (userId) => {
} }
}; };
module.exports = { export {
insertUser, insertUser,
getUserByEmail, getUserByEmail,
updateUser, updateUser,
+140 -138
View File
@@ -1,163 +1,165 @@
const path = require("path"); import path from "path";
const fs = require("fs"); import fs from "fs";
const swaggerUi = require("swagger-ui-express"); import swaggerUi from "swagger-ui-express";
const express = require("express"); import express from "express";
const helmet = require("helmet"); import helmet from "helmet";
const cors = require("cors"); import cors from "cors";
const logger = require("./utils/logger"); import logger from "./utils/logger.js";
const { verifyJWT } = require("./middleware/verifyJWT"); import { verifyJWT } from "./middleware/verifyJWT.js";
const { handleErrors } = require("./middleware/handleErrors"); import { handleErrors } from "./middleware/handleErrors.js";
const { errorMessages } = require("./utils/messages"); import { errorMessages } from "./utils/messages.js";
const authRouter = require("./routes/authRoute"); import authRouter from "./routes/authRoute.js";
const inviteRouter = require("./routes/inviteRoute"); import inviteRouter from "./routes/inviteRoute.js";
const monitorRouter = require("./routes/monitorRoute"); import monitorRouter from "./routes/monitorRoute.js";
const checkRouter = require("./routes/checkRoute"); import checkRouter from "./routes/checkRoute.js";
const maintenanceWindowRouter = require("./routes/maintenanceWindowRoute"); import maintenanceWindowRouter from "./routes/maintenanceWindowRoute.js";
const settingsRouter = require("./routes/settingsRoute"); import settingsRouter from "./routes/settingsRoute.js";
import { fileURLToPath } from "url";
const { connectDbAndRunServer } = require("./configs/db"); import { connectDbAndRunServer } from "./configs/db.js";
const queueRouter = require("./routes/queueRoute"); import queueRouter from "./routes/queueRoute.js";
const JobQueue = require("./service/jobQueue"); import JobQueue from "./service/jobQueue.js";
const NetworkService = require("./service/networkService"); import NetworkService from "./service/networkService.js";
const EmailService = require("./service/emailService"); import EmailService from "./service/emailService.js";
const SettingsService = require("./service/settingsService"); import SettingsService from "./service/settingsService.js";
import db from "./db/mongo/MongoDB.js";
import { fetchMonitorCertificate } from "./controllers/controllerUtils.js";
const SERVICE_NAME = "Server"; const SERVICE_NAME = "Server";
let cleaningUp = false; let cleaningUp = false;
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const openApiSpec = JSON.parse( const openApiSpec = JSON.parse(
fs.readFileSync(path.join(__dirname, "openapi.json"), "utf8") fs.readFileSync(path.join(__dirname, "openapi.json"), "utf8")
); );
// Need to wrap server setup in a function to handle async nature of JobQueue // Need to wrap server setup in a function to handle async nature of JobQueue
const startApp = async () => { const startApp = async () => {
// ************************** // **************************
// Here is where we can swap out DBs easily. Spin up a mongoDB instance and try it out. // Here is where we can swap out DBs easily. Spin up a mongoDB instance and try it out.
// Simply comment out the FakeDB and uncomment the MongoDB or vice versa. // Simply comment out the FakeDB and uncomment the MongoDB or vice versa.
// We can easily swap between any type of data source as long as the methods are implemented // We can easily swap between any type of data source as long as the methods are implemented
// //
// FakeDB // FakeDB
// const db = require("./db/FakeDb"); // const db = require("./db/FakeDb");
// //
// MongoDB // MongoDB
// const db = require("./db/MongoDB"); // const db = require("./db/MongoDB");
// //
// ************************** // **************************
const DB_TYPE = { // const DB_TYPE = {
MongoDB: () => require("./db/mongo/MongoDB"), // MongoDB: async () => (await import("./db/mongo/MongoDB.js")).default,
FakedDB: () => require("./db/FakeDb"), // FakedDB: async () => (await import("./db/FakeDb.js")).default,
}; // };
// const db = DB_TYPE[process.env.DB_TYPE] // const db = DB_TYPE[process.env.DB_TYPE]
// ? DB_TYPE[process.env.DB_TYPE]() // ? DB_TYPE[process.env.DB_TYPE]()
// : require("./db/FakeDb"); // : require("./db/FakeDb");
const db = DB_TYPE.MongoDB(); // const db = DB_TYPE.MongoDB();
const app = express(); const app = express();
// middlewares // middlewares
app.use( app.use(
cors() cors()
//We will add configuration later //We will add configuration later
); );
app.use(express.json()); app.use(express.json());
app.use(helmet()); app.use(helmet());
// ************************** // **************************
// Make DB accessible anywhere we have a Request object // Make DB accessible anywhere we have a Request object
// By adding the DB to the request object, we can access it in any route // By adding the DB to the request object, we can access it in any route
// Thus we do not need to import it in every route file, and we can easily swap out DBs as there is only one place to change it // Thus we do not need to import it in every route file, and we can easily swap out DBs as there is only one place to change it
// Same applies for JobQueue and emailService // Same applies for JobQueue and emailService
// ************************** // **************************
app.use((req, res, next) => { app.use((req, res, next) => {
req.db = db; req.db = db;
req.jobQueue = jobQueue; req.jobQueue = jobQueue;
req.emailService = emailService; req.emailService = emailService;
req.settingsService = settingsService; req.settingsService = settingsService;
next(); next();
}); });
// Swagger UI // Swagger UI
app.use("/api-docs", swaggerUi.serve, swaggerUi.setup(openApiSpec)); app.use("/api-docs", swaggerUi.serve, swaggerUi.setup(openApiSpec));
//routes //routes
app.use("/api/v1/auth", authRouter); app.use("/api/v1/auth", authRouter);
app.use("/api/v1/settings", verifyJWT, settingsRouter); app.use("/api/v1/settings", verifyJWT, settingsRouter);
app.use("/api/v1/invite", inviteRouter); app.use("/api/v1/invite", inviteRouter);
app.use("/api/v1/monitors", verifyJWT, monitorRouter); app.use("/api/v1/monitors", verifyJWT, monitorRouter);
app.use("/api/v1/checks", verifyJWT, checkRouter); app.use("/api/v1/checks", verifyJWT, checkRouter);
app.use("/api/v1/maintenance-window", verifyJWT, maintenanceWindowRouter); app.use("/api/v1/maintenance-window", verifyJWT, maintenanceWindowRouter);
app.use("/api/v1/queue", verifyJWT, queueRouter); app.use("/api/v1/queue", verifyJWT, queueRouter);
//health check //health check
app.use("/api/v1/healthy", (req, res) => { app.use("/api/v1/healthy", (req, res) => {
try { try {
logger.info("Checking Health of the server."); logger.info("Checking Health of the server.");
return res.status(200).json({ message: "Healthy" }); return res.status(200).json({ message: "Healthy" });
} catch (error) { } catch (error) {
logger.error(error.message); logger.error(error.message);
return res.status(500).json({ message: error.message }); return res.status(500).json({ message: error.message });
} }
}); });
app.use("/api/v1/mail", async (req, res) => { app.use("/api/v1/mail", async (req, res) => {
try { try {
const id = await req.emailService.buildAndSendEmail( const id = await req.emailService.buildAndSendEmail(
"welcomeEmailTemplate", "welcomeEmailTemplate",
{ {
name: "Alex", name: "Alex",
}, },
"ajhollid@gmail.com", "ajhollid@gmail.com",
"Welcome" "Welcome"
); );
res.status(200).json({ success: true, msg: "Email sent", data: id }); res.status(200).json({ success: true, msg: "Email sent", data: id });
} catch (error) { } catch (error) {
logger.error(error.message); logger.error(error.message);
return res.status(500).json({ message: error.message }); return res.status(500).json({ message: error.message });
} }
}); });
/** /**
* Error handler middleware * Error handler middleware
* Should be called last * Should be called last
*/ */
app.use(handleErrors); app.use(handleErrors);
// Create services // Create services
await connectDbAndRunServer(app, db); await connectDbAndRunServer(app, db);
const settingsService = new SettingsService(); const settingsService = new SettingsService();
await settingsService.loadSettings(); await settingsService.loadSettings();
const emailService = new EmailService(settingsService); const emailService = new EmailService(settingsService);
const networkService = new NetworkService(db, emailService); const networkService = new NetworkService(db, emailService);
const jobQueue = await JobQueue.createJobQueue( const jobQueue = await JobQueue.createJobQueue(db, networkService, settingsService);
db,
networkService,
settingsService
);
const cleanup = async () => { const cleanup = async () => {
if (cleaningUp) { if (cleaningUp) {
console.log("Already cleaning up"); console.log("Already cleaning up");
return; return;
} }
cleaningUp = true; cleaningUp = true;
try { try {
console.log("Shutting down gracefully"); console.log("Shutting down gracefully");
await jobQueue.obliterate(); await jobQueue.obliterate();
console.log("Finished cleanup"); console.log("Finished cleanup");
} catch (error) { } catch (error) {
logger.error(errorMessages.JOB_QUEUE_DELETE_JOB, { logger.error(errorMessages.JOB_QUEUE_DELETE_JOB, {
service: SERVICE_NAME, service: SERVICE_NAME,
errorMsg: error.message, errorMsg: error.message,
}); });
} }
process.exit(0); process.exit(0);
}; };
process.on("SIGUSR2", cleanup); process.on("SIGUSR2", cleanup);
process.on("SIGINT", cleanup); process.on("SIGINT", cleanup);
process.on("SIGTERM", cleanup); process.on("SIGTERM", cleanup);
}; };
startApp().catch((error) => { startApp().catch((error) => {
console.log(error); console.log(error);
}); });
+3 -3
View File
@@ -1,5 +1,5 @@
const logger = require("../utils/logger"); import logger from "../utils/logger.js";
const { errorMessages } = require("../utils/messages"); import { errorMessages } from "../utils/messages.js";
const handleErrors = (error, req, res, next) => { const handleErrors = (error, req, res, next) => {
const status = error.status || 500; const status = error.status || 500;
@@ -12,4 +12,4 @@ const handleErrors = (error, req, res, next) => {
res.status(status).json({ success: false, msg: message }); res.status(status).json({ success: false, msg: message });
}; };
module.exports = { handleErrors }; export { handleErrors };
+3 -3
View File
@@ -1,7 +1,7 @@
const jwt = require("jsonwebtoken"); import jwt from "jsonwebtoken";
const TOKEN_PREFIX = "Bearer "; const TOKEN_PREFIX = "Bearer ";
const SERVICE_NAME = "allowedRoles"; const SERVICE_NAME = "allowedRoles";
const { errorMessages } = require("../utils/messages"); import { errorMessages } from "../utils/messages.js";
const isAllowed = (allowedRoles) => { const isAllowed = (allowedRoles) => {
return (req, res, next) => { return (req, res, next) => {
@@ -52,4 +52,4 @@ const isAllowed = (allowedRoles) => {
}; };
}; };
module.exports = { isAllowed }; export { isAllowed };
+6 -4
View File
@@ -1,8 +1,9 @@
const jwt = require("jsonwebtoken"); import jwt from "jsonwebtoken";
import { errorMessages } from "../utils/messages.js";
import { handleError } from "../controllers/controllerUtils.js";
const SERVICE_NAME = "verifyJWT"; const SERVICE_NAME = "verifyJWT";
const TOKEN_PREFIX = "Bearer "; const TOKEN_PREFIX = "Bearer ";
const { errorMessages } = require("../utils/messages");
const { handleError } = require("../controllers/controllerUtils");
/** /**
* Verifies the JWT token * Verifies the JWT token
@@ -91,4 +92,5 @@ function handleExpiredJwtToken(req, res, next) {
}); });
} }
module.exports = { verifyJWT }; export { verifyJWT };
+3 -3
View File
@@ -1,6 +1,6 @@
const logger = require("../utils/logger"); import logger from "../utils/logger.js";
import { errorMessages } from "../utils/messages.js";
const SERVICE_NAME = "verifyOwnership"; const SERVICE_NAME = "verifyOwnership";
const { errorMessages } = require("../utils/messages");
const verifyOwnership = (Model, paramName) => { const verifyOwnership = (Model, paramName) => {
return async (req, res, next) => { return async (req, res, next) => {
@@ -46,4 +46,4 @@ const verifyOwnership = (Model, paramName) => {
}; };
}; };
module.exports = { verifyOwnership }; export { verifyOwnership };
+6789 -8041
View File
File diff suppressed because it is too large. Load diff
+7 -7
View File
@@ -3,8 +3,9 @@
"version": "1.0.0", "version": "1.0.0",
"description": "", "description": "",
"main": "index.js", "main": "index.js",
"type": "module",
"scripts": { "scripts": {
"test": "nyc mocha", "test": "c8 mocha",
"dev": "nodemon index.js" "dev": "nodemon index.js"
}, },
"keywords": [], "keywords": [],
@@ -15,7 +16,6 @@
"axios": "^1.7.2", "axios": "^1.7.2",
"bcrypt": "^5.1.1", "bcrypt": "^5.1.1",
"bullmq": "5.7.15", "bullmq": "5.7.15",
"chai": "5.1.1",
"cors": "^2.8.5", "cors": "^2.8.5",
"dotenv": "^16.4.5", "dotenv": "^16.4.5",
"express": "^4.19.2", "express": "^4.19.2",
@@ -25,21 +25,21 @@
"jsonwebtoken": "9.0.2", "jsonwebtoken": "9.0.2",
"mailersend": "^2.2.0", "mailersend": "^2.2.0",
"mjml": "^5.0.0-alpha.4", "mjml": "^5.0.0-alpha.4",
"mocha": "10.7.3",
"mongoose": "^8.3.3", "mongoose": "^8.3.3",
"multer": "1.4.5-lts.1", "multer": "1.4.5-lts.1",
"nodemailer": "^6.9.14", "nodemailer": "^6.9.14",
"ping": "0.4.4", "ping": "0.4.4",
"sharp": "0.33.4", "sharp": "0.33.4",
"ssl-checker": "2.0.10",
"swagger-ui-express": "5.0.1", "swagger-ui-express": "5.0.1",
"winston": "^3.13.0" "winston": "^3.13.0"
}, },
"devDependencies": { "devDependencies": {
"nodemon": "3.1.0",
"prettier": "^3.3.3", "prettier": "^3.3.3",
"nyc": "17.1.0", "chai": "5.1.1",
"proxyquire": "2.1.3", "mocha": "10.7.3",
"c8": "10.1.2",
"esm": "3.2.25",
"nodemon": "3.1.0",
"sinon": "19.0.2" "sinon": "19.0.2"
} }
} }
+12 -10
View File
@@ -1,12 +1,14 @@
const router = require("express").Router(); import { Router } from "express";
const { verifyJWT } = require("../middleware/verifyJWT"); import { verifyJWT } from "../middleware/verifyJWT.js";
const { verifyOwnership } = require("../middleware/verifyOwnership"); import { verifyOwnership } from "../middleware/verifyOwnership.js";
const { isAllowed } = require("../middleware/isAllowed"); import { isAllowed } from "../middleware/isAllowed.js";
const multer = require("multer"); import multer from "multer";
const upload = multer(); import User from "../db/models/User.js";
const User = require("../db/models/User");
const { const router = Router();
const upload = multer();
import {
registerUser, registerUser,
loginUser, loginUser,
editUser, editUser,
@@ -16,7 +18,7 @@ const {
checkSuperadminExists, checkSuperadminExists,
getAllUsers, getAllUsers,
deleteUser, deleteUser,
} = require("../controllers/authController"); } from "../controllers/authController.js";
//Auth routes //Auth routes
router.post("/register", upload.single("profileImage"), registerUser); router.post("/register", upload.single("profileImage"), registerUser);
@@ -31,4 +33,4 @@ router.post("/recovery/request", requestRecovery);
router.post("/recovery/validate", validateRecovery); router.post("/recovery/validate", validateRecovery);
router.post("/recovery/reset/", resetPassword); router.post("/recovery/reset/", resetPassword);
module.exports = router; export default router;
+21 -20
View File
@@ -1,33 +1,34 @@
const router = require("express").Router(); import { Router } from "express";
const checkController = require("../controllers/checkController"); import {
const { verifyOwnership } = require("../middleware/verifyOwnership"); createCheck,
const { isAllowed } = require("../middleware/isAllowed"); getChecks,
const Monitor = require("../db/models/Monitor"); deleteChecks,
getTeamChecks,
deleteChecksByTeamId,
updateChecksTTL,
} from "../controllers/checkController.js";
import { verifyOwnership } from "../middleware/verifyOwnership.js";
import { isAllowed } from "../middleware/isAllowed.js";
import Monitor from "../db/models/Monitor.js";
router.get("/:monitorId", checkController.getChecks); const router = Router();
router.post(
"/:monitorId", router.get("/:monitorId", getChecks);
verifyOwnership(Monitor, "monitorId"), router.post("/:monitorId", verifyOwnership(Monitor, "monitorId"), createCheck);
checkController.createCheck
);
router.delete( router.delete(
"/:monitorId", "/:monitorId",
verifyOwnership(Monitor, "monitorId"), verifyOwnership(Monitor, "monitorId"),
checkController.deleteChecks deleteChecks
); );
router.get("/team/:teamId", checkController.getTeamChecks); router.get("/team/:teamId", getTeamChecks);
router.delete( router.delete(
"/team/:teamId", "/team/:teamId",
isAllowed(["admin", "superadmin"]), isAllowed(["admin", "superadmin"]),
checkController.deleteChecksByTeamId deleteChecksByTeamId
); );
router.put( router.put("/team/ttl", isAllowed(["admin", "superadmin"]), updateChecksTTL);
"/team/ttl",
isAllowed(["admin", "superadmin"]),
checkController.updateChecksTTL
);
module.exports = router; export default router;
+8 -7
View File
@@ -1,11 +1,12 @@
const router = require("express").Router(); import { Router } from "express";
const { verifyJWT } = require("../middleware/verifyJWT"); import { verifyJWT } from "../middleware/verifyJWT.js";
const { isAllowed } = require("../middleware/isAllowed"); import { isAllowed } from "../middleware/isAllowed.js";
import {
const {
issueInvitation, issueInvitation,
inviteVerifyController, inviteVerifyController,
} = require("../controllers/inviteController"); } from "../controllers/inviteController.js";
const router = Router();
router.post( router.post(
"/", "/",
@@ -15,4 +16,4 @@ router.post(
); );
router.post("/verify", issueInvitation); router.post("/verify", issueInvitation);
module.exports = router; export default router;
+20 -11
View File
@@ -1,22 +1,31 @@
const router = require("express").Router(); import { Router } from "express";
const maintenanceWindowController = require("../controllers/maintenanceWindowController"); import {
const { verifyOwnership } = require("../middleware/verifyOwnership"); createMaintenanceWindows,
const Monitor = require("../db/models/Monitor"); getMaintenanceWindowById,
getMaintenanceWindowsByTeamId,
getMaintenanceWindowsByMonitorId,
deleteMaintenanceWindow,
editMaintenanceWindow,
} from "../controllers/maintenanceWindowController.js";
import { verifyOwnership } from "../middleware/verifyOwnership.js";
import Monitor from "../db/models/Monitor.js";
router.post("/", maintenanceWindowController.createMaintenanceWindows); const router = Router();
router.post("/", createMaintenanceWindows);
router.get( router.get(
"/monitor/:monitorId", "/monitor/:monitorId",
verifyOwnership(Monitor, "monitorId"), verifyOwnership(Monitor, "monitorId"),
maintenanceWindowController.getMaintenanceWindowsByMonitorId getMaintenanceWindowsByMonitorId
); );
router.get("/team/", maintenanceWindowController.getMaintenanceWindowsByTeamId); router.get("/team/", getMaintenanceWindowsByTeamId);
router.get("/:id", maintenanceWindowController.getMaintenanceWindowById); router.get("/:id", getMaintenanceWindowById);
router.put("/:id", maintenanceWindowController.editMaintenanceWindow); router.put("/:id", editMaintenanceWindow);
router.delete("/:id", maintenanceWindowController.deleteMaintenanceWindow); router.delete("/:id", deleteMaintenanceWindow);
module.exports = router; export default router;
+34 -43
View File
@@ -1,51 +1,42 @@
const router = require("express").Router(); import { Router } from "express";
const monitorController = require("../controllers/monitorController"); import {
const { isAllowed } = require("../middleware/isAllowed"); getAllMonitors,
getMonitorStatsById,
getMonitorCertificate,
getMonitorById,
getMonitorsAndSummaryByTeamId,
getMonitorsByTeamId,
createMonitor,
deleteMonitor,
deleteAllMonitors,
editMonitor,
pauseMonitor,
addDemoMonitors,
} from "../controllers/monitorController.js";
import { isAllowed } from "../middleware/isAllowed.js";
import { fetchMonitorCertificate } from "../controllers/controllerUtils.js";
router.get("/", monitorController.getAllMonitors); const router = Router();
router.get("/stats/:monitorId", monitorController.getMonitorStatsById);
router.get("/certificate/:monitorId", monitorController.getMonitorCertificate);
router.get("/:monitorId", monitorController.getMonitorById);
router.get(
"/team/summary/:teamId",
monitorController.getMonitorsAndSummaryByTeamId
);
router.get("/team/:teamId", monitorController.getMonitorsByTeamId);
router.post( router.get("/", getAllMonitors);
"/", router.get("/stats/:monitorId", getMonitorStatsById);
isAllowed(["admin", "superadmin"]), router.get("/certificate/:monitorId", (req, res, next) => {
monitorController.createMonitor getMonitorCertificate(req, res, next, fetchMonitorCertificate);
); });
router.get("/:monitorId", getMonitorById);
router.get("/team/summary/:teamId", getMonitorsAndSummaryByTeamId);
router.get("/team/:teamId", getMonitorsByTeamId);
router.delete( router.post("/", isAllowed(["admin", "superadmin"]), createMonitor);
"/:monitorId",
isAllowed(["admin", "superadmin"]),
monitorController.deleteMonitor
);
router.put( router.delete("/:monitorId", isAllowed(["admin", "superadmin"]), deleteMonitor);
"/:monitorId",
isAllowed(["admin", "superadmin"]),
monitorController.editMonitor
);
router.delete( router.put("/:monitorId", isAllowed(["admin", "superadmin"]), editMonitor);
"/",
isAllowed(["superadmin"]),
monitorController.deleteAllMonitors
);
router.post( router.delete("/", isAllowed(["superadmin"]), deleteAllMonitors);
"/pause/:monitorId",
isAllowed(["admin", "superadmin"]),
monitorController.pauseMonitor
);
router.post( router.post("/pause/:monitorId", isAllowed(["admin", "superadmin"]), pauseMonitor);
"/demo",
isAllowed(["admin", "superadmin"]),
monitorController.addDemoMonitors
);
module.exports = router; router.post("/demo", isAllowed(["admin", "superadmin"]), addDemoMonitors);
export default router;
+13 -7
View File
@@ -1,15 +1,21 @@
const router = require("express").Router(); import { Router } from "express";
const queueController = require("../controllers/queueController"); import {
getMetrics,
getJobs,
addJob,
obliterateQueue,
} from "../controllers/queueController.js";
router.get("/metrics", queueController.getMetrics); const router = Router();
router.get("/metrics", getMetrics);
// Get Jobs // Get Jobs
router.get("/jobs", queueController.getJobs); router.get("/jobs", getJobs);
// Add Job // Add Job
router.post("/jobs", queueController.addJob); router.post("/jobs", addJob);
// Obliterate Queue // Obliterate Queue
router.post("/obliterate", queueController.obliterateQueue); router.post("/obliterate", obliterateQueue);
module.exports = router; export default router;
+11 -11
View File
@@ -1,13 +1,13 @@
const router = require("express").Router(); import { Router } from "express";
const settingsController = require("../controllers/settingsController"); import {
const { isAllowed } = require("../middleware/isAllowed"); getAppSettings,
const Monitor = require("../db/models/Monitor"); updateAppSettings,
} from "../controllers/settingsController.js";
import { isAllowed } from "../middleware/isAllowed.js";
router.get("/", settingsController.getAppSettings); const router = Router();
router.put(
"/",
isAllowed(["superadmin"]),
settingsController.updateAppSettings
);
module.exports = router; router.get("/", getAppSettings);
router.put("/", isAllowed(["superadmin"]), updateAppSettings);
export default router;
+12 -8
View File
@@ -1,10 +1,15 @@
const fs = require("fs"); import fs from "fs";
const path = require("path"); import path from "path";
const nodemailer = require("nodemailer"); import nodemailer from "nodemailer";
const { compile } = require("handlebars"); import pkg from "handlebars";
const mjml2html = require("mjml"); const { compile } = pkg;
import mjml2html from "mjml";
import logger from "../utils/logger.js";
import { fileURLToPath } from "url";
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const SERVICE_NAME = "EmailService"; const SERVICE_NAME = "EmailService";
const logger = require("../utils/logger");
/** /**
* Represents an email service that can load templates, build, and send emails. * Represents an email service that can load templates, build, and send emails.
@@ -134,5 +139,4 @@ class EmailService {
} }
}; };
} }
export default EmailService;
module.exports = EmailService;
+4 -4
View File
@@ -1,9 +1,9 @@
const { Queue, Worker, Job } = require("bullmq"); import { Queue, Worker, Job } from "bullmq";
const QUEUE_NAME = "monitors"; const QUEUE_NAME = "monitors";
const JOBS_PER_WORKER = 5; const JOBS_PER_WORKER = 5;
const logger = require("../utils/logger"); import logger from "../utils/logger.js";
const { errorMessages, successMessages } = require("../utils/messages"); import { errorMessages, successMessages } from "../utils/messages.js";
const SERVICE_NAME = "JobQueue"; const SERVICE_NAME = "JobQueue";
/** /**
* JobQueue * JobQueue
@@ -360,4 +360,4 @@ class JobQueue {
} }
} }
module.exports = JobQueue; export default JobQueue;
+6 -6
View File
@@ -1,8 +1,8 @@
const axios = require("axios"); import axios from "axios";
const ping = require("ping"); import ping from "ping";
const logger = require("../utils/logger"); import logger from "../utils/logger.js";
const http = require("http"); import http from "http";
const { errorMessages, successMessages } = require("../utils/messages"); import { errorMessages, successMessages } from "../utils/messages.js";
/** /**
* NetworkService * NetworkService
@@ -329,4 +329,4 @@ class NetworkService {
} }
} }
module.exports = NetworkService; export default NetworkService;
+2 -3
View File
@@ -1,5 +1,4 @@
const { env } = require("process"); import AppSettings from "../db/models/AppSettings.js";
const AppSettings = require("../db/models/AppSettings");
const SERVICE_NAME = "SettingsService"; const SERVICE_NAME = "SettingsService";
const envConfig = { const envConfig = {
logLevel: undefined, logLevel: undefined,
@@ -83,4 +82,4 @@ class SettingsService {
} }
} }
module.exports = SettingsService; export default SettingsService;
File diff suppressed because it is too large. Load diff
@@ -1,16 +1,16 @@
const { import {
createCheck, createCheck,
getChecks, getChecks,
getTeamChecks, getTeamChecks,
deleteChecks, deleteChecks,
deleteChecksByTeamId, deleteChecksByTeamId,
updateChecksTTL, updateChecksTTL,
} = require("../../controllers/checkController"); } from "../../controllers/checkController.js";
const jwt = require("jsonwebtoken"); import jwt from "jsonwebtoken";
const { errorMessages, successMessages } = require("../../utils/messages"); import { errorMessages, successMessages } from "../../utils/messages.js";
const sinon = require("sinon"); import sinon from "sinon";
describe("Check Controller - createCheck", () => { describe("Check Controller - createCheck", () => {
let req, res, next, handleError;
beforeEach(() => { beforeEach(() => {
req = { req = {
params: {}, params: {},
@@ -88,6 +88,7 @@ describe("Check Controller - createCheck", () => {
}); });
describe("Check Controller - getChecks", () => { describe("Check Controller - getChecks", () => {
let req, res, next;
beforeEach(() => { beforeEach(() => {
req = { req = {
params: {}, params: {},
@@ -143,6 +144,7 @@ describe("Check Controller - getChecks", () => {
}); });
describe("Check Controller - getTeamChecks", () => { describe("Check Controller - getTeamChecks", () => {
let req, res, next;
beforeEach(() => { beforeEach(() => {
req = { req = {
params: {}, params: {},
@@ -197,6 +199,7 @@ describe("Check Controller - getTeamChecks", () => {
}); });
describe("Check Controller - deleteChecks", () => { describe("Check Controller - deleteChecks", () => {
let req, res, next;
beforeEach(() => { beforeEach(() => {
req = { req = {
params: {}, params: {},
@@ -248,6 +251,7 @@ describe("Check Controller - deleteChecks", () => {
}); });
describe("Check Controller - deleteChecksByTeamId", () => { describe("Check Controller - deleteChecksByTeamId", () => {
let req, res, next;
beforeEach(() => { beforeEach(() => {
req = { req = {
params: {}, params: {},
@@ -301,6 +305,7 @@ describe("Check Controller - deleteChecksByTeamId", () => {
}); });
describe("Check Controller - updateCheckTTL", () => { describe("Check Controller - updateCheckTTL", () => {
let stub, req, res, next;
beforeEach(() => { beforeEach(() => {
stub = sinon.stub(jwt, "verify").callsFake(() => { stub = sinon.stub(jwt, "verify").callsFake(() => {
return { teamId: "123" }; return { teamId: "123" };
+195 -90
View File
@@ -1,105 +1,210 @@
const { import sinon from "sinon";
handleValidationError,
handleError, import {
} = require("../../controllers/controllerUtils"); handleValidationError,
handleError,
fetchMonitorCertificate,
} from "../../controllers/controllerUtils.js";
import { expect } from "chai";
describe("controllerUtils - handleValidationError", () => { describe("controllerUtils - handleValidationError", () => {
it("should set status to 422", () => { it("should set status to 422", () => {
const error = {}; const error = {};
const serviceName = "TestService"; const serviceName = "TestService";
const result = handleValidationError(error, serviceName); const result = handleValidationError(error, serviceName);
expect(result.status).to.equal(422); expect(result.status).to.equal(422);
}); });
it("should set service to the provided serviceName", () => { it("should set service to the provided serviceName", () => {
const error = {}; const error = {};
const serviceName = "TestService"; const serviceName = "TestService";
const result = handleValidationError(error, serviceName); const result = handleValidationError(error, serviceName);
expect(result.service).to.equal(serviceName); expect(result.service).to.equal(serviceName);
}); });
it("should set message to error.details[0].message if present", () => { it("should set message to error.details[0].message if present", () => {
const error = { const error = {
details: [{ message: "Detail message" }], details: [{ message: "Detail message" }],
}; };
const serviceName = "TestService"; const serviceName = "TestService";
const result = handleValidationError(error, serviceName); const result = handleValidationError(error, serviceName);
expect(result.message).to.equal("Detail message"); expect(result.message).to.equal("Detail message");
}); });
it("should set message to error.message if error.details is not present", () => { it("should set message to error.message if error.details is not present", () => {
const error = { const error = {
message: "Error message", message: "Error message",
}; };
const serviceName = "TestService"; const serviceName = "TestService";
const result = handleValidationError(error, serviceName); const result = handleValidationError(error, serviceName);
expect(result.message).to.equal("Error message"); expect(result.message).to.equal("Error message");
}); });
it('should set message to "Validation Error" if neither error.details nor error.message is present', () => { it('should set message to "Validation Error" if neither error.details nor error.message is present', () => {
const error = {}; const error = {};
const serviceName = "TestService"; const serviceName = "TestService";
const result = handleValidationError(error, serviceName); const result = handleValidationError(error, serviceName);
expect(result.message).to.equal("Validation Error"); expect(result.message).to.equal("Validation Error");
}); });
}); });
describe("handleError", () => { describe("controllerUtils - handleError", () => {
it("should set stats to the provided status if error.code is undefined", () => { it("should set stats to the provided status if error.code is undefined", () => {
const error = {}; const error = {};
const serviceName = "TestService"; const serviceName = "TestService";
const method = "testMethod"; const method = "testMethod";
const status = 400; const status = 400;
const result = handleError(error, serviceName, method, status); const result = handleError(error, serviceName, method, status);
expect(result.status).to.equal(status); expect(result.status).to.equal(status);
}); });
it("should not overwrite error.code if it is already defined", () => { it("should not overwrite error.code if it is already defined", () => {
const error = { status: 404 }; const error = { status: 404 };
const serviceName = "TestService"; const serviceName = "TestService";
const method = "testMethod"; const method = "testMethod";
const status = 400; const status = 400;
const result = handleError(error, serviceName, method, status); const result = handleError(error, serviceName, method, status);
expect(result.status).to.equal(404); expect(result.status).to.equal(404);
}); });
it("should set service to the provided serviceName if error.service is undefined", () => { it("should set service to the provided serviceName if error.service is undefined", () => {
const error = {}; const error = {};
const serviceName = "TestService"; const serviceName = "TestService";
const method = "testMethod"; const method = "testMethod";
const result = handleError(error, serviceName, method); const result = handleError(error, serviceName, method);
expect(result.service).to.equal(serviceName); expect(result.service).to.equal(serviceName);
}); });
it("should not overwrite error.service if it is already defined", () => { it("should not overwrite error.service if it is already defined", () => {
const error = { service: "ExistingService" }; const error = { service: "ExistingService" };
const serviceName = "TestService"; const serviceName = "TestService";
const method = "testMethod"; const method = "testMethod";
const result = handleError(error, serviceName, method); const result = handleError(error, serviceName, method);
expect(result.service).to.equal("ExistingService"); expect(result.service).to.equal("ExistingService");
}); });
it("should set method to the provided method if error.method is undefined", () => { it("should set method to the provided method if error.method is undefined", () => {
const error = {}; const error = {};
const serviceName = "TestService"; const serviceName = "TestService";
const method = "testMethod"; const method = "testMethod";
const result = handleError(error, serviceName, method); const result = handleError(error, serviceName, method);
expect(result.method).to.equal(method); expect(result.method).to.equal(method);
}); });
it("should not overwrite error.method if it is already defined", () => { it("should not overwrite error.method if it is already defined", () => {
const error = { method: "existingMethod" }; const error = { method: "existingMethod" };
const serviceName = "TestService"; const serviceName = "TestService";
const method = "testMethod"; const method = "testMethod";
const result = handleError(error, serviceName, method); const result = handleError(error, serviceName, method);
expect(result.method).to.equal("existingMethod"); expect(result.method).to.equal("existingMethod");
}); });
it("should set code to 500 if error.code is undefined and no code is provided", () => { it("should set code to 500 if error.code is undefined and no code is provided", () => {
const error = {}; const error = {};
const serviceName = "TestService"; const serviceName = "TestService";
const method = "testMethod"; const method = "testMethod";
const result = handleError(error, serviceName, method); const result = handleError(error, serviceName, method);
expect(result.status).to.equal(500); expect(result.status).to.equal(500);
}); });
});
describe("controllerUtils - fetchMonitorCertificate", () => {
const originalTls = {
connect: sinon.stub().callsFake((options, callback) => {
// Create socket stub with sinon stubs for all methods
socket = {
getPeerX509Certificate: sinon.stub().returns({
subject: "CN=fake-cert",
validTo: "Dec 31 23:59:59 2023 GMT",
}),
end: sinon.stub(),
on: sinon.stub(),
};
// Use process.nextTick to ensure async behavior
process.nextTick(() => {
callback.call(socket); // Ensure correct 'this' binding
});
return socket;
}),
};
let tls, monitor, socket;
beforeEach(() => {
monitor = { url: "https://www.google.com" };
tls = {
connect: sinon.stub().callsFake((options, callback) => {
// Create socket stub with sinon stubs for all methods
socket = {
getPeerX509Certificate: sinon.stub().returns({
subject: "CN=fake-cert",
validTo: "Dec 31 23:59:59 2023 GMT",
}),
end: sinon.stub(),
on: sinon.stub(),
};
// Use process.nextTick to ensure async behavior
process.nextTick(() => {
callback.call(socket); // Ensure correct 'this' binding
});
return socket;
}),
};
});
afterEach(() => {
tls = { ...originalTls };
sinon.restore();
});
it("should resolve with the certificate when the connection is successful", async () => {
const certificate = await fetchMonitorCertificate(tls, monitor);
expect(certificate.validTo).to.equal("Dec 31 23:59:59 2023 GMT");
expect(socket.end.calledOnce).to.be.true;
});
it("should reject with an error when the connection fails", async () => {
tls.connect = sinon.stub().throws(new Error("Connection error"));
try {
await fetchMonitorCertificate(tls, monitor);
} catch (error) {
expect(error.message).to.equal("Connection error");
}
});
it("should reject with an error if monitorURL is invalid", async () => {
monitor.url = "invalid-url";
try {
await fetchMonitorCertificate(tls, monitor);
} catch (error) {
expect(error.message).to.equal("Invalid URL");
}
});
it("should do a thing", async () => {
tls = {
connect: sinon.stub().callsFake((options, callback) => {
// Create socket stub with sinon stubs for all methods
socket = {
getPeerX509Certificate: sinon.stub().throws(new Error("Certificate error")),
end: sinon.stub(),
on: sinon.stub(),
};
// Use process.nextTick to ensure async behavior
process.nextTick(() => {
callback.call(socket); // Ensure correct 'this' binding
});
return socket;
}),
};
try {
await fetchMonitorCertificate(tls, monitor);
} catch (error) {
expect(error.message).to.equal("Certificate error");
}
});
}); });
@@ -1,12 +1,12 @@
const { import {
issueInvitation, issueInvitation,
inviteVerifyController, inviteVerifyController,
} = require("../../controllers/inviteController"); } from "../../controllers/inviteController.js";
const jwt = require("jsonwebtoken"); import jwt from "jsonwebtoken";
const { errorMessages, successMessages } = require("../../utils/messages"); import sinon from "sinon";
const sinon = require("sinon"); import joi from "joi";
const joi = require("joi");
describe("inviteController - issueInvitation", () => { describe("inviteController - issueInvitation", () => {
let req, res, next, stub;
beforeEach(() => { beforeEach(() => {
req = { req = {
headers: { authorization: "Bearer token" }, headers: { authorization: "Bearer token" },
@@ -154,6 +154,7 @@ describe("inviteController - issueInvitation", () => {
}); });
describe("inviteController - inviteVerifyController", () => { describe("inviteController - inviteVerifyController", () => {
let req, res, next;
beforeEach(() => { beforeEach(() => {
req = { req = {
body: { token: "token" }, body: { token: "token" },
@@ -1,17 +1,18 @@
const { import {
createMaintenanceWindows, createMaintenanceWindows,
getMaintenanceWindowById, getMaintenanceWindowById,
getMaintenanceWindowsByTeamId, getMaintenanceWindowsByTeamId,
getMaintenanceWindowsByMonitorId, getMaintenanceWindowsByMonitorId,
deleteMaintenanceWindow, deleteMaintenanceWindow,
editMaintenanceWindow, editMaintenanceWindow,
} = require("../../controllers/maintenanceWindowController"); } from "../../controllers/maintenanceWindowController.js";
const jwt = require("jsonwebtoken"); import jwt from "jsonwebtoken";
const { errorMessages, successMessages } = require("../../utils/messages"); import { successMessages } from "../../utils/messages.js";
const sinon = require("sinon"); import sinon from "sinon";
describe("maintenanceWindowController - createMaintenanceWindows", () => { describe("maintenanceWindowController - createMaintenanceWindows", () => {
let req, res, next, stub;
beforeEach(() => { beforeEach(() => {
req = { req = {
body: { body: {
@@ -103,6 +104,7 @@ describe("maintenanceWindowController - createMaintenanceWindows", () => {
}); });
describe("maintenanceWindowController - getMaintenanceWindowById", () => { describe("maintenanceWindowController - getMaintenanceWindowById", () => {
let req, res, next;
beforeEach(() => { beforeEach(() => {
req = { req = {
body: {}, body: {},
@@ -154,6 +156,7 @@ describe("maintenanceWindowController - getMaintenanceWindowById", () => {
}); });
describe("maintenanceWindowController - getMaintenanceWindowsByTeamId", () => { describe("maintenanceWindowController - getMaintenanceWindowsByTeamId", () => {
let req, res, next, stub;
beforeEach(() => { beforeEach(() => {
req = { req = {
body: {}, body: {},
@@ -220,6 +223,7 @@ describe("maintenanceWindowController - getMaintenanceWindowsByTeamId", () => {
}); });
describe("maintenanceWindowController - getMaintenanceWindowsByMonitorId", () => { describe("maintenanceWindowController - getMaintenanceWindowsByMonitorId", () => {
let req, res, next;
beforeEach(() => { beforeEach(() => {
req = { req = {
body: {}, body: {},
@@ -283,6 +287,7 @@ describe("maintenanceWindowController - getMaintenanceWindowsByMonitorId", () =>
}); });
describe("maintenanceWindowController - deleteMaintenanceWindow", () => { describe("maintenanceWindowController - deleteMaintenanceWindow", () => {
let req, res, next;
beforeEach(() => { beforeEach(() => {
req = { req = {
body: {}, body: {},
@@ -338,6 +343,7 @@ describe("maintenanceWindowController - deleteMaintenanceWindow", () => {
}); });
describe("maintenanceWindowController - editMaintenanceWindow", () => { describe("maintenanceWindowController - editMaintenanceWindow", () => {
let req, res, next;
beforeEach(() => { beforeEach(() => {
req = { req = {
body: { body: {
File diff suppressed because it is too large. Load diff
@@ -1,16 +1,15 @@
const { afterEach } = require("node:test"); import { afterEach } from "node:test";
const { import {
getMetrics, getMetrics,
getJobs, getJobs,
addJob, addJob,
obliterateQueue, obliterateQueue,
} = require("../../controllers/queueController"); } from "../../controllers/queueController.js";
const SERVICE_NAME = "JobQueueController"; import { successMessages } from "../../utils/messages.js";
import sinon from "sinon";
const { errorMessages, successMessages } = require("../../utils/messages");
const sinon = require("sinon");
describe("Queue Controller - getMetrics", () => { describe("Queue Controller - getMetrics", () => {
let req, res, next;
beforeEach(() => { beforeEach(() => {
req = { req = {
headers: {}, headers: {},
@@ -26,7 +25,6 @@ describe("Queue Controller - getMetrics", () => {
json: sinon.stub(), json: sinon.stub(),
}; };
next = sinon.stub(); next = sinon.stub();
handleError = sinon.stub();
}); });
afterEach(() => { afterEach(() => {
sinon.restore(); sinon.restore();
@@ -52,6 +50,7 @@ describe("Queue Controller - getMetrics", () => {
}); });
describe("Queue Controller - getJobs", () => { describe("Queue Controller - getJobs", () => {
let req, res, next;
beforeEach(() => { beforeEach(() => {
req = { req = {
headers: {}, headers: {},
@@ -67,7 +66,6 @@ describe("Queue Controller - getJobs", () => {
json: sinon.stub(), json: sinon.stub(),
}; };
next = sinon.stub(); next = sinon.stub();
handleError = sinon.stub();
}); });
afterEach(() => { afterEach(() => {
sinon.restore(); sinon.restore();
@@ -92,6 +90,7 @@ describe("Queue Controller - getJobs", () => {
}); });
describe("Queue Controller - addJob", () => { describe("Queue Controller - addJob", () => {
let req, res, next;
beforeEach(() => { beforeEach(() => {
req = { req = {
headers: {}, headers: {},
@@ -107,7 +106,6 @@ describe("Queue Controller - addJob", () => {
json: sinon.stub(), json: sinon.stub(),
}; };
next = sinon.stub(); next = sinon.stub();
handleError = sinon.stub();
}); });
afterEach(() => { afterEach(() => {
sinon.restore(); sinon.restore();
@@ -130,6 +128,7 @@ describe("Queue Controller - addJob", () => {
}); });
describe("Queue Controller - obliterateQueue", () => { describe("Queue Controller - obliterateQueue", () => {
let req, res, next;
beforeEach(() => { beforeEach(() => {
req = { req = {
headers: {}, headers: {},
@@ -145,7 +144,6 @@ describe("Queue Controller - obliterateQueue", () => {
json: sinon.stub(), json: sinon.stub(),
}; };
next = sinon.stub(); next = sinon.stub();
handleError = sinon.stub();
}); });
afterEach(() => { afterEach(() => {
sinon.restore(); sinon.restore();
@@ -1,13 +1,14 @@
const { afterEach } = require("node:test"); import { afterEach } from "node:test";
const { import {
getAppSettings, getAppSettings,
updateAppSettings, updateAppSettings,
} = require("../../controllers/settingsController"); } from "../../controllers/settingsController.js";
const { errorMessages, successMessages } = require("../../utils/messages"); import { successMessages } from "../../utils/messages.js";
const sinon = require("sinon"); import sinon from "sinon";
describe("Settings Controller - getAppSettings", () => { describe("Settings Controller - getAppSettings", () => {
let req, res, next;
beforeEach(() => { beforeEach(() => {
req = { req = {
headers: {}, headers: {},
@@ -23,7 +24,6 @@ describe("Settings Controller - getAppSettings", () => {
json: sinon.stub(), json: sinon.stub(),
}; };
next = sinon.stub(); next = sinon.stub();
handleError = sinon.stub();
}); });
afterEach(() => { afterEach(() => {
sinon.restore(); sinon.restore();
@@ -49,6 +49,7 @@ describe("Settings Controller - getAppSettings", () => {
}); });
describe("Settings Controller - updateAppSettings", () => { describe("Settings Controller - updateAppSettings", () => {
let req, res, next;
beforeEach(() => { beforeEach(() => {
req = { req = {
headers: {}, headers: {},
@@ -66,7 +67,6 @@ describe("Settings Controller - updateAppSettings", () => {
json: sinon.stub(), json: sinon.stub(),
}; };
next = sinon.stub(); next = sinon.stub();
handleError = sinon.stub();
}); });
afterEach(() => { afterEach(() => {
sinon.restore(); sinon.restore();
+68
View File
@@ -0,0 +1,68 @@
import { NormalizeData, calculatePercentile } from "../../utils/dataUtils.js";
import sinon from "sinon";
describe("NormalizeData", () => {
it("should normalize response times when checks length is greater than 1", () => {
const checks = [
{ responseTime: 20, _doc: { id: 1 } },
{ responseTime: 40, _doc: { id: 2 } },
{ responseTime: 60, _doc: { id: 3 } },
];
const rangeMin = 1;
const rangeMax = 100;
const result = NormalizeData(checks, rangeMin, rangeMax);
expect(result).to.be.an("array");
expect(result).to.have.lengthOf(3);
result.forEach((check) => {
expect(check).to.have.property("responseTime").that.is.a("number");
expect(check).to.have.property("originalResponseTime").that.is.a("number");
});
});
it("should return checks with original response times when checks length is 1", () => {
const checks = [{ responseTime: 20, _doc: { id: 1 } }];
const rangeMin = 1;
const rangeMax = 100;
const result = NormalizeData(checks, rangeMin, rangeMax);
expect(result).to.be.an("array");
expect(result).to.have.lengthOf(1);
expect(result[0]).to.have.property("originalResponseTime", 20);
});
it("should handle edge cases with extreme response times", () => {
const checks = [
{ responseTime: 5, _doc: { id: 1 } },
{ responseTime: 95, _doc: { id: 2 } },
];
const rangeMin = 1;
const rangeMax = 100;
const result = NormalizeData(checks, rangeMin, rangeMax);
expect(result).to.be.an("array");
expect(result).to.have.lengthOf(2);
expect(result[0]).to.have.property("responseTime").that.is.at.least(rangeMin);
expect(result[1]).to.have.property("responseTime").that.is.at.most(rangeMax);
});
});
describe("calculatePercentile", () => {
it("should return the lower value when upper is greater than or equal to the length of the sorted array", () => {
const checks = [
{ responseTime: 10 },
{ responseTime: 20 },
{ responseTime: 30 },
{ responseTime: 40 },
{ responseTime: 50 },
];
const percentile = 100;
const result = calculatePercentile(checks, percentile);
const expected = 50;
console.log(result);
expect(result).to.equal(expected);
});
});
@@ -0,0 +1,57 @@
import { expect } from "chai";
import sinon from "sinon";
import sharp from "sharp";
import { GenerateAvatarImage } from "../../utils/imageProcessing.js";
describe("imageProcessing - GenerateAvatarImage", () => {
it("should resize the image to 64x64 and return a base64 string", async () => {
const file = {
buffer: Buffer.from("test image buffer"),
};
// Stub the sharp function
const toBufferStub = sinon.stub().resolves(Buffer.from("resized image buffer"));
const resizeStub = sinon.stub().returns({ toBuffer: toBufferStub });
const sharpStub = sinon
.stub(sharp.prototype, "resize")
.returns({ toBuffer: toBufferStub });
const result = await GenerateAvatarImage(file);
// Verify the result
const expected = Buffer.from("resized image buffer").toString("base64");
expect(result).to.equal(expected);
// Verify that the sharp function was called with the correct arguments
expect(sharpStub.calledOnceWith({ width: 64, height: 64, fit: "cover" })).to.be.true;
expect(toBufferStub.calledOnce).to.be.true;
// Restore the stubbed functions
sharpStub.restore();
});
it("should throw an error if resizing fails", async () => {
const file = {
buffer: Buffer.from("test image buffer"),
};
// Stub the sharp function to throw an error
const toBufferStub = sinon.stub().rejects(new Error("Resizing failed"));
const resizeStub = sinon.stub().returns({ toBuffer: toBufferStub });
const sharpStub = sinon
.stub(sharp.prototype, "resize")
.returns({ toBuffer: toBufferStub });
try {
await GenerateAvatarImage(file);
// If no error is thrown, fail the test
expect.fail("Expected error to be thrown");
} catch (error) {
// Verify that the error message is correct
expect(error.message).to.equal("Resizing failed");
}
// Restore the stubbed functions
sharpStub.restore();
});
});
+29
View File
@@ -0,0 +1,29 @@
import { errorMessages, successMessages } from "../../utils/messages.js";
describe("Messages", () => {
describe("messages - errorMessages", () => {
it("should have a DB_FIND_MONITOR_BY_ID function", () => {
const monitorId = "12345";
expect(errorMessages.DB_FIND_MONITOR_BY_ID(monitorId)).to.equal(
`Monitor with id ${monitorId} not found`
);
});
it("should have a DB_DELETE_CHECKS function", () => {
const monitorId = "12345";
expect(errorMessages.DB_DELETE_CHECKS(monitorId)).to.equal(
`No checks found for monitor with id ${monitorId}`
);
});
});
describe("messages - successMessages", () => {
it("should have a MONITOR_GET_BY_USER_ID function", () => {
const userId = "12345";
expect(successMessages.MONITOR_GET_BY_USER_ID(userId)).to.equal(
`Got monitor for ${userId} successfully"`
);
});
// Add more tests for other success messages as needed
});
});
+50
View File
@@ -0,0 +1,50 @@
import { ParseBoolean, getTokenFromHeaders } from "../../utils/utils.js";
describe("utils - ParseBoolean", () => {
it("should return true", () => {
const result = ParseBoolean("true");
expect(result).to.be.true;
});
it("should return false", () => {
const result = ParseBoolean("false");
expect(result).to.be.false;
});
it("should return false", () => {
const result = ParseBoolean(null);
expect(result).to.be.false;
});
it("should return false", () => {
const result = ParseBoolean(undefined);
expect(result).to.be.false;
});
});
describe("utils - getTokenFromHeaders", () => {
it("should throw an error if authorization header is missing", () => {
const headers = {};
expect(() => getTokenFromHeaders(headers)).to.throw("No auth headers");
});
it("should throw an error if authorization header does not start with Bearer", () => {
const headers = { authorization: "Basic abcdef" };
expect(() => getTokenFromHeaders(headers)).to.throw("Invalid auth headers");
});
it("should return the token if authorization header is correctly formatted", () => {
const headers = { authorization: "Bearer abcdef" };
expect(getTokenFromHeaders(headers)).to.equal("abcdef");
});
it("should throw an error if authorization header has more than two parts", () => {
const headers = { authorization: "Bearer abc def" };
expect(() => getTokenFromHeaders(headers)).to.throw("Invalid auth headers");
});
it("should throw an error if authorization header has less than two parts", () => {
const headers = { authorization: "Bearer" };
expect(() => getTokenFromHeaders(headers)).to.throw("Invalid auth headers");
});
});
+35 -41
View File
@@ -1,50 +1,44 @@
const calculatePercentile = (arr, percentile) => { const calculatePercentile = (arr, percentile) => {
const sorted = arr.slice().sort((a, b) => a.responseTime - b.responseTime); const sorted = arr.slice().sort((a, b) => a.responseTime - b.responseTime);
const index = (percentile / 100) * (sorted.length - 1); const index = (percentile / 100) * (sorted.length - 1);
const lower = Math.floor(index); const lower = Math.floor(index);
const upper = lower + 1; const upper = lower + 1;
const weight = index % 1; const weight = index % 1;
if (upper >= sorted.length) return sorted[lower].responseTime; if (upper >= sorted.length) return sorted[lower].responseTime;
return ( return sorted[lower].responseTime * (1 - weight) + sorted[upper].responseTime * weight;
sorted[lower].responseTime * (1 - weight) +
sorted[upper].responseTime * weight
);
}; };
const NormalizeData = (checks, rangeMin, rangeMax) => { const NormalizeData = (checks, rangeMin, rangeMax) => {
if (checks.length > 1) { if (checks.length > 1) {
// Get the 5th and 95th percentile // Get the 5th and 95th percentile
const min = calculatePercentile(checks, 0); const min = calculatePercentile(checks, 0);
const max = calculatePercentile(checks, 95); const max = calculatePercentile(checks, 95);
const normalizedChecks = checks.map((check) => { const normalizedChecks = checks.map((check) => {
const originalResponseTime = check.responseTime; const originalResponseTime = check.responseTime;
// Normalize the response time between 1 and 100 // Normalize the response time between 1 and 100
let normalizedResponseTime = let normalizedResponseTime =
rangeMin + rangeMin + ((check.responseTime - min) * (rangeMax - rangeMin)) / (max - min);
((check.responseTime - min) * (rangeMax - rangeMin)) / (max - min);
// Put a floor on the response times so we don't have extreme outliers // Put a floor on the response times so we don't have extreme outliers
// Better visuals // Better visuals
normalizedResponseTime = Math.max( normalizedResponseTime = Math.max(
rangeMin, rangeMin,
Math.min(rangeMax, normalizedResponseTime) Math.min(rangeMax, normalizedResponseTime)
); );
return { return {
...check._doc, ...check._doc,
responseTime: normalizedResponseTime, responseTime: normalizedResponseTime,
originalResponseTime: originalResponseTime, originalResponseTime: originalResponseTime,
}; };
}); });
return normalizedChecks; return normalizedChecks;
} else { } else {
return checks.map((check) => { return checks.map((check) => {
return { ...check._doc, originalResponseTime: check.responseTime }; return { ...check._doc, originalResponseTime: check.responseTime };
}); });
} }
}; };
module.exports = { export { calculatePercentile, NormalizeData };
NormalizeData,
};
+2 -4
View File
@@ -1,4 +1,4 @@
const sharp = require("sharp"); import sharp from "sharp";
/** /**
* Generates a 64 * 64 pixel image from a given image * Generates a 64 * 64 pixel image from a given image
* @param {} file * @param {} file
@@ -22,6 +22,4 @@ const GenerateAvatarImage = async (file) => {
} }
}; };
module.exports = { export { GenerateAvatarImage };
GenerateAvatarImage,
};
+10 -10
View File
@@ -1,8 +1,8 @@
const winston = require('winston'); import winston from "winston";
/** /**
* @module * @module
* @example * @example
* logger.info("Registered a new user!") * logger.info("Registered a new user!")
* logger.warn("User not found!") * logger.warn("User not found!")
* logger.error("Cannot save") * logger.error("Cannot save")
* @example * @example
@@ -12,15 +12,15 @@ const winston = require('winston');
* logger.error("User not found!",{"service":"Auth"}) * logger.error("User not found!",{"service":"Auth"})
*/ */
const logger = winston.createLogger({ const logger = winston.createLogger({
level: 'info', level: "info",
format: winston.format.combine( format: winston.format.combine(
winston.format.timestamp(), winston.format.timestamp(),
winston.format.json() winston.format.json()
), ),
transports: [ transports: [
new winston.transports.Console(), new winston.transports.Console(),
new winston.transports.File({ filename: 'app.log' }), new winston.transports.File({ filename: "app.log" }),
], ],
}); });
module.exports = logger; export default logger;
+1 -4
View File
@@ -121,7 +121,4 @@ const successMessages = {
UPDATE_APP_SETTINGS: "Updated app settings successfully", UPDATE_APP_SETTINGS: "Updated app settings successfully",
}; };
module.exports = { export { errorMessages, successMessages };
errorMessages,
successMessages,
};
+19 -23
View File
@@ -4,36 +4,32 @@
* @returns {boolean} * @returns {boolean}
*/ */
const ParseBoolean = (value) => { const ParseBoolean = (value) => {
if (value === true || value === "true") { if (value === true || value === "true") {
return true; return true;
} else if ( } else if (
value === false || value === false ||
value === "false" || value === "false" ||
value === null || value === null ||
value === undefined value === undefined
) { ) {
return false; return false;
} }
}; };
const getTokenFromHeaders = (headers) => { const getTokenFromHeaders = (headers) => {
const authorizationHeader = headers.authorization; const authorizationHeader = headers.authorization;
if (!authorizationHeader) throw new Error("No auth headers"); if (!authorizationHeader) throw new Error("No auth headers");
const parts = authorizationHeader.split(" "); const parts = authorizationHeader.split(" ");
if (parts.length !== 2 || parts[0] !== "Bearer") if (parts.length !== 2 || parts[0] !== "Bearer")
throw new Error("Invalid auth headers"); throw new Error("Invalid auth headers");
return parts[1]; return parts[1];
}; };
const tokenType = Object.freeze({ const tokenType = Object.freeze({
ACCESS_TOKEN: "Access token", ACCESS_TOKEN: "Access token",
REFRESH_TOKEN: "Refresh token" REFRESH_TOKEN: "Refresh token",
}); });
module.exports = { export { ParseBoolean, getTokenFromHeaders, tokenType };
ParseBoolean,
getTokenFromHeaders,
tokenType,
};
+4 -7
View File
@@ -1,7 +1,4 @@
const exp = require("constants"); import joi from "joi";
const joi = require("joi");
const { normalize } = require("path");
const { start } = require("repl");
//**************************************** //****************************************
// Custom Validators // Custom Validators
@@ -143,7 +140,7 @@ const inviteBodyValidation = joi.object({
teamId: joi.string().required(), teamId: joi.string().required(),
}); });
const inviteVerifciationBodyValidation = joi.object({ const inviteVerificationBodyValidation = joi.object({
token: joi.string().required(), token: joi.string().required(),
}); });
@@ -427,7 +424,7 @@ const updateAppSettingsBodyValidation = joi.object({
systemEmailPassword: joi.string().allow(""), systemEmailPassword: joi.string().allow(""),
}); });
module.exports = { export {
roleValidatior, roleValidatior,
loginValidation, loginValidation,
registrationBodyValidation, registrationBodyValidation,
@@ -436,7 +433,7 @@ module.exports = {
newPasswordValidation, newPasswordValidation,
inviteRoleValidation, inviteRoleValidation,
inviteBodyValidation, inviteBodyValidation,
inviteVerificationBodyValidation: inviteVerifciationBodyValidation, inviteVerificationBodyValidation,
createMonitorBodyValidation, createMonitorBodyValidation,
getMonitorByIdParamValidation, getMonitorByIdParamValidation,
getMonitorByIdQueryValidation, getMonitorByIdQueryValidation,